SPB Git

Repository Public

Styler.swift 17.4 KB 250 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/Styler.swift3// Description: Derives fonts, colours, indents and block decorations from the semantic attributes, for the edited paragraphs only (never the whole document on a keystroke).4import AppKit5import SPNotesDocument6import SPNotesDesign78@MainActor public struct Styler {9    public var theme: EditorTheme10    public init(theme: EditorTheme) { self.theme = theme }1112    static let listTypes: Set<String> = ["bulletList", "orderedList", "taskList"]13    static let itemTypes: Set<String> = ["listItem", "taskItem"]14    static let textTypes: Set<String> = ["paragraph", "heading", "codeBlock", "footnote", "detailsSummary"]15    public static func unknownHeader(_ type: String) -> String { "Bloc non pris en charge · « \(type) » — conservé tel quel" }1617    /// The paragraphs that must be restyled when `range` was edited: the edited paragraphs, widened to the whole top-level18    /// structure they belong to (list numbering, panel corners) and to one neighbour on each side.19    public func affectedRange(in text: NSAttributedString, for range: NSRange) -> NSRange {20        let ns = text.string as NSString21        guard ns.length > 0 else { return NSRange(location: 0, length: 0) }22        var r = ns.paragraphRange(for: NSRange(location: min(range.location, ns.length - 1), length: min(range.length, ns.length - min(range.location, ns.length - 1))))23        func root(at loc: Int) -> Int? { (text.attribute(.spPara, at: loc, effectiveRange: nil) as? ParaStyle)?.path.first?.key }24        func codeStyle(at loc: Int) -> ParaStyle? { let s = text.attribute(.spPara, at: loc, effectiveRange: nil) as? ParaStyle; return s?.isCode == true ? s : nil }25        // backwards26        while r.location > 0 {27            let prev = ns.paragraphRange(for: NSRange(location: r.location - 1, length: 0))28            let same = (root(at: r.location) != nil && root(at: prev.location) == root(at: r.location)) || (codeStyle(at: r.location) != nil && codeStyle(at: prev.location) === codeStyle(at: r.location))29            r = NSUnionRange(r, prev)30            if !same { break }31        }32        while NSMaxRange(r) < ns.length {33            let next = ns.paragraphRange(for: NSRange(location: NSMaxRange(r), length: 0))34            let last = NSMaxRange(r) - 135            let same = (root(at: last) != nil && root(at: next.location) == root(at: last)) || (codeStyle(at: last) != nil && codeStyle(at: next.location) === codeStyle(at: last))36            r = NSUnionRange(r, next)37            if !same { break }38        }39        return r40    }4142    private struct Para { let range: NSRange; let style: ParaStyle }4344    /// Applies derived attributes to the paragraphs of `range` (expected: a range returned by `affectedRange`).45    public func style(_ text: NSMutableAttributedString, in range: NSRange) {46        let ns = text.string as NSString47        guard ns.length > 0, range.length > 0 else { return }48        var paras: [Para] = []49        var loc = range.location50        while loc < NSMaxRange(range), loc < ns.length {51            let pr = ns.paragraphRange(for: NSRange(location: loc, length: 0))52            var eff = NSRange()53            var st = text.attribute(.spPara, at: pr.location, longestEffectiveRange: &eff, in: pr) as? ParaStyle54            if st == nil || NSMaxRange(eff) < NSMaxRange(pr) {55                // paragraphs joined by a deletion, or text typed with foreign attributes: the style at the start wins56                let s = st ?? ParaStyle(); st = s57                text.addAttribute(.spPara, value: s, range: pr)58            }59            paras.append(Para(range: pr, style: st!)); loc = NSMaxRange(pr)60        }61        func neighbour(before: Bool) -> ParaStyle? {62            if before { guard range.location > 0 else { return nil }; return text.attribute(.spPara, at: range.location - 1, effectiveRange: nil) as? ParaStyle }63            guard NSMaxRange(range) < ns.length else { return nil }; return text.attribute(.spPara, at: NSMaxRange(range), effectiveRange: nil) as? ParaStyle64        }65        var counters: [Int: Int] = [:]       // list key → items seen66        var lastItem: [Int: Int] = [:]       // list key → last item key67        var seenItems = Set<Int>()68        for (i, p) in paras.enumerated() {69            let prev = i > 0 ? paras[i - 1].style : neighbour(before: true)70            let next = i + 1 < paras.count ? paras[i + 1].style : neighbour(before: false)71            apply(p, prev: prev, next: next, counters: &counters, lastItem: &lastItem, seenItems: &seenItems, to: text)72        }73        highlightCode(paras, in: text)74    }7576    private func apply(_ p: Para, prev: ParaStyle?, next: ParaStyle?, counters: inout [Int: Int], lastItem: inout [Int: Int], seenItems: inout Set<Int>, to text: NSMutableAttributedString) {77        let st = p.style; let deco = ParaDecoration()78        var indent: CGFloat = 0; var bulletLevel = 0; var checked = false; var inQuote = false79        var idx = 080        while idx < st.path.count {81            let c = st.path[idx]82            switch c.type {83            case "blockquote": deco.quoteBars.append(indent + NVSpace.xxs); indent += EditorMetrics.quoteIndent; inQuote = true84            case "callout":85                let kind = c.attrs["kind"]?.string ?? "note"86                deco.panel = .callout(kind: kind, icon: c.attrs["icon"]?.string ?? CalloutKind(rawValue: kind).defaultIcon); deco.panelX = indent; deco.calloutIconX = indent + EditorMetrics.calloutIconInset; indent += EditorMetrics.calloutIndent87                deco.panelFirst = !(prev?.path.contains { $0.key == c.key } ?? false); deco.panelLast = !(next?.path.contains { $0.key == c.key } ?? false)88            case "aiBlock":89                deco.panel = .ai; deco.panelX = indent; indent += EditorMetrics.panelInset90                deco.panelFirst = !(prev?.path.contains { $0.key == c.key } ?? false); deco.panelLast = !(next?.path.contains { $0.key == c.key } ?? false)91                let info = AIBlockInfo(attrs: c.attrs)92                if deco.panelFirst { deco.panelHeader = Self.panelHeader(info) }93                if deco.panelLast { deco.aiSources = info.sources.enumerated().map { i, s in ParaDecoration.Chip(text: "\(i + 1)  " + (s.title.isEmpty ? "Source" : s.title), tone: .ai, pageId: s.pageId, blockId: s.blockId) } }94            case "detailsContent": indent += theme.indentWidth95            case _ where Self.listTypes.contains(c.type):96                indent += theme.indentWidth97                if idx + 1 < st.path.count, Self.itemTypes.contains(st.path[idx + 1].type) {98                    let item = st.path[idx + 1]99                    let isNew = lastItem[c.key] != item.key100                    if isNew { lastItem[c.key] = item.key; if seenItems.insert(item.key).inserted { counters[c.key, default: 0] += 1 } }101                    // nested lists restart: forget the counters of lists that live inside this item when it changes102                    if idx + 1 == st.path.count - 1 {103                        // the marker belongs to the first paragraph of the item only104                        let firstOfItem = !(prev?.path.contains { $0.key == item.key } ?? false) || isNew105                        if firstOfItem {106                            deco.markerX = indent - theme.indentWidth107                            switch c.type {108                            case "bulletList": deco.marker = .bullet(level: bulletLevel)109                            case "orderedList": deco.marker = .number("\((c.attrs["start"]?.int ?? 1) + (counters[c.key] ?? 1) - 1).")110                            default:111                                deco.marker = .checkbox(item.attrs["checked"]?.bool ?? false)112                                deco.taskChips = Self.taskChips(item.attrs)113                            }114                        }115                    }116                    if c.type == "taskList", idx + 1 == st.path.count - 1 { checked = item.attrs["checked"]?.bool ?? false }117                    if c.type == "bulletList" { bulletLevel += 1 }118                    idx += 1119                }120            default:121                // a container of a type this build does not know (a newer editor's): its content is shown, the block is122                // framed and labelled, and it is saved exactly as it came123                if deco.panel == nil {124                    deco.panel = .unknown(type: c.type); deco.panelX = indent; indent += EditorMetrics.panelInset125                    deco.panelFirst = !(prev?.path.contains { $0.key == c.key } ?? false); deco.panelLast = !(next?.path.contains { $0.key == c.key } ?? false)126                    if deco.panelFirst { deco.panelHeader = Self.unknownHeader(c.type) }127                }128            }129            idx += 1130        }131        if !st.isAtom, !Self.textTypes.contains(st.type), deco.panel == nil {132            // an unknown text block: same frame, one paragraph133            deco.panel = .unknown(type: st.type); deco.panelX = indent; indent += EditorMetrics.panelInset; deco.panelHeader = Self.unknownHeader(st.type)134        }135        if st.type == "detailsSummary" { deco.marker = .disclosure; deco.markerX = indent; indent += EditorMetrics.quoteIndent }136        if st.isCode {137            deco.panel = .code; deco.panelX = indent; indent += EditorMetrics.panelInset138            deco.panelFirst = prev !== st; deco.panelLast = next !== st139        }140        let para = NSMutableParagraphStyle()141        para.firstLineHeadIndent = indent; para.headIndent = indent142        para.lineSpacing = st.isCode ? NVSpace.xxs : theme.lineSpacing143        para.tailIndent = deco.panel != nil ? -EditorMetrics.panelInset : 0144        if !deco.taskChips.isEmpty { para.tailIndent -= ChipDrawing.width(of: deco.taskChips) + NVSpace.sm }145        let inItem = st.item != nil146        if let level = st.headingLevel { para.paragraphSpacingBefore = level == 1 ? NVSpace.xl : NVSpace.lg; para.paragraphSpacing = NVSpace.sm - NVSpace.xxs }147        else if st.isCode { para.paragraphSpacingBefore = deco.panelFirst ? EditorMetrics.panelGap : 0; para.paragraphSpacing = deco.panelLast ? EditorMetrics.panelGap : 0 }148        else if case .callout = deco.panel { para.paragraphSpacingBefore = deco.panelFirst ? EditorMetrics.panelGap : 0; para.paragraphSpacing = deco.panelLast ? EditorMetrics.panelGap : NVSpace.xs }149        else if st.isAtom { para.paragraphSpacingBefore = NVSpace.xs; para.paragraphSpacing = NVSpace.sm }150        else { para.paragraphSpacing = inItem ? NVSpace.xs : NVSpace.sm }151        var labelled = deco.panel == .ai; if case .unknown = deco.panel { labelled = true }152        if labelled {153            // the label (AI marker, unknown type) and the source chips are drawn in the spacing of the first and last paragraphs154            para.paragraphSpacingBefore = deco.panelHeader != nil ? EditorMetrics.panelGap + EditorMetrics.aiHeaderHeight : 0155            para.paragraphSpacing = deco.panelLast ? EditorMetrics.panelGap + (deco.aiSources.isEmpty ? 0 : EditorMetrics.aiFooterHeight) : NVSpace.xs156        }157        if case .string(let align)? = st.attrs["textAlign"] { para.alignment = align == "center" ? .center : align == "right" ? .right : align == "justify" ? .justified : .natural }158        deco.struck = checked159160        let r = p.range161        text.addAttributes([.paragraphStyle: para, .spDecoration: deco], range: r)162        for key in [NSAttributedString.Key.backgroundColor, .underlineStyle, .strikethroughStyle, .baselineOffset, .underlineColor, .toolTip, .cursor] { text.removeAttribute(key, range: r) }163        let baseColor: NSColor = checked || inQuote || st.type == "footnote" ? EditorTheme.mutedText : EditorTheme.text164        text.enumerateAttribute(.spMarks, in: r) { value, run, _ in165            let marks = (value as? MarkSet) ?? .none166            var attrs: [NSAttributedString.Key: Any] = [.foregroundColor: baseColor]167            let bold = marks.has("bold") || st.headingLevel != nil, italic = marks.has("italic")168            if st.isCode { attrs[.font] = theme.codeFont() }169            else if marks.has("code") { attrs[.font] = theme.codeFont(bold: bold, italic: italic); attrs[.backgroundColor] = EditorTheme.inlineCodeBackground }170            else if let level = st.headingLevel, !marks.has("subscript"), !marks.has("superscript") { attrs[.font] = theme.headingFont(level, italic: italic) }171            else {172                var size = st.headingLevel.map(theme.headingSize) ?? (st.type == "footnote" ? (theme.fontSize * 0.88).rounded() : theme.fontSize)173                if marks.has("subscript") { size *= 0.75; attrs[.baselineOffset] = -size * 0.25 }174                if marks.has("superscript") { size *= 0.75; attrs[.baselineOffset] = size * 0.45 }175                attrs[.font] = theme.baseFont(size: size, bold: bold, italic: italic)176            }177            if !st.isCode {178                if marks.has("underline") { attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue }179                if marks.has("strike") || checked { attrs[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }180                if marks.has("highlight") { attrs[.backgroundColor] = EditorTheme.highlight }181                if let href = marks.href { attrs[.foregroundColor] = EditorTheme.link; attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue; attrs[.underlineColor] = NSColor.nv(.accent, alpha: 0.45); attrs[.toolTip] = href; attrs[.cursor] = NSCursor.pointingHand }182            }183            text.addAttributes(attrs, range: run)184        }185    }186187    /// « Généré par IA » and the model, as SPEC §0.10 requires on any AI content.188    static func panelHeader(_ info: AIBlockInfo) -> String { ["Généré par IA", info.model, info.action].compactMap { $0?.isEmpty == false ? $0 : nil }.joined(separator: " · ") }189190    /// Chips of a task item from its 3.0 attributes: due date (red when it is past and the task is open) and priority.191    public static func taskChips(_ attrs: [String: JSONValue], today: Date = Date()) -> [ParaDecoration.Chip] {192        var chips: [ParaDecoration.Chip] = []193        let done = attrs["checked"]?.bool ?? false194        if let due = attrs["due"]?.string, !due.isEmpty {195            let date = Self.localDay(due)196            let late = !done && date.map { Calendar.current.startOfDay(for: $0) < Calendar.current.startOfDay(for: today) } == true197            chips.append(.init(text: date.map { Self.dueLabel($0, today: today) } ?? due, symbol: "calendar", tone: late ? .danger : .neutral))198        }199        if let raw = attrs["priority"]?.string, let p = TaskPriority(rawValue: raw) {200            chips.append(.init(text: Self.priorityLabel(p), symbol: "flag", tone: p == .high ? .danger : p == .medium ? .warning : .neutral))201        }202        return chips203    }204    /// A due value as a day of the local calendar: `YYYY-MM-DD` is that very day (not midnight UTC shifted by the time zone).205    public static func localDay(_ due: String) -> Date? {206        if due.utf8.count == 10 {207            let parts = due.split(separator: "-").compactMap { Int($0) }208            guard parts.count == 3 else { return nil }209            return Calendar.current.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: 12))210        }211        return TaskItemDetail.date(from: due)212    }213    public static func priorityLabel(_ p: TaskPriority) -> String { switch p { case .high: "Haute"; case .medium: "Moyenne"; case .low: "Basse" } }214    public static func dueLabel(_ date: Date, today: Date = Date()) -> String {215        let cal = Calendar.current; let days = cal.dateComponents([.day], from: cal.startOfDay(for: today), to: cal.startOfDay(for: date)).day ?? 0216        switch days { case 0: return "Aujourd'hui"; case 1: return "Demain"; case -1: return "Hier"; default: break }217        let f = DateFormatter(); f.locale = Locale(identifier: "fr_CA"); f.dateFormat = cal.component(.year, from: date) == cal.component(.year, from: today) ? "d MMM" : "d MMM yyyy"218        return f.string(from: date)219    }220221    /// Syntax colours of the code blocks touched by the pass: one tokenisation per block, over all its lines.222    private func highlightCode(_ paras: [Para], in text: NSMutableAttributedString) {223        var i = 0224        while i < paras.count {225            guard paras[i].style.isCode else { i += 1; continue }226            var j = i; while j + 1 < paras.count, paras[j + 1].style === paras[i].style { j += 1 }227            let range = NSUnionRange(paras[i].range, paras[j].range)228            let lang = paras[i].style.attrs["language"]?.string229            if range.length < 200_000 {230                var loc = range.location231                for token in SyntaxHighlighter.tokens((text.string as NSString).substring(with: range), language: lang) {232                    let len = (token.text as NSString).length233                    if token.kind != .plain, token.kind != .punctuation, loc + len <= NSMaxRange(range) { text.addAttribute(.foregroundColor, value: EditorTheme.tokenColor(token.kind), range: NSRange(location: loc, length: len)) }234                    loc += len235                }236            }237            i = j + 1238        }239    }240241    /// Attributes for text typed in a paragraph of `style` with `marks` (used for typing attributes and inserted text).242    public func typingAttributes(style: ParaStyle, marks: MarkSet) -> [NSAttributedString.Key: Any] {243        let probe = NSMutableAttributedString(string: "x\n", attributes: [.spPara: style, .spMarks: marks])244        self.style(probe, in: NSRange(location: 0, length: 2))245        var a = probe.attributes(at: 0, effectiveRange: nil)246        a[.spDecoration] = nil; a[.toolTip] = nil; a[.cursor] = nil247        return a248    }249}250
Files main
Menu

Theme