| new file mode 100644 |
| index 0000000..63412f9 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsSnapshots/EditorSnapshots.swift |
| @@ -0,0 +1,616 @@ |
| +import Foundation |
| +import ImageIO |
| +import RastrilloApple |
| +import RastrilloSnapshots |
| +import RastrilloTestSupport |
| +import SwiftUI |
| +import UniformTypeIdentifiers |
| +import XCTest |
| +@testable import DocsKit |
| +#if os(macOS) |
| +import AppKit |
| +#else |
| +import UIKit |
| +#endif |
| + |
| +/// The editor's page, drawn by today's renderer from fixed fixtures, so that |
| +/// rendering work (the native redesign's S1a and S1b) is held to the pixel. |
| +/// Spec 2026-11-22-native-redesign-design.md §11, plan S0. |
| +/// |
| +/// Each screen opens a fixture document through the real path: a replica |
| +/// seeded on an in-memory server, `DocsModel.open`, `NativeTextProjection` |
| +/// and `NativeDocumentTextView` wired as `DocsWorkspace.editor` wires them |
| +/// (the page only: the toolbar, sync row and window chrome are not here). |
| +/// The kit draws a screen once two pictures 50 ms apart agree, and a model |
| +/// answers asynchronously, so a screen shows a counter that changes on |
| +/// every frame until its document is open, rendered, laid out |
| +/// (`ensureLayout` on the container, then a run-loop turn) and scrolled to |
| +/// its fixed offset. A screen that never gets there is reported unsettled |
| +/// and fails; it is never recorded half drawn. |
| +/// |
| +/// Fixed state: the bundled faces are registered first (never a fallback |
| +/// face), the selection is the model's (a caret at 0, or where the script |
| +/// leaves it; on iOS it is pinned, see `EditorPage.selection`), and the |
| +/// text view is never first responder, so no caret or selection is drawn |
| +/// and nothing blinks. No animation or clock is read; the Mac's scrollers |
| +/// are pinned to overlay. |
| +final class DocsEditorSnapshots: XCTestCase { |
| + @MainActor func testEditorScreens() async throws { |
| + try XCTSkipUnless(ProcessInfo.processInfo.environment["RASTRILLO_SNAPSHOTS"] != nil, |
| + "Run with native/scripts/snapshots.sh") |
| + DocsFonts.register() |
| + let settings = SnapshotSettings(tint: OficinaPalette.accent(.docs)) |
| + await assertSnapshots(of: SnapshotCatalog(app: "docs-editor", variants: [.init(.light, .standard), .init(.dark, .standard)], |
| + settings: settings, screens: Self.screens)) |
| + #if os(iOS) |
| + // The page's text does not scale with Dynamic Type (spec §9); these |
| + // prove it at AX3 on the two plain screens, without drawing every |
| + // editor screen twice more. |
| + await assertSnapshots(of: SnapshotCatalog(app: "docs-editor-ax3", variants: [.init(.light, .accessibility), .init(.dark, .accessibility)], |
| + settings: settings, screens: Self.accessibilityScreens)) |
| + #endif |
| + await EditorScreen.stopAll() |
| + } |
| + |
| + /// Mac windows are 1000 points wide (the page at its 4:3 magnification |
| + /// fits at 100% and is cut at 150%, as in a window that size); the |
| + /// iPhone is an iPhone 18 Pro's 402 × 874 and the iPad width an iPad |
| + /// Air's 820 × 1180 in portrait, drawn by the same iOS renderer. |
| + static let macTop = SnapshotSize.fixed(width: 1000, height: 900) |
| + static let macBreak = SnapshotSize.fixed(width: 1000, height: 640) |
| + static let phone = SnapshotSize.fixed(width: 402, height: 874) |
| + static let pad = SnapshotSize.fixed(width: 820, height: 1180) |
| + |
| + /// Where the page breaks are drawn, in the text view's own points. |
| + /// Fixed numbers, never measured at run time: a measured offset would |
| + /// follow a moved line and hide the move. The edited screen starts |
| + /// higher, at the typed lines. |
| + static let editedBreak: CGFloat = 440 |
| + #if os(macOS) |
| + static let headingBreak: CGFloat = 560 |
| + static let imageBreak: CGFloat = 1250 |
| + #else |
| + static let headingBreak: CGFloat = 560 |
| + static let imageBreak: CGFloat = 1300 |
| + #endif |
| + |
| + @MainActor static var screens: [SnapshotScreen] { |
| + [ |
| + screen("editor-paged", mac: macTop, iphone: phone, .millbrook, paged: true), |
| + screen("editor-pageless", mac: macTop, iphone: phone, .millbrook, paged: false), |
| + screen("editor-paged-150", mac: macTop, iphone: nil, .millbrook, paged: true, zoom: 1.5), |
| + screen("editor-pageless-150", mac: macTop, iphone: nil, .millbrook, paged: false, zoom: 1.5), |
| + // The first line after a break: a large heading, then an image. |
| + screen("editor-paged-heading-break", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: headingBreak), |
| + screen("editor-pageless-heading-break", mac: macBreak, iphone: phone, .breaks, paged: false, scroll: headingBreak), |
| + screen("editor-paged-image-break", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: imageBreak), |
| + screen("editor-pageless-image-break", mac: macBreak, iphone: phone, .breaks, paged: false, scroll: imageBreak), |
| + // Typed through the text view before the first break (a Return |
| + // among it, which moves the break), then a peer's insert. |
| + screen("editor-paged-edited", mac: macBreak, iphone: phone, .breaks, paged: true, scroll: editedBreak, |
| + script: .typeBeforeBreakThenPeer), |
| + screen("editor-ar", mac: macTop, iphone: phone, .arabic, paged: true), |
| + screen("editor-ru", mac: macTop, iphone: phone, .russian, paged: true), |
| + screen("editor-ipad-paged", mac: nil, iphone: pad, .millbrook, paged: true), |
| + ] |
| + } |
| + |
| + @MainActor static var accessibilityScreens: [SnapshotScreen] { |
| + [ |
| + screen("editor-paged", mac: nil, iphone: phone, .millbrook, paged: true), |
| + screen("editor-pageless", mac: nil, iphone: phone, .millbrook, paged: false), |
| + ] |
| + } |
| + |
| + /// A screen whose editor knows the size the kit will draw it at here. |
| + @MainActor static func screen(_ name: String, mac: SnapshotSize?, iphone: SnapshotSize?, _ fixture: EditorFixture, |
| + paged: Bool, zoom: Double = 1, scroll: CGFloat = 0, script: EditorScript = .none) -> SnapshotScreen { |
| + #if os(macOS) |
| + let size = mac |
| + #else |
| + let size = iphone |
| + #endif |
| + var window = CGSize.zero |
| + if case .fixed(let width, let height)? = size { window = CGSize(width: width, height: height) } |
| + return SnapshotScreen(name, mac: mac, iphone: iphone) { [window] in |
| + EditorScreen(fixture, window: window, paged: paged, zoom: zoom, scroll: scroll, script: script) |
| + } |
| + } |
| +} |
| + |
| +// MARK: - The screen |
| + |
| +/// What a screen does to its document after it opens. |
| +enum EditorScript: Sendable { |
| + case none |
| + /// Types at the end of the 30th ledger line through the text view, with |
| + /// a Return among it, waits for it to be saved, then a peer inserts at |
| + /// the start of the 34th. |
| + case typeBeforeBreakThenPeer |
| +} |
| + |
| +/// One editor screen: the page of a fixture document, opened, rendered, |
| +/// laid out and scrolled before the counter stops. |
| +@MainActor struct EditorScreen: View { |
| + let fixture: EditorFixture |
| + /// The size the kit draws this screen at. |
| + let window: CGSize |
| + let paged: Bool |
| + let zoom: Double |
| + let scroll: CGFloat |
| + let script: EditorScript |
| + @State private var model: DocsModel? |
| + @State private var server: EditorServer? |
| + @State private var images = DocsImageStore() |
| + @State private var ready = false |
| + private let probe = ViewProbe() |
| + |
| + init(_ fixture: EditorFixture, window: CGSize, paged: Bool, zoom: Double = 1, scroll: CGFloat = 0, script: EditorScript = .none) { |
| + self.fixture = fixture; self.window = window; self.paged = paged; self.zoom = zoom; self.scroll = scroll; self.script = script |
| + } |
| + |
| + /// Every model a screen opened, stopped when the run ends. |
| + private static var opened: [DocsModel] = [] |
| + static func stopAll() async { |
| + for model in opened { await model.stop() } |
| + opened.removeAll() |
| + } |
| + |
| + var body: some View { |
| + ZStack(alignment: .topLeading) { |
| + if let model, let server { |
| + EditorPage(model: model, images: images, client: server, paged: paged, zoom: zoom) |
| + .background { ProbeView(probe: probe) } |
| + } |
| + if !ready { OpeningCounter() } |
| + } |
| + .environment(\.layoutDirection, fixture.direction) |
| + .task { await open() } |
| + } |
| + |
| + private func open() async { |
| + do { |
| + let server = EditorServer() |
| + try await server.seed(fixture.blocks) |
| + let connectivity = NativeConnectivity(source: ScriptedPathSource(.satisfied)) |
| + let account = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, |
| + connectivity: connectivity, transport: { server }) |
| + let model = DocsModel(transport: { server }, connectivity: connectivity, offlineAccount: account) |
| + Self.opened.append(model) |
| + await model.open("doc") |
| + guard let projection = model.projection else { throw EditorScreenFailure("the fixture did not open") } |
| + await images.load(sources: DocsImageStore.sources(in: projection), client: server, documentPath: "/d/doc") |
| + self.server = server |
| + self.model = model |
| + try await until("the stream opened") { await server.openStreams == 1 } |
| + try await until("the first render") { model.renderedGeneration == model.projectionGeneration && probe.textView != nil } |
| + if case .typeBeforeBreakThenPeer = script { try await typeBeforeBreakThenPeer(model, server, account) } |
| + try await settle(model, account) |
| + try await layOut() |
| + await Task.yield() |
| + ready = true |
| + } catch { |
| + // Never ready: the kit reports the screen unsettled and fails. |
| + print("editor snapshot \(fixture) did not open: \(error)") |
| + } |
| + } |
| + |
| + private func settle(_ model: DocsModel, _ account: DocsOfflineAccount) async throws { |
| + try await until("everything sent and rendered") { |
| + guard !model.hasPendingInput, await account.outbox.summary.isEmpty else { return false } |
| + guard model.renderedGeneration == model.projectionGeneration, let projection = model.projection, |
| + let shown = probe.textView.map(EditorScreen.string) else { return false } |
| + let expected = NativeTextProjection.render(projection).string |
| + return shown == expected |
| + } |
| + } |
| + |
| + private func typeBeforeBreakThenPeer(_ model: DocsModel, _ server: EditorServer, _ account: DocsOfflineAccount) async throws { |
| + guard let text = probe.textView, let projection = model.projection else { throw EditorScreenFailure("no text view") } |
| + let content = NativeTextProjection.render(projection).string as NSString |
| + let line = content.range(of: EditorFixture.ledger(30)) |
| + guard line.location != NSNotFound else { throw EditorScreenFailure("no 30th ledger line") } |
| + var at = NSMaxRange(line) |
| + func type(_ characters: String) { |
| + for character in characters { |
| + let piece = String(character) |
| + #if os(macOS) |
| + text.setSelectedRange(NSRange(location: at, length: 0)) |
| + if piece == "\n" { text.insertNewline(nil) } else { text.insertText(piece, replacementRange: text.selectedRange()) } |
| + #else |
| + // UITextView.insertText called from code skips the delegate, |
| + // so the keyboard's path is taken by hand: ask the delegate, |
| + // and only if it agrees, edit the storage and move the caret. |
| + let range = NSRange(location: at, length: 0) |
| + text.selectedRange = range |
| + if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true { |
| + text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes)) |
| + text.selectedRange = NSRange(location: at + piece.utf16.count, length: 0) |
| + text.delegate?.textViewDidChange?(text) |
| + } |
| + #endif |
| + at += piece.utf16.count |
| + } |
| + } |
| + type(" Typed here.\nAnd a Return.") |
| + try await settle(model, account) |
| + // The peer types into another block, on screen: the start of the |
| + // 34th ledger line. |
| + guard let settled = model.projection else { throw EditorScreenFailure("no projection") } |
| + let peerAt = (NativeTextProjection.render(settled).string as NSString).range(of: EditorFixture.ledger(34)).location |
| + guard peerAt != NSNotFound else { throw EditorScreenFailure("no 34th ledger line") } |
| + try await server.peerInsert("A peer’s note. ", at: peerAt) |
| + try await until("the peer’s note") { |
| + model.projection?.children.contains { $0.plainText.hasPrefix("A peer’s note") } == true |
| + } |
| + } |
| + |
| + /// Once the kit has sized the window and SwiftUI the text view: the text |
| + /// view's own layout, TextKit's for the whole container, then the fixed |
| + /// scroll offset. The page's width follows the scroll view's, and a |
| + /// layout run before SwiftUI sized it leaves the paper at the minimum |
| + /// width (it does in the app too, until the next layout), which would |
| + /// make the picture depend on timing. |
| + private func layOut() async throws { |
| + guard let text = probe.textView, let window = text.window else { throw EditorScreenFailure("no text view") } |
| + #if os(macOS) |
| + guard let scrollView = text.enclosingScrollView else { throw EditorScreenFailure("no scroll view") } |
| + // A Mac with a mouse draws legacy scrollers, with a trackpad overlay |
| + // ones: pinned, like the kit pins the accent, so the picture does |
| + // not depend on what is plugged in. |
| + scrollView.scrollerStyle = .overlay |
| + try await until("the scroll view is \(self.window)") { |
| + window.contentView?.layoutSubtreeIfNeeded() |
| + return scrollView.frame.size == self.window |
| + } |
| + text.needsLayout = true |
| + text.layoutSubtreeIfNeeded() |
| + if let container = text.textContainer { text.layoutManager?.ensureLayout(for: container) } |
| + scrollView.contentView.scroll(to: NSPoint(x: 0, y: scroll)) |
| + scrollView.reflectScrolledClipView(scrollView.contentView) |
| + #else |
| + try await until("the text view is \(self.window)") { |
| + window.layoutIfNeeded() |
| + return text.frame.size == self.window |
| + } |
| + text.setNeedsLayout() |
| + text.layoutIfNeeded() |
| + text.layoutManager.ensureLayout(for: text.textContainer) |
| + text.setContentOffset(CGPoint(x: 0, y: scroll), animated: false) |
| + #endif |
| + } |
| + |
| + private func until(_ what: String, _ condition: () async -> Bool) async throws { |
| + let deadline = ContinuousClock.now + .seconds(2) |
| + while await !condition() { |
| + guard ContinuousClock.now < deadline else { throw EditorScreenFailure("timed out waiting for \(what)") } |
| + try await Task.sleep(for: .milliseconds(5)) |
| + } |
| + } |
| + |
| + #if os(macOS) |
| + static func string(_ text: NSTextView) -> String { text.string } |
| + #else |
| + static func string(_ text: UITextView) -> String { text.text } |
| + #endif |
| +} |
| + |
| +/// Changes on every frame until the screen is ready, so the kit can never |
| +/// take two equal pictures of a half-open one. Its own view, so its ticks |
| +/// never re-evaluate the editor's body (on iOS each would re-assign the |
| +/// text view's whole text: see the S0 discussion). |
| +@MainActor private struct OpeningCounter: View { |
| + @State private var frame = 0 |
| + var body: some View { |
| + Text(verbatim: "opening \(frame)").padding(4).background(Color.red).foregroundStyle(.white) |
| + .task { |
| + while !Task.isCancelled { |
| + frame &+= 1 |
| + try? await Task.sleep(for: .milliseconds(10)) |
| + } |
| + } |
| + } |
| +} |
| + |
| +struct EditorScreenFailure: Error, CustomStringConvertible { |
| + let description: String |
| + init(_ description: String) { self.description = description } |
| +} |
| + |
| +/// The page as `DocsWorkspace.editor` draws it: the projection rendered with |
| +/// its images, in `NativeDocumentTextView`, wired to the model. |
| +@MainActor private struct EditorPage: View { |
| + /// Held as `DocsWorkspace` holds it, in `@State`. |
| + @State private var model: DocsModel |
| + let images: DocsImageStore |
| + let client: NativeTransport |
| + let paged: Bool |
| + let zoom: Double |
| + |
| + init(model: DocsModel, images: DocsImageStore, client: NativeTransport, paged: Bool, zoom: Double) { |
| + _model = State(initialValue: model) |
| + self.images = images; self.client = client; self.paged = paged; self.zoom = zoom |
| + } |
| + |
| + /// The model's selection, as `DocsWorkspace` binds it, on the Mac. On |
| + /// iOS the text view's writes are dropped and the caret stays where the |
| + /// model has it: through the real binding, today's iOS coordinator |
| + /// writes the selection while it applies a render (assigning |
| + /// `attributedText` moves the caret to the end and back), and when |
| + /// `applyRender` then finds the content unequal to what it drew (any |
| + /// list or attachment does) the next `updateUIView` assigns it again, |
| + /// without end. `DocsWorkspace` hangs the same way in the simulator |
| + /// opening a document with a list (S0 discussion). A fixed selection is |
| + /// what these pictures want anyway; the loop is for its own fix. |
| + private var selection: Binding<NSRange> { |
| + #if os(macOS) |
| + $model.selection |
| + #else |
| + .constant(model.selection) |
| + #endif |
| + } |
| + |
| + var body: some View { |
| + if let projection = model.projection { |
| + let documentPath = "/d/" + (model.detail?.sqid ?? "") |
| + let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: client)) |
| + NativeDocumentTextView(content: text, generation: model.projectionGeneration, didRender: model.didRender, |
| + compositionChanged: model.compositionChanged, |
| + isEditable: model.detail?.can_write == true && !model.inputPaused, paged: paged, |
| + pendingInput: model.hasPendingInput, canRender: model.canRender, |
| + currentSelection: model.currentSelection, selection: selection, edit: model.enqueue, |
| + action: { DocumentCommands(model: model, content: text).perform($0) }, |
| + selectionMoved: model.selectionMovedExplicitly, |
| + canAction: { action in |
| + model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputPaused |
| + && (action == "undo" ? projection.canUndo : projection.canRedo) |
| + }, |
| + explicitCommandRevision: model.explicitCommandRevision, zoom: zoom, typingMarks: model.typingMarks) |
| + .id(model.editorIdentity) |
| + } |
| + } |
| +} |
| + |
| +// MARK: - Finding the text view |
| + |
| +/// Holds the view a `ProbeView` made, so the screen can find the text view |
| +/// in the same window. Not observed: nothing draws from it. |
| +@MainActor final class ViewProbe { |
| + #if os(macOS) |
| + weak var view: NSView? |
| + var textView: DocsPagedTextView? { view?.window?.contentView.flatMap { Self.find(in: $0) } } |
| + private static func find(in view: NSView) -> DocsPagedTextView? { |
| + if let text = view as? DocsPagedTextView { return text } |
| + for child in view.subviews { if let text = find(in: child) { return text } } |
| + return nil |
| + } |
| + #else |
| + weak var view: UIView? |
| + var textView: DocsPagedTextView? { view?.window.flatMap { Self.find(in: $0) } } |
| + private static func find(in view: UIView) -> DocsPagedTextView? { |
| + if let text = view as? DocsPagedTextView { return text } |
| + for child in view.subviews { if let text = find(in: child) { return text } } |
| + return nil |
| + } |
| + #endif |
| +} |
| + |
| +#if os(macOS) |
| +private struct ProbeView: NSViewRepresentable { |
| + let probe: ViewProbe |
| + func makeNSView(context: Context) -> NSView { let view = NSView(); probe.view = view; return view } |
| + func updateNSView(_ view: NSView, context: Context) {} |
| +} |
| +#else |
| +private struct ProbeView: UIViewRepresentable { |
| + let probe: ViewProbe |
| + func makeUIView(context: Context) -> UIView { let view = UIView(); probe.view = view; return view } |
| + func updateUIView(_ view: UIView, context: Context) {} |
| +} |
| +#endif |
| + |
| +// MARK: - The server |
| + |
| +/// One document, "doc", on the production replica: GET answers its detail |
| +/// and state, POST commits an update and announces it on the stream, as |
| +/// handlers.go does. Nothing leaves the process. |
| +actor EditorServer: NativeTransport { |
| + nonisolated let origin = URL(string: "https://docs.snapshot.invalid")! |
| + private let replica = CRDTReplica(guid: "editor-snapshots") |
| + private var sequence: Int64 = 0 |
| + private var rows: [Int64: Data] = [:] |
| + private var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:] |
| + var openStreams: Int { listeners.count } |
| + |
| + func seed(_ blocks: [JSONValue]) async throws { |
| + try await replica.open(update: Data()) |
| + _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| + _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) |
| + } |
| + |
| + /// Another client's typing, committed as the next row. |
| + func peerInsert(_ text: String, at position: Int) async throws { |
| + let peer = CRDTReplica(guid: "editor-snapshots") |
| + try await peer.open(update: try await replica.persistentState().state) |
| + let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(position)), "length": .number(0), "text": .string(text)]) |
| + await peer.close() |
| + commit(try await apply(update)) |
| + } |
| + |
| + private func apply(_ update: Data) async throws -> Data { try await replica.apply(update); return update } |
| + |
| + @discardableResult private func commit(_ update: Data) -> Int64 { |
| + sequence += 1; rows[sequence] = update |
| + for listener in listeners.values { listener.yield(sequence) } |
| + return sequence |
| + } |
| + |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + let route = String(path.split(separator: "?")[0]) |
| + guard route == "/d/doc" || route.hasPrefix("/d/doc/") else { return NativeResponse(data: Data(), status: 404, headers: [:]) } |
| + if method == "POST", route == "/d/doc/updates", let body { |
| + let assigned = commit(try await apply(body)) |
| + return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(assigned)]) |
| + } |
| + if method == "POST" { return NativeResponse(data: Data(), status: 200, headers: [:]) } |
| + if route == "/d/doc/updates" { |
| + if let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) { |
| + let kept = rows.keys.sorted().filter { $0 > since } |
| + let highest = kept.last ?? since |
| + let data = kept.isEmpty ? Data() : try await replica.mergeUpdates(kept.compactMap { rows[$0] }) |
| + return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(highest)]) |
| + } |
| + let highest = sequence |
| + return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": String(highest)]) |
| + } |
| + let detail = DocumentDetail(sqid: "doc", title: "A History of the Millbrook Waterworks", guid: "editor-snapshots", can_write: true, can_share: false) |
| + return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| + } |
| + |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1)) |
| + listeners[id] = events.continuation |
| + defer { listeners.removeValue(forKey: id) } |
| + try await onOpen(); try await onLine("data: \(sequence)") |
| + for await announced in events.stream { try Task.checkCancellation(); try await onLine("data: \(announced)") } |
| + } |
| + |
| + func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| +} |
| + |
| +// MARK: - Fixtures |
| + |
| +/// The documents the screens open, as the blocks a paste carries. |
| +enum EditorFixture: Sendable, CustomStringConvertible { |
| + /// The mock-ups' Millbrook document: every block type and mark the |
| + /// renderer draws, an image, alignment and three bundled faces. |
| + case millbrook |
| + /// Width-independent pages: 38 one-line paragraphs fill the first page |
| + /// on every platform, so a large heading is the first line of page 2; |
| + /// 30 more and then an image make the image the first line of page 3. |
| + case breaks |
| + /// Arabic, right to left, with an English name in it. |
| + case arabic |
| + /// Russian: long words and long lines. |
| + case russian |
| + |
| + var description: String { |
| + switch self { case .millbrook: "millbrook"; case .breaks: "breaks"; case .arabic: "arabic"; case .russian: "russian" } |
| + } |
| + |
| + var direction: LayoutDirection { if case .arabic = self { .rightToLeft } else { .leftToRight } } |
| + |
| + static func ledger(_ line: Int) -> String { "Ledger, line \(line): water drawn and paid for." } |
| + |
| + var blocks: [JSONValue] { |
| + switch self { |
| + case .millbrook: |
| + return [ |
| + heading(1, "A History of the Millbrook Waterworks"), |
| + paragraph([run("Compiled for the centenary, ", ["em"]), run("from the town’s own records and the council’s minutes.")]), |
| + heading(2, "Early years"), |
| + 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. "), |
| + run("This worked poorly.", ["strong"]), run(" The town’s health records show "), run("summer fever", ["strong", "em"]), run(" year after year.")]), |
| + list("bullet_list", ["Private wells", "Shared pumps on the main street", "Cisterns fed by roof runoff"]), |
| + list("ordered_list", ["Survey the creek", "Build the dam", "Lay the mains"], order: "3"), |
| + block("blockquote", [paragraph([run("The water is as clear as any in the county, and the town shall own it.")])]), |
| + block("code_block", [text([run("reservoir.capacity = 1_200_000 # gallons\nfilter = .slowSand")])]), |
| + paragraph([run("The engineer, "), run("Alasdair Reid", ["link": .object(["href": .string("https://example.com/reid")])]), |
| + run(", insisted on "), run("slow sand", ["code"]), run(" filtration.")]), |
| + paragraph([run("Opened October 1887", ["font_caladea", "size_14"])], attrs: ["align": "center"]), |
| + paragraph([image(alt: "The first reservoir, 1887")]), |
| + heading(3, "Expansion"), |
| + paragraph([run("The population nearly doubled between 1890 and 1910, ", ["font_playfair"]), |
| + run("and a second reservoir followed in 1912.", ["font_garamond", "em"])], attrs: ["align": "right"]), |
| + paragraph([run("Indented once, as a note on the sources.")], attrs: ["indent": "1"]), |
| + block("horizontal_rule", []), |
| + heading(4, "Sources"), |
| + paragraph([run("Council minutes, 1883–1887.")]), |
| + ] |
| + case .breaks: |
| + var blocks = (1...38).map { paragraph([run(Self.ledger($0))]) } |
| + blocks.append(heading(1, "Expansion through the early twentieth century")) |
| + blocks += (39...68).map { paragraph([run(Self.ledger($0))]) } |
| + blocks.append(paragraph([image(alt: "The second reservoir, 1912")])) |
| + blocks += (69...84).map { paragraph([run(Self.ledger($0))]) } |
| + return blocks |
| + case .arabic: |
| + return [ |
| + heading(1, "تاريخ محطة مياه ميلبروك"), |
| + heading(2, "السنوات الأولى"), |
| + paragraph([run("قبل عام 1887، كانت ميلبروك تحصل على مياهها كما تفعل معظم البلدات الصغيرة: من آبار خاصة، ومن مضخات مشتركة في الشارع الرئيسي، ومن صهاريج تملؤها مياه الأسطح. "), |
| + run("لم ينجح ذلك جيدًا.", ["strong"])]), |
| + paragraph([run("أصرّ المهندس "), run("Alasdair Reid"), run(" على الترشيح بالرمل البطيء، فانخفضت الأمراض بعد افتتاح المحطة في أكتوبر 1887.")]), |
| + list("bullet_list", ["آبار خاصة", "مضخات مشتركة", "صهاريج مياه الأسطح"]), |
| + list("ordered_list", ["مسح الجدول", "بناء السد", "مدّ الأنابيب"]), |
| + block("blockquote", [paragraph([run("الماء صافٍ كأي ماء في المقاطعة، وستملكه البلدة.")])]), |
| + ] |
| + case .russian: |
| + return [ |
| + heading(1, "История миллбрукского водопровода"), |
| + heading(2, "Первые годы"), |
| + paragraph([run("До 1887 года Миллбрук получал воду так же, как большинство небольших городов: из частных колодцев, нескольких общественных насосов на главной улице и цистерн, наполнявшихся дождевой водой с крыш. "), |
| + run("Это работало плохо.", ["strong"])]), |
| + paragraph([run("Водоочистительные сооружения, высокопроизводительные фильтры и водораспределительная сеть обсуждались городским советом почти четыре года.")]), |
| + list("bullet_list", ["Частные колодцы", "Общественные насосы", "Цистерны для дождевой воды"]), |
| + list("ordered_list", ["Обследовать ручей", "Построить плотину", "Проложить магистрали"]), |
| + block("blockquote", [paragraph([run("Вода чиста, как нигде в округе, и город будет владеть ею сам.")])]), |
| + ] |
| + } |
| + } |
| + |
| + private func run(_ insert: String, _ marks: [String] = []) -> JSONValue { |
| + run(insert, Dictionary(uniqueKeysWithValues: marks.map { ($0, JSONValue.object([:])) })) |
| + } |
| + private func run(_ insert: String, _ marks: [String: JSONValue]) -> JSONValue { |
| + .object(["insert": .string(insert), "marks": .object(marks)]) |
| + } |
| + private func text(_ runs: [JSONValue]) -> JSONValue { .object(["type": .string("text"), "runs": .array(runs)]) } |
| + private func paragraph(_ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { |
| + // Runs are grouped into one text node; an image stands alone. |
| + var grouped: [JSONValue] = [], runs: [JSONValue] = [] |
| + for child in children { |
| + if case .object(let object) = child, object["insert"] != nil { runs.append(child); continue } |
| + if !runs.isEmpty { grouped.append(text(runs)); runs = [] } |
| + grouped.append(child) |
| + } |
| + if !runs.isEmpty { grouped.append(text(runs)) } |
| + return block("paragraph", grouped, attrs: attrs) |
| + } |
| + private func heading(_ level: Int, _ title: String) -> JSONValue { |
| + block("heading", [text([run(title)])], attrs: ["level": String(level)]) |
| + } |
| + private func list(_ type: String, _ items: [String], order: String? = nil) -> JSONValue { |
| + block(type, items.map { block("list_item", [paragraph([run($0)])]) }, attrs: order.map { ["order": $0] } ?? [:]) |
| + } |
| + private func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { |
| + var object: [String: JSONValue] = ["type": .string(type)] |
| + if !children.isEmpty { object["children"] = .array(children) } |
| + if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues { .string($0) }) } |
| + return .object(object) |
| + } |
| + private func image(alt: String) -> JSONValue { |
| + .object(["type": .string("image"), "attrs": .object(["src": .string(Self.picture), "alt": .string(alt)])]) |
| + } |
| + |
| + /// A 320 × 180 picture drawn here, so no file or network is involved: |
| + /// sky, water, a dam and a sun, in flat colours. |
| + static let picture: String = { |
| + let width = 320, height = 180 |
| + let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, |
| + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! |
| + func fill(_ rect: CGRect, _ red: CGFloat, _ green: CGFloat, _ blue: CGFloat) { |
| + context.setFillColor(red: red, green: green, blue: blue, alpha: 1); context.fill(rect) |
| + } |
| + fill(CGRect(x: 0, y: 0, width: 320, height: 180), 0.62, 0.80, 0.93) |
| + fill(CGRect(x: 0, y: 0, width: 320, height: 70), 0.16, 0.42, 0.62) |
| + fill(CGRect(x: 0, y: 60, width: 320, height: 26), 0.45, 0.40, 0.34) |
| + context.setFillColor(red: 0.98, green: 0.80, blue: 0.30, alpha: 1) |
| + context.fillEllipse(in: CGRect(x: 236, y: 112, width: 44, height: 44)) |
| + let data = NSMutableData() |
| + let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)! |
| + CGImageDestinationAddImage(destination, context.makeImage()!, nil) |
| + CGImageDestinationFinalize(destination) |
| + return "data:image/png;base64," + (data as Data).base64EncodedString() |
| + }() |
| +} |