SPB Git

Repository Public

EditorAttributes.swift 12.8 KB 211 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/EditorAttributes.swift3// Description: Semantic attributes carried by the text storage (block style of each paragraph, raw marks of each run) and the theme that turns them into fonts and colours.4import AppKit5import SPNotesDocument6import SPNotesDesign78public extension NSAttributedString.Key {9    /// `ParaStyle` of the paragraph (same object on every character of the paragraph, including its terminating newline).10    static let spPara = NSAttributedString.Key("sp.para")11    /// `MarkSet` of the run (raw ProseMirror marks, unknown ones included).12    static let spMarks = NSAttributedString.Key("sp.marks")13    /// Derived, never serialised: what the layout fragment draws around the paragraph (`ParaDecoration`).14    static let spDecoration = NSAttributedString.Key("sp.decoration")15}1617/// Block identity and structure of one paragraph of the text storage: the flattened `Line` without its content.18/// Reference semantics on purpose: paragraphs that share one instance belong to the same block (the lines of a code block).19public final class ParaStyle: NSObject, @unchecked Sendable {20    /// The line this paragraph came from, content emptied: keeps what the public fields do not show (unknown keys of the node).21    public let template: Line22    /// True when the paragraph is exactly one attachment character holding a block node (table, image, rule…).23    public let isAtom: Bool24    public var path: [Container] { template.path }25    public var type: String { template.type }26    public var attrs: [String: JSONValue] { template.attrs }2728    public init(line: Line, isAtom: Bool? = nil) {29        var t = line30        if case .blockAtom = line.content { self.isAtom = isAtom ?? true } else { self.isAtom = isAtom ?? false; t.content = .inline([]) }31        template = t32    }33    public convenience init(path: [Container] = [], type: String = "paragraph", attrs: [String: JSONValue] = [:]) {34        self.init(line: Line(path: path, type: type, attrs: attrs, content: .inline([])), isAtom: false)35    }3637    /// The line of this paragraph with the given content.38    public func line(_ content: LineContent) -> Line { var l = template; l.content = content; if case .blockAtom(let n) = content { l.type = n.type; if !isAtom { l.attrs = n.attrs ?? [:] } }; return l }3940    public var isCode: Bool { type == "codeBlock" }41    public var headingLevel: Int? { guard type == "heading", case .int(let n)? = attrs["level"] else { return type == "heading" ? 1 : nil }; return Int(n) }42    public var blockID: String? { if case .string(let s)? = attrs["id"] { return s }; return nil }43    /// Innermost list item (`listItem` / `taskItem`) and the list that holds it.44    public var item: (list: Container, item: Container, depth: Int)? {45        guard path.count >= 2, let last = path.last, last.type == "listItem" || last.type == "taskItem" else { return nil }46        return (path[path.count - 2], last, path.filter { $0.type == "listItem" || $0.type == "taskItem" }.count)47    }4849    public func with(path: [Container]? = nil, type: String? = nil, attrs: [String: JSONValue]? = nil) -> ParaStyle {50        var l = template51        if let path { l.path = path }52        if let type, type != l.type { l = Line(path: l.path, type: type, attrs: attrs ?? l.attrs, content: .inline([])) }53        if let attrs { l.attrs = attrs }54        return ParaStyle(line: l, isAtom: isAtom)55    }56    /// A copy for a new block born from this one (Return key): same place in the structure, no block id.57    public func sibling(type: String? = nil) -> ParaStyle {58        var a = attrs; a["id"] = nil59        if let type, type != self.type { a = [:] }60        return ParaStyle(path: path, type: type ?? self.type, attrs: a)61    }62}6364/// Raw marks of a run. Value semantics through `isEqual`, so the text storage merges adjacent runs with the same marks.65public final class MarkSet: NSObject, @unchecked Sendable {66    public let marks: [PMMark]67    public init(_ marks: [PMMark]) { self.marks = marks }68    public static let none = MarkSet([])69    public override func isEqual(_ object: Any?) -> Bool { (object as? MarkSet)?.marks == marks }70    public override var hash: Int { marks.hashValue }71    public func has(_ type: String) -> Bool { marks.contains { $0.type == type } }72    public func mark(_ type: String) -> PMMark? { marks.first { $0.type == type } }73    public var href: String? { if case .string(let s)? = mark("link")?.attrs?["href"] { return s }; return nil }74    public func adding(_ mark: PMMark) -> MarkSet { MarkSet(marks.filter { $0.type != mark.type } + [mark]) }75    public func removing(_ type: String) -> MarkSet { MarkSet(marks.filter { $0.type != type }) }76}7778/// What is drawn around a paragraph by `BlockLayoutFragment`. Computed by the styler from the paragraph and its neighbours.79public final class ParaDecoration: NSObject, @unchecked Sendable {80    public enum Marker: Equatable, Sendable { case bullet(level: Int), number(String), checkbox(Bool), disclosure }81    public enum Panel: Equatable, Sendable { case code, callout(kind: String, icon: String), ai82        /// A container or text block of a type this build does not know: kept verbatim, framed and labelled.83        case unknown(type: String) }84    /// A small label drawn at the right of a task item (due date, priority) or under an AI block (source).85    public struct Chip: Equatable, Sendable {86        public var text: String, symbol: String?, tone: EditorTone87        /// AI source chips open their target: page and block.88        public var pageId: String?, blockId: String?89        public init(text: String, symbol: String? = nil, tone: EditorTone = .neutral, pageId: String? = nil, blockId: String? = nil) { self.text = text; self.symbol = symbol; self.tone = tone; self.pageId = pageId; self.blockId = blockId }90    }91    public var marker: Marker?92    /// Left edge of the marker column, from the left edge of the text container.93    public var markerX: CGFloat = 094    public var quoteBars: [CGFloat] = []95    public var panel: Panel?96    public var panelX: CGFloat = 097    public var panelFirst = true98    public var panelLast = true99    public var calloutIconX: CGFloat?100    public var struck = false101    /// Due date and priority of the task item this paragraph opens (3.0), drawn right-aligned on its first line.102    public var taskChips: [Chip] = []103    /// First paragraph of a panel with a label: the visible « Généré par IA » marker of an AI block (SPEC §0.10, with the104    /// model when known), or « Bloc non pris en charge » on a block of an unknown type.105    public var panelHeader: String?106    /// Last paragraph of an AI block: its sources, as chips that open the cited block.107    public var aiSources: [Chip] = []108    public override func isEqual(_ object: Any?) -> Bool {109        guard let o = object as? ParaDecoration else { return false }110        return o.marker == marker && o.markerX == markerX && o.quoteBars == quoteBars && o.panel == panel && o.panelX == panelX && o.panelFirst == panelFirst && o.panelLast == panelLast && o.calloutIconX == calloutIconX111            && o.struck == struck && o.taskChips == taskChips && o.panelHeader == panelHeader && o.aiSources == aiSources112    }113    public override var hash: Int {114        var h = Hasher(); h.combine(markerX); h.combine(quoteBars.count); h.combine(panelX); h.combine(struck); h.combine(taskChips.count); h.combine(aiSources.count)115        return h.finalize()116    }117}118119/// Fonts, colours and metrics of the editor. All colours are dynamic: one attributed string serves light and dark appearances.120/// Note Visual System 2.0: graphite neutrals, ultramarine accent, violet for anything AI, serif reading titles.121public struct EditorTheme: Sendable, Equatable {122    public var fontSize: CGFloat = 16123    public var fontDesign: FontDesign = .system124    public var lineSpacing: CGFloat = 4125    public var indentWidth: CGFloat = EditorMetrics.listIndent126    public enum FontDesign: String, Sendable, CaseIterable { case system, serif, rounded, monospaced }127    public init(fontSize: CGFloat = 16, fontDesign: FontDesign = .system) { self.fontSize = fontSize; self.fontDesign = fontDesign }128129    public func baseFont(size: CGFloat? = nil, bold: Bool = false, italic: Bool = false) -> NSFont { font(size: size ?? fontSize, design: fontDesign, weight: bold ? .semibold : .regular, italic: italic) }130    private func font(size s: CGFloat, design: FontDesign, weight: NSFont.Weight, italic: Bool) -> NSFont {131        var d = NSFont.systemFont(ofSize: s, weight: weight).fontDescriptor132        switch design {133        case .system: break134        case .serif: d = d.withDesign(.serif) ?? d135        case .rounded: d = d.withDesign(.rounded) ?? d136        case .monospaced: d = d.withDesign(.monospaced) ?? d137        }138        if italic { d = d.withSymbolicTraits(d.symbolicTraits.union(.italic)) }139        return NSFont(descriptor: d, size: s) ?? .systemFont(ofSize: s)140    }141    /// Reading titles are set in the editorial serif (New York) unless the owner chose a rounded or fixed-width text face.142    public var headingDesign: FontDesign { fontDesign == .system || fontDesign == .serif ? .serif : fontDesign }143    public func headingFont(_ level: Int, italic: Bool = false) -> NSFont { font(size: headingSize(level), design: headingDesign, weight: level == 1 ? .bold : .semibold, italic: italic) }144    public func codeFont(bold: Bool = false, italic: Bool = false) -> NSFont {145        var d = NSFont.monospacedSystemFont(ofSize: (fontSize * 0.86).rounded(), weight: bold ? .semibold : .regular).fontDescriptor146        if italic { d = d.withSymbolicTraits(d.symbolicTraits.union(.italic)) }147        return NSFont(descriptor: d, size: (fontSize * 0.86).rounded()) ?? .monospacedSystemFont(ofSize: fontSize * 0.86, weight: .regular)148    }149    /// The type scale of the design system (h1 30, h2 24, h3 20 for a 16-pt body), proportional to the chosen body size.150    public func headingSize(_ level: Int) -> CGFloat { (fontSize * ([1: 30.0 / 16, 2: 24.0 / 16, 3: 20.0 / 16][level] ?? 1.0)).rounded() }151    /// Small interface text inside the document (card labels, chips), independent of the body size.152    public static func uiFont(_ size: CGFloat = EditorMetrics.uiFontSize, weight: NSFont.Weight = .regular) -> NSFont { .systemFont(ofSize: size, weight: weight) }153154    public static let accent = NSColor.nv(.accent)155    public static let text = NSColor.nv(.fg)156    public static let mutedText = NSColor.nv(.fgMuted)157    public static let faint = NSColor.nv(.fgFaint)158    public static let background = NSColor.nv(.bg)159    public static let surface = NSColor.nv(.bgElevated)160    public static let hairline = NSColor.nv(.line)161    public static let strongLine = NSColor.nv(.lineStrong)162    public static let link = NSColor.nv(.accent)163    public static let codeBackground = NSColor.nv(.bgSunken)164    public static let inlineCodeBackground = NSColor.nv(.bgHover)165    public static let highlight = NSColor.nv(.warning, alpha: 0.32)166    public static let quoteBar = NSColor.nv(.lineStrong)167    public static let aiBackground = NSColor.nv(.aiSoft)168    public static let ai = NSColor.nv(.ai)169    public static let flash = NSColor.nv(.accent, alpha: 0.18)170171    /// Tone of a callout kind (3.0 adds decision, question, hypothesis); an unknown kind is neutral.172    public static func calloutTone(_ kind: String) -> EditorTone {173        switch kind {174        case "note", "info", "decision": .accent175        case "warning": .warning176        case "danger": .danger177        case "success": .success178        default: .neutral      // question, hypothesis and kinds of a newer editor (violet stays reserved for AI content)179        }180    }181    public static func calloutBackground(_ kind: String) -> NSColor { calloutTone(kind).fill }182183    public static func tokenColor(_ kind: TokenKind) -> NSColor {184        switch kind {185        case .keyword: return .nv(.ai)186        case .string: return .nv(.dangerText)187        case .comment: return .nv(.fgFaint)188        case .number: return .nv(.warningText)189        case .type: return .nv(.successText)190        case .function: return .nv(.accent)191        case .attribute: return .nv(.ai)192        case .plain, .punctuation: return .nv(.fg)193        }194    }195}196197/// Hands out container keys that never collide with the ones already in the document.198public final class KeyAllocator: @unchecked Sendable {199    private var next: Int200    public init(after max: Int = 0) { next = max + 1 }201    public func make() -> Int { defer { next += 1 }; return next }202    public func reserve(above key: Int) { if key >= next { next = key + 1 } }203    public func container(_ type: String, attrs: [String: JSONValue] = [:]) -> Container { Container(key: make(), type: type, attrs: attrs) }204}205206extension JSONValue {207    var string: String? { if case .string(let s) = self { return s }; return nil }208    var int: Int? { if case .int(let n) = self { return Int(n) }; if case .double(let d) = self { return Int(d) }; return nil }209    var bool: Bool? { if case .bool(let b) = self { return b }; return nil }210}211
Files main
Menu

Theme