SPB Git

Repository Public

QuickNote.swift 14.5 KB 215 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Platform/QuickNote.swift3// Description: Quick capture: the floating panel opened by the global shortcut or the menu bar (type at once; drop or paste text, files, images and links; lands in the inbox, among the notes, or at the end of a chosen note), and the capture of a selection sent through the Services menu.4import AppKit5import SwiftUI6import UniformTypeIdentifiers7import SPNotesDocument8import SPNotesStore9import SPNotesDesign1011/// Turns captured material into a page (or appends it to one). Shared by the panel, the Service and the menu bar.12struct QuickCapture {13    let env: AppEnvironment1415    /// The first line is the title, the rest the body. Links on their own line become real links.16    static func document(body lines: [String]) -> NoteDocument {17        NoteDocument(lines: (lines.isEmpty ? [""] : lines).map { line in18            let t = line.trimmingCharacters(in: .whitespaces)19            if let url = URL(string: t), let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme), url.host != nil, !t.contains(" ") {20                return Line(type: "paragraph", content: .inline([.text(t, marks: [PMMark(type: "link", attrs: ["href": .string(t)])])]))21            }22            return Line.paragraph(text: line)23        })24    }25    static func split(_ text: String) -> (title: String, body: [String]) {26        let lines = text.components(separatedBy: "\n")27        return (String(lines.first?.trimmingCharacters(in: .whitespaces).prefix(120) ?? ""), Array(lines.dropFirst()))28    }2930    /// Creates the capture where the preference says (inbox by default). Returns the page id.31    @discardableResult func capture(text: String, files: [URL] = [], images: [NSImage] = [], source: String? = nil, target: QuickNoteTarget? = nil) async -> String? {32        guard !env.isBlocked else { return nil }33        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)34        guard !trimmed.isEmpty || !files.isEmpty || !images.isEmpty else { return nil }35        var (title, body) = Self.split(trimmed)36        if title.isEmpty { title = files.first?.lastPathComponent ?? (images.isEmpty ? "" : "Image capturée") }37        let inbox = (target ?? env.preferences.quickNoteTarget) == .inbox38        guard let id = await env.library.newNote(title: title, content: Self.document(body: body), parentId: nil, inbox: inbox) else { return nil }39        if !files.isEmpty || !images.isEmpty { await attach(files: files, images: images, to: id) }40        return id41    }4243    /// Adds the capture at the end of an existing note (one undo step when the note is open).44    @discardableResult func append(text: String, files: [URL] = [], images: [NSImage] = [], to pageId: String) async -> Bool {45        guard !env.isBlocked, let session = await env.session(for: pageId), session.isEditable else { return false }46        let v = session.editor.textView47        let lines = text.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: "\n")48        v.setSelectedRange(NSRange(location: max(0, v.storage.length - 1), length: 0))49        if !(lines.count == 1 && lines[0].isEmpty) { var d = Self.document(body: lines); d.ensureBlockIds(); v.insert(d, actionName: "Capture rapide") }50        await attach(files: files, images: images, to: pageId)51        await session.saveNow(reason: "Capture rapide")52        return true53    }5455    private func attach(files: [URL], images: [NSImage], to id: String) async {56        guard let session = await env.session(for: id) else { return }57        let service = AttachmentService(env: env); let v = session.editor.textView58        v.setSelectedRange(NSRange(location: max(0, v.storage.length - 1), length: 0))59        for url in files { do { let a = try await service.importFile(url, pageId: 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) } } catch { env.toasts.error(error) } }60        for image in images { do { let a = try await service.importImage(image, pageId: id); v.insertImage(src: a.src, alt: a.name) } catch { env.toasts.error(error) } }61        await session.saveNow(reason: nil)62    }63}6465/// Floating quick-note window: type at once, saved on this Mac, sent later by the synchronisation.66final class QuickNotePanel {67    private let panel: NSPanel68    private let model: QuickNoteModel69    init(env: AppEnvironment) {70        model = QuickNoteModel(env: env)71        panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 520, height: 340), styleMask: [.titled, .closable, .resizable, .fullSizeContentView, .nonactivatingPanel], backing: .buffered, defer: true)72        panel.titleVisibility = .hidden; panel.titlebarAppearsTransparent = true; panel.isFloatingPanel = true; panel.level = .floating73        panel.hidesOnDeactivate = false; panel.isReleasedWhenClosed = false; panel.isMovableByWindowBackground = true74        panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]75        panel.backgroundColor = .clear; panel.isOpaque = false76        let model = model77        let host = NSHostingView(rootView: QuickNoteView(model: model, close: { [weak panel] in panel?.orderOut(nil) }).environment(env).tint(NVColor.accent).preferredColorScheme(env.preferences.appearance.colorScheme))78        host.safeAreaRegions = []   // the glass card fills the panel, title bar included79        panel.contentView = host80        for b in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] { panel.standardWindowButton(b)?.isHidden = true }81        panel.hasShadow = true82        panel.setFrameAutosaveName("SPNotesQuickPanel")83    }84    func toggle() {85        if panel.isVisible { Task { await model.finish() }; panel.orderOut(nil); return }86        if panel.frame.origin == .zero { panel.center() }87        model.begin()88        panel.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true)89    }90    #if DEBUG91    /// Development screenshots: on screen behind everything, never key, with sample content.92    func showForScreenshot() {93        model.begin(); model.text = "Idée pour le chapitre 3\nComparer la volatilité réalisée à 1 min et à 5 min.\nhttps://note.spboucher.ai"94        model.files = [URL(fileURLWithPath: "/tmp/figure-volatilite.png"), URL(fileURLWithPath: "/tmp/article.pdf")]95        panel.setFrameOrigin(NSPoint(x: 60, y: 60)); panel.order(.below, relativeTo: 0)96    }97    #endif98}99100@Observable final class QuickNoteModel {101    var text = ""102    var files: [URL] = []103    var images: [NSImage] = []104    /// Where this capture goes: nil = the preference (inbox or notes), or the end of a chosen note.105    var appendTo: PageSummary?106    private(set) var savedCount = 0107    private(set) var lastSaved: String?108    private(set) var recent: [PageSummary] = []109    /// 1.x compatibility for callers and tests: the page created by the last save.110    private(set) var noteId: String?111    @ObservationIgnored private let env: AppEnvironment112    init(env: AppEnvironment) { self.env = env }113114    var isEmpty: Bool { text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && files.isEmpty && images.isEmpty }115    var targetLabel: String { appendTo.map { "À la fin de « \(Format.title($0.title)) »" } ?? env.preferences.quickNoteTarget.label }116117    func begin() { noteId = nil; lastSaved = nil; Task { recent = Array(((try? await env.store.summaries(list: .recent, limit: 8)) ?? []).prefix(8)) } }118119    /// Saves the capture and empties the panel. Returns the page it went to.120    @discardableResult func save() async -> String? {121        guard !isEmpty else { return nil }122        let t = text, f = files, i = images123        var id: String?124        if let target = appendTo { if await QuickCapture(env: env).append(text: t, files: f, images: i, to: target.id) { id = target.id } }125        else { id = await QuickCapture(env: env).capture(text: t, files: f, images: i) }126        guard let id else { return nil }127        noteId = id; text = ""; files = []; images = []128        lastSaved = appendTo != nil ? "Ajouté à la note" : env.preferences.quickNoteTarget == .inbox ? "Dans la boîte de réception" : "Enregistrée sur ce Mac"129        savedCount += 1130        return id131    }132    func finish() async { await save() }133    func openInMainWindow() async -> String? { await save() }134135    /// Smart paste and drop: files and images become attachments, a link becomes a line of its own, text is appended.136    func accept(pasteboard pb: NSPasteboard) -> Bool {137        var took = false138        if let urls = pb.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty { files += urls; took = true }139        else if let image = NSImage(pasteboard: pb), pb.availableType(from: [.png, .tiff]) != nil { images.append(image); took = true }140        else if let s = pb.string(forType: .string), !s.isEmpty { append(s); took = true }141        return took142    }143    func append(_ s: String) {144        let piece = s.trimmingCharacters(in: .whitespacesAndNewlines); guard !piece.isEmpty else { return }145        let isLink = URL(string: piece).flatMap { $0.scheme.map { ["http", "https"].contains($0.lowercased()) } } == true && !piece.contains(" ")146        if text.isEmpty { text = piece } else { text += (text.hasSuffix("\n") || !isLink && !piece.contains("\n") ? (text.hasSuffix("\n") || text.hasSuffix(" ") ? "" : " ") : "\n") + piece }147        if isLink, !text.hasSuffix("\n") { text += "\n" }148    }149    func accept(providers: [NSItemProvider]) {150        for p in providers {151            if p.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { _ = p.loadObject(ofClass: URL.self) { url, _ in if let url { Task { @MainActor in if url.isFileURL { self.files.append(url) } else { self.append(url.absoluteString) } } } } }152            else if p.hasItemConformingToTypeIdentifier(UTType.url.identifier) { _ = p.loadObject(ofClass: URL.self) { url, _ in if let url { Task { @MainActor in self.append(url.absoluteString) } } } }153            else if p.canLoadObject(ofClass: NSImage.self) { _ = p.loadObject(ofClass: NSImage.self) { img, _ in if let img = img as? NSImage { nonisolated(unsafe) let image = img; Task { @MainActor in self.images.append(image) } } } }154            else if p.canLoadObject(ofClass: String.self) { _ = p.loadObject(ofClass: String.self) { s, _ in if let s { Task { @MainActor in self.append(s) } } } }155        }156    }157}158159struct QuickNoteView: View {160    @Environment(AppEnvironment.self) private var env161    @Environment(\.accessibilityReduceMotion) private var reduceMotion162    @Bindable var model: QuickNoteModel163    let close: () -> Void164    @FocusState private var focused: Bool165    @State private var dropping = false166167    var body: some View {168        VStack(spacing: 0) {169            HStack(spacing: NVSpace.sm) {170                Image(systemName: "bolt.fill").foregroundStyle(NVColor.lumen).accessibilityHidden(true)171                Text("Capture rapide").nvFont(.h3)172                Spacer()173                if let saved = model.lastSaved { Label(saved, systemImage: "checkmark.circle.fill").nvFont(.micro).foregroundStyle(NVColor.successText).transition(.opacity) }174            }175            .padding(.horizontal, NVSpace.lg).padding(.top, NVSpace.lg).padding(.bottom, NVSpace.sm)176            ZStack(alignment: .topLeading) {177                TextEditor(text: $model.text).font(NVFont.fixed(.body)).scrollContentBackground(.hidden).focused($focused).accessibilityIdentifier("quick-note-text")178                if model.text.isEmpty { Text("Écris, colle ou dépose ici — texte, lien, image, fichier…").nvFont(.body).foregroundStyle(NVColor.fgFaint).padding(.leading, NVSpace.xs + 1).allowsHitTesting(false) }179            }180            .padding(.horizontal, NVSpace.md)181            if !model.files.isEmpty || !model.images.isEmpty {182                ScrollView(.horizontal, showsIndicators: false) {183                    HStack(spacing: NVSpace.sm) {184                        ForEach(Array(model.files.enumerated()), id: \.offset) { i, url in NVChip(url.lastPathComponent, systemImage: "paperclip", tone: .accent) { model.files.remove(at: i) }.help("Cliquer pour retirer") }185                        ForEach(Array(model.images.enumerated()), id: \.offset) { i, _ in NVChip("Image \(i + 1)", systemImage: "photo", tone: .accent) { model.images.remove(at: i) }.help("Cliquer pour retirer") }186                    }.padding(.horizontal, NVSpace.lg).padding(.vertical, NVSpace.sm)187                }188            }189            Divider().overlay(NVColor.line)190            HStack(spacing: NVSpace.sm) {191                Menu {192                    Button(env.preferences.quickNoteTarget.label) { model.appendTo = nil }193                    if !model.recent.isEmpty { Divider(); Text("Ajouter à la fin d'une note récente"); ForEach(model.recent) { p in Button(Format.title(p.title)) { model.appendTo = p } } }194                } label: { Label(model.targetLabel, systemImage: model.appendTo == nil ? "tray.and.arrow.down" : "text.append").nvFont(.ui).lineLimit(1) }195                .menuStyle(.borderlessButton).fixedSize().help("Où va cette capture").accessibilityIdentifier("quick-note-target")196                Spacer()197                Button { _ = model.accept(pasteboard: .general) } label: { Image(systemName: "doc.on.clipboard") }.keyboardShortcut("v", modifiers: [.command, .shift]).help("Coller intelligemment (⇧⌘V) : fichiers et images en pièces jointes, lien sur sa propre ligne")198                Button("Ouvrir") { Task { if let id = await model.openInMainWindow() { close(); MainWindowOpener.open?(); env.open(noteId: id) } } }.disabled(model.isEmpty)199                Button("Enregistrer") { Task { await model.finish(); if model.isEmpty { try? await Task.sleep(for: .milliseconds(reduceMotion ? 250 : 650)); close() } } }.buttonStyle(.borderedProminent).keyboardShortcut(.return, modifiers: .command).disabled(model.isEmpty).accessibilityIdentifier("quick-note-save")200            }201            .padding(NVSpace.md).controlSize(.small)202        }203        .frame(minWidth: 380, minHeight: 230)204        .nvGlass(radius: NVRadius.xl)205        .overlay(NVRadius.shape(NVRadius.xl).strokeBorder(dropping ? NVColor.accent : .clear, lineWidth: 2))206        .nvCapturePulse(trigger: model.savedCount, radius: NVRadius.xl)207        .nvCaptureScaleIn()208        .animation(NVMotion.animation(.fast, reduceMotion: reduceMotion), value: model.lastSaved)209        .onDrop(of: [.fileURL, .url, .image, .plainText], isTargeted: $dropping) { providers in model.accept(providers: providers); return true }210        .onAppear { focused = true }211        .onExitCommand { Task { await model.finish(); close() } }212        .accessibilityIdentifier("quick-note")213    }214}215
Files main
Menu

Theme