SPB Git

Repository Public

NoteEditor.swift 20.3 KB 368 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Studio/NoteEditor.swift3// Description: Notes of a research project: the list, a native markdown editor (NSTextView source with ⌘B / ⌘I, live preview with the kit's renderer, debounced autosave through the sync engine) and the note's versions (list, preview, restore as a new revision).4import AppKit5import SwiftUI6import VQuantCore7import VQuantKit8import VQuantUI910// MARK: - AppKit text view1112/// Lets toolbar buttons act on the text view that currently has the note.13final class MarkdownEditorProxy {14    weak var textView: NSTextView?1516    func apply(_ edit: (String, NSRange) -> MarkdownEditing.Edit) {17        guard let tv = textView else { return }18        let e = edit(tv.string, tv.selectedRange())19        // through the text view's own editing path: one undo step, delegate notified20        guard tv.shouldChangeText(in: e.range, replacementString: e.replacement) else { return }21        tv.textStorage?.replaceCharacters(in: e.range, with: e.replacement)22        tv.didChangeText()23        tv.setSelectedRange(e.selection)24        tv.window?.makeFirstResponder(tv)25    }26    func bold() { apply { MarkdownEditing.toggle("**", in: $0, selection: $1) } }27    func italic() { apply { MarkdownEditing.toggle("*", in: $0, selection: $1) } }28    func code() { apply { MarkdownEditing.toggle("`", in: $0, selection: $1) } }29    func prefix(_ p: String) { apply { MarkdownEditing.togglePrefix(p, in: $0, selection: $1) } }30}3132final class MarkdownNSTextView: NSTextView {33    var proxy: MarkdownEditorProxy?34    override func performKeyEquivalent(with event: NSEvent) -> Bool {35        if window?.firstResponder === self, event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command, let key = event.charactersIgnoringModifiers?.lowercased() {36            if key == "b" { proxy?.bold(); return true }37            if key == "i" { proxy?.italic(); return true }38        }39        return super.performKeyEquivalent(with: event)40    }41}4243/// Monospaced markdown source in a native text view (undo, find bar, spelling, system text services).44struct MarkdownSourceView: NSViewRepresentable {45    @Binding var text: String46    let proxy: MarkdownEditorProxy47    var editable = true4849    func makeCoordinator() -> Coordinator { Coordinator(self) }5051    func makeNSView(context: Context) -> NSScrollView {52        let scroll = NSScrollView()53        scroll.hasVerticalScroller = true; scroll.drawsBackground = false; scroll.borderType = .noBorder; scroll.autohidesScrollers = true54        let tv = MarkdownNSTextView()55        tv.proxy = proxy; proxy.textView = tv56        tv.delegate = context.coordinator57        tv.isRichText = false; tv.allowsUndo = true; tv.usesFindBar = true; tv.isIncrementalSearchingEnabled = true58        tv.isAutomaticQuoteSubstitutionEnabled = false; tv.isAutomaticDashSubstitutionEnabled = false; tv.isAutomaticTextReplacementEnabled = false59        tv.font = .monospacedSystemFont(ofSize: 13, weight: .regular)60        tv.textColor = .labelColor; tv.insertionPointColor = NSColor(VQTokens.Palette.accent)61        tv.drawsBackground = false62        tv.textContainerInset = NSSize(width: 18, height: 16)63        tv.isVerticallyResizable = true; tv.isHorizontallyResizable = false; tv.autoresizingMask = [.width]64        tv.minSize = .zero; tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)65        tv.textContainer?.widthTracksTextView = true66        tv.textContainer?.containerSize = NSSize(width: scroll.contentSize.width, height: .greatestFiniteMagnitude)67        let style = NSMutableParagraphStyle(); style.lineSpacing = 468        tv.defaultParagraphStyle = style69        tv.typingAttributes = [.font: tv.font!, .foregroundColor: NSColor.labelColor, .paragraphStyle: style]70        tv.string = text71        tv.setAccessibilityIdentifier("note.editor")72        tv.setAccessibilityLabel("Note source (markdown)")73        scroll.documentView = tv74        return scroll75    }7677    func updateNSView(_ scroll: NSScrollView, context: Context) {78        guard let tv = scroll.documentView as? NSTextView else { return }79        context.coordinator.parent = self80        proxy.textView = tv81        tv.isEditable = editable82        if tv.string != text {83            let sel = tv.selectedRange()84            tv.string = text85            tv.setSelectedRange(NSRange(location: min(sel.location, (text as NSString).length), length: 0))86        }87    }8889    final class Coordinator: NSObject, NSTextViewDelegate {90        var parent: MarkdownSourceView91        init(_ parent: MarkdownSourceView) { self.parent = parent }92        func textDidChange(_ notification: Notification) {93            guard let tv = notification.object as? NSTextView else { return }94            if parent.text != tv.string { parent.text = tv.string }95        }96    }97}9899// MARK: - Notes of a project100101struct ProjectNotesPane: View {102    let app: AppEnvironment103    let projectId: String104    let project: VQProject105    @Binding var noteId: String?106    @State private var deleting: String?107108    private var collection: VQSyncedCollection<VQNote>? { app.sync.active?.notes }109    private var notes: [VQObject<VQNote>] { (collection?.items ?? []).filter { $0.data.projectId == projectId }.sorted { $0.updatedAt > $1.updatedAt } }110    private var selected: VQObject<VQNote>? { noteId.flatMap { collection?[$0] } ?? notes.first }111112    var body: some View {113        HStack(spacing: 0) {114            VStack(alignment: .leading, spacing: 0) {115                HStack {116                    Overline("Notes")117                    Spacer()118                    Button { Task { if let n = await app.studio.createNote(project: projectId, title: "Untitled note") { noteId = n } } } label: { Image(systemName: "square.and.pencil").font(.system(size: 12, weight: .semibold)) }119                        .buttonStyle(.borderless).help("New note").accessibilityIdentifier("notes.new")120                }121                .padding(.horizontal, VQTokens.Space.s4).padding(.top, VQTokens.Space.s3).padding(.bottom, VQTokens.Space.s2)122                ScrollView {123                    VStack(alignment: .leading, spacing: 2) {124                        ForEach(notes) { n in125                            MasterRow(isSelected: selected?.id == n.id) { noteId = n.id } content: {126                                VStack(alignment: .leading, spacing: 2) {127                                    HStack(spacing: 6) {128                                        Text(n.data.title.isEmpty ? "Untitled note" : n.data.title).font(VQTokens.Typography.bodySm.font.weight(.medium)).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)129                                        if collection?.pendingIDs.contains(n.id) == true { PendingSyncMark() }130                                    }131                                    Text(Self.excerpt(n.data.body)).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)132                                    Text(VQFormat.relative(n.updatedAt, language: .en)).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)133                                }134                            }135                            .accessibilityIdentifier("notes.row.\(n.data.title)")136                            .contextMenu { Button("Delete Note…", role: .destructive) { deleting = n.id } }137                        }138                        if notes.isEmpty { Text("No note in this project yet.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).padding(VQTokens.Space.s3) }139                    }140                    .padding(.horizontal, VQTokens.Space.s2)141                }142            }143            .frame(width: 210)144            .background(VQTokens.Palette.ink1)145            VHairline()146            if let n = selected {147                NoteEditorView(app: app, object: n, pending: collection?.pendingIDs.contains(n.id) == true).id(n.id)148            } else {149                CenteredEmpty {150                VQEmptyState(systemImage: "note.text", title: "Notes", message: "Write the reasoning of the project in markdown. Notes sync to your devices, keep their last 30 versions, and are given to the agent by title when it works in the project.") {151                    Button("New Note") { Task { if let n = await app.studio.createNote(project: projectId, title: "Untitled note") { noteId = n } } }.buttonStyle(EmberButtonStyle())152                }153                }154            }155        }156        .confirmationDialog("Delete this note?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } })) {157            Button("Delete Note", role: .destructive) { if let d = deleting { if noteId == d { noteId = nil }; Task { await app.studio.deleteNote(d, project: projectId) } } }158        } message: { Text("The note and its saved versions are erased from your account on every device.") }159    }160161    static func excerpt(_ body: String) -> String {162        let line = body.split(separator: "\n").first { !$0.trimmingCharacters(in: .whitespaces).isEmpty }.map(String.init) ?? "Empty"163        return line.trimmingCharacters(in: CharacterSet(charactersIn: "#>*- ").union(.whitespaces))164    }165}166167enum NoteLayout: String, CaseIterable { case write, split, preview }168169struct NoteEditorView: View {170    let app: AppEnvironment171    let object: VQObject<VQNote>172    let pending: Bool173174    @State private var bodyText = ""175    @State private var loaded = false176    /// The body as last handed to the sync engine (what "saved" means here).177    @State private var savedBody = ""178    @State private var layout: NoteLayout = .split179    @State private var proxy = MarkdownEditorProxy()180    @State private var showVersions = false181    @State private var versions: [VQObjectVersion]?182    @State private var versionsError: String?183    @State private var viewing: VQObjectEnvelope?184    @State private var loadingVersion: Int?185186    private var dirty: Bool { loaded && bodyText != savedBody }187188    var body: some View {189        VStack(alignment: .leading, spacing: 0) {190            toolbar191            Hairline()192            if let v = viewing { versionBanner(v); Hairline() }193            HStack(spacing: 0) {194                if layout != .preview, viewing == nil {195                    MarkdownSourceView(text: $bodyText, proxy: proxy).background(VQTokens.Palette.ink2)196                }197                if layout == .split, viewing == nil { VHairline() }198                if layout != .write || viewing != nil {199                    ScrollView {200                        let shown = viewing.map { VQNote(json: $0.data).body } ?? bodyText201                        Group {202                            if shown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {203                                Text("Nothing to preview yet.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3)204                            } else { VQMarkdownText(shown) }205                        }206                        .padding(.horizontal, VQTokens.Space.s6).padding(.vertical, VQTokens.Space.s5)207                        .frame(maxWidth: 760, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)208                    }209                    .background(VQTokens.Palette.ink0)210                    .accessibilityElement(children: .contain)211                    .accessibilityIdentifier("note.preview")212                }213                if showVersions { VHairline(); versionsList }214            }215        }216        .onAppear {217            if !loaded {218                bodyText = object.data.body; savedBody = object.data.body; loaded = true219                if let m = app.options.extra["NoteMode"].flatMap(NoteLayout.init(rawValue:)) { layout = m }220                if app.options.extra["Versions"] == "1" { showVersions = true }221            }222        }223        // another device (or a restore) changed the note while nothing is unsaved here: follow it224        .onChange(of: object.data.body) { _, remote in if !dirty, remote != bodyText { bodyText = remote; savedBody = remote } else if remote == bodyText { savedBody = remote } }225        // autosave: 1.2 s after the last keystroke, through the durable queue of the sync engine226        .task(id: bodyText) {227            guard dirty else { return }228            try? await Task.sleep(for: .milliseconds(1200))229            if !Task.isCancelled { save() }230        }231        .onDisappear { if dirty { save() } }232    }233234    private func save() {235        guard dirty, let notes = app.sync.active?.notes else { return }236        let text = bodyText237        savedBody = text238        Task { await notes.update(object.id) { $0.body = text }; if let e = notes.lastError { app.toasts.show(e.userMessage, error: true) } }239    }240241    private var toolbar: some View {242        VStack(alignment: .leading, spacing: 2) {243            HStack(spacing: VQTokens.Space.s2) {244                InlineField(value: object.data.title, placeholder: "Note title", role: VQTokens.Typography.title, identifier: "note.title") { t in245                    let v = t.trimmingCharacters(in: .whitespaces)246                    guard !v.isEmpty, let notes = app.sync.active?.notes else { return false }247                    Task { await notes.update(object.id) { $0.title = v } }248                    if let pid = object.data.projectId { app.studio.update(pid) { p in var l = p.items; for i in l.indices where l[i].type == .note && l[i].ref == object.id { l[i].title = v }; p.items = l } }249                    return true250                }251                .padding(.leading, -6)252                Text(viewing != nil ? "" : dirty ? "Editing…" : pending ? "Saved on this Mac · syncing" : "Saved · rev \(object.rev)")253                    .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).lineLimit(1).monospacedDigit().fixedSize()254                    .accessibilityIdentifier("note.state")255            }256            HStack(spacing: VQTokens.Space.s2) {257                HStack(spacing: 0) {258                    fmt("bold", "Bold (⌘B)") { proxy.bold() }259                    fmt("italic", "Italic (⌘I)") { proxy.italic() }260                    fmt("chevron.left.forwardslash.chevron.right", "Inline code") { proxy.code() }261                    fmt("number", "Heading") { proxy.prefix("## ") }262                    fmt("list.bullet", "Bulleted list") { proxy.prefix("- ") }263                }264                .disabled(layout == .preview || viewing != nil)265                .padding(.leading, -6)266                Spacer(minLength: VQTokens.Space.s2)267                VQSegmentedControl("Layout", selection: $layout, options: [.init(.write, "Write"), .init(.split, "Split"), .init(.preview, "Preview")])268                    .accessibilityIdentifier("note.layout")269                Button { showVersions.toggle() } label: { Label("Versions", systemImage: "clock.arrow.circlepath") }270                    .controlSize(.small).fixedSize().accessibilityIdentifier("note.versions")271            }272        }273        .padding(.horizontal, VQTokens.Space.s4).padding(.vertical, VQTokens.Space.s2)274    }275276    private func fmt(_ symbol: String, _ help: String, _ action: @escaping () -> Void) -> some View {277        Button(action: action) { Image(systemName: symbol).font(.system(size: 12)).frame(width: 26, height: 24).contentShape(Rectangle()) }278            .buttonStyle(.borderless).help(help).accessibilityLabel(help)279    }280281    // MARK: versions282283    private var versionsList: some View {284        VStack(alignment: .leading, spacing: 0) {285            VStack(alignment: .leading, spacing: 2) {286                Text("Versions").font(VQTokens.Typography.heading.font)287                Text("The server keeps the last 30 replaced revisions of a note.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)288            }289            .padding(VQTokens.Space.s3)290            Hairline()291            ScrollView {292                VStack(alignment: .leading, spacing: 0) {293                    versionRow(rev: object.rev, date: object.updatedAt, device: object.device, current: true)294                    if let versions {295                        ForEach(versions, id: \.rev) { v in Hairline(); versionRow(rev: v.rev, date: v.updatedAt, device: v.device, current: false) }296                        if versions.isEmpty { Hairline(); Text("No earlier revision yet.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).padding(VQTokens.Space.s3) }297                    } else if let versionsError {298                        Hairline(); Text(versionsError).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.warn).padding(VQTokens.Space.s3)299                    } else { Hairline(); ProgressView().controlSize(.small).padding(VQTokens.Space.s3) }300                }301            }302        }303        .frame(width: 250)304        .frame(maxHeight: .infinity, alignment: .top)305        .background(VQTokens.Palette.ink1)306        .task(id: object.rev) { await loadVersions() }307    }308309    private func versionRow(rev: Int, date: Date?, device: String, current: Bool) -> some View {310        Button {311            if current { viewing = nil } else { Task { await open(rev) } }312        } label: {313            HStack(spacing: VQTokens.Space.s2) {314                Text("rev \(rev)").font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text1).frame(width: 52, alignment: .leading)315                VStack(alignment: .leading, spacing: 0) {316                    Text(VQFormat.dateTime(date, language: .en)).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2)317                    Text(Self.deviceLabel(device)).font(.system(size: 10)).foregroundStyle(VQTokens.Palette.text3).lineLimit(1)318                }319                Spacer()320                if current { QuietChip(text: "Current") } else if loadingVersion == rev { ProgressView().controlSize(.mini) } else if viewing?.rev == rev { QuietChip(text: "Shown", tint: VQTokens.Palette.accentText) }321            }322            .padding(.horizontal, VQTokens.Space.s3).padding(.vertical, 6).contentShape(Rectangle())323        }324        .buttonStyle(.plain)325        .accessibilityIdentifier("note.version.\(rev)")326    }327328    static func deviceLabel(_ d: String) -> String {329        switch d { case "web": "Web"; case "server": "Server"; case "": "Unknown device"; default: "Device \(d.prefix(8))" }330    }331332    private func loadVersions() async {333        await app.sync.syncNow()334        do { versions = try await app.vq.objects.versions(.note, object.id).filter { $0.rev != object.rev }; versionsError = nil }335        catch let e as VQError { versionsError = e.kind == .notFound ? "The note has not reached the server yet." : e.userMessage; if versions == nil { versions = nil } }336        catch { versionsError = error.localizedDescription }337    }338339    private func open(_ rev: Int) async {340        loadingVersion = rev; defer { loadingVersion = nil }341        do { viewing = try await app.vq.objects.version(.note, object.id, rev: rev) }342        catch let e as VQError { app.toasts.show(e.userMessage, error: true) } catch { app.toasts.error(error) }343    }344345    private func versionBanner(_ v: VQObjectEnvelope) -> some View {346        HStack(spacing: VQTokens.Space.s3) {347            Image(systemName: "clock.arrow.circlepath").foregroundStyle(VQTokens.Palette.info)348            Text("Revision \(v.rev) of \(VQFormat.dateTime(v.updatedAt, language: .en)) — read only.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text1)349                .accessibilityIdentifier("note.version.banner")350            Spacer()351            Button("Back to Current") { viewing = nil }.controlSize(.small)352            Button("Restore This Version") { restore(v) }.controlSize(.small).accessibilityIdentifier("note.version.restore")353                .help("Saves this content as a new revision; the current one stays in the versions")354        }355        .padding(.horizontal, VQTokens.Space.s4).padding(.vertical, VQTokens.Space.s2)356        .background(VQTokens.Palette.info.opacity(0.08))357    }358359    /// Restore = the old data saved as a NEW revision (nothing is rewound; the present content becomes a version).360    private func restore(_ v: VQObjectEnvelope) {361        guard let notes = app.sync.active?.notes else { return }362        var old = VQNote(json: v.data)363        if old.projectId == nil { old.projectId = object.data.projectId }364        bodyText = old.body; savedBody = old.body; viewing = nil365        Task { await notes.save(old, id: object.id); app.toasts.show("Revision \(v.rev) restored as a new revision.") }366    }367}368
Files main
Menu

Theme