import Foundation import Observation import RastrilloApple /// The Share panel's state (spec 2026-11-22 §1, "Share popover"): the web /// panel's model (`docs.share.panel.*`, share_panel.go) over the share /// routes' native JSON. The Mac shows it as a popover under Share…, the /// iPhone as a sheet; both draw `DocsSharePanel` over one of these. /// /// - A switch holds its new position until its request settles; on failure /// it goes back and the callout says so. /// - One request at a time: a second submit while one is in flight is /// refused. A control waiting longer than `spinnerDelay` shows a spinner /// on itself, and nothing else is busy. /// - The once-only public URL lives only here, in memory, for as long as the /// panel shows it. It is never logged or stored, and reaches the /// pasteboard only through Copy link. While it shows, the panel is not /// dismissed by a click outside (Mac) or a swipe (iPhone). @MainActor @Observable final class DocsSharePanelModel: Identifiable { enum Role: String, CaseIterable, Sendable { case reader, writer } /// What is waiting for the server, so its own control can spin. enum Control: Hashable, Sendable { case load, invite, remove(String), team, link, newLink } let sqid: String let title: String @ObservationIgnored private let transport: @MainActor () -> NativeTransport? private(set) var information: DocsShareInformation? var inviteAddress = "" var inviteRole = Role.reader /// The callout's key: `docs.share.panel.failed`, `native.share.loadFailed`, /// or the server's own (`docs.share.error.address`). private(set) var errorKey: String? private(set) var inFlight: Control? /// The control that has waited longer than `spinnerDelay`. private(set) var spinning: Control? /// A switch's new position while its request settles. private(set) var heldTeam: Bool? private(set) var heldLink: Bool? /// The once-only URL, for this panel's lifetime only. private(set) var onceURL: URL? /// Copy link was used for the URL showing now. private(set) var copied = false /// How long a control waits before it shows a spinner (spec: 500 ms). @ObservationIgnored static var spinnerDelay: Duration = .milliseconds(500) @ObservationIgnored private var spinnerTask: Task? init(sqid: String, title: String, transport: @escaping @MainActor () -> NativeTransport?) { self.sqid = sqid; self.title = title; self.transport = transport } /// A panel in a fixed state and wired to nothing: the snapshot gate's. init(sqid: String, title: String, information: DocsShareInformation, onceURL: URL? = nil) { self.sqid = sqid; self.title = title; self.transport = { nil } self.information = information; self.onceURL = onceURL } var isBusy: Bool { inFlight != nil } /// The team rung: on while the document is on it, or held on. var teamOn: Bool { heldTeam ?? (information?.visibility == "team") } var linkOn: Bool { heldLink ?? (information?.published == true) } /// Not dismissed from outside while the once-only URL shows. var blocksOutsideDismissal: Bool { onceURL != nil } var canInvite: Bool { information != nil && !isBusy && !inviteAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } /// The panel closed: the URL is gone with it. func closed() { onceURL = nil; copied = false spinnerTask?.cancel(); spinnerTask = nil } func load() async { _ = await run(.load) { try await self.reload() } } @discardableResult func invite() async -> Bool { guard canInvite else { return false } let address = inviteAddress.trimmingCharacters(in: .whitespacesAndNewlines) let done = await mutate(.invite, path: "", values: ["address": address, "role": inviteRole.rawValue]) if done { inviteAddress = "" } return done } @discardableResult func remove(_ address: String) async -> Bool { await mutate(.remove(address), path: "/revoke", values: ["address": address]) } @discardableResult func setTeam(_ on: Bool) async -> Bool { guard information != nil, !isBusy, on != teamOn else { return false } heldTeam = on defer { heldTeam = nil } return await mutate(.team, path: "/team", values: ["visibility": on ? "team" : "private"]) } @discardableResult func setLink(_ on: Bool) async -> Bool { guard information != nil, !isBusy, on != linkOn else { return false } heldLink = on defer { heldLink = nil } return await mutate(.link, path: "/link", values: ["on": on ? "1" : "0"]) } /// Make a new link: the old one stops working, and the new one shows once. @discardableResult func newLink() async -> Bool { guard information?.published == true else { return false } return await mutate(.newLink, path: "/link", values: ["on": "1"]) } /// Copy link: the only way the URL leaves the panel. func copyLink(_ write: (URL) -> Void) { guard let onceURL else { return } write(onceURL) copied = true } // MARK: - Requests /// One request at a time; refused (false) while another is in flight. private func run(_ control: Control, _ body: @escaping () async throws -> Void) async -> Bool { guard inFlight == nil else { return false } inFlight = control spinnerTask?.cancel() spinnerTask = Task { [weak self] in try? await Task.sleep(for: Self.spinnerDelay) guard let self, !Task.isCancelled, self.inFlight == control else { return } self.spinning = control } defer { spinnerTask?.cancel(); spinnerTask = nil inFlight = nil if spinning != nil { spinning = nil } } do { try await body(); return true } catch { return false } } private func mutate(_ control: Control, path: String, values: [String: String]) async -> Bool { guard information != nil else { return false } return await run(control) { do { try await self.post(path, values: values, control: control) } catch let failure as Failure { self.errorKey = failure.key throw failure } catch { self.errorKey = "docs.share.panel.failed" throw error } // The panel shows the server's state after every change. try await self.reload() } } private struct Failure: Error { let key: String } private func client() throws -> NativeTransport { guard let client = transport() else { throw NativeClientError.unauthorized } return client } private func reload() async throws { do { let reply = try await client().responseDetails("/d/\(sqid)/share", maxBytes: 1024 * 1024) try reply.requireSuccess() let state = try JSONDecoder().decode(DocsShareInformation.self, from: reply.data) information = state if !state.published { onceURL = nil; copied = false } else if let url = URL(string: state.public_url), !state.public_url.isEmpty { adopt(url) } errorKey = nil } catch { errorKey = "native.share.loadFailed" throw error } } private func post(_ path: String, values: [String: String], control: Control) async throws { // URL query encoding leaves '+' literal; forms read it as a space. var components = URLComponents() components.queryItems = values.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } let body = Data((components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) let reply = try await client().responseDetails("/d/\(sqid)/share\(path)", method: "POST", body: body, contentType: "application/x-www-form-urlencoded", maxBytes: 1024 * 1024) if reply.status == 400, let refused = try? JSONDecoder().decode(DocsShareInformation.self, from: reply.data), !refused.error.isEmpty { throw Failure(key: refused.error) } try reply.requireSuccess() let result = try JSONDecoder().decode(DocsShareMutation.self, from: reply.data) if path == "/link" { guard let published = result.published else { throw Failure(key: "docs.share.panel.failed") } if published, let raw = result.public_url, let url = URL(string: raw), !raw.isEmpty { adopt(url) } else if !published { onceURL = nil; copied = false } } else if result.ok != true { throw Failure(key: "docs.share.panel.failed") } } private func adopt(_ url: URL) { if url != onceURL { copied = false } onceURL = url } }