Cotton code
53 lines · 2.5 KB · SwiftRaw
// The share walk (8 Nov 2026): Safari's share sheet does// not open "More" under XCUITest, so `testWalkUrlShare` could not reach the// app in the sheet and the step was walked by hand. Launched with// `-walk-share <url>` (a development build only), the app makes the item the// sheet would hand its extension — an `NSExtensionItem` with the URL as its// one attachment and, with `-walk-share-title <words>`, the page's title as// its content text, as Safari shares a page — and reads it through the extension's own reader// (`ShareItems.accept`) into this app's mailbox, then knocks as the extension// does: the drain that follows is the one a real share runs.import CottonKitimport Foundationimport UniformTypeIdentifiers@MainActorenum ShareWalk {    private static var arguments: [String] { ProcessInfo.processInfo.arguments }    /// The link asked for, or none.    static var link: URL? {        guard let at = arguments.firstIndex(of: "-walk-share"), at + 1 < arguments.count else { return nil }        return URL(string: arguments[at + 1]).flatMap { $0.scheme?.hasPrefix("http") == true ? $0 : nil }    }    /// The page's title the sharing app would carry, or none.    static var title: String? {        guard let at = arguments.firstIndex(of: "-walk-share-title"), at + 1 < arguments.count else { return nil }        return arguments[at + 1]    }    /// The link written into the mailbox as a share, once per launch; true    /// when an entry was written and the caller should knock.    static func share() async -> Bool {        #if COTTON_DEV        guard let link, !shared else { return false }        shared = true        let item = NSExtensionItem()        // The URL registered as an ITEM under public.url, as Safari hands it:        // `NSItemProvider(object:)` registers a data representation instead,        // whose `loadItem` answers bytes the reader rightly takes for no URL        // (walk, 8 Nov 2026: "walk-share: 0 entries").        item.attachments = [NSItemProvider(item: link as NSURL, typeIdentifier: UTType.url.identifier)]        if let title { item.attributedContentText = NSAttributedString(string: title) }        let written = await ShareItems.accept([item], stamp: CottonDate.format(Date()))        Log.write("walk-share: \(written.count) entr\(written.count == 1 ? "y" : "ies") for \(link.absoluteString)")        return !written.isEmpty        #else        return false        #endif    }    private static var shared = false}