SPB Git

Repository Public

ShareView.swift 8.6 KB 207 lines swift

1// SP Notes iOS2// File: ShareExtension/ShareView.swift3// Description: The sheet of the share extension: what is being shared (text, link, image thumbnails, file names), an optional4//              title, "Enregistrer" and "Annuler". Saving writes one item into the shared inbox and closes the sheet.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Observation9import SwiftUI10import UIKit1112@MainActor13@Observable14final class ShareModel {15    enum Phase: Equatable { case loading, ready, saving, failed(String) }1617    private(set) var phase = Phase.loading18    private(set) var payload = SharePayload()19    private(set) var thumbnails: [UUID: UIImage] = [:]20    var title = ""21    /// Called once, with true when the item was saved.22    @ObservationIgnored var onFinish: (Bool) -> Void = { _ in }23    @ObservationIgnored private let loader = ShareContentLoader()2425    var canSave: Bool { phase == .ready && !payload.isEmpty }2627    func load(_ items: [NSExtensionItem]) async {28        let payload = await loader.load(items)29        self.payload = payload30        title = payload.suggestedTitle31        guard !payload.isEmpty else {32            phase = .failed(payload.failures.first ?? String(localized: "Il n’y a rien à enregistrer dans ce partage."))33            return34        }35        phase = .ready36        for file in payload.files where file.isImage {37            let url = file.url38            thumbnails[file.id] = await Task.detached(priority: .userInitiated) { ShareFiles.thumbnail(of: url) }.value39        }40    }4142    func save() {43        guard canSave else { return }44        phase = .saving45        let cleanTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)46        let item = SharedItem(title: cleanTitle.isEmpty ? nil : cleanTitle, text: payload.text.isEmpty ? nil : payload.text, url: payload.link?.absoluteString)47        let files = payload.files.map { (name: $0.name, source: $0.url) }48        Task {49            let saved = await Task.detached(priority: .userInitiated) { () -> Bool in50                let inbox = SharedInbox(container: AppGroup.containerURL.appendingPathComponent("SPNotes", isDirectory: true))51                do {52                    try inbox.save(item, files: files)53                    return true54                } catch {55                    inbox.remove(item) // nothing half-written is left behind56                    return false57                }58            }.value59            if saved {60                loader.cleanUp()61                onFinish(true)62            } else {63                phase = .failed(String(localized: "L’enregistrement a échoué. Vérifie l’espace libre sur l’appareil, puis réessaie."))64            }65        }66    }6768    func cancel() {69        loader.cleanUp()70        onFinish(false)71    }72}7374struct ShareView: View {75    @Bindable var model: ShareModel76    @FocusState private var titleFocused: Bool7778    var body: some View {79        NavigationStack {80            content81                .background(Color("Background"))82                .navigationTitle("SP Notes")83                .navigationBarTitleDisplayMode(.inline)84                .toolbar {85                    ToolbarItem(placement: .cancellationAction) {86                        Button("Annuler") { model.cancel() }.accessibilityIdentifier("share-cancel")87                    }88                    ToolbarItem(placement: .confirmationAction) {89                        if model.phase == .saving {90                            ProgressView()91                        } else {92                            Button("Enregistrer") { model.save() }.fontWeight(.semibold).disabled(!model.canSave).accessibilityIdentifier("share-save")93                        }94                    }95                }96        }97    }9899    @ViewBuilder private var content: some View {100        switch model.phase {101        case .loading:102            ProgressView("Préparation…").frame(maxWidth: .infinity, maxHeight: .infinity)103        case .failed(let message):104            ContentUnavailableView {105                Label("Impossible d’enregistrer", systemImage: "exclamationmark.triangle")106            } description: {107                Text(message)108            } actions: {109                Button("Fermer") { model.cancel() }.buttonStyle(.borderedProminent)110            }111        case .ready, .saving:112            Form {113                Section {114                    TextField("Titre (facultatif)", text: $model.title, axis: .vertical)115                        .lineLimit(1...3)116                        .font(.headline)117                        .focused($titleFocused)118                        .submitLabel(.done)119                        .accessibilityIdentifier("share-title")120                }121                Section {122                    if let link = model.payload.link { LinkRow(link: link) }123                    if !model.payload.text.isEmpty {124                        Text(model.payload.text).font(.subheadline).foregroundStyle(Color("TextPrimary")).lineLimit(8)125                    }126                    let images = model.payload.files.filter(\.isImage)127                    if !images.isEmpty { ThumbnailStrip(files: images, thumbnails: model.thumbnails) }128                    ForEach(model.payload.files.filter { !$0.isImage }) { FileRow(file: $0) }129                } header: {130                    Text("Sera enregistré dans une nouvelle note")131                } footer: {132                    Text("La note apparaîtra dans SP Notes à sa prochaine ouverture.")133                }134                if !model.payload.failures.isEmpty || model.payload.skipped > 0 {135                    Section {136                        ForEach(Array(Set(model.payload.failures)).sorted(), id: \.self) { message in137                            Label(message, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Color("Warning"))138                        }139                        if model.payload.skipped > 0 {140                            Label("\(model.payload.skipped) éléments en trop n’ont pas été ajoutés (10 images et 10 fichiers au plus).", systemImage: "exclamationmark.triangle")141                                .font(.footnote)142                                .foregroundStyle(Color("Warning"))143                        }144                    }145                }146            }147            .scrollContentBackground(.hidden)148            .disabled(model.phase == .saving)149        }150    }151}152153private struct LinkRow: View {154    let link: URL155    var body: some View {156        HStack(alignment: .top, spacing: 12) {157            Image(systemName: "link").foregroundStyle(Color.accentColor).frame(width: 24).accessibilityHidden(true)158            VStack(alignment: .leading, spacing: 2) {159                if let host = link.host() { Text(host).font(.subheadline.weight(.semibold)).foregroundStyle(Color("TextPrimary")) }160                Text(link.absoluteString).font(.footnote).foregroundStyle(Color("TextSecondary")).lineLimit(2)161            }162        }163        .accessibilityElement(children: .combine)164    }165}166167private struct ThumbnailStrip: View {168    let files: [StagedFile]169    let thumbnails: [UUID: UIImage]170    var body: some View {171        ScrollView(.horizontal, showsIndicators: false) {172            HStack(spacing: 8) {173                ForEach(files) { file in174                    Group {175                        if let image = thumbnails[file.id] {176                            Image(uiImage: image).resizable().scaledToFill()177                        } else {178                            Color("Surface2").overlay { Image(systemName: "photo").foregroundStyle(Color("Muted")) }179                        }180                    }181                    .frame(width: 76, height: 76)182                    .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))183                    .accessibilityLabel(Text(file.name))184                }185            }186        }187        .listRowInsets(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 0))188    }189}190191private struct FileRow: View {192    let file: StagedFile193    var body: some View {194        HStack(spacing: 12) {195            Image(systemName: (file.name as NSString).pathExtension.lowercased() == "pdf" ? "doc.richtext" : "doc")196                .foregroundStyle(Color.accentColor)197                .frame(width: 24)198                .accessibilityHidden(true)199            VStack(alignment: .leading, spacing: 2) {200                Text(file.name).font(.subheadline).foregroundStyle(Color("TextPrimary")).lineLimit(2)201                Text(file.size, format: .byteCount(style: .file)).font(.footnote).foregroundStyle(Color("TextSecondary"))202            }203        }204        .accessibilityElement(children: .combine)205    }206}207
Files main
Menu

Theme