// The three sources an editor offers a picture or a file from — the camera,// the photo library, the files — presented once, so the photo and file// column's editor and a long text's attach offer the same three the same way// (`PictureSources.swift` holds the camera and the staging they share).//// Whatever is picked arrives as an `AttachmentSource`: a file staged in the// temporary folder, which the receiver deletes once it is kept. Nothing here// keeps or writes anything — the editor hands the source on.importCottonKitimportPhotosUIimportSwiftUIimportUniformTypeIdentifiers/// Which of the sources is open, one at a time.structAttachmentSourceState: Equatable {var library = falsevar files = falsevar camera = falsevar isOpen: Bool { library || files || camera }/// The most the library hands over at once where it takes several.staticlet mostAtOnce = 20}/// The words each source is offered with.enumAttachmentSourceWords {staticlet camera = "Camera"staticlet library = "Library"staticlet files = "Files"staticvar unreadablePhoto: String { ShellLines.line("editing", "attachment.unreadable_photo") }staticvar unreadableFile: String { ShellLines.line("editing", "attachment.unreadable_file") }}extensionView {/// Presents the sources `state` opens. `photosOnly` keeps the library to/// pictures and the files to images (a photo column); otherwise the/// library offers films too and the files anything./// `several` lets the library hand over more than one at a time (the/// box's "Choose photos"), each arriving as its own source.func attachmentSources( _ state: Binding<AttachmentSourceState>, photosOnly: Bool, several: Bool = false, onPicked: @escaping (AttachmentSource) -> Void, onRefused: @escaping (String) -> Void, onCancelled: @escaping () -> Void = {} ) -> someView { modifier(AttachmentSourcesModifier( state: state, photosOnly: photosOnly, several: several, onPicked: onPicked, onRefused: onRefused, onCancelled: onCancelled)) }}privatestructAttachmentSourcesModifier: ViewModifier { @Binding var state: AttachmentSourceStatelet photosOnly: Boollet several: Boollet onPicked: (AttachmentSource) -> Voidlet onRefused: (String) -> Voidlet onCancelled: () -> Void @State privatevar libraryItems: [PhotosPickerItem] = []/// Something was picked since the sources last opened. @State privatevar picked = falsefunc body(content: Content) -> someView { content .photosPicker( isPresented: $state.library, selection: $libraryItems, maxSelectionCount: several ? AttachmentSourceState.mostAtOnce : 1, matching: photosOnly ? .images : .any(of: [.images, .videos])) .onChange(of: libraryItems) { _, items inguard !items.isEmpty else { return } picked = true libraryItems = []// In the order they were picked, one after another.Task { for item in items { await stage(item) } } } .onChange(of: state.isOpen) { _, openin// Closed with nothing picked. The pick's own change lands in// the same update when there was one, so a yield lets it.guard !open else { picked = falsereturn }Task {awaitTask.yield()if !picked { onCancelled() } } } .fileImporter( isPresented: $state.files, allowedContentTypes: photosOnly ? [.image] : [.item], allowsMultipleSelection: false ) { result inguardcase .success(let urls) = result, let url = urls.first else { return } picked = true imported(url) } .fullScreenCover(isPresented: $state.camera) {CameraPicker( onTaken: { url in picked = true state.camera = false onPicked(AttachmentSource( url: url, mime: "image/jpeg", kind: .photo, filename: url.lastPathComponent, origin: .camera)) }, onCancelled: { state.camera = false } ) } }privatefunc stage(_ item: PhotosPickerItem) async {guardlet staged = awaitMediaStaging.stage(item) else { onRefused(AttachmentSourceWords.unreadablePhoto)return } onPicked(AttachmentSource( url: staged.url, mime: staged.mime, kind: RecordAttachments.captureKind(UTType(mimeType: staged.mime)), filename: staged.url.lastPathComponent, origin: .library)) }/// A file from the files app is only readable inside its security scope,/// so it is copied out before anything reads it.privatefunc imported(_ url: URL) {let scoped = url.startAccessingSecurityScopedResource()defer { if scoped { url.stopAccessingSecurityScopedResource() } }let copy = FileManager.default.temporaryDirectory .appendingPathComponent("imported-\(UUID().uuidString)-\(url.lastPathComponent)")do {tryFileManager.default.copyItem(at: url, to: copy) } catch { onRefused(AttachmentSourceWords.unreadableFile)return }let type = UTType(filenameExtension: url.pathExtension) onPicked(AttachmentSource( url: copy, mime: type?.preferredMIMEType ?? "application/octet-stream", kind: RecordAttachments.captureKind(type), filename: url.lastPathComponent, origin: .files)) }}