SPB Git

Repository Public

NoteEditorScreen.swift 17.6 KB 358 lines swift

1// SP Notes iOS2// File: Features/Editor/NoteEditorScreen.swift3// Description: The screen of one note: the native editor on a readable column, the save and sync state, the "…" menu (organise,4//              reminders, files, history, export, find, statistics) and the states a note can be in (loading, deleted elsewhere,5//              in the trash, database page). What the editor asks for is presented by NoteEditorPresentations.swift.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SwiftUI11import UIKit1213/// What makes the open note read the store again: an external change of its page, a conflict, a file — not its own autosaves.14struct EditorReloadKey: Equatable { var page: Int; var conflicts: Int; var attachments: Int; var reset: Int }1516struct NoteEditorScreen: View {17    let noteId: String18    var isNew = false19    /// 2.0 (shell): the block to scroll to, passed to `NoteEditorModel.reveal(blockId:)`.20    var reveal: NoteReveal?2122    @Environment(AppModel.self) private var app23    /// One model per note id, created once and kept while the screen lives.24    @State private var model: NoteEditorModel?2526    init(noteId: String, isNew: Bool = false, reveal: NoteReveal? = nil) {27        self.noteId = noteId28        self.isNew = isNew29        self.reveal = reveal30    }3132    var body: some View {33        ZStack {34            Color.spBackground.ignoresSafeArea()35            if let model, model.noteId == noteId {36                NoteEditorContent(model: model, isNew: isNew).id(noteId)37            } else {38                ProgressView()39            }40        }41        .task(id: noteId) {42            guard model?.noteId != noteId else { return }43            model?.flush()44            model = NoteEditorModel(noteId: noteId, app: app)45            if let reveal { model?.reveal(blockId: reveal.blockId) }46        }47        .onChange(of: reveal) { _, new in if let new, model?.noteId == noteId { model?.reveal(blockId: new.blockId) } }48    }49}5051struct NoteEditorContent: View {52    let model: NoteEditorModel53    let isNew: Bool5455    @Environment(AppModel.self) var app56    @Environment(\.dismiss) var dismiss57    @Environment(\.scenePhase) private var scenePhase58    @Environment(\.horizontalSizeClass) private var sizeClass5960    // Presentation state (used by the extension in NoteEditorPresentations.swift).61    @State var sheet: EditorSheet?62    @State var cover: EditorCover?63    @State var atomTarget: EditorAtomTarget?64    @State var showsFileImporter = false65    @State var showsPDFImporter = false66    @State var showsAudioImporter = false67    @State var notice: String?68    @State var recognizedOffer: String?69    @State var pendingRecognizedText: String?70    @State var isBusy = false71    @State var isLeaving = false72    @State var dropHandler = EditorDropHandler()73    @State private var keyboardAvoider = EditorKeyboardAvoider()7475    /// Width of the text column on large screens.76    static let readableWidth: CGFloat = 7607778    private var page: PageRecord? { model.page }79    private var isTrashed: Bool { page?.deletedAt != nil }80    private var isDatabase: Bool { page?.kind == .database }81    private var isEditable: Bool { model.isLoaded && !model.isMissing && !isTrashed && !isDatabase }8283    var body: some View {84        content85            .navigationBarTitleDisplayMode(.inline)86            .toolbar { toolbar }87            .task { await model.load() }88            .task(id: EditorReloadKey(page: app.feed.page(model.noteId), conflicts: app.feed.conflicts, attachments: app.feed.attachments, reset: app.feed.resetGeneration)) { await model.storeChanged() }89            .onAppear { if model.isLoaded, !model.isMissing { keyboardAvoider.install(on: model.controller.textView) } }90            .onDisappear { model.flush(); keyboardAvoider.uninstall() }91            .onChange(of: scenePhase) { _, phase in if phase != .active { model.flush() } }92            .onChange(of: model.request) { _, request in93                guard let request else { return }94                model.request = nil95                present(request)96            }97            .onChange(of: [model.isLoaded, isEditable], initial: true) { _, _ in98                guard model.isLoaded, !model.isMissing else { return }99                let editable = isEditable100                // After this render pass: the title field is created with the editor view.101                DispatchQueue.main.async {102                    model.setReadOnly(!editable)103                    keyboardAvoider.install(on: model.controller.textView)104                    if editable { dropHandler.install(on: model) } else { dropHandler.uninstall() }105                }106            }107            .editorPresentations(self)108            // 2.0 (shell): the Format menu of the hardware keyboard / menu bar reaches the note that has the focus109            .focusedSceneValue(\.editorCommands, EditorCommandTarget(isEditable: isEditable) { [model] action in model.perform(action) })110    }111112    // MARK: states113114    @ViewBuilder private var content: some View {115        if !model.isLoaded {116            ProgressView().accessibilityLabel("Chargement de la note")117        } else if model.isMissing {118            EmptyStateView(symbol: "doc.questionmark", title: "Cette note n’existe plus",119                           message: "Elle a été supprimée définitivement, ici ou sur un autre appareil.", actionTitle: "Fermer") { dismiss() }120                .accessibilityIdentifier("note-missing")121        } else if isDatabase {122            EmptyStateView(symbol: "tablecells", title: "Base de données",123                           message: "Les bases de données se consultent et se modifient dans la version web de SP Notes. Cette page n’est pas modifiable ici.",124                           actionTitle: "Ouvrir sur le web") {125                if let url = app.webURL(forPage: model.noteId) { UIApplication.shared.open(url) }126            }127            .accessibilityIdentifier("note-database")128        } else {129            VStack(spacing: 0) {130                if isTrashed && !isLeaving { trashBanner } else if model.hasConflict { ConflictBanner { sheet = .conflict } }131                if case .failed(let message) = model.saveState { saveFailureBanner(message) }132                // The editor is a UITextView: it extends under the keyboard and the home indicator and insets its own content,133                // so nothing moves when the keyboard appears. On wide screens the hosting view is a centred readable column.134                NoteEditorView(model: model, focusTitleOnAppear: isNew && isEditable)135                    .frame(maxWidth: Self.readableWidth)136                    .frame(maxWidth: .infinity)137                    .ignoresSafeArea(.all, edges: .bottom)138            }139        }140    }141142    private var trashBanner: some View {143        HStack(spacing: 10) {144            Image(systemName: "trash").foregroundStyle(Color.spTextSecondary).accessibilityHidden(true)145            VStack(alignment: .leading, spacing: 1) {146                Text("Note dans la corbeille").font(.subheadline.weight(.semibold)).foregroundStyle(Color.spText)147                Text("Lecture seule. Restaure-la pour la modifier.").font(.caption).foregroundStyle(Color.spTextSecondary)148            }149            Spacer(minLength: 0)150            Button("Restaurer") { run { try await app.restore(model.noteId) } }151                .buttonStyle(.borderedProminent)152                .accessibilityIdentifier("note-restore")153        }154        .padding(.horizontal, 16)155        .padding(.vertical, 10)156        .frame(maxWidth: .infinity, alignment: .leading)157        .background(Color.spSurface2)158        .accessibilityIdentifier("note-trash-banner")159    }160161    private func saveFailureBanner(_ message: String) -> some View {162        Label("L’enregistrement sur l’appareil a échoué : \(message)", systemImage: "exclamationmark.triangle")163            .font(.footnote)164            .foregroundStyle(Color.spText)165            .padding(.horizontal, 16)166            .padding(.vertical, 8)167            .frame(maxWidth: .infinity, alignment: .leading)168            .background(Color.spDanger.opacity(0.16))169    }170171    // MARK: navigation bar172173    private var badge: NoteSyncBadge {174        NoteSyncBadge.make(save: model.saveState, sync: page?.syncState, session: app.session, isOnline: app.network.isOnline)175    }176177    @ToolbarContentBuilder private var toolbar: some ToolbarContent {178        ToolbarItem(placement: .principal) {179            if model.isLoaded, !model.isMissing, !isDatabase {180                let badge = badge181                HStack(spacing: 5) {182                    Image(systemName: badge.symbol)183                    Text(badge.text)184                }185                .font(.caption)186                .foregroundStyle(badge.tone == .problem ? Color.spDanger : (badge.tone == .attention ? Color.spWarning : Color.spTextSecondary))187                .lineLimit(1)188                .accessibilityElement(children: .ignore)189                .accessibilityLabel(badge.detail)190                .accessibilityIdentifier("note-sync-state")191            }192        }193        ToolbarItemGroup(placement: .topBarTrailing) {194            if isEditable, sizeClass == .regular {195                Button { model.perform(.undo) } label: { Image(systemName: "arrow.uturn.backward") }196                    .disabled(!model.context.canUndo)197                    .accessibilityLabel("Annuler")198                    .accessibilityIdentifier("note-undo")199                Button { model.perform(.redo) } label: { Image(systemName: "arrow.uturn.forward") }200                    .disabled(!model.context.canRedo)201                    .accessibilityLabel("Rétablir")202                    .accessibilityIdentifier("note-redo")203            }204            if model.isLoaded, !model.isMissing, !isDatabase {205                Menu { menu } label: { Image(systemName: "ellipsis.circle") }206                    .accessibilityLabel("Actions de la note")207                    .accessibilityIdentifier("note-menu")208            }209        }210    }211212    @ViewBuilder private var menu: some View {213        if isTrashed {214            Button { run { try await app.restore(model.noteId) } } label: { Label("Restaurer", systemImage: "arrow.uturn.backward") }215            Button { sheet = .history } label: { Label("Historique", systemImage: "clock.arrow.circlepath") }216            exportMenu217            Button { sheet = .statistics } label: { Label("Statistiques", systemImage: "chart.bar") }218        } else {219            Section {220                Button { run { try await app.setFavorite(model.noteId, !(page?.favorite ?? false)) } } label: {221                    Label(page?.favorite == true ? "Retirer des favoris" : "Favori", systemImage: page?.favorite == true ? "star.slash" : "star")222                }223                .accessibilityIdentifier("menu-favorite")224                Button { run { try await app.setPinned(model.noteId, !(page?.pinned ?? false)) } } label: {225                    Label(page?.pinned == true ? "Désépingler" : "Épingler", systemImage: page?.pinned == true ? "pin.slash" : "pin")226                }227                .accessibilityIdentifier("menu-pin")228                Button { sheet = .tags } label: { Label("Tags…", systemImage: "tag") }229                Button { sheet = .move } label: { Label("Déplacer…", systemImage: "folder") }230            }231            Section {232                Button { sheet = .reminders } label: { Label("Rappel…", systemImage: "bell") }.accessibilityIdentifier("menu-reminders")233                Button { sheet = .attachments } label: { Label("Pièces jointes", systemImage: "paperclip") }.accessibilityIdentifier("menu-attachments")234                Button { sheet = .history } label: { Label("Historique", systemImage: "clock.arrow.circlepath") }.accessibilityIdentifier("menu-history")235                Button { sheet = .links } label: { Label("Liens", systemImage: "link") }.accessibilityIdentifier("menu-links")236                // 2.0: screens of SPNotesFeatures about this note, offered when the server has them237                if NoteFeatureSheet.offers(.ask, HostedSectionRegistry.shared.features) { Button { sheet = .ask } label: { Label("Demander à propos de cette note", systemImage: "sparkles") }.accessibilityIdentifier("menu-ask") }238                if NoteFeatureSheet.offers(.outline, HostedSectionRegistry.shared.features) { Button { sheet = .outline } label: { Label("Plan et synopsis", systemImage: "list.bullet.indent") }.accessibilityIdentifier("menu-outline") }239                if NoteFeatureSheet.offers(.timeline, HostedSectionRegistry.shared.features) { Button { sheet = .timeline } label: { Label("Chronologie et machine à remonter le temps", systemImage: "clock.badge") }.accessibilityIdentifier("menu-timeline") }240            }241            Section {242                exportMenu243                Button { share() } label: { Label("Partager", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("menu-share")244            }245            Section {246                Button { model.presentFind() } label: { Label("Rechercher dans la note", systemImage: "magnifyingglass") }.accessibilityIdentifier("menu-find")247                Button { sheet = .statistics } label: { Label("Statistiques", systemImage: "chart.bar") }.accessibilityIdentifier("menu-statistics")248            }249            Section {250                Button { duplicate() } label: { Label("Dupliquer", systemImage: "plus.square.on.square") }.accessibilityIdentifier("menu-duplicate")251                Button { archive() } label: {252                    Label(page?.archived == true ? "Désarchiver" : "Archiver", systemImage: page?.archived == true ? "tray.and.arrow.up" : "archivebox")253                }254                .accessibilityIdentifier("menu-archive")255                Button(role: .destructive) { trash() } label: { Label("Supprimer", systemImage: "trash") }.accessibilityIdentifier("menu-trash")256            }257        }258    }259260    private var exportMenu: some View {261        Menu {262            ForEach(NoteExportMenu.formats) { format in263                Button { export(format) } label: { Label(format.label, systemImage: format.symbolName) }264                    .accessibilityIdentifier(NoteExportMenu.identifier(format))265            }266        } label: { Label("Exporter…", systemImage: "arrow.up.doc") }267    }268269    // MARK: actions270271    /// Runs a local operation; a failure is shown instead of being swallowed.272    func run(_ operation: @escaping @MainActor () async throws -> Void) {273        Task { @MainActor in274            do { try await operation() } catch { notice = error.localizedDescription }275        }276    }277278    private func export(_ format: ExportFormat) {279        do {280            ShareSheet.present(urls: [try NoteExportMenu.export(model: model, format: format)], from: model.controller.textView.window?.rootViewController?.view)281        } catch { notice = error.localizedDescription }282    }283284    private func share() {285        let document = model.controller.document()286        let title = AppModel.displayTitle(model.title.trimmingCharacters(in: .whitespacesAndNewlines))287        let body = document.plainText().trimmingCharacters(in: .whitespacesAndNewlines)288        TextShare.present(body.isEmpty ? title : title + "\n\n" + body)289    }290291    private func duplicate() {292        run {293            await model.saveNow()294            let copy = try await app.duplicate(model.noteId)295            app.pendingRoute = .note(copy)296        }297    }298299    private func archive() {300        let archiving = page?.archived != true301        run {302            await model.saveNow()303            try await app.setArchived(model.noteId, archiving)304            if archiving { dismiss() }305        }306    }307308    private func trash() {309        isLeaving = true310        run {311            await model.saveNow()312            do { try await app.trash(model.noteId) } catch { isLeaving = false; throw error }313            dismiss()314        }315    }316}317318// MARK: - Statistics sheet319320struct NoteStatisticsSheet: View {321    let title: String322    let statistics: NoteStatistics323    let page: PageRecord?324    let badge: NoteSyncBadge325    @Environment(\.dismiss) private var dismiss326327    var body: some View {328        NavigationStack {329            Form {330                Section("Texte") {331                    LabeledContent("Mots", value: statistics.words.formatted())332                    LabeledContent("Caractères", value: statistics.characters.formatted())333                    LabeledContent("Caractères sans espaces", value: statistics.charactersWithoutSpaces.formatted())334                    LabeledContent("Paragraphes", value: statistics.paragraphs.formatted())335                    LabeledContent("Temps de lecture", value: statistics.readingMinutes == 0 ? "—" : String(localized: "environ \(statistics.readingMinutes) min"))336                }337                if let page {338                    Section("Dates") {339                        LabeledContent("Création", value: DocumentFacts.dateTime(page.createdAt))340                        LabeledContent("Dernière modification", value: DocumentFacts.dateTime(page.updatedAt))341                        if let opened = page.lastOpenedAt { LabeledContent("Dernière ouverture", value: DocumentFacts.dateTime(opened)) }342                    }343                }344                Section("Synchronisation") {345                    Label(badge.detail, systemImage: badge.symbol).font(.subheadline).foregroundStyle(Color.spTextSecondary)346                }347            }348            .scrollContentBackground(.hidden)349            .background(Color.spBackground)350            .navigationTitle(AppModel.displayTitle(title))351            .navigationBarTitleDisplayMode(.inline)352            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("OK") { dismiss() }.accessibilityIdentifier("statistics-close") } }353        }354        .presentationDetents([.medium, .large])355        .accessibilityIdentifier("statistics-sheet")356    }357}358
Files main
Menu

Theme