oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import CoreText
2import Foundation
3import RastrilloApple
4import XCTest
5@testable import DocsKit
6#if os(macOS)
7import AppKit
8#endif
9
10/// The picker and the commands it drives, against the shared list in
11/// internal/fonts/fonts.json (DocsFontsTests reads it the same way).
12final class DocsFontPickerTests: XCTestCase {
13 /// The picker lists the shared list's families, in its order and by its
14 /// names, each drawn in its own face. A row is the name alone: a metric
15 /// twin does not say so (Paul, 2026-10-26), though it is still one.
16 @MainActor func testPickerEntriesAreDrawnInTheirOwnFace() throws {
17 let shared = try DocsFontsTests.shared()
18 let entries = DocsFontPicker.entries
19 XCTAssertEqual(entries.map(\.key), shared.families.map(\.key))
20 XCTAssertEqual(entries.map(\.name), shared.families.map(\.name))
21 XCTAssertEqual(entries.first?.key, "carlito")
22 for (entry, family) in zip(entries, shared.families) {
23 XCTAssertEqual(DocsFontsTests.url(of: entry.font), try DocsFontsTests.bundled(family, "regular"), "\(family.name) is drawn in \(family.name)")
24 }
25 #if os(macOS)
26 // The toolbar's pop-up button: each item's title in its own face, the
27 // current family checked, its key what a choice reports.
28 let menu = DocsFontPicker.menu(selected: "sans")
29 XCTAssertEqual(menu.items.count, shared.families.count)
30 for (item, family) in zip(menu.items, shared.families) {
31 let title = try XCTUnwrap(item.attributedTitle, family.name)
32 XCTAssertEqual(title.string, family.name, "\(family.name)'s row is its name and nothing else")
33 var face = NSRange()
34 let font = try XCTUnwrap(title.attribute(.font, at: 0, effectiveRange: &face) as? NSFont, family.name)
35 XCTAssertEqual(DocsFontsTests.url(of: font), try DocsFontsTests.bundled(family, "regular"), family.name)
36 XCTAssertEqual(face.length, (family.name as NSString).length, "\(family.name): the name, and only the name, is in its face")
37 XCTAssertEqual(item.state, family.key == "sans" ? .on : .off)
38 XCTAssertEqual(item.representedObject as? String, family.key)
39 }
40 #endif
41 }
42
43 /// setFont is the picker's command: Sans is font_sans, the default clears
44 /// the group, one font at a time, and an unknown key changes nothing.
45 @MainActor func testSetFontKeepsSansAndDefaultApart() throws {
46 let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!))
47 model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false)
48 model.projection = CRDTProjection(children: [CRDTNode(id: "p", type: "paragraph", children: [CRDTNode(id: "t", type: "text", runs: [
49 CRDTRun(insert: "plain words"),
50 ])])], canUndo: false, canRedo: false)
51 let commands = DocumentCommands(model: model, content: NativeTextProjection.render(model.projection!))
52 model.selection = NSRange(location: 2, length: 0)
53 XCTAssertTrue(commands.setFont("sans"))
54 XCTAssertEqual(model.typingMarks?["font_sans"], .object([:]), "Sans is a mark, not the default")
55 XCTAssertTrue(commands.setFont("inter"))
56 XCTAssertEqual(model.typingMarks?["font_inter"], .object([:]))
57 XCTAssertNil(model.typingMarks?["font_sans"], "one font at a time")
58 XCTAssertTrue(commands.setFont("carlito"))
59 XCTAssertEqual(model.typingMarks?.keys.filter { $0.hasPrefix("font_") } ?? ["missing"], [], "the default clears every font mark")
60 model.typingMarks = ["font_playfair": .object([:])]
61 XCTAssertFalse(commands.setFont("futura"), "a family this build does not know changes nothing")
62 XCTAssertEqual(model.typingMarks, ["font_playfair": .object([:])])
63
64 }
65
66 /// The face a collapsed-caret pick will type in, so IME marked text is
67 /// drawn in it rather than in its neighbour's.
68 @MainActor func testTypingFontFollowsAPickAtTheCaret() throws {
69 let projection = CRDTProjection(children: [
70 CRDTNode(id: "h", type: "heading", attrs: ["level": "2"], children: [CRDTNode(id: "ht", type: "text", runs: [CRDTRun(insert: "Title")])]),
71 ], canUndo: false, canRedo: false)
72 let content = NativeTextProjection.render(projection)
73 let font = try XCTUnwrap(NativeTextProjection.typingFont(in: content, at: 2, marks: ["font_playfair": .object([:])]))
74 XCTAssertEqual(DocsFontsTests.url(of: font)?.lastPathComponent, "PlayfairDisplay-Bold.ttf", "a heading is bold")
75 XCTAssertEqual(font.pointSize, 15.6, accuracy: 0.01)
76 }
77
78 /// Pasted font names map onto the shared list once and deterministically.
79 @MainActor func testPastedFontNamesMapByTheSharedList() {
80 XCTAssertEqual(DocsFonts.family(cssStack: "Calibri, sans-serif")?.key, "carlito", "Calibri is Carlito")
81 XCTAssertEqual(DocsFonts.family(cssStack: "Cambria")?.key, "caladea")
82 XCTAssertEqual(DocsFonts.family(cssStack: "'Liberation Sans', Arial")?.key, "sans")
83 XCTAssertEqual(DocsFonts.family(cssStack: "Arial")?.key, "sans")
84 XCTAssertEqual(DocsFonts.family(cssStack: "Helvetica")?.key, "sans")
85 XCTAssertEqual(DocsFonts.family(cssStack: "\"Times New Roman\", serif")?.key, "serif")
86 XCTAssertEqual(DocsFonts.family(cssStack: "Georgia")?.key, "caladea")
87 XCTAssertEqual(DocsFonts.family(cssStack: "Wingdings, Menlo, monospace")?.key, "jetbrains")
88 XCTAssertEqual(DocsFonts.family(cssStack: "monospace")?.key, "mono")
89 XCTAssertEqual(DocsFonts.family(cssStack: "Source Serif 4")?.key, "sourceserif")
90 XCTAssertEqual(DocsFonts.family(cssStack: "sans-serif")?.key, "carlito")
91 XCTAssertNil(DocsFonts.family(cssStack: "Wingdings"))
92 // A stack is read in order: the first name that maps wins, whether it
93 // maps by its own name or as a name a family stands in for.
94 XCTAssertEqual(DocsFonts.family(cssStack: "Georgia, \"Times New Roman\", serif")?.key, "caladea")
95 XCTAssertEqual(DocsFonts.family(cssStack: "Menlo, \"Courier New\", monospace")?.key, "jetbrains")
96 XCTAssertEqual(DocsFonts.family(cssStack: "Helvetica, Calibri, sans-serif")?.key, "sans")
97 XCTAssertEqual(DocsFonts.family(cssStack: "Wingdings, Cambria, Georgia")?.key, "caladea")
98 XCTAssertEqual(DocsFonts.family(cssStack: "Wingdings, Calibri, Arial")?.key, "carlito")
99 }
100
101 /// fixtures/vectors/font-stacks.json is the one list of paste cases the
102 /// web's familyForStack and this resolver are both held to.
103 @MainActor func testSharedFontStackVectors() throws {
104 let url = DocsFontsTests.repository.appendingPathComponent("fixtures/vectors/font-stacks.json")
105 let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
106 let cases = try XCTUnwrap(json["cases"] as? [[Any]])
107 XCTAssertGreaterThanOrEqual(cases.count, 23)
108 for pair in cases {
109 let stack = try XCTUnwrap(pair.first as? String)
110 let expected = pair.last as? String
111 XCTAssertEqual(DocsFonts.family(cssStack: stack)?.key, expected, stack)
112 }
113 }
114
115 /// Nested paste, against the shared vectors' "nested" cases: an inner
116 /// font-family that maps to the default or to nothing clears the outer
117 /// font, one that maps to another family replaces it, and a span with no
118 /// font-family keeps the outer font, as the web's parse rule does.
119 @MainActor func testNestedPastedFontsFollowTheSharedVectors() throws {
120 let url = DocsFontsTests.repository.appendingPathComponent("fixtures/vectors/font-stacks.json")
121 let json = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
122 let cases = try XCTUnwrap(json["nested"] as? [[Any]])
123 XCTAssertGreaterThanOrEqual(cases.count, 8)
124 func attribute(_ stack: String) -> String { "font-family: " + stack.replacingOccurrences(of: "\"", with: """) }
125 for pair in cases {
126 let outer = try XCTUnwrap(pair[0] as? String), inner = pair[1] as? String, expected = pair[2] as? String
127 let innerOpen = inner.map { "<span style=\"\(attribute($0))\">" } ?? "<span>"
128 let html = "<p><span style=\"\(attribute(outer))\">Outer \(innerOpen)Inner</span></span></p>"
129 let runs = Self.runs(DocsHTMLClipboard.blocks(html))
130 let run = try XCTUnwrap(runs.first { $0.text.contains("Inner") }, html)
131 let fonts = run.marks.keys.filter { $0.hasPrefix("font_") }.sorted()
132 XCTAssertEqual(fonts, expected.map { ["font_" + $0] } ?? [], "\(outer) > \(inner ?? "(no font-family)")")
133 }
134 }
135 static func runs(_ blocks: [JSONValue]) -> [(text: String, marks: [String: JSONValue])] {
136 var out: [(String, [String: JSONValue])] = []
137 func walk(_ value: JSONValue) {
138 guard case .object(let node) = value else { return }
139 if case .array(let runs)? = node["runs"] {
140 for case .object(let run) in runs {
141 guard case .string(let text)? = run["insert"] else { continue }
142 if case .object(let marks)? = run["marks"] { out.append((text, marks)) } else { out.append((text, [:])) }
143 }
144 }
145 if case .array(let children)? = node["children"] { children.forEach(walk) }
146 }
147 blocks.forEach(walk)
148 return out
149 }
150
151 /// A run copied out of web Docs names its private face first, then that
152 /// family's fallback stack (internal/fonts' generated stylesheet). The
153 /// private name decides: Source Sans 3's fallbacks start with Segoe UI,
154 /// which is Carlito's, and IBM Plex Sans's with Helvetica Neue, Inter's.
155 @MainActor func testDocsPrivateFontNamesMapToTheirFamily() throws {
156 let data = try Data(contentsOf: DocsFontsTests.repository.appendingPathComponent("internal/fonts/fonts.json"))
157 let families = try XCTUnwrap((try JSONSerialization.jsonObject(with: data) as? [String: Any])?["families"] as? [[String: Any]])
158 for family in families {
159 let name = try XCTUnwrap(family["name"] as? String), key = try XCTUnwrap(family["key"] as? String)
160 let fallback = try XCTUnwrap(family["fallback"] as? [String])
161 let stack = (["\"Docs \(name)\""] + fallback.map { $0.contains(" ") ? "\"\($0)\"" : $0 }).joined(separator: ", ")
162 XCTAssertEqual(DocsFonts.family(cssStack: stack)?.key, key, stack)
163 }
164 }
165
166 /// The same order through an HTML paste, which is where it writes a mark.
167 @MainActor func testPastedStackKeepsItsFirstMappedFamily() {
168 let blocks = DocsHTMLClipboard.blocks("<p><span style='font-family: Georgia, \"Times New Roman\", serif'>Serif</span></p>")
169 guard case .object(let paragraph)? = blocks.first, case .array(let children)? = paragraph["children"],
170 case .object(let text)? = children.first, case .array(let runs)? = text["runs"],
171 case .object(let run)? = runs.first, case .object(let marks)? = run["marks"] else { return XCTFail("no run: \(blocks)") }
172 XCTAssertEqual(marks.keys.filter { $0.hasPrefix("font_") }, ["font_caladea"])
173 }
174}
175