oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import ImageIO
3import RastrilloApple
4import RastrilloSnapshots
5import RastrilloTestSupport
6import SwiftUI
7import UniformTypeIdentifiers
8import XCTest
9@testable import DocsKit
10#if os(macOS)
11import AppKit
12#else
13import UIKit
14#endif
15
16/// The editor's page, drawn by today's renderer from fixed fixtures, so that
17/// rendering work (the native redesign's S1a and S1b) is held to the pixel.
18/// Spec 2026-11-22-native-redesign-design.md §11, plan S0.
19///
20/// Each screen opens a fixture document through the real path: a replica
21/// seeded on an in-memory server, `DocsModel.open`, `NativeTextProjection`
22/// and `NativeDocumentTextView` wired as `DocsWorkspace.editor` wires them
23/// (the page only: the toolbar, sync row and window chrome are not here).
24/// The kit draws a screen once two pictures 50 ms apart agree, and a model
25/// answers asynchronously, so a screen shows a counter that changes on
26/// every frame until its document is open, rendered, laid out
27/// (`ensureLayout` on the container, then a run-loop turn) and scrolled to
28/// its fixed offset. A screen that never gets there is reported unsettled
29/// and fails; it is never recorded half drawn.
30///
31/// Fixed state: the bundled faces are registered first (never a fallback
32/// face), the selection is the model's (a caret at 0, or where the script
33/// leaves it), bound as `DocsWorkspace` binds it, and the text view is
34/// never first responder, so no caret or selection is drawn and nothing
35/// blinks. No animation or clock is read; the Mac's scrollers
36/// are pinned to overlay.
37final class DocsEditorSnapshots: XCTestCase {
38 @MainActor func testEditorScreens() async throws {
39 try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil,
40 "Run with native/scripts/snapshots.sh")
41 DocsFonts.register()
42 let settings = SnapshotSettings(tint: OficinaPalette.accent(.docs))
43 await assertSnapshots(of: SnapshotCatalog(app: "docs-editor", variants: [.init(.light, .standard), .init(.dark, .standard)],
44 settings: settings, screens: Self.screens))
45 #if os(iOS)
46 // The page's text does not scale with Dynamic Type (spec §9); these
47 // prove it at AX3 on the two plain screens, without drawing every
48 // editor screen twice more.
49 await assertSnapshots(of: SnapshotCatalog(app: "docs-editor-ax3", variants: [.init(.light, .accessibility), .init(.dark, .accessibility)],
50 settings: settings, screens: Self.accessibilityScreens))
51 #endif
52 await EditorScreen.stopAll()
53 }
54
55 /// Mac windows are 1000 points wide (the page at its 4:3 magnification
56 /// fits at 100% and is cut at 150%, as in a window that size); the
57 /// iPhone is an iPhone 18 Pro's 402 × 874 and the iPad width an iPad
58 /// Air's 820 × 1180 in portrait, drawn by the same iOS renderer.
59 static let macTop = SnapshotSize.fixed(width: 1000, height: 900)
60 static let macBreak = SnapshotSize.fixed(width: 1000, height: 640)
61 static let phone = SnapshotSize.fixed(width: 402, height: 874)
62 static let pad = SnapshotSize.fixed(width: 820, height: 1180)
63
64 /// Where the page breaks are drawn, in the text view's own points.
65 /// Fixed numbers, never measured at run time: a measured offset would
66 /// follow a moved line and hide the move. The edited screen starts
67 /// higher, at the typed lines.
68 static let editedBreak: CGFloat = 440
69 /// Mac only: the heading break at 150%.
70 static let headingBreak150: CGFloat = 640
71 #if os(macOS)
72 static let headingBreak: CGFloat = 560
73 static let imageBreak: CGFloat = 1250
74 #else
75 static let headingBreak: CGFloat = 560
76 static let imageBreak: CGFloat = 1300
77 #endif
78
79 @MainActor static var screens: [SnapshotScreen] {
80 [
81 screen("editor-paged", mac: macTop, iphone: phone, .millbrook, paged: true),
82 screen("editor-pageless", mac: macTop, iphone: phone, .millbrook, paged: false),
83 // At the top of a page the Mac draws paged and pageless alike,
84 // so 150% shows the Millbrook top once, and the two modes at
85 // the first page break.
86 screen("editor-150", mac: macTop, iphone: nil, .millbrook, paged: true, zoom: 1.5),
87 screen("editor-paged-150-heading-break", mac: macBreak, iphone: nil, .breaks, paged: true, zoom: 1.5, scroll: headingBreak150),
88 screen("editor-pageless-150-heading-break", mac: macBreak, iphone: nil, .breaks, paged: false, zoom: 1.5, scroll: headingBreak150),
89 // The first line after a break: a large heading, then an image.
90 screen("editor-paged-heading-break", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: headingBreak),
91 screen("editor-pageless-heading-break", mac: macBreak, iphone: phone, .breaks, paged: false, scroll: headingBreak),
92 screen("editor-paged-image-break", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: imageBreak),
93 screen("editor-pageless-image-break", mac: macBreak, iphone: phone, .breaks, paged: false, scroll: imageBreak),
94 // Typed through the text view before the first break (a Return
95 // among it, which moves the break), then a peer's insert.
96 screen("editor-paged-edited", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: editedBreak,
97 script: .typeBeforeBreakThenPeer),
98 screen("editor-ar", mac: macTop, iphone: phone, .arabic, paged: true),
99 screen("editor-ru", mac: macTop, iphone: phone, .russian, paged: true),
100 screen("editor-ipad-paged", mac: nil, iphone: pad, .millbrook, paged: true),
101 ]
102 }
103
104 @MainActor static var accessibilityScreens: [SnapshotScreen] {
105 [
106 screen("editor-paged", mac: nil, iphone: phone, .millbrook, paged: true),
107 screen("editor-pageless", mac: nil, iphone: phone, .millbrook, paged: false),
108 ]
109 }
110
111 /// A screen whose editor knows the size the kit will draw it at here.
112 @MainActor static func screen(_ name: String, mac: SnapshotSize?, iphone: SnapshotSize?, _ fixture: EditorFixture,
113 paged: Bool, zoom: Double = 1, scroll: CGFloat = 0, script: EditorScript = .none) -> SnapshotScreen {
114 #if os(macOS)
115 let size = mac
116 #else
117 let size = iphone
118 #endif
119 var window = CGSize.zero
120 if case .fixed(let width, let height)? = size { window = CGSize(width: width, height: height) }
121 return SnapshotScreen(name, mac: mac, iphone: iphone) { [window] in
122 EditorScreen(fixture, window: window, paged: paged, zoom: zoom, scroll: scroll, script: script)
123 }
124 }
125}
126
127// MARK: - The screen
128
129/// What a screen does to its document after it opens.
130enum EditorScript: Sendable {
131 case none
132 /// Types at the end of the 30th ledger line through the text view, with
133 /// a Return among it, waits for it to be saved, then a peer inserts at
134 /// the start of the 34th.
135 case typeBeforeBreakThenPeer
136}
137
138/// One editor screen: the page of a fixture document, opened, rendered,
139/// laid out and scrolled before the counter stops.
140@MainActor struct EditorScreen: View {
141 let fixture: EditorFixture
142 /// The size the kit draws this screen at.
143 let window: CGSize
144 let paged: Bool
145 let zoom: Double
146 let scroll: CGFloat
147 let script: EditorScript
148 /// The S2a window chrome around the page (WindowSnapshots.swift), nil
149 /// for the page alone.
150 var chrome: WindowChrome? = nil
151 @State private var model: DocsModel?
152 @State private var server: EditorServer?
153 @State private var images = DocsImageStore()
154 @State private var ready = false
155 private let probe = ViewProbe()
156
157 init(_ fixture: EditorFixture, window: CGSize, paged: Bool, zoom: Double = 1, scroll: CGFloat = 0, script: EditorScript = .none) {
158 self.fixture = fixture; self.window = window; self.paged = paged; self.zoom = zoom; self.scroll = scroll; self.script = script
159 }
160
161 /// Every model a screen opened, stopped when the run ends.
162 private static var opened: [DocsModel] = []
163 static func stopAll() async {
164 for model in opened { await model.stop() }
165 opened.removeAll()
166 }
167
168 var body: some View {
169 ZStack(alignment: .topLeading) {
170 if let model, let server {
171 #if os(macOS)
172 if let chrome {
173 WindowChromeView(chrome: chrome, model: model) {
174 EditorPage(model: model, images: images, client: server, paged: paged, zoom: zoom, inspector: chrome.inspectorSide)
175 .background { ProbeView(probe: probe) }
176 }
177 } else {
178 EditorPage(model: model, images: images, client: server, paged: paged, zoom: zoom)
179 .background { ProbeView(probe: probe) }
180 }
181 #else
182 EditorPage(model: model, images: images, client: server, paged: paged, zoom: zoom)
183 .background { ProbeView(probe: probe) }
184 #endif
185 }
186 if !ready { OpeningCounter() }
187 }
188 .environment(\.layoutDirection, fixture.direction)
189 .task { await open() }
190 }
191
192 private func open() async {
193 do {
194 let server = EditorServer()
195 if let chrome, chrome.reader { await server.readOnly() }
196 try await server.seed(fixture.blocks)
197 let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied))
198 let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString,
199 connectivity: connectivity, transport: { server })
200 let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account)
201 Self.opened.append(model)
202 await model.open("doc")
203 guard let projection = model.projection else { throw EditorScreenFailure("the fixture did not open") }
204 await images.load(sources: DocsImageStore.sources(in: projection), client: server, documentPath: "/d/doc")
205 EditorPage.link(images, to: model, client: server)
206 self.server = server
207 self.model = model
208 try await until("the stream opened") { await server.openStreams == 1 }
209 try await until("the first render") { model.renderedGeneration == model.projectionGeneration && probe.textView != nil }
210 if case .typeBeforeBreakThenPeer = script { try await typeBeforeBreakThenPeer(model, server, account) }
211 try await settle(model, account)
212 // A document deleted or unshared while open (spec §6 row 1).
213 if chrome?.unavailable == true { model.unavailable = true; model.inputPaused = true }
214 if let key = chrome?.errorKey { model.errorKey = key }
215 try await layOut()
216 await Task.yield()
217 ready = true
218 } catch {
219 // Never ready: the kit reports the screen unsettled and fails.
220 print("editor snapshot \(fixture) did not open: \(error)")
221 }
222 }
223
224 private func settle(_ model: DocsModel, _ account: DocsOfflineAccount) async throws {
225 try await until("everything sent and rendered") {
226 guard !model.hasPendingInput, await account.outbox.summary.isEmpty else { return false }
227 guard model.renderedGeneration == model.projectionGeneration, let projection = model.projection,
228 let shown = probe.textView.map(EditorScreen.string) else { return false }
229 let expected = NativeTextProjection.render(projection).string
230 return shown == expected
231 }
232 }
233
234 private func typeBeforeBreakThenPeer(_ model: DocsModel, _ server: EditorServer, _ account: DocsOfflineAccount) async throws {
235 guard let text = probe.textView, let projection = model.projection else { throw EditorScreenFailure("no text view") }
236 let content = NativeTextProjection.render(projection).string as NSString
237 let line = content.range(of: EditorFixture.ledger(30))
238 guard line.location != NSNotFound else { throw EditorScreenFailure("no 30th ledger line") }
239 var at = NSMaxRange(line)
240 func type(_ characters: String) {
241 for character in characters {
242 let piece = String(character)
243 #if os(macOS)
244 text.setSelectedRange(NSRange(location: at, length: 0))
245 if piece == "\n" { text.insertNewline(nil) } else { text.insertText(piece, replacementRange: text.selectedRange()) }
246 #else
247 // UITextView.insertText called from code skips the delegate,
248 // so the keyboard's path is taken by hand: ask the delegate,
249 // and only if it agrees, edit the storage and move the caret.
250 let range = NSRange(location: at, length: 0)
251 text.selectedRange = range
252 if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true {
253 text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes))
254 text.selectedRange = NSRange(location: at + piece.utf16.count, length: 0)
255 text.delegate?.textViewDidChange?(text)
256 }
257 #endif
258 at += piece.utf16.count
259 }
260 }
261 type(" Typed here.\nAnd a Return.")
262 try await settle(model, account)
263 // The peer types into another block, on screen: the start of the
264 // 34th ledger line.
265 guard let settled = model.projection else { throw EditorScreenFailure("no projection") }
266 let peerAt = (NativeTextProjection.render(settled).string as NSString).range(of: EditorFixture.ledger(34)).location
267 guard peerAt != NSNotFound else { throw EditorScreenFailure("no 34th ledger line") }
268 try await server.peerInsert("A peer’s note. ", at: peerAt)
269 try await until("the peer’s note") {
270 model.projection?.children.contains { $0.plainText.hasPrefix("A peer’s note") } == true
271 }
272 }
273
274 /// Once the kit has sized the window and SwiftUI the text view: the text
275 /// view's own layout, TextKit's for the whole container, then the fixed
276 /// scroll offset. The page's width follows the scroll view's, and a
277 /// layout run before SwiftUI sized it leaves the paper at the minimum
278 /// width (it does in the app too, until the next layout), which would
279 /// make the picture depend on timing.
280 private func layOut() async throws {
281 guard let text = probe.textView, let window = text.window else { throw EditorScreenFailure("no text view") }
282 #if os(macOS)
283 guard let scrollView = text.enclosingScrollView else { throw EditorScreenFailure("no scroll view") }
284 // A Mac with a mouse draws legacy scrollers, with a trackpad overlay
285 // ones: pinned, like the kit pins the accent, so the picture does
286 // not depend on what is plugged in.
287 scrollView.scrollerStyle = .overlay
288 let expected = CGSize(width: self.window.width, height: self.window.height - (chrome == nil ? 0 : WindowChrome.headerHeight))
289 try await until("the scroll view is \(expected)") {
290 window.contentView?.layoutSubtreeIfNeeded()
291 return scrollView.frame.size == expected
292 }
293 text.needsLayout = true
294 text.layoutSubtreeIfNeeded()
295 if let container = text.textContainer { text.layoutManager?.ensureLayout(for: container) }
296 scrollView.contentView.scroll(to: NSPoint(x: 0, y: scroll))
297 scrollView.reflectScrolledClipView(scrollView.contentView)
298 #else
299 try await until("the text view is \(self.window)") {
300 window.layoutIfNeeded()
301 return text.frame.size == self.window
302 }
303 text.setNeedsLayout()
304 text.layoutIfNeeded()
305 // TextKit 2 (S3): never `layoutManager`, which would switch to TextKit 1.
306 if let layout = text.textLayoutManager { layout.ensureLayout(for: layout.documentRange) }
307 text.setContentOffset(CGPoint(x: 0, y: scroll), animated: false)
308 #endif
309 }
310
311 private func until(_ what: String, _ condition: () async -> Bool) async throws {
312 let deadline = ContinuousClock.now + .seconds(2)
313 while await !condition() {
314 guard ContinuousClock.now < deadline else { throw EditorScreenFailure("timed out waiting for \(what)") }
315 try await Task.sleep(for: .milliseconds(5))
316 }
317 }
318
319 #if os(macOS)
320 static func string(_ text: NSTextView) -> String { text.string }
321 #else
322 static func string(_ text: UITextView) -> String { text.text }
323 #endif
324}
325
326/// Changes on every frame until the screen is ready, so the kit can never
327/// take two equal pictures of a half-open one. Its own view, so its ticks
328/// never re-evaluate the editor's body.
329@MainActor private struct OpeningCounter: View {
330 @State private var frame = 0
331 var body: some View {
332 Text(verbatim: "opening \(frame)").padding(4).background(Color.red).foregroundStyle(.white)
333 .task {
334 while !Task.isCancelled {
335 frame &+= 1
336 try? await Task.sleep(for: .milliseconds(10))
337 }
338 }
339 }
340}
341
342struct EditorScreenFailure: Error, CustomStringConvertible {
343 let description: String
344 init(_ description: String) { self.description = description }
345}
346
347/// The page as `DocsWorkspace.editor` draws it: the model's surface in
348/// `DocumentEditorHost`, with the document's images.
349@MainActor struct EditorPage: View {
350 /// Held as `DocsWorkspace` holds it, in `@State`.
351 @State private var model: DocsModel
352 let images: DocsImageStore
353 let client: NativeTransport
354 let paged: Bool
355 let zoom: Double
356 var inspector: DocsDeskLayout.Side? = nil
357
358 init(model: DocsModel, images: DocsImageStore, client: NativeTransport, paged: Bool, zoom: Double, inspector: DocsDeskLayout.Side? = nil) {
359 _model = State(initialValue: model)
360 self.images = images; self.client = client; self.paged = paged; self.zoom = zoom; self.inspector = inspector
361 }
362
363 var body: some View {
364 if model.showsDocument {
365 DocumentEditorHost(surface: model.surface, paged: paged, zoom: zoom, inspector: inspector)
366 .equatable()
367 .id(model.editorIdentity)
368 }
369 }
370
371 /// The images the screen loaded before it opened, handed to the
372 /// surface as `DocsWorkspace` hands them, so the first frame has them.
373 static func link(_ images: DocsImageStore, to model: DocsModel, client: NativeTransport) {
374 let surface = model.surface
375 images.changed = { [weak images] _ in surface.imagesChanged(images?.images(forDocumentPath: "/d/doc", client: client) ?? [:]) }
376 surface.imagesChanged(images.images(forDocumentPath: "/d/doc", client: client))
377 }
378}
379
380// MARK: - Finding the text view
381
382/// Holds the view a `ProbeView` made, so the screen can find the text view
383/// in the same window. Not observed: nothing draws from it.
384@MainActor final class ViewProbe {
385 #if os(macOS)
386 weak var view: NSView?
387 var textView: DocsPagedTextView? { view?.window?.contentView.flatMap { Self.find(in: $0) } }
388 private static func find(in view: NSView) -> DocsPagedTextView? {
389 if let text = view as? DocsPagedTextView { return text }
390 for child in view.subviews { if let text = find(in: child) { return text } }
391 return nil
392 }
393 #else
394 weak var view: UIView?
395 var textView: DocsPagedTextView? { view?.window.flatMap { Self.find(in: $0) } }
396 private static func find(in view: UIView) -> DocsPagedTextView? {
397 if let text = view as? DocsPagedTextView { return text }
398 for child in view.subviews { if let text = find(in: child) { return text } }
399 return nil
400 }
401 #endif
402}
403
404#if os(macOS)
405private struct ProbeView: NSViewRepresentable {
406 let probe: ViewProbe
407 func makeNSView(context: Context) -> NSView { let view = NSView(); probe.view = view; return view }
408 func updateNSView(_ view: NSView, context: Context) {}
409}
410#else
411private struct ProbeView: UIViewRepresentable {
412 let probe: ViewProbe
413 func makeUIView(context: Context) -> UIView { let view = UIView(); probe.view = view; return view }
414 func updateUIView(_ view: UIView, context: Context) {}
415}
416#endif
417
418// MARK: - The server
419
420/// One document, "doc", on the production replica: GET answers its detail
421/// and state, POST commits an update and announces it on the stream, as
422/// handlers.go does. Nothing leaves the process.
423actor EditorServer: NativeTransport {
424 nonisolated let origin = URL(string: "https://docs.snapshot.invalid")!
425 private let replica = CRDTReplica(guid: "editor-snapshots")
426 private var canWrite = true
427 /// The detail answers can_write false: a reader's window.
428 func readOnly() { canWrite = false }
429 private var sequence: Int64 = 0
430 private var rows: [Int64: Data] = [:]
431 private var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:]
432 var openStreams: Int { listeners.count }
433
434 func seed(_ blocks: [JSONValue]) async throws {
435 try await replica.open(update: Data())
436 _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
437 _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)])
438 }
439
440 /// Another client's typing, committed as the next row.
441 func peerInsert(_ text: String, at position: Int) async throws {
442 let peer = CRDTReplica(guid: "editor-snapshots")
443 try await peer.open(update: try await replica.persistentState().state)
444 let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(position)), "length": .number(0), "text": .string(text)])
445 await peer.close()
446 commit(try await apply(update))
447 }
448
449 private func apply(_ update: Data) async throws -> Data { try await replica.apply(update); return update }
450
451 @discardableResult private func commit(_ update: Data) -> Int64 {
452 sequence += 1; rows[sequence] = update
453 for listener in listeners.values { listener.yield(sequence) }
454 return sequence
455 }
456
457 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
458 let route = String(path.split(separator: "?")[0])
459 guard route == "/d/doc" || route.hasPrefix("/d/doc/") else { return NativeResponse(data: Data(), status: 404, headers: [:]) }
460 if method == "POST", route == "/d/doc/updates", let body {
461 let assigned = commit(try await apply(body))
462 return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(assigned)])
463 }
464 if method == "POST" { return NativeResponse(data: Data(), status: 200, headers: [:]) }
465 if route == "/d/doc/updates" {
466 if let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) {
467 let kept = rows.keys.sorted().filter { $0 > since }
468 let highest = kept.last ?? since
469 let data = kept.isEmpty ? Data() : try await replica.mergeUpdates(kept.compactMap { rows[$0] })
470 return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(highest)])
471 }
472 let highest = sequence
473 return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": String(highest)])
474 }
475 let detail = DocumentDetail(sqid: "doc", title: "A History of the Millbrook Waterworks", guid: "editor-snapshots", can_write: canWrite, can_share: canWrite)
476 return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:])
477 }
478
479 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
480 let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1))
481 listeners[id] = events.continuation
482 defer { listeners.removeValue(forKey: id) }
483 try await onOpen(); try await onLine("data: \(sequence)")
484 for await announced in events.stream { try Task.checkCancellation(); try await onLine("data: \(announced)") }
485 }
486
487 func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound }
488}
489
490// MARK: - Fixtures
491
492/// The documents the screens open, as the blocks a paste carries.
493enum EditorFixture: Sendable, CustomStringConvertible {
494 /// The mock-ups' Millbrook document: every block type and mark the
495 /// renderer draws, an image, alignment and three bundled faces.
496 case millbrook
497 /// Width-independent pages: 38 one-line paragraphs fill the first page
498 /// on every platform, so a large heading is the first line of page 2;
499 /// 30 more and then an image make the image the first line of page 3.
500 case breaks
501 /// Arabic, right to left, with an English name in it.
502 case arabic
503 /// Russian: long words and long lines.
504 case russian
505
506 var description: String {
507 switch self { case .millbrook: "millbrook"; case .breaks: "breaks"; case .arabic: "arabic"; case .russian: "russian" }
508 }
509
510 var direction: LayoutDirection { if case .arabic = self { .rightToLeft } else { .leftToRight } }
511
512 static func ledger(_ line: Int) -> String { "Ledger, line \(line): water drawn and paid for." }
513
514 var blocks: [JSONValue] {
515 switch self {
516 case .millbrook:
517 return [
518 heading(1, "A History of the Millbrook Waterworks"),
519 paragraph([run("Compiled for the centenary, ", ["em"]), run("from the town’s own records and the council’s minutes.")]),
520 heading(2, "Early years"),
521 paragraph([run("Before 1887, Millbrook drew its water the way most small towns did: from private wells, a handful of shared pumps on the main street, and a cistern fed by roof runoff. "),
522 run("This worked poorly.", ["strong"]), run(" The town’s health records show "), run("summer fever", ["strong", "em"]), run(" year after year.")]),
523 list("bullet_list", ["Private wells", "Shared pumps on the main street", "Cisterns fed by roof runoff"]),
524 list("ordered_list", ["Survey the creek", "Build the dam", "Lay the mains"], order: "3"),
525 block("blockquote", [paragraph([run("The water is as clear as any in the county, and the town shall own it.")])]),
526 block("code_block", [text([run("reservoir.capacity = 1_200_000 # gallons\nfilter = .slowSand")])]),
527 paragraph([run("The engineer, "), run("Alasdair Reid", ["link": .object(["href": .string("https://example.com/reid")])]),
528 run(", insisted on "), run("slow sand", ["code"]), run(" filtration.")]),
529 paragraph([run("Opened October 1887", ["font_caladea", "size_14"])], attrs: ["align": "center"]),
530 paragraph([image(alt: "The first reservoir, 1887")]),
531 heading(3, "Expansion"),
532 paragraph([run("The population nearly doubled between 1890 and 1910, ", ["font_playfair"]),
533 run("and a second reservoir followed in 1912.", ["font_garamond", "em"])], attrs: ["align": "right"]),
534 paragraph([run("Indented once, as a note on the sources.")], attrs: ["indent": "1"]),
535 block("horizontal_rule", []),
536 heading(4, "Sources"),
537 paragraph([run("Council minutes, 1883–1887.")]),
538 ]
539 case .breaks:
540 var blocks = (1...38).map { paragraph([run(Self.ledger($0))]) }
541 blocks.append(heading(1, "Expansion through the early twentieth century"))
542 blocks += (39...68).map { paragraph([run(Self.ledger($0))]) }
543 blocks.append(paragraph([image(alt: "The second reservoir, 1912")]))
544 blocks += (69...84).map { paragraph([run(Self.ledger($0))]) }
545 return blocks
546 case .arabic:
547 return [
548 heading(1, "تاريخ محطة مياه ميلبروك"),
549 heading(2, "السنوات الأولى"),
550 paragraph([run("قبل عام 1887، كانت ميلبروك تحصل على مياهها كما تفعل معظم البلدات الصغيرة: من آبار خاصة، ومن مضخات مشتركة في الشارع الرئيسي، ومن صهاريج تملؤها مياه الأسطح. "),
551 run("لم ينجح ذلك جيدًا.", ["strong"])]),
552 paragraph([run("أصرّ المهندس "), run("Alasdair Reid"), run(" على الترشيح بالرمل البطيء، فانخفضت الأمراض بعد افتتاح المحطة في أكتوبر 1887.")]),
553 list("bullet_list", ["آبار خاصة", "مضخات مشتركة", "صهاريج مياه الأسطح"]),
554 list("ordered_list", ["مسح الجدول", "بناء السد", "مدّ الأنابيب"]),
555 block("blockquote", [paragraph([run("الماء صافٍ كأي ماء في المقاطعة، وستملكه البلدة.")])]),
556 ]
557 case .russian:
558 return [
559 heading(1, "История миллбрукского водопровода"),
560 heading(2, "Первые годы"),
561 paragraph([run("До 1887 года Миллбрук получал воду так же, как большинство небольших городов: из частных колодцев, нескольких общественных насосов на главной улице и цистерн, наполнявшихся дождевой водой с крыш. "),
562 run("Это работало плохо.", ["strong"])]),
563 paragraph([run("Водоочистительные сооружения, высокопроизводительные фильтры и водораспределительная сеть обсуждались городским советом почти четыре года.")]),
564 list("bullet_list", ["Частные колодцы", "Общественные насосы", "Цистерны для дождевой воды"]),
565 list("ordered_list", ["Обследовать ручей", "Построить плотину", "Проложить магистрали"]),
566 block("blockquote", [paragraph([run("Вода чиста, как нигде в округе, и город будет владеть ею сам.")])]),
567 ]
568 }
569 }
570
571 private func run(_ insert: String, _ marks: [String] = []) -> JSONValue {
572 run(insert, Dictionary(uniqueKeysWithValues: marks.map { ($0, JSONValue.object([:])) }))
573 }
574 private func run(_ insert: String, _ marks: [String: JSONValue]) -> JSONValue {
575 .object(["insert": .string(insert), "marks": .object(marks)])
576 }
577 private func text(_ runs: [JSONValue]) -> JSONValue { .object(["type": .string("text"), "runs": .array(runs)]) }
578 private func paragraph(_ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue {
579 // Runs are grouped into one text node; an image stands alone.
580 var grouped: [JSONValue] = [], runs: [JSONValue] = []
581 for child in children {
582 if case .object(let object) = child, object["insert"] != nil { runs.append(child); continue }
583 if !runs.isEmpty { grouped.append(text(runs)); runs = [] }
584 grouped.append(child)
585 }
586 if !runs.isEmpty { grouped.append(text(runs)) }
587 return block("paragraph", grouped, attrs: attrs)
588 }
589 private func heading(_ level: Int, _ title: String) -> JSONValue {
590 block("heading", [text([run(title)])], attrs: ["level": String(level)])
591 }
592 private func list(_ type: String, _ items: [String], order: String? = nil) -> JSONValue {
593 block(type, items.map { block("list_item", [paragraph([run($0)])]) }, attrs: order.map { ["order": $0] } ?? [:])
594 }
595 private func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue {
596 var object: [String: JSONValue] = ["type": .string(type)]
597 if !children.isEmpty { object["children"] = .array(children) }
598 if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues { .string($0) }) }
599 return .object(object)
600 }
601 private func image(alt: String) -> JSONValue {
602 .object(["type": .string("image"), "attrs": .object(["src": .string(Self.picture), "alt": .string(alt)])])
603 }
604
605 /// A 320 × 180 picture drawn here, so no file or network is involved:
606 /// sky, water, a dam and a sun, in flat colours.
607 static let picture: String = {
608 let width = 320, height = 180
609 let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
610 space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
611 func fill(_ rect: CGRect, _ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) {
612 context.setFillColor(red: red, green: green, blue: blue, alpha: 1); context.fill(rect)
613 }
614 fill(CGRect(x: 0, y: 0, width: 320, height: 180), 0.62, 0.80, 0.93)
615 fill(CGRect(x: 0, y: 0, width: 320, height: 70), 0.16, 0.42, 0.62)
616 fill(CGRect(x: 0, y: 60, width: 320, height: 26), 0.45, 0.40, 0.34)
617 context.setFillColor(red: 0.98, green: 0.80, blue: 0.30, alpha: 1)
618 context.fillEllipse(in: CGRect(x: 236, y: 112, width: 44, height: 44))
619 let data = NSMutableData()
620 let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)!
621 CGImageDestinationAddImage(destination, context.makeImage()!, nil)
622 CGImageDestinationFinalize(destination)
623 return "data:image/png;base64," + (data as Data).base64EncodedString()
624 }()
625}
626