Docs native S2a: tests for the subtitle, access, centring and the hosted window
- DocsSubtitleTests: every §6 row in precedence order, its words, style and announcement; every key the new views use resolves in all twelve tables. - DocsAccessTests: 401 pauses input and leaves can_write alone (and retry() no longer resumes input under it), 403 and 404 are No longer available and a later 200 leaves it, a 200 without can_write is View only in place. - DocsDeskLayoutTests: the web's clamp at the six widths and two zooms, open and closed, the 1,108pt boundary, right to left. - DocumentWindowChromeTests (hosted, toolbar and title bridged): one title, no .principal item, the page's frame at the six widths open and closed, the inspector's app-wide state, a reader's window, the 1 s debounce. Each was seen red with its mechanism broken (401 as 403, row 1 never left, the desk ignoring the inspector, the inspector shown to readers). The subtitle reads `loading` rather than the projection, which S1a takes out of observation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+536
−10
native/apple/Sources/DocsKit/DocsModel.swift+3 −1native/apple/Sources/DocsKit/DocsSubtitle.swift+23 −9native/apple/Tests/DocsKitTests/DocsAccessTests.swift+114 −0native/apple/Tests/DocsKitTests/DocsDeskLayoutTests.swift+60 −0native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift+115 −0native/apple/Tests/DocsWindowTests/DocumentWindowChromeTests.swift+221 −0
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift| index 41427f0..c1f914d 100644 |
| --- a/native/apple/Sources/DocsKit/DocsModel.swift |
| +++ b/native/apple/Sources/DocsKit/DocsModel.swift |
| @@ -421,7 +421,9 @@ import RastrilloNative |
| offlineAccount.drainer.retryNow() |
| if inputPaused { |
| if let detail { await refreshAccess(detail.sqid, epoch: epoch) } |
| - guard documentEpoch == epoch, detail?.can_write == true else { return } |
| + // Not while the document is gone (§6 row 1) or the session is |
| + // being re-minted after a 401: its 200 resumes input itself. |
| + guard documentEpoch == epoch, detail?.can_write == true, !unavailable, !pausedForSession else { return } |
| inputPaused = false; errorKey = nil |
| if editingTask == nil { editingTask = Task { await drainEdits() } } |
| } else { await flush() } |
diff --git a/native/apple/Sources/DocsKit/DocsSubtitle.swift b/native/apple/Sources/DocsKit/DocsSubtitle.swift| index 3b70b67..a9875a2 100644 |
| --- a/native/apple/Sources/DocsKit/DocsSubtitle.swift |
| +++ b/native/apple/Sources/DocsKit/DocsSubtitle.swift |
| @@ -137,27 +137,41 @@ struct DocsStrings { |
| @MainActor struct DocsSubtitleView: View { |
| let model: DocsModel |
| let team: String? |
| + var body: some View { |
| + DocsSubtitleBody(status: model.syncStatus, access: model.access, loading: model.loading, draft: model.isDraft, team: team) |
| + } |
| +} |
| + |
| +/// The subtitle given its inputs, holding the "Saving…" debounce and the |
| +/// announcements. `observe` hears every row shown (tests). |
| +@MainActor struct DocsSubtitleBody: View { |
| + let status: SyncStatus |
| + let access: DocsAccess |
| + let loading: Bool |
| + let draft: Bool |
| + let team: String? |
| + var observe: ((DocsSubtitleRow) -> Void)? = nil |
| @Environment(\.locale) private var locale |
| /// The 1 s debounce for row 9, set only from the `.task` below. |
| @State private var savingShown = false |
| - @State private var announced: DocsSubtitleRow? |
| + @State private var shown: DocsSubtitleRow? |
| var body: some View { |
| - let status = model.syncStatus |
| - let row = DocsSubtitleRow(access: model.access, status: status, savingShown: savingShown, loading: model.projection == nil) |
| + let row = DocsSubtitleRow(access: access, status: status, savingShown: savingShown, loading: loading) |
| DocsSubtitleLine(row: row, team: team, strings: DocsStrings(locale: locale)) |
| // Not `.saved` continuously for a second shows "Saving…"; every |
| // return to `.saved` restarts the clock (spec §6, row 9). |
| - .task(id: Self.unsettled(status, draft: model.isDraft)) { |
| - guard Self.unsettled(status, draft: model.isDraft) else { savingShown = false; return } |
| + .task(id: Self.unsettled(status, draft: draft)) { |
| + guard Self.unsettled(status, draft: draft) else { savingShown = false; return } |
| try? await Task.sleep(for: .seconds(1)) |
| if !Task.isCancelled { savingShown = true } |
| } |
| .onChange(of: row, initial: true) { old, new in |
| - defer { announced = new } |
| - guard let previous = announced, previous != new, DocsSubtitleRow.announces(from: old, to: new) else { return } |
| - let strings = DocsStrings(locale: locale) |
| - AccessibilityNotification.Announcement(strings.state(new) ?? "").post() |
| + observe?(new) |
| + defer { shown = new } |
| + // Nothing is announced as the window opens, only changes. |
| + guard let previous = shown, previous != new, DocsSubtitleRow.announces(from: old, to: new) else { return } |
| + AccessibilityNotification.Announcement(DocsStrings(locale: locale).state(new) ?? "").post() |
| } |
| } |
| static func unsettled(_ status: SyncStatus, draft: Bool) -> Bool { draft || status != .saved } |
diff --git a/native/apple/Tests/DocsKitTests/DocsAccessTests.swift b/native/apple/Tests/DocsKitTests/DocsAccessTests.swift| new file mode 100644 |
| index 0000000..88d3209 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/DocsAccessTests.swift |
| @@ -0,0 +1,114 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import RastrilloNative |
| +import RastrilloTestSupport |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Spec §6 and plan S2a step 4: what `refreshAccess` does with each answer. |
| +/// 401 pauses input and leaves the access alone; 403 and 404 are "No longer |
| +/// available", left again on a later 200; a 200 without can_write is View |
| +/// only, in place. |
| +@MainActor final class DocsAccessTests: XCTestCase { |
| + private func open() async throws -> (DocsModel, AccessServer) { |
| + let server = AccessServer() |
| + try await server.inner.seed([.object(["type": .string("paragraph"), "children": .array([ |
| + .object(["type": .string("text"), "runs": .array([.object(["insert": .string("Hello"), "marks": .object([:])])])])])])]) |
| + 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) |
| + await model.open("doc") |
| + XCTAssertNotNil(model.projection, "the document opened") |
| + XCTAssertEqual(model.access, .writable) |
| + return (model, server) |
| + } |
| + |
| + /// Asks again, as the window does after a refused write or stream. |
| + private func revalidate(_ model: DocsModel) async { |
| + model.inputPaused = true |
| + await model.retry() |
| + } |
| + |
| + private func row(_ model: DocsModel) -> DocsSubtitleRow { |
| + DocsSubtitleRow(access: model.access, status: .saved, savingShown: false, loading: model.loading) |
| + } |
| + |
| + func testA403IsNoLongerAvailableAndALater200LeavesIt() async throws { |
| + let (model, server) = try await open() |
| + await server.answer(403) |
| + await revalidate(model) |
| + XCTAssertEqual(model.access, .unavailable) |
| + XCTAssertEqual(row(model), .unavailable) |
| + XCTAssertTrue(model.inputPaused, "the editor becomes read-only") |
| + XCTAssertFalse(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("x")])) |
| + |
| + await server.answer(200, canWrite: true) |
| + await revalidate(model) |
| + XCTAssertEqual(model.access, .writable, "re-shared or restored: row 1 is left") |
| + XCTAssertEqual(row(model), .saved) |
| + XCTAssertFalse(model.inputPaused) |
| + await model.stop() |
| + } |
| + |
| + func testA404IsNoLongerAvailable() async throws { |
| + let (model, server) = try await open() |
| + await server.answer(404) |
| + await revalidate(model) |
| + XCTAssertEqual(model.access, .unavailable) |
| + XCTAssertEqual(model.detail?.can_write, false) |
| + await model.stop() |
| + } |
| + |
| + func testA401PausesInputAndLeavesTheAccessAlone() async throws { |
| + let (model, server) = try await open() |
| + await server.answer(401) |
| + await revalidate(model) |
| + XCTAssertEqual(model.detail?.can_write, true, "a 401 never touches can_write") |
| + XCTAssertEqual(model.access, .writable, "and so no reader chrome") |
| + XCTAssertTrue(model.inputPaused, "input pauses while the session is re-minted") |
| + |
| + // The re-minted session's 200 resumes input, can_write unchanged. |
| + await server.answer(200, canWrite: true) |
| + await revalidate(model) |
| + XCTAssertFalse(model.inputPaused) |
| + XCTAssertEqual(model.access, .writable) |
| + await model.stop() |
| + } |
| + |
| + func testA200WithoutWriteIsViewOnlyInPlace() async throws { |
| + let (model, server) = try await open() |
| + model.selection = NSRange(location: 2, length: 1) |
| + let identity = model.editorIdentity |
| + await server.answer(200, canWrite: false) |
| + await revalidate(model) |
| + XCTAssertEqual(model.access, .readOnly) |
| + XCTAssertEqual(row(model), .viewOnly) |
| + XCTAssertTrue(model.inputPaused) |
| + XCTAssertEqual(model.editorIdentity, identity, "applied in place: the same text view") |
| + XCTAssertEqual(model.selection, NSRange(location: 2, length: 1), "the selection is kept") |
| + await model.stop() |
| + } |
| +} |
| + |
| +/// LoopServer, with the document's detail answer under the test's control. |
| +actor AccessServer: NativeTransport { |
| + nonisolated let origin = URL(string: "https://docs.access.invalid")! |
| + let inner = LoopServer() |
| + private var status = 200 |
| + private var canWrite = true |
| + |
| + func answer(_ status: Int, canWrite: Bool = true) { self.status = status; self.canWrite = canWrite } |
| + |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + if method == "GET", path == "/d/doc" { |
| + guard status == 200 else { return NativeResponse(data: Data(), status: status, headers: [:]) } |
| + let detail = DocumentDetail(sqid: "doc", title: "Access", guid: "render-loop", can_write: canWrite, can_share: canWrite) |
| + return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| + } |
| + return try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| + } |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + try await inner.stream(path, onOpen: onOpen, onLine: onLine) |
| + } |
| + func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| +} |
diff --git a/native/apple/Tests/DocsKitTests/DocsDeskLayoutTests.swift b/native/apple/Tests/DocsKitTests/DocsDeskLayoutTests.swift| new file mode 100644 |
| index 0000000..d46c327 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/DocsDeskLayoutTests.swift |
| @@ -0,0 +1,60 @@ |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Spec §1, "Page centring": the web's clamp in window points at the six |
| +/// widths, both zooms, inspector open and closed, the 1,108pt boundary, |
| +/// and the paddings swapped right to left. |
| +final class DocsDeskLayoutTests: XCTestCase { |
| + /// The page's width in window points: 612 × 4/3 × zoom. |
| + private func page(_ zoom: CGFloat) -> CGFloat { DocsDeskLayout.paperWidth * 4 / 3 * zoom } |
| + |
| + func testTheReserveIsTheInspectorAndItsGaps() { |
| + XCTAssertEqual(DocsDeskLayout.reserve, 276) |
| + } |
| + |
| + func testClosedThePageIsPlainlyCentred() { |
| + for zoom in [1.0, 1.5] as [CGFloat] { |
| + for width in [1800, 1440, 1280, 1108, 1000, 920] as [CGFloat] { |
| + XCTAssertEqual(DocsDeskLayout.inspectorPadding(width: width, page: page(zoom), inspector: false), 16) |
| + let x = DocsDeskLayout.pageX(width: width, page: page(zoom), inspector: nil) |
| + XCTAssertEqual(x, max(16, (width - page(zoom)) / 2), accuracy: 0.001, "width \(width) zoom \(zoom)") |
| + } |
| + } |
| + } |
| + |
| + /// E = clamp(16, 16 + P + 2R − W, R) and the page centred in [16, W − E]. |
| + func testOpenFollowsTheWebsClamp() { |
| + let expected: [(CGFloat, CGFloat, CGFloat, CGFloat)] = [ |
| + // width, zoom, E, page's left edge |
| + (1800, 1, 16, 492), (1440, 1, 16, 312), (1280, 1, 104, 188), (1108, 1, 276, 16), (1000, 1, 276, 16), (920, 1, 276, 16), |
| + (1800, 1.5, 16, 288), (1440, 1.5, 276, 16), (1280, 1.5, 276, 16), (1108, 1.5, 276, 16), (1000, 1.5, 276, 16), (920, 1.5, 276, 16), |
| + ] |
| + for (width, zoom, e, x) in expected { |
| + XCTAssertEqual(DocsDeskLayout.inspectorPadding(width: width, page: page(zoom), inspector: true), e, accuracy: 0.001, "E at \(width) zoom \(zoom)") |
| + XCTAssertEqual(DocsDeskLayout.pageX(width: width, page: page(zoom), inspector: .right), x, accuracy: 0.001, "x at \(width) zoom \(zoom)") |
| + } |
| + } |
| + |
| + /// At W = P + 16 + R the page just clears the inspector (16pt apart); |
| + /// a point narrower and it starts to run under it. |
| + func testTheBoundaryAtZoom100IsOneThousandOneHundredAndEight() { |
| + let p = page(1) |
| + let boundary = p + 16 + DocsDeskLayout.reserve |
| + XCTAssertEqual(boundary, 1108, accuracy: 0.001) |
| + let x = DocsDeskLayout.pageX(width: boundary, page: p, inspector: .right) |
| + let inspectorLeft = boundary - DocsDeskLayout.inspectorInset - DocsDeskLayout.inspectorWidth |
| + XCTAssertEqual(inspectorLeft - (x + p), 16, accuracy: 0.001) |
| + let narrower = DocsDeskLayout.pageX(width: boundary - 1, page: p, inspector: .right) |
| + XCTAssertGreaterThan(narrower + p, boundary - 1 - DocsDeskLayout.inspectorInset - DocsDeskLayout.inspectorWidth - 16) |
| + XCTAssertEqual(narrower, 16, "the page's leading edge stays at 16; it never shrinks") |
| + } |
| + |
| + /// Right to left the inspector is on the left and the paddings swap. |
| + func testRightToLeftMirrors() { |
| + for (width, zoom) in [(1800, 1), (1440, 1), (1280, 1), (1108, 1), (1800, 1.5)] as [(CGFloat, CGFloat)] { |
| + let ltr = DocsDeskLayout.pageX(width: width, page: page(zoom), inspector: .right) |
| + let rtl = DocsDeskLayout.pageX(width: width, page: page(zoom), inspector: .left) |
| + XCTAssertEqual(rtl, width - ltr - page(zoom), accuracy: 0.001, "width \(width)") |
| + } |
| + } |
| +} |
diff --git a/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift b/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift| new file mode 100644 |
| index 0000000..d594ac6 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsKitTests/DocsSubtitleTests.swift |
| @@ -0,0 +1,115 @@ |
| +import RastrilloApple |
| +import RastrilloNative |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// Spec §6: every subtitle row, its words, style and announcement. |
| +final class DocsSubtitleTests: XCTestCase { |
| + private let en = DocsStrings(locale: Locale(identifier: "en")) |
| + |
| + private func row(_ status: SyncStatus, access: DocsAccess = .writable, saving: Bool = false, loading: Bool = false) -> DocsSubtitleRow { |
| + DocsSubtitleRow(access: access, status: status, savingShown: saving, loading: loading) |
| + } |
| + |
| + func testEveryRowInPrecedenceOrder() { |
| + let held = SyncStatus.failed(pending: 1, reason: .held(.accessLost)) |
| + // 1 beats everything. |
| + XCTAssertEqual(row(held, access: .unavailable), .unavailable) |
| + XCTAssertEqual(row(held), .failedHeld) |
| + XCTAssertEqual(row(.failed(pending: 0, reason: .cannotSaveOnDevice)), .cannotSaveOnDevice) |
| + XCTAssertEqual(row(.failed(pending: 2, reason: .tooManyUnsent)), .tooManyUnsent) |
| + XCTAssertEqual(row(.needsSignIn(pending: 3)), .needsSignIn(pending: 3)) |
| + XCTAssertEqual(row(.needsSignIn(pending: 0)), .signedOut) |
| + XCTAssertEqual(row(.offline(pending: 2)), .offline(pending: 2)) |
| + XCTAssertEqual(row(.retrying(pending: 1)), .retrying(pending: 1)) |
| + // 9 only once the debounce says so. |
| + XCTAssertEqual(row(.saving), .saved) |
| + XCTAssertEqual(row(.saving, saving: true), .saving) |
| + XCTAssertEqual(row(.saving, access: .readOnly), .viewOnly) |
| + XCTAssertEqual(row(.saved, access: .readOnly), .viewOnly) |
| + XCTAssertEqual(row(.saved), .saved) |
| + // 13: the team alone while the document loads. |
| + XCTAssertEqual(row(.saved, loading: true), .loading) |
| + // A negative row still shows while loading: it is news. |
| + XCTAssertEqual(row(.offline(pending: 1), loading: true), .offline(pending: 1)) |
| + } |
| + |
| + func testWordsAndJoin() { |
| + XCTAssertEqual(en.subtitle(team: "Tito", row: .saved), "Tito · Saved") |
| + XCTAssertEqual(en.subtitle(team: "Tito", row: .viewOnly), "Tito · View only") |
| + XCTAssertEqual(en.subtitle(team: "Tito", row: .unavailable), "Tito · No longer available") |
| + XCTAssertEqual(en.subtitle(team: "Tito", row: .signedOut), "Tito · Signed out") |
| + XCTAssertEqual(en.subtitle(team: nil, row: .saved), "Saved", "no team: the state alone, no separator") |
| + XCTAssertEqual(en.subtitle(team: "", row: .saved), "Saved") |
| + XCTAssertEqual(en.subtitle(team: "Tito", row: .loading), "Tito", "loading: the team only") |
| + let sync = NativeSyncStrings.kit(localization: "en") |
| + XCTAssertEqual(en.state(.offline(pending: 2)), sync.offline(2)) |
| + XCTAssertEqual(en.state(.needsSignIn(pending: 3)), sync.needsSignIn(3)) |
| + XCTAssertEqual(en.state(.retrying(pending: 1)), sync.retrying) |
| + XCTAssertEqual(en.state(.saving), sync.saving) |
| + XCTAssertEqual(en.state(.failedHeld), sync.failed(.held(.tooLarge))) |
| + XCTAssertEqual(en.state(.cannotSaveOnDevice), sync.failed(.cannotSaveOnDevice)) |
| + XCTAssertEqual(en.state(.tooManyUnsent), sync.failed(.tooManyUnsent)) |
| + } |
| + |
| + func testStyles() { |
| + for negative in [DocsSubtitleRow.unavailable, .failedHeld, .cannotSaveOnDevice, .tooManyUnsent, .needsSignIn(pending: 1), .signedOut] { |
| + XCTAssertTrue(negative.isNegative, "\(negative)") |
| + } |
| + for muted in [DocsSubtitleRow.offline(pending: 1), .retrying(pending: 1), .saving, .viewOnly, .saved, .loading] { |
| + XCTAssertFalse(muted.isNegative, "\(muted)") |
| + } |
| + XCTAssertTrue(DocsSubtitleRow.failedHeld.isEmphasised) |
| + XCTAssertFalse(DocsSubtitleRow.unavailable.isEmphasised) |
| + } |
| + |
| + func testAnnouncements() { |
| + // Entering offline, needs sign-in, failed or unavailable is news. |
| + for new in [DocsSubtitleRow.offline(pending: 1), .needsSignIn(pending: 1), .signedOut, .failedHeld, .cannotSaveOnDevice, .tooManyUnsent, .unavailable] { |
| + XCTAssertTrue(DocsSubtitleRow.announces(from: .saved, to: new), "\(new)") |
| + } |
| + // A count changing inside one kind is not; saving never is. |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .offline(pending: 1), to: .offline(pending: 2))) |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .needsSignIn(pending: 2), to: .signedOut)) |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .saved, to: .saving)) |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .saving, to: .saved)) |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .saved, to: .retrying(pending: 1))) |
| + // View only is news mid-session, not as a reader's window opens. |
| + XCTAssertTrue(DocsSubtitleRow.announces(from: .saved, to: .viewOnly)) |
| + XCTAssertFalse(DocsSubtitleRow.announces(from: .loading, to: .viewOnly)) |
| + } |
| + |
| + /// Spec §8: every key the new views use resolves in all twelve tables, |
| + /// and no value is its own key. |
| + func testEveryNewKeyResolvesInEveryLanguage() throws { |
| + let keys = ["docs.editor.toolbar.history", "docs.editor.toolbar.group.style", "docs.editor.toolbar.group.text", |
| + "docs.editor.toolbar.group.align", "docs.editor.toolbar.group.lists", "docs.editor.inspector.label", |
| + "docs.editor.inspector.toggle", "docs.share.action", "native.subtitle.saved", "native.subtitle.viewOnly", |
| + "native.subtitle.joined", "native.subtitle.unavailable", "native.unavailable.body", "native.subtitle.signedOut", |
| + "native.format.show", "native.format.hide", |
| + // Reused by the header, inspector and menus. |
| + "docs.editor.toolbar.undo", "docs.editor.toolbar.redo", "docs.editor.toolbar.bold", "docs.editor.toolbar.italic", |
| + "docs.editor.toolbar.code", "docs.editor.toolbar.align.left", "docs.editor.toolbar.align.center", |
| + "docs.editor.toolbar.align.right", "docs.editor.toolbar.bulletlist", "docs.editor.toolbar.orderedlist", |
| + "docs.editor.toolbar.quote", "docs.editor.toolbar.block", "docs.editor.toolbar.block.paragraph", |
| + "docs.editor.toolbar.font", "docs.editor.toolbar.size", "docs.editor.menu.format.indent", |
| + "docs.editor.menu.format.outdent", "docs.editor.menu.format.clear", "docs.editor.menu.format", |
| + "docs.editor.menu.tools", "docs.editor.menu.tools.wordcount", "docs.editor.menu.tools.shortcuts", |
| + "docs.editor.menu.view.paged", "docs.editor.menu.view.infinite", "docs.editor.menu.file.open", |
| + "docs.document.rename", "native.close", "native.retry", "native.discard.action"] |
| + let languages = DocsResources.bundle.localizations.filter { $0 != "Base" } |
| + XCTAssertEqual(Set(languages), ["ar", "bn", "en", "es", "ga", "hi", "ja", "pt", "ru", "vi", "yue", "zh-Hans"]) |
| + for language in languages { |
| + let strings = DocsStrings(locale: Locale(identifier: language)) |
| + XCTAssertEqual(strings.localization, language) |
| + for key in keys { |
| + let value = strings(key) |
| + XCTAssertNotEqual(value, key, "\(language): \(key) has no value") |
| + XCTAssertFalse(value.isEmpty, "\(language): \(key) is empty") |
| + } |
| + let joined = strings("native.subtitle.joined") |
| + XCTAssertTrue(joined.contains("%1$@") && joined.contains("%2$@"), "\(language): the join keeps both placeholders") |
| + XCTAssertFalse(strings.subtitle(team: "T", row: .saved).contains("%"), language) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Tests/DocsWindowTests/DocumentWindowChromeTests.swift b/native/apple/Tests/DocsWindowTests/DocumentWindowChromeTests.swift| new file mode 100644 |
| index 0000000..8a1a601 |
| --- /dev/null |
| +++ b/native/apple/Tests/DocsWindowTests/DocumentWindowChromeTests.swift |
| @@ -0,0 +1,221 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import Foundation |
| +import Observation |
| +import RastrilloApple |
| +import RastrilloNative |
| +import SwiftUI |
| +import XCTest |
| +@testable import DocsKit |
| + |
| +/// The S2a document window, hosted in a real titled window with SwiftUI's |
| +/// toolbar and title bridged into it (spec §11, hosted-window tests): one |
| +/// title, the page placed by the centring rule at the six widths with the |
| +/// inspector open and closed, the inspector's app-wide state, and a |
| +/// reader's window, which never shows the inspector nor writes its state. |
| +@MainActor final class DocumentWindowChromeTests: XCTestCase { |
| + override func setUp() async throws { UserDefaults.standard.removeObject(forKey: DocsInspectorState.key) } |
| + override func tearDown() async throws { UserDefaults.standard.removeObject(forKey: DocsInspectorState.key) } |
| + |
| + private struct Hosted { |
| + let window: NSWindow |
| + let server: ChromeServer |
| + var text: DocsPagedTextView? { Self.find(window.contentView) } |
| + static func find(_ view: NSView?) -> DocsPagedTextView? { |
| + guard let view else { return nil } |
| + if let text = view as? DocsPagedTextView { return text } |
| + return view.subviews.lazy.compactMap(find).first |
| + } |
| + } |
| + |
| + private func host(canWrite: Bool = true, width: CGFloat = 1120) async throws -> Hosted { |
| + let server = ChromeServer(canWrite: canWrite) |
| + try await server.seed() |
| + let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", team: "Tito") |
| + let controller = NSHostingController(rootView: workspace) |
| + controller.sceneBridgingOptions = [.toolbars, .title] |
| + // The window's size is the test's, not the content's ideal size. |
| + controller.sizingOptions = [] |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: 800), |
| + styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) |
| + window.isReleasedWhenClosed = false |
| + window.contentViewController = controller |
| + window.setContentSize(NSSize(width: width, height: 800)) |
| + window.orderFrontRegardless() |
| + let hosted = Hosted(window: window, server: server) |
| + try await until("the document opened") { hosted.text.map { !$0.string.isEmpty } == true } |
| + hosted.text?.enclosingScrollView?.scrollerStyle = .overlay |
| + await pump(0.3) |
| + return hosted |
| + } |
| + |
| + private func close(_ hosted: Hosted) async { |
| + hosted.window.orderOut(nil) |
| + hosted.window.contentViewController = nil |
| + await pump(0.1) |
| + } |
| + |
| + private func pump(_ seconds: Double) async { |
| + let end = Date().addingTimeInterval(seconds) |
| + while Date() < end { |
| + NSApp?.windows.forEach { $0.contentView?.layoutSubtreeIfNeeded() } |
| + try? await Task.sleep(for: .milliseconds(10)) |
| + } |
| + } |
| + |
| + private func until(_ what: String, _ condition: () -> Bool) async throws { |
| + let deadline = Date().addingTimeInterval(10) |
| + while !condition() { |
| + guard Date() < deadline else { throw XCTSkip("timed out waiting for \(what)") } |
| + await pump(0.02) |
| + } |
| + } |
| + |
| + /// The page's left edge and the clip view's width, in window points. |
| + private func measure(_ hosted: Hosted) throws -> (x: CGFloat, width: CGFloat, page: CGFloat) { |
| + let text = try XCTUnwrap(hosted.text) |
| + let scroll = try XCTUnwrap(text.enclosingScrollView) |
| + hosted.window.contentView?.layoutSubtreeIfNeeded() |
| + let clip = scroll.contentView.convert(scroll.contentView.bounds, to: nil) |
| + let page = text.convert(text.bounds, to: nil) |
| + return (page.minX - clip.minX, clip.width, page.width) |
| + } |
| + |
| + func testOneTitleDrawnByDocsAndTheWindowTitleIsTheDocuments() async throws { |
| + let hosted = try await host() |
| + defer { Task { await close(hosted) } } |
| + XCTAssertEqual(hosted.window.title, "Chrome test", "the Window menu, tabs and VoiceOver read the document's title") |
| + XCTAssertEqual(hosted.window.titleVisibility, .hidden, "the system does not draw it a second time") |
| + let toolbar = try XCTUnwrap(hosted.window.toolbar, "the header is in the window's toolbar") |
| + XCTAssertTrue(toolbar.centeredItemIdentifiers.isEmpty, "no .principal item: it drew the title twice") |
| + XCTAssertGreaterThanOrEqual(toolbar.items.count, 3, "the title area, a flexible space and the controls") |
| + XCTAssertEqual(hosted.window.tab.title, "Chrome test") |
| + } |
| + |
| + /// Spec §1 page centring, finding 5: the page's frame in window points |
| + /// at W = 1800, 1440, 1280, 1108, 1000 and 920, open and closed. |
| + func testThePageFollowsTheCentringRuleAtTheSixWidths() async throws { |
| + let hosted = try await host() |
| + defer { Task { await close(hosted) } } |
| + let text = try XCTUnwrap(hosted.text) |
| + let container = text.textContainer?.size |
| + for open in [true, false] { |
| + UserDefaults.standard.set(open, forKey: DocsInspectorState.key) |
| + for target in [1800, 1440, 1280, 1108, 1000, 920] as [CGFloat] { |
| + hosted.window.setContentSize(NSSize(width: target, height: 800)) |
| + await pump(0.15) |
| + let measured = try measure(hosted) |
| + let expected = DocsDeskLayout.pageX(width: measured.width, page: measured.page, inspector: open ? .right : nil) |
| + XCTAssertEqual(measured.x, expected, accuracy: 0.5, "W \(measured.width) (asked \(target)), inspector \(open ? "open" : "closed")") |
| + XCTAssertEqual(measured.page, 612 * 4 / 3, accuracy: 0.5, "the page never shrinks") |
| + } |
| + } |
| + XCTAssertEqual(text.textContainer?.size, container, "moving the page never changes the text's geometry") |
| + } |
| + |
| + /// ⌥⌘I flips one app-wide state: every open window follows it. |
| + func testTheInspectorStateIsAppWide() async throws { |
| + let first = try await host(width: 1280) |
| + let second = try await host(width: 1280) |
| + defer { Task { await close(first); await close(second) } } |
| + XCTAssertNil(UserDefaults.standard.object(forKey: DocsInspectorState.key), "nothing written on open") |
| + let openX = try (measure(first).x, measure(second).x) |
| + UserDefaults.standard.set(false, forKey: DocsInspectorState.key) |
| + await pump(0.3) |
| + let closedX = try (measure(first).x, measure(second).x) |
| + XCTAssertNotEqual(openX.0, closedX.0, accuracy: 1, "the first window's page moved") |
| + XCTAssertNotEqual(openX.1, closedX.1, accuracy: 1, "and the second's") |
| + } |
| + |
| + /// A reader never sees the inspector, whatever the stored state, and |
| + /// their window does not write it. |
| + func testAReaderNeverSeesTheInspector() async throws { |
| + UserDefaults.standard.set(true, forKey: DocsInspectorState.key) |
| + let hosted = try await host(canWrite: false, width: 1280) |
| + defer { Task { await close(hosted) } } |
| + let measured = try measure(hosted) |
| + XCTAssertEqual(measured.x, DocsDeskLayout.pageX(width: measured.width, page: measured.page, inspector: nil), accuracy: 0.5, |
| + "centred as if closed: no inspector over the desk") |
| + XCTAssertEqual(UserDefaults.standard.object(forKey: DocsInspectorState.key) as? Bool, true, "the reader's window wrote nothing") |
| + XCTAssertFalse(try XCTUnwrap(hosted.text).isEditable) |
| + } |
| + |
| + /// Row 9's debounce: "Saving…" only after a whole second not saved, and |
| + /// every return to saved restarts the clock. |
| + func testSavingShowsOnlyAfterASecondAndRestartsOnSaved() async throws { |
| + let state = SubtitleState() |
| + var rows: [DocsSubtitleRow] = [] |
| + let view = SubtitleHost(state: state) { rows.append($0) } |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 40), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.isReleasedWhenClosed = false |
| + window.contentView = NSHostingView(rootView: view) |
| + window.orderFrontRegardless() |
| + defer { window.orderOut(nil); window.contentView = nil } |
| + await pump(0.2) |
| + XCTAssertEqual(rows.last, .saved) |
| + state.status = .saving |
| + await pump(0.6) |
| + XCTAssertEqual(rows.last, .saved, "not yet a second") |
| + state.status = .saved |
| + await pump(0.1) |
| + state.status = .saving |
| + await pump(0.6) |
| + XCTAssertEqual(rows.last, .saved, "the clock restarted on .saved") |
| + await pump(0.7) |
| + XCTAssertEqual(rows.last, .saving, "a whole second not saved") |
| + state.status = .saved |
| + await pump(0.1) |
| + XCTAssertEqual(rows.last, .saved) |
| + state.status = .offline(pending: 2) |
| + await pump(0.1) |
| + XCTAssertEqual(rows.last, .offline(pending: 2), "rows 1–8 show at once") |
| + } |
| +} |
| + |
| +@MainActor @Observable private final class SubtitleState { var status: SyncStatus = .saved } |
| +private struct SubtitleHost: View { |
| + let state: SubtitleState |
| + let observe: (DocsSubtitleRow) -> Void |
| + var body: some View { |
| + DocsSubtitleBody(status: state.status, access: .writable, loading: false, draft: false, team: "Tito", observe: observe) |
| + } |
| +} |
| + |
| +/// One document, "doc": GET answers its detail (with the test's can_write) |
| +/// and state; POSTs are taken; the stream announces nothing. |
| +actor ChromeServer: NativeTransport { |
| + nonisolated let origin = URL(string: "https://docs.chrome.invalid")! |
| + private let replica = CRDTReplica(guid: "chrome") |
| + private let canWrite: Bool |
| + init(canWrite: Bool) { self.canWrite = canWrite } |
| + |
| + func seed() async throws { |
| + try await replica.open(update: Data()) |
| + _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| + let runs: JSONValue = .array([.object(["insert": .string("A page on the desk, placed by the web's rule."), "marks": .object([:])])]) |
| + let paragraph: JSONValue = .object(["type": .string("paragraph"), "children": .array([.object(["type": .string("text"), "runs": runs])])]) |
| + _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array([paragraph])]) |
| + } |
| + |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| + let route = String(path.split(separator: "?")[0]) |
| + if method == "POST" { return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": "1"]) } |
| + if route == "/d/doc/updates" { |
| + return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": "0"]) |
| + } |
| + if route == "/d/doc" { |
| + let detail = DocumentDetail(sqid: "doc", title: "Chrome test", guid: "chrome", can_write: canWrite, can_share: canWrite) |
| + return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| + } |
| + return NativeResponse(data: Data(), status: 404, headers: [:]) |
| + } |
| + |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| + try await onOpen() |
| + try await onLine("data: 0") |
| + while !Task.isCancelled { try await Task.sleep(for: .seconds(60)) } |
| + } |
| + |
| + func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| +} |
| +#endif |