SPB Git

Repository Public

EditorStyler.swift 16.7 KB 302 lines swift

1// SP Notes iOS2// File: Editor/EditorStyler.swift3// Description: Presentation of the text storage: derives fonts, colours and paragraph styles from the model attributes (LineStyle, marks),4//              paragraph by paragraph, so that only the edited paragraphs are restyled while typing.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import SPNotesCore1011/// Metrics and colours of the editor. Fonts follow Dynamic Type.12struct EditorTheme {13    var body: UIFont { UIFont.preferredFont(forTextStyle: .body) }14    var code: UIFont { UIFontMetrics(forTextStyle: .body).scaledFont(for: .monospacedSystemFont(ofSize: 15, weight: .regular)) }15    func heading(_ level: Int) -> UIFont {16        let style: UIFont.TextStyle = level <= 1 ? .title1 : level == 2 ? .title2 : .title317        let base = UIFont.preferredFont(forTextStyle: style)18        return UIFont(descriptor: base.fontDescriptor.withSymbolicTraits(.traitBold) ?? base.fontDescriptor, size: 0)19    }20    let text = UIColor(named: "TextPrimary") ?? .label21    let secondary = UIColor(named: "TextSecondary") ?? .secondaryLabel22    let muted = UIColor(named: "Muted") ?? .tertiaryLabel23    let accent = UIColor(named: "AccentColor") ?? .systemOrange24    let codeBackground = UIColor(named: "CodeBackground") ?? .secondarySystemBackground25    let highlight = UIColor(named: "Highlight") ?? UIColor.systemYellow.withAlphaComponent(0.4)26    let quoteBar = UIColor(named: "QuoteBar") ?? .systemOrange27    let border = UIColor(named: "Border") ?? .separator28    let surface = UIColor(named: "Surface2") ?? .secondarySystemBackground2930    /// Horizontal space taken by one level of list nesting, by a quote bar, by a callout/code inset.31    let listIndent: CGFloat = 2832    let quoteIndent: CGFloat = 1633    let boxInset: CGFloat = 1234    let paragraphSpacing: CGFloat = 735    /// 2.0: column of the callout icon (and of the AI mark), of the disclosure chevron of a toggle, of a footnote label.36    let calloutGutter: CGFloat = 2637    let disclosureGutter: CGFloat = 223839    static let shared = EditorTheme()40}4142/// The left inset of a paragraph and what occupies it; shared by the styler (indents) and the layout fragment (drawing).43struct LineGeometry {44    var textIndent: CGFloat = 045    /// x of each quote bar.46    var quoteBars: [CGFloat] = []47    /// Left edge of the callout / code box when the line sits in one.48    var boxLeft: CGFloat?49    /// x where the list marker is drawn (right-aligned to textIndent - 8).50    var hasMarker = false51    /// 2.0: left edge of the icon column of the innermost callout / AI block, and of the chevron column of the innermost toggle.52    var calloutIconLeft: CGFloat?53    var disclosureLeft: CGFloat?5455    init(style: LineStyle, theme: EditorTheme) {56        var x: CGFloat = 057        for container in style.path {58            switch container.type {59            case "blockquote": quoteBars.append(x + 2); x += theme.quoteIndent60            case "callout", "aiBlock": if boxLeft == nil { boxLeft = x }; calloutIconLeft = x + theme.boxInset - 2; x += theme.boxInset + theme.calloutGutter61            case "details": if boxLeft == nil { boxLeft = x }; disclosureLeft = x + theme.boxInset - 4; x += theme.boxInset + theme.disclosureGutter62            case "listItem", "taskItem": x += theme.listIndent63            default: break64            }65        }66        if style.isCode { if boxLeft == nil { boxLeft = x }; x += theme.boxInset }67        if style.type == "footnote" { x += theme.listIndent }68        hasMarker = style.innermostItem != nil69        textIndent = x70    }71}7273@MainActor74final class EditorStyler {75    let theme: EditorTheme76    let atoms: AtomRenderer77    /// Usable width for block atoms (text container width); updated by the text view on layout.78    var contentWidth: CGFloat = 3207980    /// 2.0: code blocks longer than this (UTF-16 units) are not re-coloured at each keystroke: their id is put in81    /// `pendingCode` and the owner colours them after a pause in typing (`colourPendingCode`).82    static let immediateColouringLimit = 600083    var defersLargeCode = false84    var pendingCode = Set<String>()8586    init(theme: EditorTheme = .shared, atoms: AtomRenderer) { self.theme = theme; self.atoms = atoms }8788    private static let presentationKeys: [NSAttributedString.Key] = [.font, .foregroundColor, .backgroundColor, .underlineStyle, .underlineColor, .strikethroughStyle, .baselineOffset, .paragraphStyle, .kern]8990    /// Restyles every paragraph intersecting `range`. Characters are never changed.91    func restyle(_ storage: NSMutableAttributedString, range: NSRange) {92        let string = storage.string as NSString93        guard string.length > 0 else { return }94        let clamped = NSIntersectionRange(range, NSRange(location: 0, length: string.length))95        var location = string.paragraphRange(for: NSRange(location: min(clamped.location, max(0, string.length - 1)), length: 0)).location96        let end = max(NSMaxRange(clamped), location + 1)97        while location < min(end, string.length) {98            let paragraph = string.paragraphRange(for: NSRange(location: location, length: 0))99            restyleParagraph(storage, paragraph: paragraph)100            location = NSMaxRange(paragraph)101        }102    }103104    func restyleAll(_ storage: NSMutableAttributedString) {105        let deferred = defersLargeCode106        defersLargeCode = false107        defer { defersLargeCode = deferred }108        restyle(storage, range: NSRange(location: 0, length: storage.length))109        renumber(storage)110    }111112    func paragraphStyle(for style: LineStyle) -> NSParagraphStyle {113        let geometry = LineGeometry(style: style, theme: theme)114        let p = NSMutableParagraphStyle()115        p.firstLineHeadIndent = geometry.textIndent116        p.headIndent = geometry.textIndent117        p.tailIndent = (style.callout != nil || style.isCode || style.isInDetails) ? -theme.boxInset : 0118        p.paragraphSpacing = style.innermostItem != nil ? 3 : theme.paragraphSpacing119        if let level = style.headingLevel { p.paragraphSpacingBefore = level == 1 ? 14 : 10; p.paragraphSpacing = 6 }120        if style.isCode { p.paragraphSpacingBefore = 6; p.paragraphSpacing = 16; p.lineBreakMode = .byCharWrapping }121        else if style.callout != nil || style.isInDetails { p.paragraphSpacing = max(p.paragraphSpacing, 12) }122        if case .string(let align)? = style.attrs["textAlign"] {123            p.alignment = align == "center" ? .center : align == "right" ? .right : align == "justify" ? .justified : .natural124        }125        p.lineHeightMultiple = style.isCode ? 1.1 : 1.12126        // 2.0: room at the right of a task item for its due date / priority badge127        if let reserved = TaskBadge.reservedWidth(for: style) { p.tailIndent -= reserved }128        return p129    }130131    func baseAttributes(for style: LineStyle) -> [NSAttributedString.Key: Any] {132        var font = theme.body133        var color = theme.text134        if let level = style.headingLevel { font = theme.heading(level) }135        if style.isCode { font = theme.code }136        if style.type == "detailsSummary" { font = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor, size: 0) }137        if style.type == "footnote" { font = UIFont.preferredFont(forTextStyle: .footnote); color = theme.secondary }138        if style.quoteDepth > 0 { color = theme.secondary }139        if style.isTaskChecked { color = theme.muted }140        return [.font: font, .foregroundColor: color, .paragraphStyle: paragraphStyle(for: style)]141    }142143    /// Typing attributes for a caret in a paragraph of this style with these marks.144    func typingAttributes(style: LineStyle, marks: [PMMark]) -> [NSAttributedString.Key: Any] {145        var attributes = baseAttributes(for: style)146        attributes[.spnLine] = LineBox(style)147        if !marks.isEmpty && !style.isCode {148            attributes[.spnMarks] = MarksBox(marks)149            apply(marks: marks, style: style, to: &attributes)150        }151        return attributes152    }153154    private func restyleParagraph(_ storage: NSMutableAttributedString, paragraph: NSRange) {155        guard paragraph.length > 0 else { return }156        let style = (storage.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox)?.style ?? LineStyle(attrs: LineStyle.paragraphAttrs)157        // A large code block being typed in keeps its (slightly stale) token colours until the pause: no flash to plain text.158        let keepsColours = style.isCode && defersLargeCode && paragraph.length - 1 > Self.immediateColouringLimit159        for key in Self.presentationKeys where !(keepsColours && key == .foregroundColor) { storage.removeAttribute(key, range: paragraph) }160        let base = baseAttributes(for: style)161        if keepsColours {162            var partial = base163            partial.removeValue(forKey: .foregroundColor)164            storage.addAttributes(partial, range: paragraph)165        } else {166            storage.addAttributes(base, range: paragraph)167        }168        if style.isTaskChecked { storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: paragraph); storage.addAttribute(.strikethroughColor, value: theme.muted, range: paragraph) }169        else { storage.removeAttribute(.strikethroughColor, range: paragraph) }170        // marks171        if !style.isCode {172            storage.enumerateAttribute(.spnMarks, in: paragraph, options: []) { value, range, _ in173                guard let box = value as? MarksBox, !box.marks.isEmpty else { return }174                var attributes = base175                self.apply(marks: box.marks, style: style, to: &attributes)176                attributes.removeValue(forKey: .paragraphStyle)177                storage.addAttributes(attributes, range: range)178            }179        } else {180            storage.removeAttribute(.spnMarks, range: paragraph)181            colourCode(storage, paragraph: paragraph, style: style)182        }183        // atoms184        storage.enumerateAttribute(.attachment, in: paragraph, options: []) { value, range, _ in185            guard let atom = value as? AtomAttachment else { return }186            let geometry = LineGeometry(style: style, theme: self.theme)187            self.atoms.prepare(atom, availableWidth: max(120, self.contentWidth - geometry.textIndent), baseFont: base[.font] as? UIFont ?? self.theme.body)188        }189    }190191    private func apply(marks: [PMMark], style: LineStyle, to attributes: inout [NSAttributedString.Key: Any]) {192        var font = attributes[.font] as? UIFont ?? theme.body193        var traits = font.fontDescriptor.symbolicTraits194        for mark in marks {195            switch mark.type {196            case "bold": traits.insert(.traitBold)197            case "italic": traits.insert(.traitItalic)198            case "underline": attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue199            case "strike": attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue200            case "code":201                font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .monospacedSystemFont(ofSize: max(12, font.pointSize * 0.9), weight: .regular))202                attributes[.backgroundColor] = theme.codeBackground203            case "highlight": attributes[.backgroundColor] = theme.highlight204            case "link":205                attributes[.foregroundColor] = theme.accent206                attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue207                attributes[.underlineColor] = theme.accent.withAlphaComponent(0.5)208            case "subscript":209                attributes[.baselineOffset] = -font.pointSize * 0.2210                font = font.withSize(font.pointSize * 0.75)211            case "superscript":212                attributes[.baselineOffset] = font.pointSize * 0.35213                font = font.withSize(font.pointSize * 0.75)214            default: break // unknown marks are kept in the model and shown as plain text215            }216        }217        if traits != font.fontDescriptor.symbolicTraits, let descriptor = font.fontDescriptor.withSymbolicTraits(traits) {218            font = UIFont(descriptor: descriptor, size: font.pointSize)219        }220        attributes[.font] = font221    }222223    /// Recomputes list presentation attributes for the whole storage: which paragraph heads its list item, and ordered-list numbers.224    /// O(paragraphs); called after structural edits only (newline inserted or removed, list commands), never for plain typing.225    func renumber(_ storage: NSMutableAttributedString) {226        let string = storage.string as NSString227        guard string.length > 0 else { return }228        var counters: [Int: Int] = [:]       // ordered list key → last number229        var seenItems = Set<Int>()           // item keys already headed230        var location = 0231        while location < string.length {232            let paragraph = string.paragraphRange(for: NSRange(location: location, length: 0))233            defer { location = NSMaxRange(paragraph) }234            guard let style = (storage.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox)?.style else { continue }235            var ordinal: Int?236            var head = false237            // Every item of the path is entered in order, so numbering advances even when a nested list starts on the same paragraph.238            for (index, container) in style.path.enumerated() where EditorNodeTypes.isItem(container.type) {239                guard !seenItems.contains(container.key) else { continue }240                seenItems.insert(container.key)241                let isInnermost = index == style.innermostItemIndex242                if index > 0, style.path[index - 1].type == "orderedList" {243                    let list = style.path[index - 1]244                    var start = 1245                    if case .int(let s)? = list.attrs["start"] { start = Int(s) }246                    let number = (counters[list.key] ?? (start - 1)) + 1247                    counters[list.key] = number248                    if isInnermost { ordinal = number }249                }250                if isInnermost { head = true }251            }252            let current = storage.attribute(.spnItemHead, at: paragraph.location, effectiveRange: nil) as? NSNumber253            let currentOrdinal = storage.attribute(.spnOrdinal, at: paragraph.location, effectiveRange: nil) as? NSNumber254            if (current != nil) != head { head ? storage.addAttribute(.spnItemHead, value: NSNumber(value: 1), range: paragraph) : storage.removeAttribute(.spnItemHead, range: paragraph) }255            if currentOrdinal?.intValue != ordinal {256                if let ordinal { storage.addAttribute(.spnOrdinal, value: NSNumber(value: ordinal), range: paragraph) } else { storage.removeAttribute(.spnOrdinal, range: paragraph) }257            }258        }259    }260}261262// MARK: - 2.0: syntax colours of code blocks (presentation only, recomputed from the text; nothing is stored)263264extension EditorStyler {265    func colourCode(_ storage: NSMutableAttributedString, paragraph: NSRange, style: LineStyle) {266        let content = NSRange(location: paragraph.location, length: max(0, paragraph.length - 1))267        guard content.length > 0 else { return }268        if defersLargeCode, content.length > Self.immediateColouringLimit {269            pendingCode.insert(style.attrs["id"]?.stringValue ?? "")270            return271        }272        let text = (storage.string as NSString).substring(with: content).replacingOccurrences(of: EditorCharacter.softBreak, with: "\n")273        for span in SyntaxHighlighter.spans(text, language: style.attrs["language"]?.stringValue) {274            guard let colour = SyntaxHighlighter.colour(for: span.kind) else { continue }275            storage.addAttribute(.foregroundColor, value: colour, range: NSRange(location: content.location + span.range.location, length: span.range.length))276        }277    }278279    /// Colours the code blocks that were skipped while typing. Returns the ranges it changed.280    func colourPendingCode(_ storage: NSMutableAttributedString) -> [NSRange] {281        guard !pendingCode.isEmpty else { return [] }282        let ids = pendingCode283        pendingCode.removeAll()284        var changed: [NSRange] = []285        let string = storage.string as NSString286        var location = 0287        while location < string.length {288            let paragraph = string.paragraphRange(for: NSRange(location: location, length: 0))289            location = NSMaxRange(paragraph)290            guard let style = (storage.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox)?.style, style.isCode,291                  ids.contains(style.attrs["id"]?.stringValue ?? "") else { continue }292            let deferred = defersLargeCode293            defersLargeCode = false294            storage.addAttribute(.foregroundColor, value: theme.text, range: paragraph)295            colourCode(storage, paragraph: paragraph, style: style)296            defersLargeCode = deferred297            changed.append(paragraph)298        }299        return changed300    }301}302
Files main
Menu

Theme