// EVERY WEB LINK TAPPED IN COMMS (COMMS WITHOUT MAIL, 26 Nov 2026; sites CONTRACT row 8, "links handed to Sites"): // a message's words, the link card, Help's links. The core's `chat.link { url }` answers where it goes: Cotton Sites // when it is on the phone (its live or Dev address, by this build's kind), else Safari's own sheet inside Comms, which // keeps Safari's Open in Safari and Share. A link that is not a web page (a phone number, a mail address, another // app's own link) goes to the phone as before. Comms keeps no sites of its own. #if os(iOS) import CottonKit import SafariServices import SwiftUI import UIKit /// `chat.link`'s answer: the link, and Cotton Sites' address for it on each phone. struct ChatLinkAnswer: Decodable, Equatable, Sendable { struct Sites: Decodable, Equatable, Sendable { struct IOS: Decodable, Equatable, Sendable { var live: String; var dev: String } var ios: IOS? } var url: String var sites: Sites? } @MainActor final class ChatLinks { static let shared = ChatLinks() static let method = "chat.link" /// The core and the look, as Comms' root last gave them (`ChatLinksHost`). fileprivate var core: (any CottonCalling)? fileprivate var tint: Color? private struct Ask: Encodable, Sendable { let url: String } /// A web page to Cotton Sites, else Safari's sheet; anything else to the phone's app for it. func open(_ url: URL) { guard let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { UIApplication.shared.open(url) return } Task { if let core, let answer = try? await core.call(Self.method, Ask(url: url.absoluteString), as: ChatLinkAnswer.self), let ios = answer.sites?.ios, let sites = URL(string: AppFlavourDev.isDev ? ios.dev : ios.live), await UIApplication.shared.open(sites) { return } read(url) } } /// Safari's own sheet over whatever stands on top (a chat opens full screen over the list). private func read(_ url: URL) { let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows) guard var top = windows.first(where: \.isKeyWindow)?.rootViewController else { UIApplication.shared.open(url) return } while let presented = top.presentedViewController, !presented.isBeingDismissed { top = presented } let safari = SFSafariViewController(url: url) if let tint { safari.preferredControlTintColor = UIColor(tint) } safari.dismissButtonStyle = .done top.present(safari, animated: true) } } /// Comms' root hands the links its core and the look's accent. struct ChatLinksHost: ViewModifier { let core: any CottonCalling let look: ChatLook func body(content: Content) -> some View { content .onAppear { ChatLinks.shared.core = core; ChatLinks.shared.tint = look.colours.accent } .onChange(of: look) { _, now in ChatLinks.shared.tint = now.colours.accent } } } #endif