Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/AtomCards.swift3// Description: The 3.0 block atoms as designed cards: a render model computed from the node (title, icon, live summary, preview, notice) and its native drawing — Mermaid render or source, ink drawing, chart, PDF first page, voice note, living view, block reference, runnable code, bibliography, canvas link, and the neutral card of a node this build does not know.4import AppKit5import PDFKit6import SPNotesDocument7import SPNotesDesign89/// What a referenced block resolves to in the local store.10public enum BlockReference: Equatable, Sendable {11 case resolved(pageTitle: String, text: String)12 /// The page or the block no longer exists: « Référence introuvable ».13 case missing14}1516/// What a card shows. Computed from the node and the local resources only: it is the testable half of the rendering.17public struct AtomCardModel: Equatable, Sendable {18 public enum Body: Equatable, Sendable {19 case none20 /// A picture stored as an attachment (`/api/files/<id>`): Mermaid render, drawing preview.21 case image(src: String)22 /// Ink strokes (`spn-ink-1` attachment) drawn natively when no preview picture exists.23 case ink(attachmentId: String)24 case code(String)25 case text(String)26 case lines([String])27 case chart28 case pdfPage(attachmentId: String, page: Int)29 }30 public var type: String31 public var symbol: String32 /// Kind of block, in small capitals above the title.33 public var eyebrow: String34 public var title: String35 /// One live line under the body: counts, duration, source, last output…36 public var summary: String37 /// Something the reader must know (render out of date, missing target, failed transcript).38 public var notice: String?39 public var body: Body40 public var tone: EditorTone41 /// A node this build has no native rendering for: kept verbatim, shown read-only.42 public var isUnsupported = false43 /// Output of a runnable block that ended in error (drawn in the danger tone).44 public var summaryIsError = false45}4647public extension AtomCardModel {48 static let mermaidStaleNotice = "Rendu à mettre à jour depuis le Web"49 static let unsupportedTitle = "Bloc non pris en charge"5051 /// True for the block types drawn as cards (the 3.0 atoms and anything unknown).52 static func isCard(_ node: PMNode) -> Bool { node.typed != nil || !Self.legacyAtoms.contains(node.type) }53 private static let legacyAtoms: Set<String> = ["horizontalRule", "image", "blockMath", "table", "fileBlock", "youtube"]5455 @MainActor static func make(_ node: PMNode, resources: AtomResources?) -> AtomCardModel {56 func plural(_ n: Int, _ one: String, _ many: String) -> String { n == 1 ? "1 \(one)" : "\(n) \(many)" }57 func oneLine(_ s: String) -> String { s.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }.joined(separator: " ") }58 switch node.typed {59 case .mermaid(let b):60 let lines = b.code.split(whereSeparator: \.isNewline).count61 if b.isPreviewCurrent, let id = b.preview {62 return AtomCardModel(type: node.type, symbol: "point.3.connected.trianglepath.dotted", eyebrow: "Diagramme", title: Self.mermaidKind(b.code), summary: plural(lines, "ligne de source", "lignes de source"), body: .image(src: "/api/files/\(id)"), tone: .accent)63 }64 let empty = b.code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty65 return AtomCardModel(type: node.type, symbol: "point.3.connected.trianglepath.dotted", eyebrow: "Diagramme", title: Self.mermaidKind(b.code), summary: empty ? "Diagramme vide — double-clic pour écrire la source" : plural(lines, "ligne de source", "lignes de source"),66 notice: empty ? nil : Self.mermaidStaleNotice, body: empty ? .none : .code(b.code), tone: .accent)67 case .drawing(let b):68 let size = b.width > 0 && b.height > 0 ? "\(Int(b.width)) × \(Int(b.height))" : ""69 let body: Body = b.preview.map { .image(src: "/api/files/\($0)") } ?? b.ink.map { .ink(attachmentId: $0) } ?? .none70 return AtomCardModel(type: node.type, symbol: "scribble.variable", eyebrow: "Dessin", title: "Dessin", summary: body == .none ? "Dessin vide — se modifie sur iPad ou sur le Web" : [size, "se modifie sur iPad ou sur le Web"].filter { !$0.isEmpty }.joined(separator: " · "), body: body, tone: .accent)71 case .chart(let b):72 let series = b.series()73 let kind = ["bar": "Barres", "line": "Courbes", "area": "Aires", "pie": "Secteurs", "scatter": "Nuage de points"][b.kind.rawValue] ?? b.kind.rawValue74 let hasData = series.contains { $0.points.contains { $0.y != nil } }75 var parts = [kind, plural(series.count, "série", "séries"), plural(b.rows.count, "ligne", "lignes")]76 if b.source != nil { parts.append("données d'une base (dernier instantané)") }77 return AtomCardModel(type: node.type, symbol: "chart.bar.xaxis", eyebrow: "Graphique", title: b.title.isEmpty ? "Graphique" : oneLine(b.title), summary: parts.joined(separator: " · "),78 notice: hasData ? nil : "Aucune donnée numérique — double-clic pour saisir le tableau", body: hasData ? .chart : .none, tone: .accent)79 case .queryView(let b):80 let source = ["tasks": "Tâches", "pages": "Notes", "database": "Base de données", "references": "Références", "backlinks": "Rétroliens"][b.source.rawValue] ?? b.source.rawValue81 let layout = ["list": "liste", "table": "tableau", "board": "tableau kanban"][b.layout.rawValue] ?? b.layout.rawValue82 var filters: [String] = []83 if let t = b.filter.tag { filters.append("#\(t)") }; if let s = b.filter.status { filters.append("statut \(s)") }; if let s = b.filter.section { filters.append("espace \(s)") }; if let t = b.filter.text { filters.append("« \(t) »") }84 if let d = b.filter.dueBefore { filters.append("échéance avant \(d)") }; if let d = b.filter.dueAfter { filters.append("échéance après \(d)") }85 return AtomCardModel(type: node.type, symbol: "rectangle.stack.badge.play", eyebrow: "Vue dynamique", title: b.title.isEmpty ? source : oneLine(b.title),86 summary: (["Source : \(source)", layout, "\(b.limit) éléments au plus"] + filters).joined(separator: " · "), body: .none, tone: .accent)87 case .bibliography(let b):88 let n = resources?.citedReferenceCount()89 return AtomCardModel(type: node.type, symbol: "books.vertical", eyebrow: "Bibliographie", title: b.title.isEmpty ? "Références" : oneLine(b.title),90 summary: (n.map { $0 == 0 ? "Aucune référence citée dans cette note" : plural($0, "référence citée", "références citées") } ?? "Références citées dans cette note") + " · style \(b.style.uppercased())", body: .none, tone: .accent)91 case .pdf(let b):92 let n = b.annotations.count93 let summary = ["page \(b.page)", n == 0 ? "aucune annotation" : plural(n, "annotation", "annotations")].joined(separator: " · ")94 guard let id = b.attachmentId else { return AtomCardModel(type: node.type, symbol: "doc.richtext", eyebrow: "PDF", title: b.name.isEmpty ? "PDF" : b.name, summary: summary, notice: "Aucun fichier — double-clic pour en joindre un", body: .none, tone: .accent) }95 return AtomCardModel(type: node.type, symbol: "doc.richtext", eyebrow: "PDF", title: b.name.isEmpty ? "Document PDF" : b.name, summary: summary, body: .pdfPage(attachmentId: id, page: b.page), tone: .accent)96 case .blockRef(let b):97 guard let page = b.pageId else { return AtomCardModel(type: node.type, symbol: "arrow.turn.down.right", eyebrow: "Référence", title: BlockRefBlock.missingTargetText, summary: "Double-clic pour choisir un bloc", notice: nil, body: .none, tone: .neutral) }98 switch resources?.blockReference(pageId: page, blockId: b.blockId) {99 case .resolved(let title, let text)?:100 let link = b.mode == .link101 return AtomCardModel(type: node.type, symbol: link ? "link" : "arrow.turn.down.right", eyebrow: link ? "Lien vers un bloc" : "Bloc référencé", title: title.isEmpty ? "Sans titre" : title, summary: "Lecture seule — se modifie dans la note d'origine",102 body: link || text.isEmpty ? .none : .text(text), tone: .accent)103 case .missing?:104 return AtomCardModel(type: node.type, symbol: "exclamationmark.triangle", eyebrow: "Référence", title: BlockRefBlock.missingTargetText, summary: "La note ou le bloc d'origine n'existe plus sur ce Mac", body: .none, tone: .warning)105 case nil:106 return AtomCardModel(type: node.type, symbol: "arrow.turn.down.right", eyebrow: "Bloc référencé", title: "…", summary: "Recherche du bloc d'origine", body: .none, tone: .accent)107 }108 case .runCode(let b):109 let out = b.output110 let last = out.map { $0.text.split(whereSeparator: \.isNewline).last.map(String.init) ?? "" }111 let summary: String112 if let out, let last { summary = (out.isError ? "Erreur : " : "Dernière sortie : ") + (last.isEmpty ? "(vide)" : last) } else { summary = "Jamais exécuté — l'exécution se fait sur le Web" }113 var m = AtomCardModel(type: node.type, symbol: "play.rectangle", eyebrow: "Code exécutable", title: b.language.isEmpty ? "code" : b.language, summary: summary, body: b.code.isEmpty ? .none : .code(b.code), tone: .accent)114 m.summaryIsError = out?.isError ?? false115 return m116 case .audio(let b):117 let duration = Self.duration(b.duration)118 let status: String? = ["pending": "transcription en cours", "failed": "transcription en échec"][b.transcriptStatus.rawValue]119 let excerpt = b.transcript.prefix(3).map { "[\($0.timecode)] \(oneLine($0.text))" }120 var summary = [duration, b.transcript.isEmpty ? (status ?? "sans transcription") : plural(b.transcript.count, "segment transcrit", "segments transcrits")]121 if b.summary != nil { summary.append("résumé IA disponible") }122 return AtomCardModel(type: node.type, symbol: "waveform", eyebrow: "Note vocale", title: b.title.isEmpty ? "Enregistrement" : oneLine(b.title), summary: summary.joined(separator: " · "),123 notice: b.transcriptStatus == .failed ? "La transcription a échoué" : b.attachmentId == nil ? "Aucun fichier audio" : nil, body: excerpt.isEmpty ? .none : .lines(excerpt), tone: .accent)124 case .canvasLink(let b):125 let title = b.pageId.flatMap { resources?.pageTitle(id: $0) }126 return AtomCardModel(type: node.type, symbol: "square.on.square.dashed", eyebrow: "Canvas", title: title.map { $0.isEmpty ? "Canvas sans titre" : $0 } ?? "Canvas", summary: b.pageId == nil ? "Aucun canvas lié" : title == nil ? "Canvas introuvable sur ce Mac" : "Double-clic pour l'ouvrir",127 notice: nil, body: .none, tone: title == nil && b.pageId != nil ? .warning : .accent)128 case .citation, nil:129 return AtomCardModel(type: node.type, symbol: "square.dashed", eyebrow: "« \(node.type) »", title: Self.unsupportedTitle, summary: "Conservé tel quel, sans aucune modification — se modifie sur le Web", body: .none, tone: .neutral, isUnsupported: true)130 }131 }132133 static func duration(_ seconds: Double) -> String {134 guard seconds.isFinite, seconds > 0 else { return "durée inconnue" }135 let s = Int(seconds.rounded()); return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s % 3600 / 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60)136 }137 /// The diagram family named on the first line of a Mermaid source.138 static func mermaidKind(_ code: String) -> String {139 let first = code.split(whereSeparator: \.isNewline).map { $0.trimmingCharacters(in: .whitespaces) }.first { !$0.isEmpty && !$0.hasPrefix("%%") }?.lowercased() ?? ""140 let kinds: [(String, String)] = [("sequencediagram", "Diagramme de séquence"), ("classdiagram", "Diagramme de classes"), ("statediagram", "Diagramme d'états"), ("erdiagram", "Diagramme entité-relation"), ("gantt", "Diagramme de Gantt"), ("pie", "Diagramme circulaire"), ("mindmap", "Carte mentale"), ("timeline", "Chronologie"), ("journey", "Parcours"), ("gitgraph", "Graphe Git"), ("flowchart", "Organigramme"), ("graph", "Organigramme")]141 return kinds.first { first.hasPrefix($0.0) }?.1 ?? "Diagramme Mermaid"142 }143}144145// MARK: - Drawing146147extension AtomRenderer {148 /// Height of the header (icon tile, eyebrow, title).149 private static var headerHeight: CGFloat { EditorMetrics.cardPadding * 2 + EditorMetrics.cardIcon }150151 func nextCard(_ node: PMNode, width: CGFloat) -> NSImage {152 let model = AtomCardModel.make(node, resources: resources)153 let w = max(220, min(width, EditorMetrics.cardMaxWidth)), pad = EditorMetrics.cardPadding, inner = w - pad * 2154 // body155 var bodyHeight: CGFloat = 0156 var drawBody: ((CGRect) -> Void)?157 switch model.body {158 case .none: break159 case .image(let src):160 if let image = resources?.image(for: src), image.size.width > 0 {161 let scale = min(1, inner / image.size.width, 420 / image.size.height)162 let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)163 bodyHeight = size.height164 drawBody = { r in Self.drawPicture(image, in: CGRect(x: r.minX + (r.width - size.width) / 2, y: r.minY, width: size.width, height: size.height)) }165 } else { pending.value = true; (bodyHeight, drawBody) = placeholder("Aperçu pas encore sur ce Mac — il se télécharge à la prochaine connexion", width: inner) }166 case .ink(let id):167 if let url = resources?.attachmentURL(id: id), let data = try? Data(contentsOf: url), let ink = try? InkDocument(data: data), let cg = InkRenderer.image(ink, scale: 2, crop: .canvas) {168 let size = CGSize(width: CGFloat(cg.width) / 2, height: CGFloat(cg.height) / 2); let scale = min(1, inner / max(1, size.width), 420 / max(1, size.height))169 bodyHeight = size.height * scale170 drawBody = { r in Self.drawPicture(NSImage(cgImage: cg, size: size), in: CGRect(x: r.minX + (r.width - size.width * scale) / 2, y: r.minY, width: size.width * scale, height: size.height * scale)) }171 } else { pending.value = true; (bodyHeight, drawBody) = placeholder("Dessin pas encore sur ce Mac", width: inner) }172 case .code(let code):173 let shown = code.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).prefix(10).joined(separator: "\n") + (code.split(whereSeparator: \.isNewline).count > 10 ? "\n…" : "")174 let s = NSMutableAttributedString(string: shown, attributes: [.font: theme.codeFont(), .foregroundColor: EditorTheme.text])175 var loc = 0176 for token in SyntaxHighlighter.tokens(shown, language: model.type == "runCode" ? model.title : nil) {177 let len = (token.text as NSString).length178 if token.kind != .plain, token.kind != .punctuation, loc + len <= s.length { s.addAttribute(.foregroundColor, value: EditorTheme.tokenColor(token.kind), range: NSRange(location: loc, length: len)) }179 loc += len180 }181 let h = ceil(s.boundingRect(with: CGSize(width: inner - pad * 2, height: 4000), options: [.usesLineFragmentOrigin]).height)182 bodyHeight = h + pad * 2183 drawBody = { r in184 EditorTheme.codeBackground.setFill(); NSBezierPath(roundedRect: CGRect(x: r.minX, y: r.minY, width: r.width, height: h + pad * 2), xRadius: NVRadius.sm, yRadius: NVRadius.sm).fill()185 s.draw(with: CGRect(x: r.minX + pad, y: r.minY + pad, width: r.width - pad * 2, height: h), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])186 }187 case .text, .lines, .chart, .pdfPage: break // laid out below188 }189 if case .text(let text) = model.body { (bodyHeight, drawBody) = paragraph(String(text.prefix(1200)), font: theme.baseFont(size: (theme.fontSize * 0.94).rounded()), color: EditorTheme.text, width: inner, quoted: true) }190 if case .lines(let lines) = model.body { (bodyHeight, drawBody) = paragraph(lines.joined(separator: "\n"), font: EditorTheme.uiFont(), color: EditorTheme.mutedText, width: inner, quoted: false) }191 if case .chart = model.body, let chart = ChartBlock(node: node) {192 bodyHeight = 200193 drawBody = { r in ChartDrawing.draw(chart, in: CGRect(x: r.minX, y: r.minY, width: r.width, height: 200)) }194 }195 if case .pdfPage(let id, let page) = model.body {196 if let url = resources?.attachmentURL(id: id), let thumb = PDFThumbnails.shared.thumbnail(url: url, page: page, maxSide: 260) {197 bodyHeight = thumb.size.height198 drawBody = { r in199 let rect = CGRect(x: r.minX, y: r.minY, width: thumb.size.width, height: thumb.size.height)200 Self.drawPicture(thumb, in: rect, radius: NVRadius.xs)201 EditorTheme.hairline.setStroke(); let b = NSBezierPath(roundedRect: rect.insetBy(dx: 0.5, dy: 0.5), xRadius: NVRadius.xs, yRadius: NVRadius.xs); b.lineWidth = 1; b.stroke()202 }203 } else { pending.value = true; (bodyHeight, drawBody) = placeholder("Le PDF n'est pas encore sur ce Mac — il se télécharge à l'ouverture", width: inner) }204 }205 // footer206 let summaryAttrs: [NSAttributedString.Key: Any] = [.font: EditorTheme.uiFont(EditorMetrics.microFontSize), .foregroundColor: model.summaryIsError ? EditorTone.danger.foreground : EditorTheme.mutedText]207 let summary = NSAttributedString(string: model.summary, attributes: summaryAttrs)208 let summaryHeight = model.summary.isEmpty ? 0 : ceil(summary.boundingRect(with: CGSize(width: inner, height: 60), options: [.usesLineFragmentOrigin]).height)209 let noticeHeight: CGFloat = model.notice == nil ? 0 : EditorMetrics.chipHeight + NVSpace.xs210 let total = Self.headerHeight + (bodyHeight > 0 ? bodyHeight + pad : 0) + (summaryHeight > 0 ? summaryHeight + pad : 0) + (noticeHeight > 0 ? noticeHeight + NVSpace.sm : 0)211 let tone = model.tone212 return make(CGSize(width: w, height: total + NVSpace.sm)) { r in213 let box = CGRect(x: 0.5, y: NVSpace.xs, width: r.width - 1, height: total)214 let shape = NSBezierPath(roundedRect: box, xRadius: EditorMetrics.cardRadius, yRadius: EditorMetrics.cardRadius)215 (model.isUnsupported ? EditorTheme.codeBackground : EditorTheme.surface).setFill(); shape.fill()216 EditorTheme.hairline.setStroke(); shape.lineWidth = 1217 if model.isUnsupported { shape.setLineDash([4, 3], count: 2, phase: 0) }218 shape.stroke()219 // header: icon tile, eyebrow, title220 let tile = CGRect(x: box.minX + pad, y: box.minY + pad, width: EditorMetrics.cardIcon, height: EditorMetrics.cardIcon)221 tone.fill.setFill(); NSBezierPath(roundedRect: tile, xRadius: NVRadius.sm, yRadius: NVRadius.sm).fill()222 if let icon = NSImage(systemSymbolName: model.symbol, accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: 14, weight: .medium)) {223 Self.drawTemplate(icon, in: CGRect(x: tile.midX - icon.size.width / 2, y: tile.midY - icon.size.height / 2, width: icon.size.width, height: icon.size.height), color: tone == .neutral ? EditorTheme.mutedText : tone.foreground)224 }225 let tx = tile.maxX + NVSpace.md, tw = box.maxX - pad - tx226 let trunc = NSMutableParagraphStyle(); trunc.lineBreakMode = .byTruncatingTail227 NSAttributedString(string: model.eyebrow.uppercased(), attributes: [.font: EditorTheme.uiFont(10, weight: .semibold), .foregroundColor: EditorTheme.mutedText, .kern: 0.6, .paragraphStyle: trunc])228 .draw(with: CGRect(x: tx, y: tile.minY - 1, width: tw, height: 13), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])229 NSAttributedString(string: model.title, attributes: [.font: EditorTheme.uiFont(14, weight: .semibold), .foregroundColor: EditorTheme.text, .paragraphStyle: trunc])230 .draw(with: CGRect(x: tx, y: tile.minY + 12, width: tw, height: 18), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])231 var y = box.minY + Self.headerHeight232 if let drawBody, bodyHeight > 0 { drawBody(CGRect(x: box.minX + pad, y: y, width: inner - 1, height: bodyHeight)); y += bodyHeight + pad }233 if let notice = model.notice {234 let chip = ParaDecoration.Chip(text: notice, symbol: "exclamationmark.circle", tone: .warning)235 ChipDrawing.draw(chip, in: CGRect(origin: CGPoint(x: box.minX + pad, y: y), size: CGSize(width: min(inner, ChipDrawing.size(of: chip).width + 60), height: EditorMetrics.chipHeight)))236 y += noticeHeight + NVSpace.sm237 }238 if summaryHeight > 0 { summary.draw(with: CGRect(x: box.minX + pad, y: y, width: inner, height: summaryHeight), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine]) }239 }240 }241242 private func placeholder(_ text: String, width: CGFloat) -> (CGFloat, ((CGRect) -> Void)?) {243 let s = NSAttributedString(string: text, attributes: [.font: EditorTheme.uiFont(EditorMetrics.microFontSize), .foregroundColor: EditorTheme.mutedText])244 return (44, { r in245 EditorTheme.codeBackground.setFill(); NSBezierPath(roundedRect: CGRect(x: r.minX, y: r.minY, width: r.width, height: 44), xRadius: NVRadius.sm, yRadius: NVRadius.sm).fill()246 let size = s.size(); s.draw(at: CGPoint(x: r.minX + EditorMetrics.cardPadding, y: r.minY + 22 - size.height / 2))247 })248 }249 private func paragraph(_ text: String, font: NSFont, color: NSColor, width: CGFloat, quoted: Bool) -> (CGFloat, ((CGRect) -> Void)?) {250 let p = NSMutableParagraphStyle(); p.lineSpacing = 2; p.lineBreakMode = .byWordWrapping251 let s = NSAttributedString(string: text, attributes: [.font: font, .foregroundColor: color, .paragraphStyle: p])252 let inset: CGFloat = quoted ? EditorMetrics.cardPadding : 0253 let h = min(260, ceil(s.boundingRect(with: CGSize(width: width - inset, height: 4000), options: [.usesLineFragmentOrigin]).height))254 return (h, { r in255 if quoted { EditorTheme.accent.withAlphaComponent(0.55).setFill(); NSBezierPath(roundedRect: CGRect(x: r.minX, y: r.minY, width: EditorMetrics.quoteBarWidth, height: h), xRadius: 1.5, yRadius: 1.5).fill() }256 s.draw(with: CGRect(x: r.minX + inset, y: r.minY, width: r.width - inset, height: h), options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])257 })258 }259 static func drawPicture(_ image: NSImage, in rect: CGRect, radius: CGFloat = EditorMetrics.imageRadius) {260 NSGraphicsContext.saveGraphicsState()261 NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).addClip()262 image.draw(in: rect, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: [.interpolation: NSImageInterpolation.high.rawValue])263 NSGraphicsContext.restoreGraphicsState()264 }265266 /// Inline citation chip: « Auteur 2020, p. 3 ».267 func citationChip(_ node: PMNode) -> NSImage {268 let c = CitationInline(storage: node)269 let label = c.label.isEmpty ? (c.refId.flatMap { resources?.citationLabel(refId: $0) }.map { c.locator.isEmpty ? $0 : "\($0), \(c.locator)" } ?? (c.refId == nil ? "citation ?" : "référence" + (c.locator.isEmpty ? "" : ", \(c.locator)"))) : c.displayText270 let font = EditorTheme.uiFont((theme.fontSize * 0.8).rounded(), weight: .medium)271 let s = NSAttributedString(string: label, attributes: [.font: font, .foregroundColor: EditorTone.accent.foreground])272 let size = s.size(); let pad = EditorMetrics.chipPadding, icon = (theme.fontSize * 0.62).rounded()273 return make(CGSize(width: size.width + pad * 2 + icon + NVSpace.xxs, height: max(size.height + 2, theme.fontSize * 1.1))) { r in274 EditorTone.accent.fill.setFill(); NSBezierPath(roundedRect: r.insetBy(dx: 0, dy: 0.5), xRadius: EditorMetrics.chipRadius, yRadius: EditorMetrics.chipRadius).fill()275 if let img = NSImage(systemSymbolName: "quote.opening", accessibilityDescription: nil)?.withSymbolConfiguration(.init(pointSize: icon, weight: .semibold)) {276 Self.drawTemplate(img, in: CGRect(x: pad, y: r.midY - img.size.height / 2, width: img.size.width, height: img.size.height), color: EditorTone.accent.foreground)277 }278 s.draw(at: CGPoint(x: pad + icon + NVSpace.xxs, y: r.midY - size.height / 2))279 }280 }281}282283/// First-page pictures of local PDF files, rendered by PDFKit and kept in memory.284@MainActor final class PDFThumbnails {285 static let shared = PDFThumbnails()286 private let cache = NSCache<NSString, NSImage>()287 func thumbnail(url: URL, page: Int, maxSide: CGFloat) -> NSImage? {288 let key = "\(url.path)#\(page)#\(Int(maxSide))" as NSString289 if let hit = cache.object(forKey: key) { return hit }290 guard let doc = PDFDocument(url: url), let p = doc.page(at: max(0, min(doc.pageCount - 1, page - 1))) else { return nil }291 let bounds = p.bounds(for: .cropBox); guard bounds.width > 0, bounds.height > 0 else { return nil }292 let scale = min(maxSide / bounds.width, maxSide / bounds.height)293 let img = p.thumbnail(of: CGSize(width: bounds.width * scale * 2, height: bounds.height * scale * 2), for: .cropBox)294 img.size = CGSize(width: (bounds.width * scale).rounded(), height: (bounds.height * scale).rounded())295 cache.setObject(img, forKey: key)296 return img297 }298}299