oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2import AppKit
3import WebKit
4import XCTest
5@testable import DocsKit
6
7/// Measures the production stylesheet, not a second copy of its typography rules.
8@MainActor final class BrowserTypographyTests: XCTestCase {
9 func testRichTextLineBreaksMatchBrowser() async throws {
10 let prose = "A shared document keeps the same words on each line across the browser and native editor. This deliberately long sentence exercises the available measure and the selected font metrics."
11 let cases: [(String, CRDTNode, String)] = [
12 ("heading4", block("h4", prose, type: "heading", attrs: ["level": "4"]), "<h4>\(prose)</h4>"),
13 ("list", CRDTNode(id: "list", type: "bullet_list", children: [CRDTNode(id: "item", type: "list_item", children: [block("li", prose)])]), "<ul><li><p>\(prose)</p></li></ul>"),
14 ("nested-list", CRDTNode(id: "outer", type: "bullet_list", children: [CRDTNode(id: "outerItem", type: "list_item", children: [CRDTNode(id: "inner", type: "ordered_list", children: [CRDTNode(id: "innerItem", type: "list_item", children: [block("nested", prose)])])])]), "<ul><li><ol><li><p>\(prose)</p></li></ol></li></ul>"),
15 ("quote", CRDTNode(id: "quote", type: "blockquote", children: [block("qp", prose)]), "<blockquote><p>\(prose)</p></blockquote>"),
16 ("serif", block("serif", prose, marks: ["font_serif": .object([:])]), "<p><span class='docs-font-serif'>\(prose)</span></p>"),
17 ("mono", block("mono", prose, marks: ["font_mono": .object([:])]), "<p><span class='docs-font-mono'>\(prose)</span></p>"),
18 ("sans", block("sans", prose, marks: ["font_sans": .object([:])]), "<p><span class='docs-font-sans'>\(prose)</span></p>"),
19 ("caladea", block("caladea", prose, marks: ["font_caladea": .object([:])]), "<p><span class='docs-font-caladea'>\(prose)</span></p>"),
20 // Inter is installed on the machine this was written on; the run must be the bundled Inter.
21 ("inter", block("inter", prose, marks: ["font_inter": .object([:])]), "<p><span class='docs-font-inter'>\(prose)</span></p>"),
22 ("garamond-bold", block("garamond", prose, marks: ["font_garamond": .object([:]), "strong": .object([:])]), "<p><span class='docs-font-garamond'><strong>\(prose)</strong></span></p>"),
23 // Caveat has no italic: upright on both sides (font-synthesis: none).
24 ("caveat-italic", block("caveat", prose, marks: ["font_caveat": .object([:]), "em": .object([:])]), "<p><span class='docs-font-caveat'><em>\(prose)</em></span></p>"),
25 ("large", block("large", prose, marks: ["size_24": .object([:])]), "<p><span class='docs-size-24'>\(prose)</span></p>"),
26 ("mixed-size", CRDTNode(id: "mixedSize", type: "paragraph", children: [CRDTNode(id: "mixedSizet", type: "text", runs: [CRDTRun(insert: "Large", marks: ["size_72": .object([:])]), CRDTRun(insert: " " + prose + " " + prose)])]), "<p><span class='docs-size-72'>Large</span> \(prose) \(prose)</p>"),
27 ("mixed-code-wrap", CRDTNode(id: "wrap", type: "paragraph", children: [CRDTNode(id: "wrapt", type: "text", runs: [CRDTRun(insert: String(repeating: "Wide words ", count: 7)), CRDTRun(insert: "WRAPPEDCODE " + prose, marks: ["code": .object([:])])])]), "<p>\(String(repeating: "Wide words ", count: 7))<code>WRAPPEDCODE \(prose)</code></p>"),
28 ("mixed-code", CRDTNode(id: "mixed", type: "paragraph", children: [CRDTNode(id: "mixedt", type: "text", runs: [CRDTRun(insert: "Before 🧪 "), CRDTRun(insert: prose, marks: ["code": .object([:])]), CRDTRun(insert: " after.")])]), "<p>Before 🧪 <code>\(prose)</code> after.</p>"),
29 ("code", block("code", prose, marks: ["code": .object([:])]), "<p><code>\(prose)</code></p>"),
30 ]
31 for (name, node, html) in cases {
32 let browser = try await browserLines(html)
33 let native = nativeLines([node])
34 XCTAssertEqual(native.map(\.text), browser.map(\.text), name)
35 if name == "mixed-size", native.count > 2, browser.count > 2 {
36 XCTAssertEqual(native.last!.y - native[native.count - 2].y, browser.last!.y - browser[browser.count - 2].y, accuracy: 0.76)
37 }
38 for (lhs, rhs) in zip(native, browser) {
39 XCTAssertEqual(lhs.x, rhs.x, accuracy: 0.76, "\(name): text origin")
40 if !name.hasPrefix("mixed") { XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76, "\(name): line spacing") }
41 }
42 }
43 }
44
45 func testTypographyFixtureIsWhatTheBrowserDraws() async throws {
46 typealias Fixture = DocumentTypographyTests
47 let html = "<h1>\(Fixture.heading)</h1><p><strong>\(Fixture.bold)</strong></p><p></p><p>\(Fixture.body)</p>"
48 let lines = try await browserLines(html).map(\.text).filter { !$0.isEmpty }
49 XCTAssertEqual(lines, Fixture.browserLines)
50 }
51
52 func testAdjacentHeadingMarginsCollapse() async throws {
53 let text = "A heading with a predictable measure"
54 let nodes = (0..<4).map { block("h\($0)", text, type: "heading", attrs: ["level": "2"]) }
55 let browser = try await browserLines(String(repeating: "<h2>\(text)</h2>", count: 4))
56 let native = nativeLines(nodes)
57 XCTAssertEqual(native.count, browser.count)
58 for (lhs, rhs) in zip(native, browser) {
59 XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76)
60 }
61 }
62
63 func testNestedBlockSpacingMatchesBrowser() async throws {
64 let text = "A repeated heading inside a quote"
65 let nodes = (0..<5).map { index in CRDTNode(id: "quote\(index)", type: "blockquote", children: [block("nestedHeading\(index)", text, type: "heading", attrs: ["level": "2"])]) }
66 let html = String(repeating: "<blockquote><h2>\(text)</h2></blockquote>", count: 5)
67 let browser = try await browserLines(html, includeBounds: true)
68 let native = nativeLines(nodes, includeBounds: true)
69 XCTAssertEqual(native.map(\.text), browser.map(\.text))
70 for (lhs, rhs) in zip(native, browser) {
71 if lhs.text == "[bottom]" { XCTAssertEqual(lhs.y, rhs.y, accuracy: 0.76) }
72 else { XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76) }
73 }
74 }
75
76 func testPageBreaksMatchBrowserAndPreserveWholeBlocks() async throws {
77 let prose = "A page keeps this whole paragraph together. "
78 let nodes = (0..<18).map { block("p\($0)", String(repeating: prose, count: $0 == 0 ? 160 : 8)) }
79 let html = nodes.map { "<p>\($0.plainText)</p>" }.joined()
80 let browser = try await browserLines(html, paged: true)
81 let native = nativeLines(nodes, paged: true)
82 XCTAssertEqual(native.map(\.text), browser.map(\.text))
83 XCTAssertGreaterThan(native.filter { $0.text == "[page]" }.count, 1)
84 for (lhs, rhs) in zip(native, browser) {
85 if lhs.text == "[page]" {
86 XCTAssertEqual(lhs.y - 72, rhs.y, accuracy: 1.5, "page separator")
87 } else {
88 XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 1.5, lhs.text)
89 }
90 }
91 }
92
93 private func block(_ id: String, _ text: String, type: String = "paragraph", attrs: [String: String]? = nil, marks: [String: JSONValue]? = nil) -> CRDTNode {
94 CRDTNode(id: id, type: type, attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])])
95 }
96
97 struct Line: Decodable { var text: String; var x: Double; var y: Double }
98 private func nativeLines(_ nodes: [CRDTNode], paged: Bool = false, includeBounds: Bool = false) -> [Line] {
99 let storage = NSTextStorage(attributedString: NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false)))
100 let manager = DocsLayoutManager()
101 let container = DocsPageTextContainer(size: CGSize(width: 636, height: 100000))
102 container.geometry = DocsPageGeometry(viewportWidth: 636, paged: false)
103 container.lineFragmentPadding = 0
104 storage.addLayoutManager(manager); manager.addTextContainer(container)
105 manager.ensureLayout(for: container)
106 let pages = paged ? DocumentPageLayoutOracle.measure(storage: storage, manager: manager, container: container) : DocumentPageLayoutOracle.Result()
107 let tops = OracleTops(pages.starts)
108 container.tops = tops
109 defer { withExtendedLifetime(tops) {} }
110 // A lookup change never invalidates by itself (production's
111 // DocsPagination invalidates from the first moved block).
112 manager.textContainerChangedGeometry(container)
113 manager.ensureLayout(for: container)
114 var lines: [Line] = []
115 var contentBottom: CGFloat = 72
116 manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { rect, _, _, range, _ in
117 contentBottom = max(contentBottom, rect.maxY)
118 let chars = manager.characterRange(forGlyphRange: range, actualGlyphRange: nil)
119 let text = (storage.string as NSString).substring(with: chars).trimmingCharacters(in: .whitespacesAndNewlines)
120 let location = manager.location(forGlyphAt: range.location)
121 lines.append(Line(text: text, x: rect.minX + location.x - container.geometry.textX, y: rect.minY))
122 }
123 lines += pages.separators.map { Line(text: "[page]", x: 0, y: $0) }
124 if includeBounds { lines.append(Line(text: "[bottom]", x: 0, y: contentBottom - 72)) }
125 return lines
126 }
127
128 private func browserLines(_ html: String, paged: Bool = false, includeBounds: Bool = false) async throws -> [Line] {
129 let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
130 let source = try String(contentsOf: root.appendingPathComponent("internal/docs/views/show.html"), encoding: .utf8)
131 // The document page's own stylesheet: the <style> in its content
132 // block (the head's <noscript> style comes first).
133 let content = try XCTUnwrap(source.range(of: "{{define \"content\"}}"))
134 let start = try XCTUnwrap(source.range(of: "<style>", range: content.upperBound..<source.endIndex))
135 let end = try XCTUnwrap(source.range(of: "</style>", range: start.upperBound..<source.endIndex))
136 var css = String(source[start.upperBound..<end.lowerBound])
137 // The font rules are internal/fonts' generated stylesheet (fonts.go's
138 // stylesheet()): each face under its private name, the default family
139 // on [docs-text], each family on its mark's class, code in the code
140 // family. Faces are the app's bundled files, as data URLs.
141 for family in DocsFonts.families where family == DocsFonts.defaultFamily || family == DocsFonts.codeFamily || html.contains("docs-font-" + family.key + "'") {
142 for style in family.styles {
143 let data = try Data(contentsOf: try XCTUnwrap(DocsFonts.url(family, style))).base64EncodedString()
144 let bold = style == .bold || style == .boldItalic, italic = style == .italic || style == .boldItalic
145 css += "@font-face{font-family:\"Docs \(family.name)\";src:url(data:font/ttf;base64,\(data));font-weight:\(bold ? 700 : 400);font-style:\(italic ? "italic" : "normal");font-display:block}"
146 }
147 }
148 css += "[docs-text]{font-family:\"Docs \(DocsFonts.defaultFamily.name)\";font-synthesis:none}"
149 for family in DocsFonts.families { css += "[docs-text] .docs-font-\(family.key){font-family:\"Docs \(family.name)\"}" }
150 css += "[docs-text] code{font-family:\"Docs \(DocsFonts.codeFamily.name)\"}"
151 let pageSource = try String(contentsOf: root.appendingPathComponent("fixtures/pages.mjs"), encoding: .utf8)
152 let measureStart = try XCTUnwrap(pageSource.range(of: "function breakPositions(view)"))
153 let measureEnd = try XCTUnwrap(pageSource.range(of: "// pagesPlugin draws"))
154 let gapStart = try XCTUnwrap(pageSource.range(of: "function gapElement(number, pageLabel)"))
155 let pageScript = "const PAGE_CONTENT_PX=864;" + pageSource[measureStart.lowerBound..<measureEnd.lowerBound] + pageSource[gapStart.lowerBound...]
156 let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1200))
157 let navigation = Navigation()
158 view.navigationDelegate = navigation
159 await withCheckedContinuation { continuation in
160 navigation.loaded = { continuation.resume() }
161 view.loadHTMLString("<!doctype html><meta charset='utf-8'><style>\(css) body{margin:0} [docs-text]{width:624px;display:flow-root;--rst-sp-6:24px}</style><main docs-text>\(html)</main>", baseURL: nil)
162 }
163 let script = """
164 await document.fonts.ready;
165 const root = document.querySelector('[docs-text]'), origin = root.getBoundingClientRect();
166 \(paged ? pageScript : "")
167 if (\(paged ? "true" : "false")) {
168 const blocks = [...root.children];
169 const view = {state:{doc:{forEach:callback=>blocks.forEach((node,i)=>callback(node,i))}},nodeDOM:i=>blocks[i]};
170 let previous = '';
171 for (let pass=0; pass<10; pass++) {
172 const positions=breakPositions(view), key=positions.join(',');
173 if (key===previous) break;
174 previous=key;
175 root.querySelectorAll('[docs-page-gap]').forEach(el=>el.remove());
176 positions.forEach((position,i)=>root.insertBefore(gapElement(i+2),blocks[position]));
177 if (pass===9) throw new Error('Pagination did not converge');
178 }
179 }
180 const lines = [];
181 const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
182 let node;
183 while (node = walker.nextNode()) {
184 if (node.parentElement.closest('[docs-page-gap]')) continue;
185 for (let i = 0; i < node.length; i++) {
186 const range = document.createRange(); range.setStart(node,i); range.setEnd(node,i+1);
187 const box = range.getBoundingClientRect(), previous = lines.at(-1);
188 if (!previous || box.y >= previous.bottom - .1 || box.bottom <= previous.top + .1)
189 lines.push({text:node.textContent[i], x:(box.x-origin.x)*.75,y:(box.y-origin.y)*.75,top:box.y,bottom:box.bottom});
190 else { previous.text += node.textContent[i]; previous.top=Math.min(previous.top,box.y); previous.bottom=Math.max(previous.bottom,box.bottom); }
191 }
192 }
193 for (const line of lines) line.text = line.text.trim();
194 for (const gap of root.querySelectorAll('[docs-page-gap]')) lines.push({text:'[page]',x:0,y:(gap.getBoundingClientRect().y-origin.y)*.75});
195 if (\(includeBounds ? "true" : "false")) lines.push({text:"[bottom]",x:0,y:root.getBoundingClientRect().height*.75});
196 return JSON.stringify(lines);
197 """
198 let json = try await view.callAsyncJavaScript(script, contentWorld: .page) as! String
199 return try JSONDecoder().decode([Line].self, from: Data(json.utf8))
200 }
201
202 private final class Navigation: NSObject, WKNavigationDelegate {
203 var loaded: (() -> Void)?
204 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loaded?(); loaded = nil }
205 }
206}
207#endif
208