Sources/OrgstarShare/ShareViewController.swift

f24016fbc9384e5bae26abb48db212a9330b488b
orgstar/Sources/OrgstarShare/ShareViewController.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form