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 Foundation
4import Observation
5import RastrilloApple
6import RastrilloNative
7import SwiftUI
8import XCTest
9@testable import DocsKit
10
11/// The S2a document window, hosted in a real titled window with SwiftUI's
12/// toolbar and title bridged into it (spec §11, hosted-window tests): one
13/// title, the page placed by the centring rule at the six widths with the
14/// inspector open and closed, the inspector's app-wide state, and a
15/// reader's window, which never shows the inspector nor writes its state.
16@MainActor final class DocumentWindowChromeTests: XCTestCase {
17 override func setUp() async throws { UserDefaults.standard.removeObject(forKey: DocsInspectorState.key) }
18 override func tearDown() async throws { UserDefaults.standard.removeObject(forKey: DocsInspectorState.key) }
19
20 private struct Hosted {
21 let window: NSWindow
22 let server: ChromeServer
23 var text: DocsPagedTextView? { Self.find(window.contentView) }
24 static func find(_ view: NSView?) -> DocsPagedTextView? {
25 guard let view else { return nil }
26 if let text = view as? DocsPagedTextView { return text }
27 return view.subviews.lazy.compactMap(find).first
28 }
29 }
30
31 private func host(canWrite: Bool = true, width: CGFloat = 1120) async throws -> Hosted {
32 let server = ChromeServer(canWrite: canWrite)
33 try await server.seed()
34 let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", team: "Tito")
35 let controller = NSHostingController(rootView: workspace)
36 controller.sceneBridgingOptions = [.toolbars, .title]
37 // The window's size is the test's, not the content's ideal size.
38 controller.sizingOptions = []
39 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: 800),
40 styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
41 window.isReleasedWhenClosed = false
42 window.contentViewController = controller
43 window.setContentSize(NSSize(width: width, height: 800))
44 window.orderFrontRegardless()
45 let hosted = Hosted(window: window, server: server)
46 try await until("the document opened") { hosted.text.map { !$0.string.isEmpty } == true }
47 hosted.text?.enclosingScrollView?.scrollerStyle = .overlay
48 await pump(0.3)
49 return hosted
50 }
51
52 private func close(_ hosted: Hosted) async {
53 hosted.window.orderOut(nil)
54 hosted.window.contentViewController = nil
55 await pump(0.1)
56 }
57
58 private func pump(_ seconds: Double) async {
59 let end = Date().addingTimeInterval(seconds)
60 while Date() < end {
61 NSApp?.windows.forEach { $0.contentView?.layoutSubtreeIfNeeded() }
62 try? await Task.sleep(for: .milliseconds(10))
63 }
64 }
65
66 private func until(_ what: String, _ condition: () -> Bool) async throws {
67 let deadline = Date().addingTimeInterval(10)
68 while !condition() {
69 guard Date() < deadline else { throw XCTSkip("timed out waiting for \(what)") }
70 await pump(0.02)
71 }
72 }
73
74 /// The page's left edge and the clip view's width, in window points.
75 private func measure(_ hosted: Hosted) throws -> (x: CGFloat, width: CGFloat, page: CGFloat) {
76 let text = try XCTUnwrap(hosted.text)
77 let scroll = try XCTUnwrap(text.enclosingScrollView)
78 hosted.window.contentView?.layoutSubtreeIfNeeded()
79 let clip = scroll.contentView.convert(scroll.contentView.bounds, to: nil)
80 let page = text.convert(text.bounds, to: nil)
81 return (page.minX - clip.minX, clip.width, page.width)
82 }
83
84 func testOneTitleDrawnByDocsAndTheWindowTitleIsTheDocuments() async throws {
85 let hosted = try await host()
86 defer { Task { await close(hosted) } }
87 XCTAssertEqual(hosted.window.title, "Chrome test", "the Window menu, tabs and VoiceOver read the document's title")
88 XCTAssertEqual(hosted.window.titleVisibility, .hidden, "the system does not draw it a second time")
89 let toolbar = try XCTUnwrap(hosted.window.toolbar, "the header is in the window's toolbar")
90 XCTAssertTrue(toolbar.centeredItemIdentifiers.isEmpty, "no .principal item: it drew the title twice")
91 XCTAssertGreaterThanOrEqual(toolbar.items.count, 3, "the title area, a flexible space and the controls")
92 XCTAssertEqual(hosted.window.tab.title, "Chrome test")
93 }
94
95 /// Spec §1 page centring, finding 5: the page's frame in window points
96 /// at W = 1800, 1440, 1280, 1108, 1000 and 920, open and closed.
97 func testThePageFollowsTheCentringRuleAtTheSixWidths() async throws {
98 let hosted = try await host()
99 defer { Task { await close(hosted) } }
100 let text = try XCTUnwrap(hosted.text)
101 let container = text.textContainer?.size
102 for open in [true, false] {
103 UserDefaults.standard.set(open, forKey: DocsInspectorState.key)
104 for target in [1800, 1440, 1280, 1108, 1000, 920] as [CGFloat] {
105 hosted.window.setContentSize(NSSize(width: target, height: 800))
106 await pump(0.15)
107 let measured = try measure(hosted)
108 let expected = DocsDeskLayout.pageX(width: measured.width, page: measured.page, inspector: open ? .right : nil)
109 XCTAssertEqual(measured.x, expected, accuracy: 0.5, "W \(measured.width) (asked \(target)), inspector \(open ? "open" : "closed")")
110 XCTAssertEqual(measured.page, 612 * 4 / 3, accuracy: 0.5, "the page never shrinks")
111 }
112 }
113 XCTAssertEqual(text.textContainer?.size, container, "moving the page never changes the text's geometry")
114 }
115
116 /// ⌥⌘I flips one app-wide state: every open window follows it.
117 func testTheInspectorStateIsAppWide() async throws {
118 let first = try await host(width: 1280)
119 let second = try await host(width: 1280)
120 defer { Task { await close(first); await close(second) } }
121 XCTAssertNil(UserDefaults.standard.object(forKey: DocsInspectorState.key), "nothing written on open")
122 let openX = try (measure(first).x, measure(second).x)
123 UserDefaults.standard.set(false, forKey: DocsInspectorState.key)
124 await pump(0.3)
125 let closedX = try (measure(first).x, measure(second).x)
126 XCTAssertNotEqual(openX.0, closedX.0, accuracy: 1, "the first window's page moved")
127 XCTAssertNotEqual(openX.1, closedX.1, accuracy: 1, "and the second's")
128 }
129
130 /// A reader never sees the inspector, whatever the stored state, and
131 /// their window does not write it.
132 func testAReaderNeverSeesTheInspector() async throws {
133 UserDefaults.standard.set(true, forKey: DocsInspectorState.key)
134 let hosted = try await host(canWrite: false, width: 1280)
135 defer { Task { await close(hosted) } }
136 let measured = try measure(hosted)
137 XCTAssertEqual(measured.x, DocsDeskLayout.pageX(width: measured.width, page: measured.page, inspector: nil), accuracy: 0.5,
138 "centred as if closed: no inspector over the desk")
139 XCTAssertEqual(UserDefaults.standard.object(forKey: DocsInspectorState.key) as? Bool, true, "the reader's window wrote nothing")
140 XCTAssertFalse(try XCTUnwrap(hosted.text).isEditable)
141 }
142
143 /// Row 9's debounce: "Saving…" only after a whole second not saved, and
144 /// every return to saved restarts the clock.
145 func testSavingShowsOnlyAfterASecondAndRestartsOnSaved() async throws {
146 let state = SubtitleState()
147 var rows: [DocsSubtitleRow] = []
148 let view = SubtitleHost(state: state) { rows.append($0) }
149 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 40), styleMask: [.titled], backing: .buffered, defer: false)
150 window.isReleasedWhenClosed = false
151 window.contentView = NSHostingView(rootView: view)
152 window.orderFrontRegardless()
153 defer { window.orderOut(nil); window.contentView = nil }
154 await pump(0.2)
155 XCTAssertEqual(rows.last, .saved)
156 state.status = .saving
157 await pump(0.6)
158 XCTAssertEqual(rows.last, .saved, "not yet a second")
159 state.status = .saved
160 await pump(0.1)
161 state.status = .saving
162 await pump(0.6)
163 XCTAssertEqual(rows.last, .saved, "the clock restarted on .saved")
164 await pump(0.7)
165 XCTAssertEqual(rows.last, .saving, "a whole second not saved")
166 state.status = .saved
167 await pump(0.1)
168 XCTAssertEqual(rows.last, .saved)
169 state.status = .offline(pending: 2)
170 await pump(0.1)
171 XCTAssertEqual(rows.last, .offline(pending: 2), "rows 1–8 show at once")
172 }
173}
174
175@MainActor @Observable private final class SubtitleState { var status: SyncStatus = .saved }
176private struct SubtitleHost: View {
177 let state: SubtitleState
178 let observe: (DocsSubtitleRow) -> Void
179 var body: some View {
180 DocsSubtitleBody(status: state.status, access: .writable, loading: false, draft: false, team: "Tito", observe: observe)
181 }
182}
183
184/// One document, "doc": GET answers its detail (with the test's can_write)
185/// and state; POSTs are taken; the stream announces nothing.
186actor ChromeServer: NativeTransport {
187 nonisolated let origin = URL(string: "https://docs.chrome.invalid")!
188 private let replica = CRDTReplica(guid: "chrome")
189 private let canWrite: Bool
190 init(canWrite: Bool) { self.canWrite = canWrite }
191
192 func seed() async throws {
193 try await replica.open(update: Data())
194 _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
195 let runs: JSONValue = .array([.object(["insert": .string("A page on the desk, placed by the web's rule."), "marks": .object([:])])])
196 let paragraph: JSONValue = .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": runs])])])
197 _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array([paragraph])])
198 }
199
200 func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
201 let route = String(path.split(separator: "?")[0])
202 if method == "POST" { return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": "1"]) }
203 if route == "/d/doc/updates" {
204 return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": "0"])
205 }
206 if route == "/d/doc" {
207 let detail = DocumentDetail(sqid: "doc", title: "Chrome test", guid: "chrome", can_write: canWrite, can_share: canWrite)
208 return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:])
209 }
210 return NativeResponse(data: Data(), status: 404, headers: [:])
211 }
212
213 func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
214 try await onOpen()
215 try await onLine("data: 0")
216 while !Task.isCancelled { try await Task.sleep(for: .seconds(60)) }
217 }
218
219 func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound }
220}
221#endif
222