#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