SPB Git

Repository Public

BlockSheets.swift 9.5 KB 158 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Notes/BlockSheets.swift3// Description: The `BlockDetailProviding` protocol behind which the block detail views live (the shared SPNotesFeatures views, see Features/Hosting), the sheet frame, the pickers this app keeps (block reference target, canvas link), and the due date / priority popover of a task item.4import SwiftUI5import AVFoundation6import SPNotesDocument7import SPNotesEditor8import SPNotesStore9import SPNotesAPI10import SPNotesDesign1112/// What a detail view receives. `apply` replaces the node in the note (one undo step); nothing else touches the document.13struct BlockDetailContext {14    let env: AppEnvironment15    let session: NoteSession16    let editable: Bool17    let router: WindowModel?18    let apply: (PMNode) -> Void19    let remove: () -> Void20    let dismiss: () -> Void21}2223/// Provider of the detail views of block atoms. `FeaturesBlockDetails` (Features/Hosting) wraps the shared views of24/// SPNotesFeatures: `MermaidBlockView`, `ChartBlockView`, `PDFBlockView`, `AudioBlockView`, `InkEditorView`…25@MainActor protocol BlockDetailProviding {26    func detail(for node: PMNode, context: BlockDetailContext) -> AnyView?27}2829/// Common frame of a block sheet: icon, title, content, and the Annuler / Terminé row.30struct BlockSheetFrame<Content: View>: View {31    let title: String, symbol: String32    var width: CGFloat = 56033    let context: BlockDetailContext34    var done: (() -> Void)?35    var canDelete = true36    @ViewBuilder var content: Content37    var body: some View {38        VStack(alignment: .leading, spacing: NVSpace.md) {39            PanelHeader(title: title, symbol: symbol)40            content41            HStack {42                if context.editable, canDelete { Button("Retirer de la note", role: .destructive, action: context.remove) }43                Spacer()44                Button(done == nil ? "Fermer" : "Annuler", role: .cancel, action: context.dismiss).keyboardShortcut(.cancelAction)45                if let done { Button("Terminé", action: done).buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).disabled(!context.editable).accessibilityIdentifier("block-done") }46            }47        }48        .padding(NVSpace.xl).frame(width: width)49    }50}5152// MARK: Block reference5354/// A block of a page that can be referenced: its id and what it says.55struct ReferencableBlock: Identifiable, Equatable { let id: String; let type: String; let text: String56    /// The blocks of a document that carry an id and some text, in order (a list, quote or callout is offered as a whole).57    static func list(_ doc: NoteDocument) -> [ReferencableBlock] {58        var out: [ReferencableBlock] = []; var seen = Set<String>()59        for line in doc.lines {60            let holder = line.path.first { $0.attrs["id"]?.stringValue?.isEmpty == false }61            guard let id = holder?.attrs["id"]?.stringValue ?? line.attrs["id"]?.stringValue, !id.isEmpty, seen.insert(id).inserted else { continue }62            let lines = holder == nil ? [line] : doc.lines.filter { $0.path.contains { $0.key == holder!.key } }63            let text = NoteDocument(lines: lines.map { var l = $0; l.path = []; return l }).plainText().trimmingCharacters(in: .whitespacesAndNewlines)64            if !text.isEmpty { out.append(ReferencableBlock(id: id, type: holder?.type ?? line.type, text: text)) }65        }66        return out67    }68}6970struct BlockRefSheet: View {71    var block: BlockRefBlock?72    let context: BlockDetailContext73    /// Picker mode (insertion): the chosen node is handed to `apply`.74    @State private var query = ""75    @State private var pages: [PageSummary] = []76    @State private var page: PageSummary?77    @State private var blocks: [ReferencableBlock] = []78    @State private var chosen: String?79    @State private var mode: BlockRefMode = .embed80    var body: some View {81        BlockSheetFrame(title: block == nil ? "Référencer un bloc" : "Référence à un bloc", symbol: "arrow.turn.down.right", width: 640, context: context, done: page == nil ? nil : { apply() }, canDelete: block != nil) {82            HStack(alignment: .top, spacing: NVSpace.md) {83                VStack(alignment: .leading, spacing: NVSpace.sm) {84                    TextField("Chercher une note…", text: $query).textFieldStyle(.roundedBorder).accessibilityIdentifier("blockref-search")85                    List(pages, selection: Binding(get: { page?.id }, set: { id in page = pages.first { $0.id == id } })) { p in Text(Format.title(p.title)).nvFont(.ui).lineLimit(1).tag(p.id) }.listStyle(.bordered).frame(height: 240)86                }.frame(width: 230)87                VStack(alignment: .leading, spacing: NVSpace.sm) {88                    Picker("Affichage", selection: $mode) { Text("Contenu du bloc").tag(BlockRefMode.embed); Text("Lien").tag(BlockRefMode.link) }.pickerStyle(.segmented).labelsHidden()89                    if page == nil { Text("Choisis une note, puis le bloc à afficher.").nvFont(.ui).foregroundStyle(NVColor.fgMuted).frame(maxHeight: .infinity) }90                    else {91                        List(selection: $chosen) {92                            Text("Toute la note (début)").nvFont(.ui).foregroundStyle(NVColor.fgMuted).tag(String?.none)93                            ForEach(blocks) { b in Text(b.text).nvFont(.ui).lineLimit(2).tag(String?.some(b.id)) }94                        }.listStyle(.bordered).frame(height: 240)95                    }96                }97            }98            if let b = block, let p = b.pageId { Button("Ouvrir la note d'origine") { context.dismiss(); context.router?.openPage(id: p, blockId: b.blockId) }.buttonStyle(.link) }99        }100        .task(id: query) { pages = await context.env.library.quickFind(query, limit: 30).filter { $0.id != context.session.id } }101        .task(id: page?.id) { blocks = []; if let id = page?.id, let rec = try? await context.env.store.page(id: id), let d = try? NoteDocument(json: rec.content) { blocks = ReferencableBlock.list(d) } }102        .task { if let b = block, let id = b.pageId, let p = try? await context.env.store.summary(id: id) { page = p; chosen = b.blockId; mode = b.mode; if !pages.contains(p) { pages.insert(p, at: 0) } } }103    }104    private func apply() {105        guard let page else { return }106        if var b = block { b.pageId = page.id; b.blockId = chosen; b.mode = mode; context.apply(b.node()) }107        else { context.apply(BlockRefBlock(pageId: page.id, blockId: chosen, mode: mode).node()) }108    }109}110111// MARK: Audio probe112113enum AudioProbe {114    static func duration(_ url: URL) async -> Double? {115        let asset = AVURLAsset(url: url)116        guard let d = try? await asset.load(.duration), d.isNumeric else { return nil }117        let s = CMTimeGetSeconds(d); return s.isFinite && s > 0 ? s : nil118    }119}120121struct CanvasLinkSheet: View {122    var block: CanvasLinkBlock?123    let context: BlockDetailContext124    @State private var canvases: [PageSummary] = []125    @State private var chosen: String?126    var body: some View {127        BlockSheetFrame(title: "Lien vers un canvas", symbol: "square.on.square.dashed", context: context, done: chosen == nil ? nil : { if var b = block { b.pageId = chosen; context.apply(b.node()) } else if let chosen { context.apply(CanvasLinkBlock(pageId: chosen).node()) } }, canDelete: block != nil) {128            if canvases.isEmpty { Text("Aucun canvas sur ce Mac. Les canvas se créent sur le Web ou sur iPad et arrivent avec la synchronisation.").nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true).frame(height: 100) }129            else { List(canvases, selection: $chosen) { p in Text(Format.title(p.title)).tag(String?.some(p.id)) }.listStyle(.bordered).frame(height: 220) }130            if let id = block?.pageId { Button("Ouvrir ce canvas") { context.dismiss(); context.router?.openCanvas(pageId: id) }.buttonStyle(.link).accessibilityIdentifier("canvas-open") }131        }132        .task { canvases = ((try? await context.env.store.summaries(list: .all, limit: 5000)) ?? []).filter { $0.type == "canvas" }; chosen = block?.pageId }133    }134}135136// MARK: Task item popover137138struct TaskDetailsPopover: View {139    let session: NoteSession140    let location: Int141    let dismiss: () -> Void142    @State private var hasDue = false143    @State private var due = Date()144    @State private var priority: SPNotesDocument.TaskPriority?145    var body: some View {146        VStack(alignment: .leading, spacing: NVSpace.md) {147            GroupLabel("Tâche")148            Toggle("Échéance", isOn: $hasDue)149            if hasDue { DatePicker("Date", selection: $due, displayedComponents: .date).datePickerStyle(.graphical).labelsHidden() }150            Picker("Priorité", selection: $priority) { Text("Aucune").tag(SPNotesDocument.TaskPriority?.none); Text("Basse").tag(SPNotesDocument.TaskPriority?.some(.low)); Text("Moyenne").tag(SPNotesDocument.TaskPriority?.some(.medium)); Text("Haute").tag(SPNotesDocument.TaskPriority?.some(.high)) }.pickerStyle(.segmented)151            HStack { Button("Effacer") { session.editor.textView.setTaskAttributes(at: location, due: nil, priority: nil); dismiss() }; Spacer(); Button("OK") { session.editor.textView.setTaskAttributes(at: location, due: hasDue ? TaskItemDetail.dayString(due) : nil, priority: priority); dismiss() }.buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).accessibilityIdentifier("task-details-ok") }152        }153        .padding(NVSpace.lg).frame(width: 300)154        .onAppear { if let t = session.editor.textView.taskItem(at: location) { priority = t.priority; if let d = t.due.flatMap(Styler.localDay) { hasDue = true; due = d } } }155        .accessibilityIdentifier("task-details")156    }157}158
Files main
Menu

Theme