| 1 | import Foundation |
| 2 | import RastrilloApple |
| 3 | import XCTest |
| 4 | @testable import DocsKit |
| 5 | |
| 6 | /// The Share panel's model (spec 2026-11-22 §11, "Share panel model"): a |
| 7 | /// switch holds and reverts; the once-only URL appears once, is gone after |
| 8 | /// close, and blocks outside dismissal while it shows; a second submit is |
| 9 | /// refused; a control that waits shows a spinner on itself only. |
| 10 | @MainActor final class DocsSharePanelModelTests: XCTestCase { |
| 11 | override func tearDown() async throws { DocsSharePanelModel.spinnerDelay = .milliseconds(500) } |
| 12 | |
| 13 | private func panel(_ server: PanelServer) async -> DocsSharePanelModel { |
| 14 | let model = DocsSharePanelModel(sqid: "doc", title: "Plan", transport: { server }) |
| 15 | await model.load() |
| 16 | XCTAssertNotNil(model.information, "the panel loaded") |
| 17 | return model |
| 18 | } |
| 19 | |
| 20 | /// Until the held request is waiting at the server. |
| 21 | private func waiting(_ server: PanelServer) async throws { |
| 22 | let deadline = Date().addingTimeInterval(5) |
| 23 | while !(await server.waiting) { |
| 24 | guard Date() < deadline else { return XCTFail("timed out: the request never reached the server") } |
| 25 | try await Task.sleep(for: .milliseconds(5)) |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | private func settle(_ condition: @autoclosure () -> Bool, _ what: String) async throws { |
| 30 | let deadline = Date().addingTimeInterval(5) |
| 31 | while !condition() { |
| 32 | guard Date() < deadline else { return XCTFail("timed out: \(what)") } |
| 33 | try await Task.sleep(for: .milliseconds(5)) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | func testASwitchHoldsUntilItSettlesThenRevertsOnFailure() async throws { |
| 38 | let server = PanelServer() |
| 39 | let model = await panel(server) |
| 40 | XCTAssertFalse(model.teamOn) |
| 41 | await server.hold() |
| 42 | let change = Task { await model.setTeam(true) } |
| 43 | try await waiting(server) |
| 44 | XCTAssertEqual(model.inFlight, .team) |
| 45 | XCTAssertTrue(model.teamOn, "the switch holds its new position") |
| 46 | await server.release(status: 500) |
| 47 | let applied = await change.value |
| 48 | XCTAssertFalse(applied) |
| 49 | XCTAssertFalse(model.teamOn, "it reverts") |
| 50 | XCTAssertEqual(model.errorKey, "docs.share.panel.failed", "and the callout says so") |
| 51 | XCTAssertNil(model.inFlight) |
| 52 | } |
| 53 | |
| 54 | func testASwitchThatSucceedsShowsTheServersState() async throws { |
| 55 | let server = PanelServer() |
| 56 | let model = await panel(server) |
| 57 | let applied = await model.setTeam(true) |
| 58 | XCTAssertTrue(applied) |
| 59 | XCTAssertTrue(model.teamOn) |
| 60 | XCTAssertNil(model.heldTeam, "no longer held: it is the server's answer") |
| 61 | let visibility = await server.visibility |
| 62 | XCTAssertEqual(visibility, "team") |
| 63 | XCTAssertNil(model.errorKey) |
| 64 | } |
| 65 | |
| 66 | func testTheOnceOnlyURLShowsOnceAndIsGoneAfterClose() async throws { |
| 67 | let server = PanelServer() |
| 68 | let model = await panel(server) |
| 69 | XCTAssertNil(model.onceURL) |
| 70 | XCTAssertFalse(model.blocksOutsideDismissal) |
| 71 | let published = await model.setLink(true) |
| 72 | XCTAssertTrue(published) |
| 73 | XCTAssertEqual(model.onceURL?.absoluteString, "https://docs.panel.invalid/p/secret", "shown, from the publish's answer") |
| 74 | XCTAssertTrue(model.linkOn) |
| 75 | XCTAssertTrue(model.blocksOutsideDismissal, "no outside dismissal while it shows") |
| 76 | // The reload after the publish no longer carries it; the panel keeps it. |
| 77 | await model.load() |
| 78 | XCTAssertNotNil(model.onceURL, "it stays for the panel's lifetime") |
| 79 | var copied: URL? |
| 80 | model.copyLink { copied = $0 } |
| 81 | XCTAssertEqual(copied, model.onceURL, "Copy link is the way it leaves the panel") |
| 82 | XCTAssertTrue(model.copied) |
| 83 | |
| 84 | model.closed() |
| 85 | XCTAssertNil(model.onceURL, "gone with the panel") |
| 86 | XCTAssertFalse(model.blocksOutsideDismissal) |
| 87 | await model.load() |
| 88 | XCTAssertNil(model.onceURL, "and never shown again") |
| 89 | XCTAssertTrue(model.linkOn, "the document is still published") |
| 90 | |
| 91 | let replaced = await model.newLink() |
| 92 | XCTAssertTrue(replaced) |
| 93 | XCTAssertEqual(model.onceURL?.absoluteString, "https://docs.panel.invalid/p/secret2", "Make a new link shows the new one once") |
| 94 | XCTAssertFalse(model.copied, "a new URL was not copied yet") |
| 95 | let off = await model.setLink(false) |
| 96 | XCTAssertTrue(off) |
| 97 | XCTAssertNil(model.onceURL, "unpublished: no URL") |
| 98 | } |
| 99 | |
| 100 | func testASecondSubmitWhileOneIsInFlightIsRefused() async throws { |
| 101 | let server = PanelServer() |
| 102 | let model = await panel(server) |
| 103 | model.inviteAddress = "bob@example.com" |
| 104 | await server.hold() |
| 105 | let invite = Task { await model.invite() } |
| 106 | try await waiting(server) |
| 107 | XCTAssertEqual(model.inFlight, .invite) |
| 108 | let calls = await server.posts |
| 109 | // In tasks: a submit that was not refused would wait at the server. |
| 110 | let second = Task { await model.setTeam(true) } |
| 111 | let again = Task { await model.invite() } |
| 112 | try await Task.sleep(for: .milliseconds(100)) |
| 113 | XCTAssertFalse(model.teamOn, "the switch did not move") |
| 114 | let after = await server.posts |
| 115 | XCTAssertEqual(after, calls, "nothing more was sent while the invite waits") |
| 116 | await server.release(status: 200) |
| 117 | let done = await invite.value |
| 118 | let secondApplied = await second.value, invitedTwice = await again.value |
| 119 | XCTAssertFalse(secondApplied, "refused while the invite waited") |
| 120 | XCTAssertFalse(invitedTwice, "the same submit twice is refused too") |
| 121 | XCTAssertTrue(done) |
| 122 | XCTAssertEqual(model.inviteAddress, "", "the field clears once the invite is in") |
| 123 | XCTAssertEqual(model.information?.grants.map(\.address), ["bob@example.com"]) |
| 124 | } |
| 125 | |
| 126 | func testAControlThatWaitsShowsASpinnerOnItselfOnly() async throws { |
| 127 | DocsSharePanelModel.spinnerDelay = .milliseconds(300) |
| 128 | let server = PanelServer() |
| 129 | let model = await panel(server) |
| 130 | await server.hold() |
| 131 | let change = Task { await model.setLink(true) } |
| 132 | try await waiting(server) |
| 133 | XCTAssertEqual(model.inFlight, .link) |
| 134 | XCTAssertNil(model.spinning, "not before the delay") |
| 135 | try await settle(model.spinning == .link, "the link switch spins") |
| 136 | await server.release(status: 200) |
| 137 | _ = await change.value |
| 138 | XCTAssertNil(model.spinning) |
| 139 | |
| 140 | // A quick answer never spins. |
| 141 | DocsSharePanelModel.spinnerDelay = .seconds(10) |
| 142 | _ = await model.setTeam(true) |
| 143 | XCTAssertNil(model.spinning) |
| 144 | } |
| 145 | |
| 146 | func testTheServersRefusalIsTheCallout() async throws { |
| 147 | let server = PanelServer() |
| 148 | let model = await panel(server) |
| 149 | model.inviteAddress = "not an address" |
| 150 | await server.refuseNextInvite() |
| 151 | let invited = await model.invite() |
| 152 | XCTAssertFalse(invited) |
| 153 | XCTAssertEqual(model.errorKey, "docs.share.error.address") |
| 154 | XCTAssertEqual(model.inviteAddress, "not an address", "the field keeps what was typed") |
| 155 | } |
| 156 | |
| 157 | /// Spec §8: every key the panel, Delete… and the offline states use |
| 158 | /// resolves in all twelve tables, no value is its own key, and the |
| 159 | /// placeholders survive translation. |
| 160 | func testEveryShareAndDeleteKeyResolvesInEveryLanguage() { |
| 161 | let keys = ["docs.share.panel.heading", "docs.share.panel.close", "docs.share.panel.failed", "docs.share.panel.invite_placeholder", |
| 162 | "docs.share.panel.invite", "docs.share.panel.access", "docs.share.panel.can_read", "docs.share.panel.can_edit", |
| 163 | "docs.share.panel.people", "docs.share.panel.general", "docs.share.panel.owner", "docs.share.panel.you", |
| 164 | "docs.share.panel.remove", "docs.share.panel.team_on", "docs.share.panel.team_off", "docs.share.panel.team_switch", |
| 165 | "docs.share.panel.link_heading", "docs.share.panel.link_on", "docs.share.panel.link_off", "docs.share.panel.link_switch", |
| 166 | "docs.share.panel.once", "docs.share.panel.shown", "docs.share.panel.new_link", "docs.share.team.heading", |
| 167 | "docs.share.public.url", "docs.share.public.copy", "docs.share.public.copied", "docs.share.address", "docs.share.title", |
| 168 | "docs.share.action", "docs.share.error.address", "native.share.loadFailed", "native.retry", "native.close", |
| 169 | "docs.editor.menu.file.delete", "docs.delete.heading", "docs.delete.body", "docs.delete.confirm", "docs.delete.cancel", |
| 170 | "native.share.offline", "native.export.offline", "native.delete.unsent", "native.delete.failed"] |
| 171 | let languages = DocsResources.bundle.localizations.filter { $0 != "Base" } |
| 172 | XCTAssertEqual(languages.count, 12) |
| 173 | for language in languages { |
| 174 | let strings = DocsStrings(locale: Locale(identifier: language)) |
| 175 | for key in keys { |
| 176 | let value = strings(key) |
| 177 | XCTAssertNotEqual(value, key, "\(language): \(key) has no value") |
| 178 | XCTAssertFalse(value.isEmpty, "\(language): \(key) is empty") |
| 179 | } |
| 180 | XCTAssertTrue(strings("docs.share.panel.heading").contains("{title}"), language) |
| 181 | XCTAssertTrue(strings("docs.delete.heading").contains("{title}"), language) |
| 182 | XCTAssertTrue(strings("docs.share.panel.remove").contains("{address}"), language) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// /d/doc/share and its three routes, as share.go answers them in JSON. |
| 188 | actor PanelServer: NativeTransport { |
| 189 | nonisolated let origin = URL(string: "https://docs.panel.invalid")! |
| 190 | private(set) var visibility = "private" |
| 191 | private var published = false |
| 192 | private var grants: [(String, String)] = [] |
| 193 | private var links = 0 |
| 194 | private var holding = false |
| 195 | private var gates: [CheckedContinuation<Int, Never>] = [] |
| 196 | private var refuseInvite = false |
| 197 | private(set) var posts = 0 |
| 198 | |
| 199 | func hold() { holding = true } |
| 200 | var waiting: Bool { !gates.isEmpty } |
| 201 | func release(status: Int) { holding = false; gates.forEach { $0.resume(returning: status) }; gates = [] } |
| 202 | func refuseNextInvite() { refuseInvite = true } |
| 203 | |
| 204 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 205 | if method == "GET", path == "/d/doc/share" { return try state(error: "") } |
| 206 | guard method == "POST" else { return NativeResponse(data: Data(), status: 404) } |
| 207 | posts += 1 |
| 208 | var status = 200 |
| 209 | if holding { status = await withCheckedContinuation { gates.append($0) } } |
| 210 | guard status == 200 else { return NativeResponse(data: Data("docs.error.generic\n".utf8), status: status) } |
| 211 | let form = Dictionary(uniqueKeysWithValues: (URLComponents(string: "?" + String(decoding: body ?? Data(), as: UTF8.self))?.queryItems ?? []) |
| 212 | .map { ($0.name, $0.value ?? "") }) |
| 213 | switch path { |
| 214 | case "/d/doc/share": |
| 215 | if refuseInvite { refuseInvite = false; var reply = try state(error: "docs.share.error.address"); reply = NativeResponse(data: reply.data, status: 400); return reply } |
| 216 | grants.append((form["address"] ?? "", form["role"] ?? "reader")) |
| 217 | return ok() |
| 218 | case "/d/doc/share/revoke": |
| 219 | grants.removeAll { $0.0 == form["address"] } |
| 220 | return ok() |
| 221 | case "/d/doc/share/team": |
| 222 | visibility = form["visibility"] ?? visibility |
| 223 | return ok() |
| 224 | case "/d/doc/share/link": |
| 225 | published = form["on"] == "1" |
| 226 | var url = "" |
| 227 | if published { links += 1; url = "https://docs.panel.invalid/p/secret" + (links > 1 ? String(links) : "") } |
| 228 | return NativeResponse(data: try JSONSerialization.data(withJSONObject: ["published": published, "public_url": url]), status: 200, |
| 229 | headers: ["Content-Type": "application/json"]) |
| 230 | default: |
| 231 | return NativeResponse(data: Data(), status: 404) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | private func ok() -> NativeResponse { |
| 236 | NativeResponse(data: Data(#"{"ok":true}"#.utf8), status: 200, headers: ["Content-Type": "application/json"]) |
| 237 | } |
| 238 | |
| 239 | private func state(error: String) throws -> NativeResponse { |
| 240 | let rows = grants.map { ["address": $0.0, "role": $0.1] } |
| 241 | let body: [String: Any] = ["sqid": "doc", "title": "Plan", "grants": rows, "published": published, "public_url": "", |
| 242 | "visibility": visibility, "error": error] |
| 243 | return NativeResponse(data: try JSONSerialization.data(withJSONObject: body), status: 200, headers: ["Content-Type": "application/json"]) |
| 244 | } |
| 245 | |
| 246 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 247 | throw NativeClientError.notFound |
| 248 | } |
| 249 | func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| 250 | } |
| 251 | |