| 1 | import Foundation |
| 2 | import Observation |
| 3 | import RastrilloApple |
| 4 | |
| 5 | /// The Share panel's state (spec 2026-11-22 §1, "Share popover"): the web |
| 6 | /// panel's model (`docs.share.panel.*`, share_panel.go) over the share |
| 7 | /// routes' native JSON. The Mac shows it as a popover under Share…, the |
| 8 | /// iPhone as a sheet; both draw `DocsSharePanel` over one of these. |
| 9 | /// |
| 10 | /// - A switch holds its new position until its request settles; on failure |
| 11 | /// it goes back and the callout says so. |
| 12 | /// - One request at a time: a second submit while one is in flight is |
| 13 | /// refused. A control waiting longer than `spinnerDelay` shows a spinner |
| 14 | /// on itself, and nothing else is busy. |
| 15 | /// - The once-only public URL lives only here, in memory, for as long as the |
| 16 | /// panel shows it. It is never logged or stored, and reaches the |
| 17 | /// pasteboard only through Copy link. While it shows, the panel is not |
| 18 | /// dismissed by a click outside (Mac) or a swipe (iPhone). |
| 19 | @MainActor @Observable final class DocsSharePanelModel: Identifiable { |
| 20 | enum Role: String, CaseIterable, Sendable { case reader, writer } |
| 21 | /// What is waiting for the server, so its own control can spin. |
| 22 | enum Control: Hashable, Sendable { case load, invite, remove(String), team, link, newLink } |
| 23 | |
| 24 | let sqid: String |
| 25 | let title: String |
| 26 | @ObservationIgnored private let transport: @MainActor () -> NativeTransport? |
| 27 | |
| 28 | private(set) var information: DocsShareInformation? |
| 29 | var inviteAddress = "" |
| 30 | var inviteRole = Role.reader |
| 31 | /// The callout's key: `docs.share.panel.failed`, `native.share.loadFailed`, |
| 32 | /// or the server's own (`docs.share.error.address`). |
| 33 | private(set) var errorKey: String? |
| 34 | private(set) var inFlight: Control? |
| 35 | /// The control that has waited longer than `spinnerDelay`. |
| 36 | private(set) var spinning: Control? |
| 37 | /// A switch's new position while its request settles. |
| 38 | private(set) var heldTeam: Bool? |
| 39 | private(set) var heldLink: Bool? |
| 40 | /// The once-only URL, for this panel's lifetime only. |
| 41 | private(set) var onceURL: URL? |
| 42 | /// Copy link was used for the URL showing now. |
| 43 | private(set) var copied = false |
| 44 | |
| 45 | /// How long a control waits before it shows a spinner (spec: 500 ms). |
| 46 | @ObservationIgnored static var spinnerDelay: Duration = .milliseconds(500) |
| 47 | @ObservationIgnored private var spinnerTask: Task<Void, Never>? |
| 48 | |
| 49 | init(sqid: String, title: String, transport: @escaping @MainActor () -> NativeTransport?) { |
| 50 | self.sqid = sqid; self.title = title; self.transport = transport |
| 51 | } |
| 52 | |
| 53 | /// A panel in a fixed state and wired to nothing: the snapshot gate's. |
| 54 | init(sqid: String, title: String, information: DocsShareInformation, onceURL: URL? = nil) { |
| 55 | self.sqid = sqid; self.title = title; self.transport = { nil } |
| 56 | self.information = information; self.onceURL = onceURL |
| 57 | } |
| 58 | |
| 59 | var isBusy: Bool { inFlight != nil } |
| 60 | /// The team rung: on while the document is on it, or held on. |
| 61 | var teamOn: Bool { heldTeam ?? (information?.visibility == "team") } |
| 62 | var linkOn: Bool { heldLink ?? (information?.published == true) } |
| 63 | /// Not dismissed from outside while the once-only URL shows. |
| 64 | var blocksOutsideDismissal: Bool { onceURL != nil } |
| 65 | var canInvite: Bool { information != nil && !isBusy && !inviteAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } |
| 66 | |
| 67 | /// The panel closed: the URL is gone with it. |
| 68 | func closed() { |
| 69 | onceURL = nil; copied = false |
| 70 | spinnerTask?.cancel(); spinnerTask = nil |
| 71 | } |
| 72 | |
| 73 | func load() async { |
| 74 | _ = await run(.load) { try await self.reload() } |
| 75 | } |
| 76 | |
| 77 | @discardableResult func invite() async -> Bool { |
| 78 | guard canInvite else { return false } |
| 79 | let address = inviteAddress.trimmingCharacters(in: .whitespacesAndNewlines) |
| 80 | let done = await mutate(.invite, path: "", values: ["address": address, "role": inviteRole.rawValue]) |
| 81 | if done { inviteAddress = "" } |
| 82 | return done |
| 83 | } |
| 84 | |
| 85 | @discardableResult func remove(_ address: String) async -> Bool { |
| 86 | await mutate(.remove(address), path: "/revoke", values: ["address": address]) |
| 87 | } |
| 88 | |
| 89 | @discardableResult func setTeam(_ on: Bool) async -> Bool { |
| 90 | guard information != nil, !isBusy, on != teamOn else { return false } |
| 91 | heldTeam = on |
| 92 | defer { heldTeam = nil } |
| 93 | return await mutate(.team, path: "/team", values: ["visibility": on ? "team" : "private"]) |
| 94 | } |
| 95 | |
| 96 | @discardableResult func setLink(_ on: Bool) async -> Bool { |
| 97 | guard information != nil, !isBusy, on != linkOn else { return false } |
| 98 | heldLink = on |
| 99 | defer { heldLink = nil } |
| 100 | return await mutate(.link, path: "/link", values: ["on": on ? "1" : "0"]) |
| 101 | } |
| 102 | |
| 103 | /// Make a new link: the old one stops working, and the new one shows once. |
| 104 | @discardableResult func newLink() async -> Bool { |
| 105 | guard information?.published == true else { return false } |
| 106 | return await mutate(.newLink, path: "/link", values: ["on": "1"]) |
| 107 | } |
| 108 | |
| 109 | /// Copy link: the only way the URL leaves the panel. |
| 110 | func copyLink(_ write: (URL) -> Void) { |
| 111 | guard let onceURL else { return } |
| 112 | write(onceURL) |
| 113 | copied = true |
| 114 | } |
| 115 | |
| 116 | // MARK: - Requests |
| 117 | |
| 118 | /// One request at a time; refused (false) while another is in flight. |
| 119 | private func run(_ control: Control, _ body: @escaping () async throws -> Void) async -> Bool { |
| 120 | guard inFlight == nil else { return false } |
| 121 | inFlight = control |
| 122 | spinnerTask?.cancel() |
| 123 | spinnerTask = Task { [weak self] in |
| 124 | try? await Task.sleep(for: Self.spinnerDelay) |
| 125 | guard let self, !Task.isCancelled, self.inFlight == control else { return } |
| 126 | self.spinning = control |
| 127 | } |
| 128 | defer { |
| 129 | spinnerTask?.cancel(); spinnerTask = nil |
| 130 | inFlight = nil |
| 131 | if spinning != nil { spinning = nil } |
| 132 | } |
| 133 | do { try await body(); return true } catch { return false } |
| 134 | } |
| 135 | |
| 136 | private func mutate(_ control: Control, path: String, values: [String: String]) async -> Bool { |
| 137 | guard information != nil else { return false } |
| 138 | return await run(control) { |
| 139 | do { |
| 140 | try await self.post(path, values: values, control: control) |
| 141 | } catch let failure as Failure { |
| 142 | self.errorKey = failure.key |
| 143 | throw failure |
| 144 | } catch { |
| 145 | self.errorKey = "docs.share.panel.failed" |
| 146 | throw error |
| 147 | } |
| 148 | // The panel shows the server's state after every change. |
| 149 | try await self.reload() |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | private struct Failure: Error { let key: String } |
| 154 | |
| 155 | private func client() throws -> NativeTransport { |
| 156 | guard let client = transport() else { throw NativeClientError.unauthorized } |
| 157 | return client |
| 158 | } |
| 159 | |
| 160 | private func reload() async throws { |
| 161 | do { |
| 162 | let reply = try await client().responseDetails("/d/\(sqid)/share", maxBytes: 1024 * 1024) |
| 163 | try reply.requireSuccess() |
| 164 | let state = try JSONDecoder().decode(DocsShareInformation.self, from: reply.data) |
| 165 | information = state |
| 166 | if !state.published { onceURL = nil; copied = false } |
| 167 | else if let url = URL(string: state.public_url), !state.public_url.isEmpty { adopt(url) } |
| 168 | errorKey = nil |
| 169 | } catch { |
| 170 | errorKey = "native.share.loadFailed" |
| 171 | throw error |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | private func post(_ path: String, values: [String: String], control: Control) async throws { |
| 176 | // URL query encoding leaves '+' literal; forms read it as a space. |
| 177 | var components = URLComponents() |
| 178 | components.queryItems = values.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } |
| 179 | let body = Data((components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) |
| 180 | let reply = try await client().responseDetails("/d/\(sqid)/share\(path)", method: "POST", body: body, |
| 181 | contentType: "application/x-www-form-urlencoded", maxBytes: 1024 * 1024) |
| 182 | if reply.status == 400, let refused = try? JSONDecoder().decode(DocsShareInformation.self, from: reply.data), !refused.error.isEmpty { |
| 183 | throw Failure(key: refused.error) |
| 184 | } |
| 185 | try reply.requireSuccess() |
| 186 | let result = try JSONDecoder().decode(DocsShareMutation.self, from: reply.data) |
| 187 | if path == "/link" { |
| 188 | guard let published = result.published else { throw Failure(key: "docs.share.panel.failed") } |
| 189 | if published, let raw = result.public_url, let url = URL(string: raw), !raw.isEmpty { adopt(url) } |
| 190 | else if !published { onceURL = nil; copied = false } |
| 191 | } else if result.ok != true { |
| 192 | throw Failure(key: "docs.share.panel.failed") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | private func adopt(_ url: URL) { |
| 197 | if url != onceURL { copied = false } |
| 198 | onceURL = url |
| 199 | } |
| 200 | } |
| 201 | |