SPB Git

Repository Public

QuickCaptureSheet.swift 24.7 KB 519 lines swift

1// SP Notes iOS2// File: Features/Capture/QuickCaptureSheet.swift3// Description: Quick Capture: one sheet, one tap away, to put a text, an idea, a link, a photo, a scan, a voice note, a dictation4//              or a file into the inbox. The title field has the keyboard at once; « Enregistrer dans la boîte de réception » is5//              ⌘Return on a hardware keyboard. Signature motion #6: sub-200 ms scale-in, Lumen pulse and haptic on save (a plain6//              fade under Reduce Motion). Entry points: `QuickCaptureSheet(initialMode:)` and `.quickCapture(isPresented:mode:)`.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SPNotesCore11import SPNotesDesign12import SwiftUI13import UIKit1415// MARK: - Entry points1617/// A request to open Quick Capture in a mode (the shell's hook, Quick Actions, deep links).18struct CaptureRequest: Identifiable, Equatable {19    let id = UUID()20    var mode: CaptureMode = .text21}2223extension View {24    /// Presents Quick Capture. `mode` is the mode it opens in (`.text` by default, `.dictation` for « Dictée »…).25    func quickCapture(isPresented: Binding<Bool>, mode: CaptureMode = .text) -> some View {26        sheet(isPresented: isPresented) { QuickCaptureSheet(initialMode: mode) }27    }2829    /// Presents Quick Capture for a request (nil = closed).30    func quickCapture(item: Binding<CaptureRequest?>) -> some View {31        sheet(item: item) { QuickCaptureSheet(initialMode: $0.mode) }32    }33}3435// MARK: - Sheet3637struct QuickCaptureSheet: View {38    @Environment(AppModel.self) private var app39    @Environment(\.dismiss) private var dismiss40    @Environment(\.accessibilityReduceMotion) private var reduceMotion41    @Environment(\.dynamicTypeSize) private var typeSize42    @State private var model: QuickCaptureModel43    @State private var appeared = false44    @State private var picker: Picker?45    @State private var showsFileImporter = false46    @State private var confirmsDiscard = false47    @State private var isRecognizing = false48    @State private var autoClose: Task<Void, Never>?49    @FocusState private var focus: Field?5051    private enum Field { case title, text, link }52    private enum Picker: String, Identifiable { case library, camera, scanner; var id: String { rawValue } }5354    init(initialMode: CaptureMode = .text) { _model = State(initialValue: QuickCaptureModel(mode: initialMode)) }55    init(model: QuickCaptureModel) { _model = State(initialValue: model) }5657    var body: some View {58        NavigationStack {59            ScrollView {60                VStack(alignment: .leading, spacing: NVSpace.lg) {61                    modeStrip62                    if appeared {63                        surface64                            .transition(CaptureMotion.transition(reduceMotion: reduceMotion))65                    }66                }67                .padding(.horizontal, NVSpace.lg)68                .padding(.top, NVSpace.sm)69                .padding(.bottom, NVSpace.xl)70                .frame(maxWidth: NVSpace.readingMeasure)71                .frame(maxWidth: .infinity)72            }73            .scrollDismissesKeyboard(.interactively)74            .background(NVColor.bg)75            .navigationTitle("Capture rapide")76            .navigationBarTitleDisplayMode(.inline)77            .toolbar {78                ToolbarItem(placement: .cancellationAction) {79                    Button("Annuler") { cancel() }.accessibilityIdentifier("capture-cancel")80                }81            }82            .safeAreaInset(edge: .bottom) { if model.savedPageId == nil { saveBar } }83            .confirmationDialog("Abandonner cette capture ?", isPresented: $confirmsDiscard, titleVisibility: .visible) {84                Button("Supprimer la capture", role: .destructive) { model.discardAll(); dismiss() }85                if !model.holdsUnsavedMedia { Button("Garder le brouillon") { model.keepDraft(); dismiss() } }86                Button("Continuer", role: .cancel) {}87            } message: {88                Text(model.holdsUnsavedMedia ? "Les fichiers et l’enregistrement de cette capture ne sont pas encore dans une note." : "Le texte peut être gardé comme brouillon pour la prochaine capture.")89            }90            .sheet(item: $picker) { pickerView($0) }91            .attachmentFileImporter(isPresented: $showsFileImporter) { files, failed in92                model.add(files: files)93                if failed > 0 { model.error = String(localized: "Un fichier n’a pas pu être lu.") }94            }95        }96        // a swipe never loses a photo or a recording; the text is kept as a draft97        .interactiveDismissDisabled(model.holdsUnsavedMedia || model.isSaving)98        .presentationDragIndicator(.visible)99        .onAppear {100            withAnimation(CaptureMotion.appearAnimation(reduceMotion: reduceMotion)) { appeared = true }101            if model.mode.startsTyping { focus = model.mode == .link ? .link : .title }102        }103        .onDisappear {104            autoClose?.cancel()105            if model.dictation.isListening { model.dictation.stop() }106            if model.recorder.phase == .recording { model.recorder.pause() }107            model.keepDraft()108        }109        .accessibilityIdentifier("quick-capture")110    }111112    // MARK: modes113114    private var modeStrip: some View {115        ScrollViewReader { proxy in116            ScrollView(.horizontal, showsIndicators: false) {117                HStack(spacing: NVSpace.sm) {118                    ForEach(CaptureMode.allCases) { mode in119                        let selected = model.mode == mode120                        Button {121                            Haptics.selection()122                            withNVAnimation(.fast, reduceMotion: reduceMotion) { model.select(mode) }123                            if mode.startsTyping { focus = mode == .link ? .link : .title } else { focus = nil }124                        } label: {125                            Label(mode.title, systemImage: mode.symbol)126                                .nvFont(.uiStrong)127                                .lineLimit(1)128                                .padding(.horizontal, NVSpace.md)129                                .frame(minHeight: 44)130                                .foregroundStyle(selected ? NVColor.accentFg : NVColor.fg)131                                .background(selected ? NVColor.accent : NVColor.bgSunken, in: Capsule())132                        }133                        .buttonStyle(.plain)134                        .id(mode)135                        .accessibilityAddTraits(selected ? .isSelected : [])136                        .accessibilityIdentifier("capture-mode-\(mode.rawValue)")137                    }138                }139                .padding(.vertical, NVSpace.xxs)140            }141            .onAppear { proxy.scrollTo(model.mode, anchor: .center) }142            .onChange(of: model.mode) { _, mode in withNVAnimation(.fast, reduceMotion: reduceMotion) { proxy.scrollTo(mode, anchor: .center) } }143        }144        .accessibilityElement(children: .contain)145        .accessibilityLabel(Text("Type de capture"))146    }147148    // MARK: surface149150    private var surface: some View {151        VStack(alignment: .leading, spacing: NVSpace.md) {152            if let saved = model.savedPageId {153                savedConfirmation(saved)154            } else {155                if model.restoredDraft {156                    Label("Brouillon repris", systemImage: "arrow.uturn.backward.circle")157                        .nvFont(.micro).foregroundStyle(NVColor.fgMuted)158                        .accessibilityIdentifier("capture-draft-restored")159                }160                TextField(titlePlaceholder, text: $model.title, axis: .vertical)161                    .nvFont(.h3)162                    .foregroundStyle(NVColor.fg)163                    .focused($focus, equals: .title)164                    .submitLabel(.next)165                    .lineLimit(1...3)166                    .onChange(of: model.title) { _, value in167                        // Return in the title goes to the body (a vertical field inserts a line break instead of submitting)168                        if value.contains("\n") { model.title = value.replacingOccurrences(of: "\n", with: ""); focus = model.mode == .link ? .link : .text }169                    }170                    .accessibilityIdentifier("capture-title")171                Divider().overlay(NVColor.line)172                modeBody173                if let error = model.error {174                    Label(error, systemImage: "exclamationmark.triangle.fill")175                        .nvFont(.ui).foregroundStyle(NVColor.fg)176                        .accessibilityIdentifier("capture-error")177                }178            }179        }180        .padding(NVSpace.lg)181        .frame(maxWidth: .infinity, alignment: .leading)182        .nvCard()183        .nvCapturePulse(trigger: model.saveCount)184    }185186    private var titlePlaceholder: String {187        switch model.mode {188        case .idea: return String(localized: "Une idée…")189        case .link: return String(localized: "Titre (facultatif)")190        case .text: return String(localized: "Titre ou première ligne")191        default: return String(localized: "Titre (facultatif)")192        }193    }194195    @ViewBuilder private var modeBody: some View {196        switch model.mode {197        case .text, .idea:198            textEditor(placeholder: model.mode == .idea ? String(localized: "Développe ton idée (facultatif)") : String(localized: "Écris ta note. Le Markdown est reconnu."))199        case .link:200            HStack(spacing: NVSpace.sm) {201                TextField("https://…", text: $model.link)202                    .nvFont(.body)203                    .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()204                    .focused($focus, equals: .link)205                    .onChange(of: model.link) { model.linkFieldChanged() }206                    .accessibilityIdentifier("capture-link")207                if UIPasteboard.general.hasURLs || UIPasteboard.general.hasStrings {208                    Button {209                        if let pasted = UIPasteboard.general.url?.absoluteString ?? UIPasteboard.general.string { model.link = pasted; model.linkFieldChanged() }210                    } label: { Label("Coller", systemImage: "doc.on.clipboard").labelStyle(.titleAndIcon) }211                        .nvFont(.ui).frame(minHeight: 44)212                        .accessibilityIdentifier("capture-paste")213                }214            }215            if !model.link.isEmpty, !model.canSave {216                Text("Ce lien n’est pas une adresse http(s) valide.").nvFont(.micro).foregroundStyle(NVColor.fgMuted)217            }218            textEditor(placeholder: String(localized: "Une note sur ce lien (facultatif)"), minHeight: 72)219        case .photo:220            ViewThatFits(in: .horizontal) {221                HStack(spacing: NVSpace.md) { photoButtons }222                VStack(alignment: .leading, spacing: NVSpace.sm) { photoButtons }223            }224            fileList225        case .scan:226            if DocumentScanner.isSupported {227                actionButton(String(localized: "Numériser un document"), symbol: "doc.viewfinder", id: "capture-scan") { picker = .scanner }228            } else {229                Text("La numérisation a besoin de l’appareil photo, absent sur cet appareil. Tu peux choisir une photo du document : son texte sera reconnu.")230                    .nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)231                    .accessibilityIdentifier("capture-scan-unavailable")232                actionButton(String(localized: "Choisir une photo"), symbol: "photo.on.rectangle", id: "capture-scan-library") { picker = .library }233            }234            if isRecognizing {235                HStack(spacing: NVSpace.sm) { ProgressView(); Text("Reconnaissance du texte…").nvFont(.ui).foregroundStyle(NVColor.fgMuted) }236            }237            fileList238            if !model.text.isEmpty { textEditor(placeholder: "", minHeight: 72) }239        case .audio:240            VoiceRecorderView(recorder: model.recorder)241                .task { if model.recorder.phase == .idle { await model.recorder.start() } }242        case .dictation:243            dictationBody244        case .file:245            actionButton(String(localized: "Choisir des fichiers"), symbol: "folder", id: "capture-files") { showsFileImporter = true }246            fileList247        }248    }249250    private func textEditor(placeholder: String, minHeight: CGFloat = 120) -> some View {251        ZStack(alignment: .topLeading) {252            if model.text.isEmpty {253                Text(placeholder).nvFont(.body).foregroundStyle(NVColor.fgFaint)254                    .padding(.top, 8).padding(.leading, 5).accessibilityHidden(true)255            }256            TextEditor(text: $model.text)257                .nvFont(.body)258                .foregroundStyle(NVColor.fg)259                .scrollContentBackground(.hidden)260                .focused($focus, equals: .text)261                .frame(minHeight: minHeight)262                .accessibilityLabel(Text(placeholder.isEmpty ? String(localized: "Texte") : placeholder))263                .accessibilityIdentifier("capture-text")264        }265    }266267    @ViewBuilder private var photoButtons: some View {268        actionButton(String(localized: "Photothèque"), symbol: "photo.on.rectangle", id: "capture-library") { picker = .library }269        if CameraPicker.isAvailable {270            actionButton(String(localized: "Appareil photo"), symbol: "camera", id: "capture-camera") { picker = .camera }271        }272    }273274    private func actionButton(_ title: String, symbol: String, id: String, action: @escaping () -> Void) -> some View {275        Button(action: action) {276            Label(title, systemImage: symbol).nvFont(.uiStrong).frame(minHeight: 44).padding(.horizontal, NVSpace.md)277                .foregroundStyle(NVColor.accent)278                .background(NVColor.accentSoft, in: NVRadius.shape(NVRadius.md))279        }280        .buttonStyle(.plain)281        .accessibilityIdentifier(id)282    }283284    @ViewBuilder private var fileList: some View {285        if !model.files.isEmpty {286            VStack(spacing: NVSpace.xs) {287                ForEach(model.files, id: \.url) { file in288                    HStack(spacing: NVSpace.md) {289                        thumbnail(file)290                        Text(file.filename ?? file.url.lastPathComponent).nvFont(.ui).foregroundStyle(NVColor.fg).lineLimit(2)291                        Spacer(minLength: 0)292                        Button(role: .destructive) { model.remove(file: file) } label: { Image(systemName: "xmark.circle.fill").frame(minWidth: 44, minHeight: 44) }293                            .foregroundStyle(NVColor.fgMuted)294                            .accessibilityLabel(Text("Retirer \(file.filename ?? file.url.lastPathComponent)"))295                    }296                    .padding(.leading, NVSpace.sm)297                    .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.md))298                }299            }300            .accessibilityIdentifier("capture-files-list")301        }302    }303304    @ViewBuilder private func thumbnail(_ file: CaptureFile) -> some View {305        if CaptureKinds.kind(forFiles: [file]) == CaptureKindName.photo, let image = UIImage(contentsOfFile: file.url.path) {306            Image(uiImage: image).resizable().scaledToFill().frame(width: 40, height: 40).clipShape(NVRadius.shape(NVRadius.sm)).accessibilityHidden(true)307        } else {308            Image(systemName: "doc").frame(width: 40, height: 40).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)309        }310    }311312    // MARK: dictation313314    @ViewBuilder private var dictationBody: some View {315        switch model.dictation.phase {316        case .microphoneDenied(let restricted):317            MicrophoneDeniedView(restricted: restricted) { Task { await model.toggleDictation() } }318        case .speechDenied(let restricted):319            dictationNotice(restricted ? String(localized: "La reconnaissance vocale est restreinte sur cet appareil.")320                            : String(localized: "SP Notes n’a pas accès à la reconnaissance vocale. Autorise-la dans Réglages pour dicter."), settings: !restricted)321        case .unavailable(let language):322            dictationNotice(String(localized: "La dictée sur l’appareil n’est pas disponible pour cette langue sur cet appareil (\(language))."), settings: false)323        default:324            textEditor(placeholder: String(localized: "Touche le micro et parle : le texte apparaît ici."))325            HStack(spacing: NVSpace.md) {326                Button {327                    Haptics.tap()328                    focus = nil329                    Task { await model.toggleDictation() }330                } label: {331                    Label(model.dictation.isListening ? "Arrêter la dictée" : "Dicter", systemImage: model.dictation.isListening ? "stop.fill" : "mic.fill")332                        .nvFont(.uiStrong).foregroundStyle(NVColor.accentFg)333                        .padding(.horizontal, NVSpace.lg).frame(minHeight: 48)334                        .background(NVColor.lumen, in: Capsule())335                }336                .buttonStyle(.plain)337                .accessibilityIdentifier("capture-dictate")338                if model.dictation.isListening {339                    NVProgressDots()340                    Text("Écoute…").nvFont(.ui).foregroundStyle(NVColor.fgMuted)341                }342                Spacer(minLength: 0)343            }344            Toggle(isOn: Bindable(model.dictation).keepsAudio) {345                VStack(alignment: .leading, spacing: NVSpace.xxs) {346                    Text("Garder l’audio").nvFont(.ui).foregroundStyle(NVColor.fg)347                    Text("Sinon seul le texte est enregistré.").nvFont(.micro).foregroundStyle(NVColor.fgMuted)348                }349            }350            .disabled(model.dictation.isListening)351            .accessibilityIdentifier("capture-keep-audio")352            Label(dictationStatus, systemImage: "iphone")353                .nvFont(.micro).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)354                .accessibilityIdentifier("capture-dictation-status")355        }356    }357358    private var dictationStatus: String {359        switch model.dictation.phase {360        case .stopped(.silence): return String(localized: "Dictée arrêtée après un silence. Dictée sur l’appareil.")361        case .stopped(.interruption): return String(localized: "Dictée interrompue par un appel ou une autre app. Le texte est conservé.")362        case .stopped(.background): return String(localized: "Dictée arrêtée : SP Notes est passée en arrière-plan. Le texte est conservé.")363        case .stopped(.failed(let reason)): return String(localized: "La dictée s’est arrêtée (\(reason)). Le texte est conservé.")364        default: return String(localized: "Dictée sur l’appareil : la voix n’est envoyée nulle part.")365        }366    }367368    private func dictationNotice(_ text: String, settings: Bool) -> some View {369        VStack(alignment: .leading, spacing: NVSpace.md) {370            Label(text, systemImage: "character.bubble").nvFont(.ui).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)371            if settings {372                Button("Ouvrir Réglages") { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } }373                    .buttonStyle(.borderedProminent)374            }375            Button("Écrire à la place") { model.select(.text); focus = .text }.nvFont(.ui)376        }377        .accessibilityIdentifier("capture-dictation-unavailable")378    }379380    // MARK: pickers381382    @ViewBuilder private func pickerView(_ picker: Picker) -> some View {383        switch picker {384        case .library:385            PhotoLibraryPicker { urls in386                self.picker = nil387                model.add(files: urls)388                if model.mode == .scan { recognize(urls) }389            }390            .ignoresSafeArea()391        case .camera:392            CameraPicker { url in393                self.picker = nil394                if let url { model.add(files: [url]) }395            }396            .ignoresSafeArea()397        case .scanner:398            DocumentScanner(onFinish: { urls in399                self.picker = nil400                model.add(files: urls)401                recognize(urls)402            }, onError: { error in403                self.picker = nil404                model.error = error.localizedDescription405            })406            .ignoresSafeArea()407        }408    }409410    /// A scan is searchable: its text is recognised on the device and saved with the pages.411    private func recognize(_ urls: [URL]) {412        guard !urls.isEmpty else { return }413        isRecognizing = true414        Task {415            let recognized = await TextRecognizer.recognizeText(atPages: urls)416            model.appendRecognized(recognized)417            isRecognizing = false418        }419    }420421    // MARK: save422423    private var saveBar: some View {424        VStack(spacing: 0) {425            if model.savedPageId == nil {426                Button { save() } label: {427                    HStack(spacing: NVSpace.sm) {428                        if model.isSaving { ProgressView().tint(NVColor.accentFg) } else { Image(systemName: "tray.and.arrow.down.fill").accessibilityHidden(true) }429                        // the short label only when the long one does not fit on a line (accessibility sizes)430                        ViewThatFits(in: .horizontal) {431                            Text("Enregistrer dans la boîte de réception").lineLimit(1)432                            Text("Enregistrer").lineLimit(1)433                        }434                    }435                    .nvFont(.uiStrong)436                    .frame(maxWidth: .infinity, minHeight: 50)437                    .padding(.horizontal, NVSpace.md)438                    .foregroundStyle(NVColor.accentFg)439                    .background(NVColor.accent.opacity(model.canSave ? 1 : 0.4), in: NVRadius.shape(NVRadius.lg))440                }441                .buttonStyle(.plain)442                .disabled(!model.canSave)443                .keyboardShortcut(.return, modifiers: .command)444                .accessibilityLabel(Text("Enregistrer dans la boîte de réception"))445                .accessibilityIdentifier("capture-save")446            }447        }448        .padding(.horizontal, NVSpace.lg)449        .padding(.vertical, NVSpace.md)450        .frame(maxWidth: .infinity)451        .nvGlass()452    }453454    private func savedConfirmation(_ pageId: String) -> some View {455        VStack(alignment: .leading, spacing: NVSpace.md) {456            Label {457                Text("Enregistré dans la boîte de réception").nvFont(.h3).foregroundStyle(NVColor.fg)458            } icon: {459                Image(systemName: "checkmark.circle.fill").foregroundStyle(NVColor.lumen).font(.title2)460            }461            .accessibilityIdentifier("capture-saved")462            Text(app.session == .signedIn ? "La capture est sur cet appareil et sera synchronisée." : "La capture est sur cet appareil.")463                .nvFont(.ui).foregroundStyle(NVColor.fgMuted)464            ViewThatFits(in: .horizontal) {465                HStack(spacing: NVSpace.md) { savedActions(pageId) }466                VStack(alignment: .leading, spacing: NVSpace.sm) { savedActions(pageId) }467            }468        }469    }470471    @ViewBuilder private func savedActions(_ pageId: String) -> some View {472        Button("Ouvrir la note") {473            autoClose?.cancel()474            dismiss()475            app.pendingRoute = .note(pageId)476        }477        .buttonStyle(.borderedProminent)478        .accessibilityIdentifier("capture-open-note")479        Button("Nouvelle capture") {480            autoClose?.cancel()481            withNVAnimation(.fast, reduceMotion: reduceMotion) { model.startAnother() }482            if model.mode.startsTyping { focus = .title }483        }484        .buttonStyle(.bordered)485        .accessibilityIdentifier("capture-another")486        Button("Terminé") { autoClose?.cancel(); dismiss() }487            .accessibilityIdentifier("capture-done")488    }489490    private func save() {491        focus = nil492        Task {493            guard await model.save(app: app) != nil else { Haptics.warning(); return }494            Haptics.success()495            guard !QuickCaptureSheet.staysOpenAfterSave else { return }496            autoClose = Task {497                try? await Task.sleep(for: CaptureMotion.confirmationDelay)498                guard !Task.isCancelled, model.savedPageId != nil else { return }499                dismiss()500            }501        }502    }503504    private func cancel() {505        if model.holdsUnsavedMedia { confirmsDiscard = true }506        else if model.hasContent, model.savedPageId == nil { confirmsDiscard = true }507        else { dismiss() }508    }509510    /// DEBUG (`SPNOTES_CAPTURE_STAY=1`): the confirmation stays on screen (screenshots, UI tests that read it).511    static var staysOpenAfterSave: Bool {512        #if DEBUG513        return ProcessInfo.processInfo.environment["SPNOTES_CAPTURE_STAY"] == "1"514        #else515        return false516        #endif517    }518}519
Files main
Menu

Theme