Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/NoteDetailView.swift3// Description: Right column: serif title, the glass format bar that morphs with the block under the caret, the native editor, banners (conflict, trash, read-only), status bar, the inspector / assistant panel, and the sheets of blocks, links, pickers and task details.4import SwiftUI5import SPNotesDocument6import SPNotesEditor7import SPNotesStore8import SPNotesAPI9import SPNotesDesign10import UniformTypeIdentifiers1112struct NoteDetailView: View {13 @Environment(AppEnvironment.self) private var env14 @Environment(WindowModel.self) private var window1516 var body: some View {17 Group {18 if let session = window.session, let native = NativePage.view(for: session, env: env, window: window) { native.id(session.id) }19 else if let session = window.session { NoteEditorPane(session: session).id(session.id) }20 else if window.selectedNotes.count > 1 { EmptyState(symbol: "square.stack", title: "\(window.selectedNotes.count) notes sélectionnées", message: "Clic droit dans la liste pour les déplacer, les exporter ou les supprimer ensemble.") }21 else { EmptyState(symbol: "note.text", title: "Aucune note sélectionnée", message: "Choisis une note dans la liste, ou crée-en une.", action: ("Nouvelle note", { window.newNote() })) }22 }23 .frame(minWidth: 360)24 .background(NVColor.bg)25 }26}2728struct NoteEditorPane: View {29 @Environment(AppEnvironment.self) private var env30 @Environment(WindowModel.self) private var window31 @Environment(\.accessibilityReduceMotion) private var reduceMotion32 @Bindable var session: NoteSession33 @FocusState private var titleFocused: Bool34 @State private var linkEditor: LinkDraft?35 @State private var mentionCache: [String: [PageSummary]] = [:]36 @State private var titleShown = false37 struct LinkDraft: Identifiable { let id = UUID(); var href: String; var text: String; var hasSelection: Bool; var existing: Bool }3839 var body: some View {40 sheets41 .onChange(of: session.editor.activeAtom) { _, atom in42 // a mention is a stable link to another note: activating it opens that note43 if let atom, atom.node.type == "mention", case .string(let id)? = atom.node.attrs?["id"] { session.editor.activeAtom = nil; window.open(id) }44 }45 .onChange(of: window.focusTitle) { _, _ in titleFocused = true }46 .onChange(of: session.editor.requestLink) { _, _ in beginLink() }47 .onChange(of: session.editor.requestFile?.id) { _, _ in if let r = session.editor.requestFile { insertFile(imagesOnly: r.imagesOnly) } }48 .onChange(of: env.preferences.fontSize) { _, _ in session.applyTypingPreferences() }49 .onChange(of: env.preferences.fontDesign) { _, _ in session.applyTypingPreferences() }50 .onChange(of: env.preferences.columnWidth) { _, _ in session.applyTypingPreferences() }51 .onChange(of: env.preferences.spellCheck) { _, _ in session.applyTypingPreferences() }52 .task(id: session.id) { await opened() }53 .onDisappear { Task { await session.saveNow(reason: nil) } }54 }5556 private func opened() async {57 wireEditor()58 // Living Pages: the blocks of the note rise and fade in; Fluid Navigation: the title settles from the list side59 titleShown = false60 try? await Task.sleep(for: .milliseconds(30))61 // a note opens at its top unless a route asked for a block or the reader had scrolled into it62 let clip = session.editor.scrollView.contentView63 if window.pendingBlock == nil, clip.bounds.origin.y > 0, clip.bounds.origin.y < 160 { clip.scroll(to: .zero); session.editor.scrollView.reflectScrolledClipView(clip) }64 session.editor.textView.playReveal(reduceMotion: reduceMotion)65 withNVAnimation(.base, reduceMotion: reduceMotion) { titleShown = true }66 }6768 private var atomBinding: Binding<EditorController.ActiveAtom?> { Binding(get: { session.editor.activeAtom.flatMap { $0.node.type == "mention" ? nil : $0 } }, set: { session.editor.activeAtom = $0 }) }69 private var pickerBinding: Binding<EditorController.EditorSheet?> { Binding(get: { session.editor.sheet.flatMap { s -> EditorController.EditorSheet? in if case .task = s { return nil }; return s } }, set: { session.editor.sheet = $0 }) }70 private var taskBinding: Binding<EditorController.EditorSheet?> { Binding(get: { session.editor.sheet.flatMap { s -> EditorController.EditorSheet? in if case .task = s { return s }; return nil } }, set: { session.editor.sheet = $0 }) }7172 @ViewBuilder private var sheets: some View {73 @Bindable var window = window74 pane75 .sheet(item: atomBinding) { atom in AtomEditorSheet(session: session, atom: atom).environment(env).environment(window) }76 .sheet(item: $linkEditor) { draft in LinkEditorSheet(draft: draft) { href, text in session.editor.textView.setLink(href.isEmpty ? nil : href, text: text); session.editor.focus() } }77 .sheet(isPresented: $window.showHistory) { HistorySheet(session: session).environment(env) }78 .sheet(item: Binding(get: { window.pageTimeline.map(IdentifiedString.init) }, set: { window.pageTimeline = $0?.value })) { page in PageTimelineSheet(pageId: page.value).environment(env).environment(window) }79 .sheet(item: pickerBinding) { sheet in PickerSheet(session: session, sheet: sheet).environment(env).environment(window) }80 .popover(item: taskBinding, attachmentAnchor: .rect(.rect(taskAnchor)), arrowEdge: .bottom) { sheet in81 if case .task(let location, _) = sheet { TaskDetailsPopover(session: session, location: location) { session.editor.sheet = nil; session.editor.focus() } }82 }83 }8485 private var pane: some View {86 VStack(spacing: 0) {87 banners88 ZStack(alignment: .top) {89 NoteZoom(session: session) {90 VStack(spacing: 0) {91 titleField92 NoteEditorView(controller: session.editor).accessibilityIdentifier("editor")93 }94 }95 .padding(.top, session.isEditable ? NVSpace.xxxl : 0)96 if session.isEditable { FormatBar(session: session, insertLink: beginLink).padding(.top, NVSpace.sm).padding(.horizontal, NVSpace.md) }97 }98 Divider().overlay(NVColor.line)99 StatusBar(session: session)100 }101 .background(NVColor.bg)102 .inspector(isPresented: Binding(get: { window.sidePanel != nil }, set: { if !$0 { window.sidePanel = nil } })) {103 SidePanel(session: session).inspectorColumnWidth(min: 240, ideal: 270, max: 420)104 }105 .navigationTitle(session.title.isEmpty ? "Sans titre" : session.title)106 .toolbar { toolbar }107 }108109 /// Where the task popover points: the chips of the item, in the pane's coordinates (the editor sits under the title).110 private var taskAnchor: CGRect {111 guard case .task(_, let anchor)? = session.editor.sheet else { return .zero }112 let v = session.editor.textView113 let inWindow = v.convert(anchor, to: nil)114 guard let host = v.window?.contentView else { return .zero }115 let r = host.convert(inWindow, from: nil)116 // SwiftUI's origin is the top-left of the hosting view117 return CGRect(x: r.minX, y: host.isFlipped ? r.minY : host.bounds.height - r.maxY, width: r.width, height: r.height)118 }119120 private var titleField: some View {121 TextField("Titre", text: $session.title, axis: .vertical)122 .textFieldStyle(.plain).font(NVFont.font(.h1, size: (env.preferences.fontSize * 30 / 16).rounded())).foregroundStyle(NVColor.fg).lineLimit(1...3)123 .focused($titleFocused).disabled(!session.isEditable)124 .onSubmit { session.editor.focus() }125 .frame(maxWidth: env.preferences.columnWidth - NVSpace.sm, alignment: .leading)126 .padding(.horizontal, NVSpace.xxl).padding(.top, NVSpace.xl).padding(.bottom, NVSpace.xxs)127 .frame(maxWidth: .infinity)128 .opacity(titleShown ? 1 : 0).offset(x: titleShown || reduceMotion ? 0 : -NVSpace.md)129 .accessibilityIdentifier("title-field")130 }131132 @ViewBuilder private var banners: some View {133 if session.wasDeleted {134 Banner(symbol: "trash.slash", text: "Cette note a été supprimée définitivement. Son texte est encore affiché ici.", tint: NVColor.danger) {135 Button("Enregistrer comme nouvelle note") { Task { if let id = await env.library.newNote(title: session.title, content: session.editor.document()) { env.forget(noteId: session.id); window.open(id) } } }136 }137 }138 if session.isInTrash {139 Banner(symbol: "trash", text: "Cette note est dans la corbeille.", tint: NVColor.fgMuted) { Button("Restaurer") { Task { await env.library.restore([session.id]) } } }140 }141 if session.isUnreadable { Banner(symbol: "exclamationmark.triangle", text: "Le contenu de cette note n'a pas pu être lu sur ce Mac. Il n'est pas modifié ; ouvre-la sur le site web.", tint: NVColor.warning) { EmptyView() } }142 if session.page.type == "canvas" { Banner(symbol: "square.on.square.dashed", text: "Cette page est un canvas : il s'ouvre et se modifie sur note.spboucher.ai ou sur iPad.", tint: NVColor.fgMuted) { EmptyView() } }143 else if session.page.type == "database" || session.page.databaseId != nil { Banner(symbol: "tablecells", text: "Cette page appartient à une base de données : elle se modifie sur note.spboucher.ai.", tint: NVColor.fgMuted) { EmptyView() } }144 if session.conflict != nil { ConflictBanner(session: session) }145 if session.remoteCopyKeptNotice {146 Banner(symbol: "clock.arrow.circlepath", text: "Une modification venue d'un autre appareil n'a pas pu être fusionnée avec ta saisie. Elle est conservée dans l'historique.", tint: NVColor.warning) {147 Button("Voir l'historique") { window.showHistory = true; session.remoteCopyKeptNotice = false }; Button("OK") { session.remoteCopyKeptNotice = false }148 }149 }150 if case .failed(let m) = session.saveState { Banner(symbol: "externaldrive.badge.exclamationmark", text: m, tint: NVColor.danger) { Button("Réessayer") { Task { await session.saveNow(reason: "Nouvel essai") } } } }151 }152153 @ToolbarContentBuilder private var toolbar: some ToolbarContent {154 ToolbarItemGroup {155 Button { Task { await env.library.setFavorite(session.id, !session.page.favorite) } } label: { Label("Favori", systemImage: session.page.favorite ? "star.fill" : "star") }.help(session.page.favorite ? "Retirer des favoris" : "Ajouter aux favoris")156 Menu {157 ForEach(ExportFormat.allCases) { f in Button(f.label) { Task { await session.saveNow(reason: nil); await Exporter(env: env).export(noteIds: [session.id], format: f) } } }158 Divider()159 Button("Imprimer…") { Task { await Exporter(env: env).print(noteId: session.id) } }160 ShareLink("Partager le texte…", item: session.editor.document().markdown())161 Button("Copier le lien de la note") { NSPasteboard.general.clearContents(); NSPasteboard.general.setString(Route(pageId: session.id).url.absoluteString, forType: .string) }162 } label: { Label("Exporter", systemImage: "square.and.arrow.up") }.help("Exporter, imprimer, partager")163 NoteZoomControl(session: session)164 Button { window.showHistory = true } label: { Label("Historique", systemImage: "clock.arrow.circlepath") }.help("Historique des versions")165 if env.preferences.aiEnabled { Button { toggle(.assistant) } label: { Label("Assistant", systemImage: "sparkles") }.help("Assistant (⇧⌘A)").accessibilityIdentifier("assistant-toggle") }166 Button { toggle(.inspector) } label: { Label("Inspecteur", systemImage: "sidebar.right") }.help("Inspecteur (⌥⌘I)").accessibilityIdentifier("inspector-toggle")167 }168 }169 private func toggle(_ panel: WindowModel.SidePanel) { withNVAnimation(.base, reduceMotion: reduceMotion) { window.sidePanel = window.sidePanel == panel ? nil : panel } }170171 // MARK: Editor wiring172173 private func wireEditor() {174 let editor = session.editor175 editor.onOpenLink = { href in176 if href.hasPrefix("/p/") { let parts = href.dropFirst(3).split(separator: "#", maxSplits: 1); if let id = parts.first { window.open(Route(pageId: String(id), blockId: parts.count > 1 ? String(parts[1]) : nil)); return } }177 guard let url = URL(string: href) else { env.toasts.show("Ce lien n'est pas une adresse web : il n'a pas été ouvert.", isError: true); return }178 window.openURL(url)179 }180 editor.onOpenRoute = { route in window.open(route) }181 editor.onReceiveFiles = { urls, images in Task { await receive(urls: urls, images: images) } }182 editor.completions = { trigger, query in trigger == "/" ? slashItems() : mentionItems(query) }183 if editor.lookup == nil { let l = EditorLookup(env: env); l.onResolved = { [weak editor] in editor?.textView.refreshAtoms() }; editor.lookup = l } else { editor.lookup?.invalidate() }184 }185186 /// Entries the application adds to the editor's own « / » menu: everything that needs a file, a picker or a service.187 private func slashItems() -> [CompletionItem] {188 var items = EditorInsertions.all(window: window, env: env).filter { !$0.builtin }.map { i in CompletionItem(id: i.id, title: i.title.replacingOccurrences(of: "…", with: ""), subtitle: i.subtitle, symbol: i.symbol, group: i.group) { v in i.run(v) } }189 items.append(CompletionItem(id: "subpage", title: "Nouvelle sous-note", subtitle: nil, symbol: "doc.badge.plus", group: "Liens") { v in Task { if let id = await env.library.newNote(title: "Sans titre", parentId: session.id) { v.insertMention(id: id, label: "Sans titre") } } })190 items.append(CompletionItem(id: "duedate", title: "Échéance et priorité", subtitle: "De la tâche sous le curseur", symbol: "calendar.badge.clock", group: "Tâches") { v in v.requestTaskDetails() })191 if env.preferences.aiEnabled { items.append(CompletionItem(id: "ai", title: "Demander à l'assistant", subtitle: "Résumer, reformuler, continuer…", symbol: "sparkles", group: "IA") { _ in window.showAssistant = true }) }192 return items193 }194195 private func mentionItems(_ query: String) -> [CompletionItem] {196 let key = query.lowercased()197 if mentionCache[key] == nil {198 mentionCache[key] = []199 Task { let found = await env.library.quickFind(query, limit: 8).filter { $0.id != session.id }; mentionCache[key] = found; session.editor.textView.refreshCompletion() }200 }201 var items = (mentionCache[key] ?? []).map { p in202 let label = Format.title(p.title)203 return CompletionItem(id: p.id, title: label, subtitle: p.preview.isEmpty ? nil : String(p.preview.prefix(60)), symbol: p.isFolder ? "folder" : "doc.text", group: "Notes") { v in v.insertMention(id: p.id, label: label) }204 }205 let name = query.trimmingCharacters(in: .whitespaces)206 if !name.isEmpty { items.append(CompletionItem(id: "__new", title: "Créer la note « \(name) »", symbol: "plus", group: "Nouvelle") { v in Task { if let id = await env.library.newNote(title: name, parentId: session.page.parentId) { v.insertMention(id: id, label: name) } } }) }207 return items208 }209210 private func beginLink() {211 let v = session.editor.textView; let sel = v.selectedRange()212 let existing = v.link(at: sel.location) ?? (sel.location > 0 ? v.link(at: sel.location - 1) : nil)213 var href = existing?.href ?? ""214 if href.isEmpty, let clip = NSPasteboard.general.string(forType: .string), clip.hasPrefix("http"), clip.count < 2000, !clip.contains("\n") { href = clip }215 linkEditor = LinkDraft(href: href, text: "", hasSelection: sel.length > 0 || existing != nil, existing: existing != nil)216 }217218 private func insertFile(imagesOnly: Bool = false) {219 let panel = NSOpenPanel(); panel.allowsMultipleSelection = true; panel.canChooseDirectories = false220 if imagesOnly { panel.allowedContentTypes = [.image] }221 panel.begin { r in if r == .OK { let urls = panel.urls; Task { await receive(urls: urls, images: []) } } }222 }223224 private func receive(urls: [URL], images: [NSImage]) async {225 guard session.isEditable else { return }226 let service = AttachmentService(env: env); let v = session.editor.textView227 for url in urls {228 // a dropped Markdown or text file can be read into the note instead of being attached — the owner chose "attach" by dropping229 do { let a = try await service.importFile(url, pageId: session.id); if a.isImage { v.insertImage(src: a.src, alt: a.name) } else { v.insertFile(src: a.src, name: a.name, size: a.size, mime: a.mime, attachmentId: a.id) } }230 catch { env.toasts.error(error) }231 }232 for image in images { do { let a = try await service.importImage(image, pageId: session.id); v.insertImage(src: a.src, alt: a.name) } catch { env.toasts.error(error) } }233 }234}235236/// The panel beside the editor (SwiftUI inspector: resizable, restored with the window): information and links, or the assistant.237struct SidePanel: View {238 @Environment(WindowModel.self) private var window239 @Environment(\.accessibilityReduceMotion) private var reduceMotion240 let session: NoteSession241 var body: some View {242 ZStack {243 if window.sidePanel == .assistant { AssistantPanel(session: session).nvPanelTransition(edge: .trailing) }244 else { InspectorPanel(session: session).nvPanelTransition(edge: .trailing) }245 }246 .animation(NVMotion.animation(.base, reduceMotion: reduceMotion), value: window.sidePanel)247 .background(NVColor.bgSidebar)248 }249}250251/// Pickers opened from the insertion commands (block reference, citation, canvas).252struct PickerSheet: View {253 @Environment(AppEnvironment.self) private var env254 @Environment(WindowModel.self) private var window255 @Environment(\.dismiss) private var dismiss256 let session: NoteSession257 let sheet: EditorController.EditorSheet258 var body: some View {259 let v = session.editor.textView260 let finish: () -> Void = { dismiss(); session.editor.focus() }261 switch sheet {262 case .blockRef: BlockRefSheet(block: nil, context: context { node in v.insertBlockAtom(node, actionName: "Référence à un bloc"); finish() })263 case .citation: FeaturesBlockDetails.citationPicker(existing: nil, context: context { node in v.insertInlineAtom(node, actionName: "Citation"); finish() })264 case .canvasLink: CanvasLinkSheet(block: nil, context: context { node in v.insertBlockAtom(node, actionName: "Lien vers un canvas"); finish() })265 case .audioRecording: AudioDetail(block: nil, node: nil, context: context { node in v.insertBlockAtom(node, actionName: "Note vocale"); finish() })266 case .task: EmptyView()267 }268 }269 private func context(_ apply: @escaping (PMNode) -> Void) -> BlockDetailContext {270 BlockDetailContext(env: env, session: session, editable: session.isEditable, router: window, apply: apply, remove: {}, dismiss: { dismiss(); session.editor.focus() })271 }272}273274struct Banner<Actions: View>: View {275 let symbol: String, text: String, tint: Color276 @ViewBuilder var actions: Actions277 var body: some View {278 HStack(spacing: NVSpace.md) {279 Image(systemName: symbol).foregroundStyle(tint)280 Text(text).nvFont(.ui).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)281 Spacer(minLength: NVSpace.sm)282 actions.controlSize(.small)283 }284 .padding(.horizontal, NVSpace.lg).padding(.vertical, NVSpace.sm).background(tint.opacity(0.1))285 .overlay(alignment: .bottom) { Divider().overlay(NVColor.line) }286 }287}288289/// Formatting controls on a glass bar that floats over the top of the note. Its content morphs with the block under the290/// caret (Morphing Editor): text marks in a paragraph, list controls in a list, due date in a task, kind in a callout,291/// « Modifier » on a block card. The controls act on the text view directly and never take the keyboard focus.292struct FormatBar: View {293 @Environment(AppEnvironment.self) private var env294 @Environment(WindowModel.self) private var window295 let session: NoteSession296 let insertLink: () -> Void297 private var v: NoteTextView { session.editor.textView }298 private var state: SelectionState { session.editor.selection }299300 var body: some View {301 NVToolbarGlass(spacing: NVSpace.xxs, radius: NVRadius.lg) {302 Menu {303 Button("Texte") { v.setBlock(.paragraph) }304 Button("Titre 1") { v.setBlock(.heading(1), toggle: false) }305 Button("Titre 2") { v.setBlock(.heading(2), toggle: false) }306 Button("Titre 3") { v.setBlock(.heading(3), toggle: false) }307 Divider()308 Button("Citation") { v.setBlock(.quote) }309 Menu("Encadré") { ForEach(CalloutKind.known, id: \.rawValue) { k in Button(k.defaultIcon + " " + k.label) { v.setCallout(k) } } }310 Button("Bloc de code") { v.setBlock(.code) }311 Button("Section repliable") { v.insertDetails() }312 } label: { Text(blockLabel).nvFont(.ui).frame(width: 84, alignment: .leading) }.menuStyle(.borderlessButton).fixedSize().help("Type de bloc").accessibilityIdentifier("block-type")313 sep314 NVMorphingToolbar(id: Self.morphKey(state.context)) { contextual }315 sep316 Menu {317 let items = EditorInsertions.all(window: window, env: env)318 ForEach(Self.groups(items), id: \.0) { group, entries in Section(group) { ForEach(entries) { i in Button { i.run(v) } label: { Label(i.title, systemImage: i.symbol) } } } }319 } label: { Image(systemName: "plus").frame(width: NVSpace.xl, height: NVSpace.xl) }.menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Insérer un bloc").accessibilityIdentifier("insert-menu")320 }321 .buttonStyle(.borderless)322 .accessibilityIdentifier("format-bar")323 }324325 static func morphKey(_ c: SelectionState.Context) -> String { switch c { case .text, .heading: "text"; case .list: "list"; case .task: "task"; case .code: "code"; case .callout: "callout"; case .ai: "ai"; case .atom: "atom" } }326 static func groups(_ items: [EditorInsertion]) -> [(String, [EditorInsertion])] { var order: [String] = []; for i in items where !order.contains(i.group) { order.append(i.group) }; return order.map { g in (g, items.filter { $0.group == g }) } }327328 @ViewBuilder private var contextual: some View {329 HStack(spacing: NVSpace.xxs) {330 switch state.context {331 case .atom(let type):332 Label(Self.atomName(type), systemImage: "square.on.square").nvFont(.ui).foregroundStyle(NVColor.fgMuted).padding(.horizontal, NVSpace.sm)333 Button("Modifier…") { v.activateInsertedAtom() }.nvFont(.ui).help("Ouvrir le bloc (Retour ou double-clic)")334 IconButton(symbol: "arrow.up", help: "Monter le bloc (⌃⌘↑)") { v.moveBlock(up: true) }335 IconButton(symbol: "arrow.down", help: "Descendre le bloc (⌃⌘↓)") { v.moveBlock(up: false) }336 case .code:337 Label("Code", systemImage: "chevron.left.forwardslash.chevron.right").nvFont(.ui).foregroundStyle(NVColor.fgMuted).padding(.horizontal, NVSpace.sm)338 Button("Quitter le bloc") { v.setBlock(.code) }.nvFont(.ui)339 default:340 marks341 sep342 IconButton(symbol: "list.bullet", help: "Liste à puces", active: state.block == .bullet) { v.setBlock(.bullet) }343 IconButton(symbol: "list.number", help: "Liste numérotée", active: { if case .ordered = state.block { return true }; return false }()) { v.setBlock(.ordered(start: 1)) }344 IconButton(symbol: "checklist", help: "Liste de tâches", active: state.block == .task) { v.setBlock(.task) }345 if state.inList {346 IconButton(symbol: "decrease.indent", help: "Diminuer le retrait (⇧⇥)") { v.outdent() }347 IconButton(symbol: "increase.indent", help: "Augmenter le retrait (⇥)") { v.indent() }348 }349 if state.inTask { sep; Button { v.requestTaskDetails() } label: { Label("Échéance", systemImage: "calendar.badge.clock").nvFont(.ui) }.help("Échéance et priorité de la tâche (⌃⌘D)").accessibilityIdentifier("task-due-button") }350 if let kind = state.calloutKind {351 sep352 Menu { ForEach(CalloutKind.known, id: \.rawValue) { k in Button(k.defaultIcon + " " + k.label) { v.setCallout(k) } }; Divider(); Button("Retirer l'encadré") { v.setBlock(.callout) } } label: { Text(CalloutKind(rawValue: kind).defaultIcon + " " + CalloutKind(rawValue: kind).label).nvFont(.ui) }.menuStyle(.borderlessButton).fixedSize().help("Type d'encadré").accessibilityIdentifier("callout-kind")353 }354 if state.inAIBlock { sep; NVAIBadge(style: .compact) }355 }356 }357 }358 private var marks: some View {359 HStack(spacing: NVSpace.xxs) {360 toggle("bold", "Gras (⌘B)", "bold")361 toggle("italic", "Italique (⌘I)", "italic")362 toggle("underline", "Souligné (⌘U)", "underline")363 toggle("strikethrough", "Barré (⇧⌘X)", "strike")364 toggle("chevron.left.forwardslash.chevron.right", "Code (⌘E)", "code")365 toggle("highlighter", "Surligner (⇧⌘H)", "highlight")366 IconButton(symbol: "link", help: "Lien (⌘K sur une sélection)", active: state.linkHref != nil, action: insertLink)367 }368 }369 private var sep: some View { Divider().frame(height: NVSpace.lg).padding(.horizontal, NVSpace.xs) }370 private var blockLabel: String {371 switch state.context { case .atom(let t): return Self.atomName(t); default: break }372 switch state.block { case .heading(let l): return "Titre \(l)"; case .code: return "Code"; case .quote: return "Citation"; case .callout: return "Encadré"; case .bullet, .ordered, .task: return "Liste"; case .paragraph: return "Texte" }373 }374 static func atomName(_ type: String) -> String {375 ["table": "Tableau", "image": "Image", "blockMath": "Équation", "fileBlock": "Fichier", "horizontalRule": "Séparateur", "youtube": "Vidéo", "mermaid": "Diagramme", "drawing": "Dessin", "chart": "Graphique", "queryView": "Vue dynamique", "bibliography": "Bibliographie", "pdf": "PDF", "blockRef": "Référence", "runCode": "Code exécutable", "audio": "Note vocale", "canvasLink": "Canvas"][type] ?? "Bloc"376 }377 private func toggle(_ symbol: String, _ help: String, _ mark: String) -> some View { IconButton(symbol: symbol, help: help, active: state.marks.contains(mark)) { v.toggleMark(mark) } }378}379380struct StatusBar: View {381 @Environment(AppEnvironment.self) private var env382 let session: NoteSession383 var body: some View {384 HStack(spacing: NVSpace.md) {385 Group {386 switch session.saveState {387 case .saved: Label(session.page.syncState == .synced && env.account.isSignedIn ? "Enregistrée et synchronisée" : "Enregistrée sur ce Mac", systemImage: session.page.syncState == .synced && env.account.isSignedIn ? "checkmark.icloud" : "internaldrive")388 case .editing: Label("Enregistrement…", systemImage: "pencil.line")389 case .failed: Label("Non enregistrée", systemImage: "exclamationmark.triangle").foregroundStyle(NVColor.dangerText)390 }391 }.accessibilityIdentifier("save-state")392 Spacer()393 Text(Format.words(session.wordCount))394 Text("Modifiée " + Format.short(session.page.updatedAt))395 }396 .nvFont(.micro).foregroundStyle(NVColor.fgMuted).labelStyle(.titleAndIcon)397 .padding(.horizontal, NVSpace.lg).padding(.vertical, NVSpace.xs + NVSpace.xxs).background(.bar)398 }399}400401extension NoteTextView {402 /// Opens the native editor of the atom next to the caret (after an insertion from the toolbar) or of the selected one.403 func activateInsertedAtom() {404 let sel = selectedRange(); let loc = sel.location405 let candidates = paraStyle(at: loc).isAtom ? [paragraphRange(at: loc).location, loc - 1, loc - 2, loc] : [loc - 1, loc - 2, loc]406 for i in candidates where i >= 0 && i < storage.length {407 if let a = storage.attribute(.attachment, at: i, effectiveRange: nil) as? AtomAttachment { noteDelegate?.noteTextView(self, activate: a, at: NSRange(location: i, length: 1)); return }408 }409 }410}411412struct IdentifiedString: Identifiable { let value: String; var id: String { value } }413