Sources/OrgstarShare/ShareViewController.swift

design-themes-widgets
orgstar/Sources/OrgstarShare/ShareViewController.swift history · blame · raw

169 lines · 6975 bytes

  1#if os(iOS)
  2import OrgApp
  3import OrgCore
  4import SwiftUI
  5import UIKit
  6import UniformTypeIdentifiers
  7
  8/// The share sheet's Orgstar: the shared page or text with a template and a note, left for the
  9/// app, which opens its capture sheet with them the next time it's active; or shared files,
 10/// which the app asks to attach to an entry.
 11@objc(ShareViewController)
 12final class ShareViewController: UIViewController {
 13    override func viewDidLoad() {
 14        super.viewDidLoad()
 15        let items = extensionContext?.inputItems as? [NSExtensionItem] ?? []
 16        let context = extensionContext
 17        Task { @MainActor in
 18            let shared = await Shared.load(items)
 19            let inbox = CaptureInbox()
 20            let form = ShareForm(shared: shared, templates: inbox?.templates() ?? [], available: inbox != nil) { link in
 21                if let link { try? inbox?.add(link) }
 22                context?.completeRequest(returningItems: nil)
 23            } attach: { files in
 24                try? AttachmentInbox()?.add(files)
 25                context?.completeRequest(returningItems: nil)
 26            }
 27            let host = UIHostingController(rootView: form)
 28            addChild(host)
 29            host.view.frame = view.bounds
 30            host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
 31            view.addSubview(host.view)
 32            host.didMove(toParent: self)
 33        }
 34    }
 35}
 36
 37/// What the other app shared: a page's address and title, text, or files.
 38struct Shared {
 39    var url: URL?
 40    var title = ""
 41    var text = ""
 42    /// Copies of shared files, photos and videos.
 43    var files: [URL] = []
 44
 45    /// Whether the item is a file to attach rather than a page or text.
 46    static func isFile(_ provider: NSItemProvider) -> Bool {
 47        provider.registeredContentTypes.contains { type in
 48            type.conforms(to: .fileURL) || ([.image, .movie, .audio, .pdf, .archive] as [UTType]).contains { type.conforms(to: $0) }
 49        }
 50    }
 51
 52    /// A copy of the provider's file, under its own name.
 53    @MainActor
 54    static func copy(_ provider: NSItemProvider) async -> URL? {
 55        guard let type = provider.registeredContentTypes.first(where: { !$0.conforms(to: .fileURL) }) ?? provider.registeredContentTypes.first else { return nil }
 56        return await withCheckedContinuation { continuation in
 57            _ = provider.loadFileRepresentation(for: type, openInPlace: false) { url, _, _ in
 58                guard let url else { return continuation.resume(returning: nil) }
 59                let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
 60                let copy = folder.appendingPathComponent(url.lastPathComponent)
 61                do {
 62                    try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
 63                    try FileManager.default.copyItem(at: url, to: copy)
 64                    continuation.resume(returning: copy)
 65                } catch {
 66                    continuation.resume(returning: nil)
 67                }
 68            }
 69        }
 70    }
 71
 72    @MainActor
 73    static func load(_ items: [NSExtensionItem]) async -> Shared {
 74        var shared = Shared()
 75        for item in items {
 76            if shared.title.isEmpty, let title = item.attributedTitle?.string ?? item.attributedContentText?.string { shared.title = title }
 77            for provider in item.attachments ?? [] {
 78                if isFile(provider) {
 79                    if let file = await copy(provider) { shared.files.append(file) }
 80                } else if shared.url == nil, provider.hasItemConformingToTypeIdentifier(UTType.url.identifier),
 81                   let url = try? await provider.loadItem(forTypeIdentifier: UTType.url.identifier) as? URL {
 82                    shared.url = url
 83                } else if shared.text.isEmpty, provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier),
 84                          let text = try? await provider.loadItem(forTypeIdentifier: UTType.plainText.identifier) as? String {
 85                    shared.text = text
 86                }
 87            }
 88        }
 89        // Text shared on its own arrives as the item's content too.
 90        if shared.url == nil, shared.text == shared.title { shared.title = "" }
 91        return shared
 92    }
 93}
 94
 95struct ShareForm: View {
 96    let shared: Shared
 97    let templates: [CaptureInbox.Template]
 98    let available: Bool
 99    let finish: (String?) -> Void
100    /// Leaves the files for the app to attach.
101    let attach: ([URL]) -> Void
102    @State private var title = ""
103    @State private var note = ""
104    @State private var template: String?
105
106    var body: some View {
107        NavigationStack {
108            Form {
109                if !available {
110                    Text("orgstar's shared folder isn't available.").foregroundStyle(.red)
111                }
112                if !shared.files.isEmpty {
113                    Section {
114                        ForEach(shared.files, id: \.self) { Text($0.lastPathComponent) }
115                    } header: {
116                        Text("Attach")
117                    } footer: {
118                        Text("orgstar asks which entry to attach them to when you next open it.")
119                    }
120                } else {
121                    captureSections
122                }
123            }
124            .navigationTitle("orgstar")
125            .navigationBarTitleDisplayMode(.inline)
126            .toolbar {
127                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
128                ToolbarItem(placement: .confirmationAction) {
129                    if shared.files.isEmpty {
130                        Button("Capture") {
131                            finish(OrgProtocol.captureURL(template: template, url: shared.url?.absoluteString, title: title, body: note))
132                        }
133                        .disabled(!available)
134                    } else {
135                        Button("Attach") { attach(shared.files) }.disabled(!available)
136                    }
137                }
138            }
139        }
140        .onAppear {
141            title = shared.title
142            note = shared.text
143            template = templates.first?.key
144        }
145    }
146
147    @ViewBuilder
148    private var captureSections: some View {
149        if !templates.isEmpty {
150            Picker("Template", selection: $template) {
151                ForEach(templates, id: \.key) { Text($0.name).tag(Optional($0.key)) }
152            }
153        }
154        if let url = shared.url {
155            Section("Link") {
156                TextField("Title", text: $title)
157                Text(url.absoluteString).font(.footnote).foregroundStyle(.secondary).lineLimit(2)
158            }
159        }
160        Section("Text") {
161            TextEditor(text: $note).frame(minHeight: 120)
162        }
163        Section {
164        } footer: {
165            Text("orgstar files it with the template when you next open it.")
166        }
167    }
168}
169#endif