232 lines · 11.9 KB · SwiftRaw
// The core's blocks, spans and tables laid onto the text storage: attributes// only, the text never touched. A change restyles only the lines whose// blocks or spans moved, so a long note stays quick to type in.#if canImport(UIKit)import UIKit@MainActorstruct WritingStyler { var look: WritingLook /// Each block's key, by where its text starts (`WritingBlockKey.keys`). var blockKeys: [Int: String] = [:] /// One indent level. static let indentStep: CGFloat = 22 /// Restyles `asked` of `storage` (widened to whole lines) from `styled`. func style(_ storage: NSTextStorage, _ styled: WritingStyled, in asked: NSRange) { let text = storage.string as NSString guard text.length > 0 else { return } let clipped = NSIntersectionRange(asked, NSRange(location: 0, length: text.length)) let range = text.paragraphRange(for: clipped.length == 0 && asked.location >= text.length ? NSRange(location: text.length - 1, length: 0) : clipped) storage.beginEditing() storage.setAttributes(look.base, range: range) for block in Self.touching(styled.blocks, range) { apply(block, to: storage, text: text) } for table in styled.tables where NSIntersectionRange(table.range, range).length > 0 { let r = NSIntersectionRange(table.range, range) storage.addAttribute(.writingBlock, value: blockKeys[table.start] ?? "table#\(table.start)", range: r) } var faces: [(NSRange, WritingFace)] = [] var looks: [(NSRange, WritingSpan)] = [] for span in Self.touching(styled.spans, range) { let r = NSIntersectionRange(span.range, range) guard r.length > 0 else { continue } if let face = WritingFace.of(span) { faces.append((r, face)) } apply(span, to: r, of: storage) if span.look != "text" { looks.append((r, span)) } } // Faces combine (bold inside a heading, italic inside bold): every // run's bits are gathered, then each run gets its one font. for (r, face) in faces { storage.enumerateAttribute(.writingFace, in: r) { value, sub, _ in let had = WritingFace(rawValue: (value as? Int) ?? 0) storage.addAttribute(.writingFace, value: had.union(face).rawValue, range: sub) } } storage.enumerateAttribute(.writingFace, in: range) { value, sub, _ in guard let bits = value as? Int else { return } let face = WritingFace(rawValue: bits) storage.addAttribute(.font, value: look.font(face), range: sub) } // How a mark looks wins over what it marks. for (r, span) in looks { lookOf(span, r, storage) } for block in Self.touching(styled.blocks, range) where Self.items.contains(block.kind) { hang(block, spans: Self.touching(styled.spans, block.range), in: storage, text: text) } storage.endEditing() } /// The list kinds whose wrapped lines hang under their words. static let items: Set<String> = ["bullet", "numbered", "check"] /// The room a list item's marker takes, as a multiple of the body size: /// the bullet or the box, then a clear gap before the words. static let hangRoom: CGFloat = 1.6 /// A list item's marker made exactly as wide as the hang, so the words of /// its first line start where its wrapped lines do, with a gap after the /// bullet or box (launch-ios walk, 22 Nov 2026: the words touched the /// bullet and wrapped lines sat further in). A number wider than the room /// widens the hang instead. private func hang(_ block: WritingBlock, spans: [WritingSpan], in storage: NSTextStorage, text: NSString) { let line = block.range guard NSMaxRange(line) <= text.length else { return } var end = block.content > block.start ? block.content : block.start for span in spans where span.start >= block.start && span.start < block.end && (span.look == "glyph" || span.style == "number") { end = max(end, span.end) } guard end > block.start, end <= NSMaxRange(line) else { return } // The indent's own spaces are hidden and take no room; only the marker counts. let indentEnd = spans.filter { $0.style == "indent" && $0.start >= block.start && $0.end <= end }.map(\.end).max() ?? block.start let marker = NSRange(location: indentEnd, length: end - indentEnd) guard marker.length > 0 else { return } storage.removeAttribute(.kern, range: marker) let width = storage.attributedSubstring(from: marker).size().width // A bullet or a box is drawn, so its room is fixed and every item of a // list lines up; only a written number wider than the room widens it. let drawn = spans.contains { $0.look == "glyph" && $0.start >= block.start && $0.start < end } let room = drawn ? look.size * Self.hangRoom : max(look.size * Self.hangRoom, ceil(width + look.size * 0.3)) let indent = CGFloat(block.depth) * Self.indentStep storage.addAttribute(.kern, value: room - width, range: NSRange(location: NSMaxRange(marker) - 1, length: 1)) storage.addAttribute(.paragraphStyle, value: look.paragraph([], indent: indent, hang: room), range: text.paragraphRange(for: line)) } private func apply(_ block: WritingBlock, to storage: NSTextStorage, text: NSString) { let line = block.range guard NSMaxRange(line) <= text.length else { return } let whole = text.paragraphRange(for: line) let indent = CGFloat(block.depth) * Self.indentStep let item = Self.items.contains(block.kind) switch block.kind { case "heading": let face: WritingFace = block.title ? .title : WritingFace.heading(block.level ?? 1) storage.addAttribute(.paragraphStyle, value: look.paragraph(face, indent: indent), range: whole) storage.addAttribute(.foregroundColor, value: look.theme.heading, range: line) case "quote": storage.addAttribute(.paragraphStyle, value: look.paragraph([], indent: indent + 14), range: whole) storage.addAttribute(.writingQuote, value: look.theme.rule, range: line) case "code", "fence": storage.addAttribute(.backgroundColor, value: look.theme.code, range: whole) case "picture": storage.addAttribute(.writingBlock, value: blockKeys[block.start] ?? "picture#\(block.start)", range: line) default: if indent > 0 || item { storage.addAttribute(.paragraphStyle, value: look.paragraph([], indent: indent, hang: item ? look.size * 1.4 : 0), range: whole) } } } private func apply(_ span: WritingSpan, to r: NSRange, of storage: NSTextStorage) { let theme = look.theme switch span.style { case "underline": storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: r) case "strike": storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: r) case "done": storage.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: r) storage.addAttribute(.foregroundColor, value: theme.dim, range: r) case "code", "code_block": storage.addAttribute(.backgroundColor, value: theme.code, range: r) case "highlight": storage.addAttribute(.backgroundColor, value: theme.highlight, range: r) case "link", "note_link": // Links in the paper's link colour (its text, in Notes) and underlined, never in the ink (Notes CONTRACT §10 // "Ink"); a [[note link]] carries its target as `note:<title>`. storage.addAttribute(.foregroundColor, value: theme.link, range: r) storage.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: r) storage.addAttribute(.underlineColor, value: theme.link, range: r) if let url = span.url { storage.addAttribute(.writingLink, value: span.style == "note_link" ? "note:" + url : url, range: r) } case "image": storage.addAttribute(.foregroundColor, value: theme.accent, range: r) if let url = span.url { storage.addAttribute(.writingLink, value: url, range: r) } case "tag": storage.addAttribute(.foregroundColor, value: theme.chipInk, range: r) storage.addAttribute(.writingChip, value: theme.chip, range: r) case "quote", "number": storage.addAttribute(.foregroundColor, value: theme.dim, range: r) case "found": storage.addAttribute(.backgroundColor, value: theme.highlight, range: r) case "found_now": storage.addAttribute(.backgroundColor, value: theme.selection, range: r) case "folded": storage.addAttribute(.writingFolded, value: true, range: r) case "fold_mark": storage.addAttribute(.writingFold, value: span.glyph ?? "open", range: r) default: break } } /// A mark dim at the cursor, hidden away from it, or a glyph in place of its characters. private func lookOf(_ span: WritingSpan, _ r: NSRange, _ storage: NSTextStorage) { switch span.look { case "dim": storage.addAttribute(.foregroundColor, value: look.theme.faint, range: r) storage.removeAttribute(.writingChip, range: r) case "hidden" where !look.hideMarks: // Marks always shown (Notes' Hide marks off): dim, never hidden. storage.addAttribute(.foregroundColor, value: look.theme.faint, range: r) storage.removeAttribute(.writingChip, range: r) case "hidden": storage.addAttributes([.foregroundColor: UIColor.clear, .font: look.hidden], range: r) storage.removeAttribute(.writingChip, range: r) storage.removeAttribute(.backgroundColor, range: r) case "glyph": storage.addAttributes([.foregroundColor: UIColor.clear, .writingGlyph: span.glyph ?? "bullet"], range: r) storage.removeAttribute(.backgroundColor, range: r) default: break } } /// The runs sorted by start that reach into `range`. A run that starts /// further back than `reach` (a long code block) is restyled by the pass /// covering its start. static func touching<T: WritingRanged>(_ runs: [T], _ range: NSRange) -> [T] { var low = 0 var high = runs.count let end = NSMaxRange(range) while low < high { let mid = (low + high) / 2 if runs[mid].start < end || (runs[mid].start == end && end == range.location) { low = mid + 1 } else { high = mid } } var found: [T] = [] var at = low - 1 while at >= 0, runs[at].start >= range.location - reach { if runs[at].end > range.location || runs[at].start >= range.location { found.append(runs[at]) } at -= 1 } return found.reversed() } static let reach = 20_000}protocol WritingRanged { var start: Int { get } var end: Int { get }}extension WritingSpan: WritingRanged {}extension WritingBlock: WritingRanged {}/// Blocks' keys: a picture by its address and how many of the same came/// before it, a table by how many tables came before it — so a block keeps/// its view while the text around it changes.enum WritingBlockKey { static func keys(_ styled: WritingStyled) -> [Int: String] { var keys: [Int: String] = [:] var seen: [String: Int] = [:] for block in styled.blocks where block.kind == "picture" { let base = "picture:\(block.src ?? "")" let n = seen[base, default: 0] seen[base] = n + 1 keys[block.start] = "\(base)#\(n)" } for (n, table) in styled.tables.enumerated() { keys[table.start] = "table#\(n)" } return keys }}#endif