// A link handed to Sites (`cottonsites://open?url=…&from=post`, Comms' and Post's Open in Sites), held until Sites' list // is up. On a cold launch the scene hands the link over while only the splash stands (the core still opening), so a // handler on SitesRoot would never see it; the app's top level holds it here and SitesRoot takes it once ready. import Foundation import Observation @MainActor @Observable public final class SitesLinkInbox { public static let shared = SitesLinkInbox() /// A link handed over and not yet taken: the page to open and who handed it. struct Held: Equatable { var url: String var from: String? } private(set) var held: Held? /// The last link taken, and when: the same hand-over reaching a second handler is not opened twice. @ObservationIgnored private var taken: (link: Held, at: Date)? /// Holds `link` when it is a Sites open link; true when it was one (whoever handles links stops there). @discardableResult public func hold(_ link: URL) -> Bool { guard SitesRoot.applies, let parsed = Self.parse(link) else { return false } keep(parsed) return true } func keep(_ link: Held) { if held == link { return } if let taken, taken.link == link, Date().timeIntervalSince(taken.at) < 2 { return } held = link } /// The held link, once: SitesRoot opens the chooser on it. func take() -> Held? { guard let link = held else { return nil } held = nil taken = (link, Date()) return link } static func parse(_ link: URL) -> Held? { guard let parts = URLComponents(url: link, resolvingAgainstBaseURL: false), parts.host == "open", let url = parts.queryItems?.first(where: { $0.name == "url" })?.value, !url.isEmpty else { return nil } return Held(url: url, from: parts.queryItems?.first(where: { $0.name == "from" })?.value) } }