Repository Public
1// SP Notes iOS2// File: Features/Editor/NoteEditorPresentations.swift3// Description: Everything the note screen presents: what the editor asks for (link, table, equation, drawing, pickers, scanner,4// attachment preview, block menu, note link, assistant) and the sheets of the "…" menu. Results go back to the editor5// through the model's insertion helpers.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SwiftUI11import UIKit1213enum EditorSheet: Identifiable {14 case link(current: String?)15 case table(node: PMNode, range: NSRange)16 case math(latex: String, inline: Bool, range: NSRange?)17 case photoLibrary18 case noteLink19 case assistant(AssistantContext)20 case tags, move, reminders, attachments, history, conflict, statistics21 /// 2.0 (shell): « Liens » — backlinks, relations, mentions.22 case links23 /// 2.0 (SPNotesFeatures): ask about this note, its outline / synopsis (semantic zoom), its timeline and time machine.24 case ask, outline, timeline25 // 2.0: the detail screen of a block (through `BlockDetails`), the choices made before inserting one, a task's due date26 case block(node: PMNode, range: NSRange)27 case blockRefPicker, canvasPicker, citationPicker28 case taskDue(current: String?)2930 var id: String {31 switch self {32 case .block(let node, let range): "block-\(node.type)-\(range.location)"33 case .blockRefPicker: "blockRefPicker"34 case .canvasPicker: "canvasPicker"35 case .citationPicker: "citationPicker"36 case .taskDue: "taskDue"37 case .link: "link"38 case .table: "table"39 case .math: "math"40 case .photoLibrary: "photoLibrary"41 case .noteLink: "noteLink"42 case .assistant: "assistant"43 case .tags: "tags"44 case .move: "move"45 case .reminders: "reminders"46 case .attachments: "attachments"47 case .history: "history"48 case .conflict: "conflict"49 case .statistics: "statistics"50 case .links: "links"51 case .ask: "ask"52 case .outline: "outline"53 case .timeline: "timeline"54 }55 }56}5758enum EditorCover: Identifiable {59 case drawing(data: Data?, range: NSRange?)60 case camera61 case scanner62 case preview(attachmentId: String, name: String)63 /// 2.0: a block whose detail screen takes the whole screen (PDF, drawing).64 case block(node: PMNode, range: NSRange)6566 var id: String {67 switch self {68 case .block(let node, let range): "block-\(node.type)-\(range.location)"69 case .drawing: "drawing"70 case .camera: "camera"71 case .scanner: "scanner"72 case .preview(let id, _): "preview-\(id)"73 }74 }75}7677/// The block the user tapped (picture or another block without an editor of its own).78struct EditorAtomTarget: Identifiable {79 let node: PMNode80 let range: NSRange81 var id: String { "\(node.type)-\(range.location)" }8283 var isImage: Bool { node.type == "image" }84 var attachmentId: String? {85 node.stringAttr("attachmentId") ?? AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? "")86 }87 var name: String { node.stringAttr("alt") ?? node.stringAttr("title") ?? node.stringAttr("name") ?? "" }8889 var title: String {90 switch node.type {91 case "image": name.isEmpty ? String(localized: "Image") : name92 case "horizontalRule": String(localized: "Séparateur")93 case "youtube": String(localized: "Vidéo")94 default: String(localized: "Bloc")95 }96 }97}9899extension View {100 func editorPresentations(_ screen: NoteEditorContent) -> some View { modifier(EditorPresentations(screen: screen)) }101}102103/// Hosts the sheets, covers, dialogs and alerts of the note screen.104struct EditorPresentations: ViewModifier {105 let screen: NoteEditorContent106107 func body(content: Content) -> some View {108 content109 .sheet(item: screen.$sheet) { screen.sheetContent($0) }110 .fullScreenCover(item: screen.$cover, onDismiss: { screen.coverDismissed() }) { screen.coverContent($0) }111 // 2.0: a PDF or an audio file picked to become a `pdf` / `audio` block (each importer on its own view: SwiftUI keeps one per view)112 .background {113 Color.clear.attachmentFileImporter(isPresented: screen.$showsPDFImporter, allowedTypes: [.pdf]) { files, _ in114 Task { @MainActor in115 await screen.model.insertPDFs(files)116 files.forEach(MediaTemp.discard)117 }118 }119 }120 .background {121 Color.clear.attachmentFileImporter(isPresented: screen.$showsAudioImporter, allowedTypes: [.audio]) { files, _ in122 Task { @MainActor in123 await screen.model.insertAudioFiles(files)124 files.forEach(MediaTemp.discard)125 }126 }127 }128 .attachmentFileImporter(isPresented: screen.$showsFileImporter) { files, failed in129 Task { @MainActor in130 await screen.model.insertFiles(files)131 files.forEach(MediaTemp.discard)132 if failed > 0 { screen.notice = failed == 1 ? String(localized: "Un fichier n’a pas pu être lu.") : String(localized: "\(failed) fichiers n’ont pas pu être lus.") }133 }134 }135 .confirmationDialog(screen.atomTarget?.title ?? "", isPresented: Binding(get: { screen.atomTarget != nil }, set: { if !$0 { screen.atomTarget = nil } }),136 titleVisibility: .visible, presenting: screen.atomTarget) { target in137 screen.atomMenu(target)138 }139 .alert("SP Notes", isPresented: Binding(get: { screen.notice != nil }, set: { if !$0 { screen.notice = nil } })) {140 Button("OK", role: .cancel) {}141 } message: { Text(screen.notice ?? "") }142 .alert("Texte reconnu", isPresented: Binding(get: { screen.recognizedOffer != nil }, set: { if !$0 { screen.recognizedOffer = nil } }), presenting: screen.recognizedOffer) { text in143 Button("Insérer le texte reconnu") { screen.model.insertRecognizedText(text) }144 Button("Copier") { UIPasteboard.general.string = text }145 Button("Ignorer", role: .cancel) {}146 } message: { text in147 Text(String(text.prefix(240)) + (text.count > 240 ? "…" : ""))148 }149 .overlay {150 if screen.isBusy {151 ProgressView()152 .padding(22)153 .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14, style: .continuous))154 .accessibilityLabel("Opération en cours")155 }156 }157 }158}159160extension NoteEditorContent {161 var controller: EditorController { model.controller }162163 // MARK: requests of the editor164165 func present(_ request: NoteEditorModel.Request) {166 switch request {167 case .link(let current): sheet = .link(current: current)168 case .table(let node, let range): sheet = .table(node: node, range: range)169 case .math(let latex, let inline, let range): sheet = .math(latex: latex, inline: inline, range: range)170 case .drawing(let attachmentId, let range):171 guard let attachmentId else { cover = .drawing(data: nil, range: range); return }172 // An existing drawing designated by its source file.173 busy {174 if case .ready(let url) = await AttachmentPreviewLoader.resolve(attachmentId, app: app), let data = try? Data(contentsOf: url) {175 cover = .drawing(data: data, range: range)176 } else {177 notice = String(localized: "La source de ce dessin n’est pas disponible sur cet appareil pour l’instant.")178 }179 }180 case .preview(let attachmentId, let name): cover = .preview(attachmentId: attachmentId, name: name)181 case .atomMenu(let node, let range): atomTarget = EditorAtomTarget(node: node, range: range)182 // 2.0 seam: presented through `BlockDetails` (sheet or full screen by the provider's style); the atom menu when no provider takes the block183 case .blockDetail(let node, let range):184 guard let provider = BlockDetails.provider(for: node) else { atomTarget = EditorAtomTarget(node: node, range: range); return }185 switch provider.style(for: node) {186 case .sheet: sheet = .block(node: node, range: range)187 case .fullScreen: cover = .block(node: node, range: range)188 }189 case .blockRefPicker: sheet = .blockRefPicker190 case .canvasPicker: sheet = .canvasPicker191 case .citationPicker: sheet = .citationPicker192 case .pdfPicker: showsPDFImporter = true193 case .audioPicker: showsAudioImporter = true194 case .taskDue(let current): sheet = .taskDue(current: current)195 case .photoLibrary: sheet = .photoLibrary196 case .camera:197 if CameraPicker.isAvailable { cover = .camera } else { notice = String(localized: "L’appareil photo n’est pas disponible sur cet appareil.") }198 case .scanner:199 if DocumentScanner.isSupported { cover = .scanner } else { notice = String(localized: "La numérisation de documents n’est pas disponible sur cet appareil.") }200 case .filePicker: showsFileImporter = true201 case .noteLink: sheet = .noteLink202 case .assistant: openAssistant()203 }204 }205206 /// Runs a longer operation with a visible progress state.207 func busy(_ operation: @escaping @MainActor () async -> Void) {208 Task { @MainActor in209 isBusy = true210 await operation()211 isBusy = false212 }213 }214215 func openAssistant() {216 let selection = controller.textView.selectedRange217 sheet = .assistant(AssistantContext(noteId: model.noteId, noteTitle: model.title, sourceText: controller.selectedPlainText(),218 hasSelection: selection.length > 0, pageIsOnServer: (model.page?.serverVersion ?? 0) > 0))219 }220221 /// Puts an assistant result in the note — the only moment the assistant writes anything.222 func insertAssistantResult(_ markdown: String, replacingSelection: Bool) {223 let textView = controller.textView224 let selection = textView.selectedRange225 if !replacingSelection, selection.length > 0 {226 // "Below" means below the last selected paragraph: the caret goes to the end of the selection first.227 textView.selectedRange = NSRange(location: max(selection.location, NSMaxRange(selection) - 1), length: 0)228 }229 model.insertMarkdown(markdown, replacingSelection: replacingSelection)230 }231232 // MARK: sheets233234 /// The detail screen of a block, from the provider registered for it.235 @ViewBuilder func blockDetail(node: PMNode, range: NSRange, dismiss: @escaping () -> Void) -> some View {236 if let provider = BlockDetails.provider(for: node) {237 provider.view(for: node, context: model.blockDetailContext(range: range, isEditable: controller.textView.isEditable, dismiss: dismiss))238 .environment(app)239 }240 }241242 @ViewBuilder func sheetContent(_ sheet: EditorSheet) -> some View {243 switch sheet {244 case .block(let node, let range):245 blockDetail(node: node, range: range) { self.sheet = nil }246 case .blockRefPicker:247 BlockRefPicker(excluding: model.noteId, onPick: { pageId, blockId in248 self.sheet = nil249 model.insertBlockRef(pageId: pageId, blockId: blockId)250 }, onCancel: { self.sheet = nil })251 case .canvasPicker:252 CanvasLinkPicker(onPick: { pageId in253 self.sheet = nil254 model.insertCanvasLink(pageId: pageId)255 }, onCancel: { self.sheet = nil })256 case .citationPicker:257 CitationSheet(citation: nil, isNew: true, app: app, onDone: { citation in258 self.sheet = nil259 if let refId = citation.refId { model.insertCitation(refId: refId, label: citation.label, locator: citation.locator) }260 model.focusBody()261 }, onCancel: { self.sheet = nil })262 case .taskDue(let current):263 TaskDueSheet(current: current, onSet: { due in264 self.sheet = nil265 controller.setTaskDue(due)266 }, onCancel: { self.sheet = nil })267 case .link(let current):268 LinkSheet(href: current ?? "", onApply: { address in269 self.sheet = nil270 if let href = EditorController.normalizedLink(address) { controller.setLink(href) } else { notice = String(localized: "Cette adresse ne peut pas servir de lien.") }271 model.focusBody()272 }, onRemove: current == nil ? nil : {273 self.sheet = nil274 controller.setLink(nil)275 model.focusBody()276 }, onCancel: { self.sheet = nil })277 .presentationDetents([.medium, .large])278 case .table(let node, let range):279 TableEditorSheet(table: node, onDone: { edited in280 self.sheet = nil281 if edited != node { controller.updateAtom(at: range, node: edited) }282 }, onCancel: { self.sheet = nil })283 case .math(let latex, let inline, let range):284 MathEditorSheet(latex: latex, isBlock: !inline, isEditing: range != nil, onDone: { source in285 self.sheet = nil286 if source.isEmpty {287 if let range { controller.deleteAtom(at: range) }288 } else {289 model.insertMath(source, inline: inline, replacing: range)290 }291 }, onCancel: { self.sheet = nil })292 case .photoLibrary:293 PhotoLibraryPicker { urls in294 self.sheet = nil295 guard !urls.isEmpty else { return }296 busy {297 await model.insertFiles(urls)298 urls.forEach(MediaTemp.discard)299 }300 }301 .ignoresSafeArea()302 case .noteLink:303 NoteLinkPicker(excluding: model.noteId, onPick: { id, title in304 self.sheet = nil305 model.insertMention(noteId: id, title: title)306 model.focusBody()307 }, onCancel: { self.sheet = nil })308 case .assistant(let context):309 AssistantSheet(context: context, provider: BackendAssistantProvider(api: app.api), availability: { [app] in310 if app.session != .signedIn { return AssistantFailure(.sessionExpired) }311 if !app.network.isOnline { return AssistantFailure(.offline) }312 return nil313 }, onInsert: { markdown, replacing in314 insertAssistantResult(markdown, replacingSelection: replacing)315 }, onOpenNote: { id, blockId in316 app.pendingRoute = .note(id, blockId: blockId)317 })318 case .tags:319 TagEditorSheet(noteId: model.noteId)320 case .move:321 MoveNoteSheet(noteIds: [model.noteId])322 case .reminders:323 NoteRemindersView(noteId: model.noteId, noteTitle: model.title)324 case .attachments:325 NoteAttachmentsView(noteId: model.noteId) { id in model.removeAtoms(forAttachment: id) }326 case .history:327 NoteHistoryView(noteId: model.noteId) { await model.saveNow() }328 case .conflict:329 ConflictSheet(noteId: model.noteId) { await model.saveNow() }330 case .ask: NoteFeatureSheet(kind: .ask, noteId: model.noteId, title: model.title, document: controller.document())331 case .outline: NoteFeatureSheet(kind: .outline, noteId: model.noteId, title: model.title, document: controller.document())332 case .timeline: NoteFeatureSheet(kind: .timeline, noteId: model.noteId, title: model.title, document: controller.document())333 case .links:334 BacklinksSheet(noteId: model.noteId, noteTitle: model.title) { id, blockId in app.pendingRoute = .note(id, blockId: blockId) }335 case .statistics:336 NoteStatisticsSheet(title: model.title, statistics: NoteStatistics(document: controller.document()), page: model.page,337 badge: NoteSyncBadge.make(save: model.saveState, sync: model.page?.syncState, session: app.session, isOnline: app.network.isOnline))338 }339 }340341 // MARK: full-screen covers342343 @ViewBuilder func coverContent(_ cover: EditorCover) -> some View {344 switch cover {345 case .block(let node, let range):346 blockDetail(node: node, range: range) { self.cover = nil }347 case .drawing(let data, let range):348 drawingCover(data: data, range: range) // Features/Drawing/DrawingEntryPoints.swift349 case .camera:350 CameraPicker { url in351 self.cover = nil352 guard let url else { return }353 busy {354 await model.insertFiles([url])355 MediaTemp.discard(url)356 }357 }358 .ignoresSafeArea()359 case .scanner:360 DocumentScanner(onFinish: { urls in361 self.cover = nil362 guard !urls.isEmpty else { return }363 busy {364 await model.insertFiles(urls)365 // The pages are read while their temporary files still exist; the text is only offered, never inserted by itself.366 let text = await TextRecognizer.recognizeText(atPages: urls).trimmingCharacters(in: .whitespacesAndNewlines)367 urls.forEach(MediaTemp.discard)368 if !text.isEmpty { offerRecognizedText(text) }369 }370 }, onError: { error in371 self.cover = nil372 notice = String(localized: "La numérisation a échoué : \(error.localizedDescription)")373 })374 .ignoresSafeArea()375 case .preview(let attachmentId, let name):376 AttachmentPreviewLoader(attachmentId: attachmentId, name: name)377 }378 }379380 /// An alert cannot appear while a cover is still closing: the offer waits for the end of the dismissal.381 func coverDismissed() {382 if let text = pendingRecognizedText {383 pendingRecognizedText = nil384 recognizedOffer = text385 }386 }387388 func offerRecognizedText(_ text: String) {389 if cover == nil { recognizedOffer = text } else { pendingRecognizedText = text }390 }391392 // MARK: menu of a tapped block393394 @ViewBuilder func atomMenu(_ target: EditorAtomTarget) -> some View {395 if target.isImage, let id = target.attachmentId {396 Button("Aperçu") { cover = .preview(attachmentId: id, name: target.name) }397 }398 if NoteEditorModel.isDrawing(target.node) {399 Button("Modifier le dessin") { editDrawing(target) }400 }401 if target.isImage, target.attachmentId != nil {402 Button("Reconnaître le texte") { recognizeText(target) }403 }404 Button("Copier") { copy(target) }405 Button("Supprimer", role: .destructive) { controller.deleteAtom(at: target.range) }406 Button("Annuler", role: .cancel) {}407 }408409 private func editDrawing(_ target: EditorAtomTarget) {410 busy {411 if let data = await model.drawingSource(forImage: target.node) {412 cover = .drawing(data: data, range: target.range)413 } else {414 notice = String(localized: "La source modifiable de ce dessin n’est pas sur cet appareil. Elle sera disponible une fois téléchargée.")415 }416 }417 }418419 private func recognizeText(_ target: EditorAtomTarget) {420 guard let id = target.attachmentId else { return }421 busy {422 switch await AttachmentPreviewLoader.resolve(id, app: app) {423 case .ready(let url):424 let text = await TextRecognizer.recognizeText(at: url).trimmingCharacters(in: .whitespacesAndNewlines)425 if text.isEmpty { notice = String(localized: "Aucun texte n’a été reconnu dans cette image."); return }426 // Below the picture: the caret goes to the picture's paragraph, the text is inserted after it.427 controller.textView.selectedRange = controller.clampSelection(NSRange(location: target.range.location, length: 0))428 model.insertRecognizedText(text)429 case .offline: notice = String(localized: "Cette image n’est pas sur l’appareil et tu es hors ligne.")430 case .failed(let message): notice = message431 case .loading: break432 }433 }434 }435436 private func copy(_ target: EditorAtomTarget) {437 if target.isImage, let image = app.image(forSource: target.node.stringAttr("src") ?? "") {438 UIPasteboard.general.image = image439 } else {440 UIPasteboard.general.string = NoteExporter.fallbackText(for: target.node, isBlock: true)441 }442 Haptics.success()443 }444}445446extension EditorCover: Equatable {447 static func == (lhs: EditorCover, rhs: EditorCover) -> Bool { lhs.id == rhs.id }448}449