// COTTON SITES' STATE (assets/design/sites/DECISIONS.md "Structure"): one place, the list; everything else rises from// it or from the bar on an open page, and goes back to it. The core answers every word and decision; this holds what// is on screen, the page in front, and the sheet raised over it.#if os(iOS)importCottonKitimportLocalAuthenticationimportSwiftUIimport UIKitimportWebKit/// A sheet over the list or a page.enumSitesRaised: Identifiable, Equatable {case morecase switchercase choose(SitesChoice, moving: Bool, from: String?)case forget(SitesRow, SitesAsk, first: String?)case add(home: String?, thenOpen: String?)case site(SitesRow)case arrangecase sizecase ask(SitesRow, kind: String, line: String, yes: String)case twins(SitesHome.Twins)case stores([SitesGoneStore])case orphan(SitesHome.Orphan)var id: String {switchself {case .more: "more"case .switcher: "switcher"case .choose(let c, let moving, _): "choose-\(c.url)-\(moving)"case .forget(let r, _, _): "forget-\(r.id)"case .add(let home, _): "add-\(home ?? "")"case .site(let r): "site-\(r.id)"case .arrange: "arrange"case .size: "size"case .ask(let r, let kind, _, _): "ask-\(kind)-\(r.id)"case .twins(let t): "twins-\(t.id)"case .stores: "stores"case .orphan(let o): "orphan-\(o.id)" } }}/// A full page over the list (You and its pages, search, the hidden lock).enumSitesPlace: Equatable {case searchcase youcase enginecase storagecase lookcase privacycase synccase hideAftercase helpcase aboutcase hiddenLock}/// A removal the core holds for Undo (one site, or the extras Keep one dropped).structSitesRemoving: Equatable {let ids: [String]let words: Stringlet undo: String}@MainActor @ObservablefinalclassSitesModel {let core: any CottonCallinglet book: SitesCallsprivate(set) var home: SitesHome?/// Hidden sites shown (after Face ID), until he taps Hide or leaves Sites.private(set) var unlocked = false/// The page in front; nil is the list.private(set) var page: SitesPage?var sheet: SitesRaised?var place: SitesPlace?/// A line passing at the foot.var toast: String?privatevar toastTask: Task<Void, Never>?/// A removal the core holds for Undo, as long as it says (SYNC-DESIGN, Remove).private(set) var removing: SitesRemoving?privatevar removingTask: Task<Void, Never>?privatevar sweeping = false/// Find on this page: the bar becomes the find line.var finding = false/// The search line was opened for a quick visit: what he types opens there, keeping nothing.var quickNext = falsevar settings: SitesSettings?var storage: SitesStorage?/// The live pages changed (the list's dots).private(set) var liveTick = 0/// The list could not be read with this phone's key: it was set aside.private(set) var unreadable: String?init(core: any CottonCalling, key: (@Sendable () throws -> String)? = nil) {self.core = corevar book = SitesCalls(core: core)iflet key { book.key = key }self.book = bookSitesLive.shared.core = core }// MARK: The listfunc refresh() async {do { home = tryawait book.home(unlocked: unlocked) unreadable = nil } catch { unreadable = (error as? SitesRefusal)?.words ?? SitesWords.line("refused.unreadable")return }await sweepStores() }/// The website stores the core says are owed (removals whose Undo ran out, sites removed on his other phones, sites/// left off at sign-in, a deleted account's): each removed from WebKit, then told back to the core. More than/// `askAbove` in one answer is never removed without his yes (the coordinator, SITES ROWS 3: a sign-in store goes/// only for his own remove or a held delete, never en masse); "Keep for now" is told to the core, which asks again/// only once the set of removed sites grows.func sweepStores() async {guard !sweeping else { return } sweeping = truedefer { sweeping = false }guardlet owed = try? await book.storesOwed(), !owed.stores.isEmpty, !owed.kept else { return }let gone = owed.storesif gone.count > Self.askAbove {guard sheet == nil, page == nilelse { return } withAnimation(.easeOut(duration: 0.2)) { sheet = .stores(gone) }return }await removeStores(gone) }/// At most this many website stores go in one answer without asking.staticlet askAbove = 3/// His answer to "Delete the sign-ins of 5 removed sites?": yes removes them now; no keeps them, asked again only/// once the set grows (`sites.stores.keep`).func answerStores(_ gone: [SitesGoneStore], delete: Bool) async { withAnimation(.easeOut(duration: 0.2)) { sheet = nil }guard delete else { try? await book.storesKeep(gone.map(\.store)); return } sweeping = truedefer { sweeping = false }await removeStores(gone) }privatefunc removeStores(_ gone: [SitesGoneStore]) async {Self.webKitStarted()var removed: [String] = []for owed in gone {if owed.store.hasPrefix("site-") {let id = String(owed.store.dropFirst(5))SitesLive.shared.end(id)if page?.row?.id == id { SitesLive.shared.showing = nil; page = nil } }guardlet id = UUID(uuidString: owed.storeUUID) else { removed.append(owed.store); continue }do {tryawait WKWebsiteDataStore.remove(forIdentifier: id) removed.append(owed.store) } catch {// Never made on this phone (a site that only ever lived on another): gone all the same.if !(await WKWebsiteDataStore.allDataStoreIdentifiers).contains(id) { removed.append(owed.store) } } }if !removed.isEmpty { try? await book.storesRemoved(removed) } }/// Every site shown now, in his order: pinned, then the rest, then hidden ones while they show.var rows: [SitesRow] { (home?.rows ?? []) + (home?.hidden.rows ?? []) }func isLive(_ id: String) -> Bool { _ = liveTick; returnSitesLive.shared.isAlive(id) }func tell(_ words: String) { toastTask?.cancel() withAnimation(.easeOut(duration: 0.2)) { toast = words } toastTask = Task { @MainActor intry? awaitTask.sleep(for: .seconds(2.6))guard !Task.isCancelled else { return } withAnimation(.easeOut(duration: 0.3)) { toast = nil } } }privatefunc refused(_ error: Error) { tell((error as? SitesRefusal)?.words ?? ActionRefused.words(for: error)) }// MARK: Opening and switching/// Opens a site: its live page as left, else at its last page (by its saved state), or at `url` (a link).funcopen(_ row: SitesRow, url: String? = nil, from: String? = nil) async {do {let opened = tryawait book.open(id: row.id, url: url, from: from)await trackersReady(row.id)await leaveFront()let page = SitesLive.shared.page(for: row, opened: opened, link: url.flatMap(URL.init(string:)))if row.stay {let id = row.id, book = book page.report = { url, title inTask { try? await book.left(id, url: url.absoluteString, title: title) } } } show(page)awaitSitesLive.shared.switched(to: row.id, book: book, showing: row.id) liveTick += 1 } catch { refused(error) } }/// A quick visit (keeps nothing at all) or a search's throwaway place, at `url`.func openQuick(_ url: String?, search: Bool = false) async {do {let opened = tryawait book.open(id: nil, url: url, quick: !search, search: search)// The rules are the same for every site; a quick visit has no row to ask by, so any site's asks (none kept:// nothing to ask by, and WebKit's own tracking prevention is all that stands).iflet any = rows.first { await trackersReady(any.id) }await leaveFront()let page = SitesLive.shared.page(for: nil, opened: opened, link: nil)if search { page.engineHost = URL(string: opened.url)?.host()?.replacingOccurrences(of: "www.", with: "") } show(page) } catch { refused(error) } }/// The tracker list compiled before the first page that needs it (CONTRACT Trackers: `sites.trackers` as a site/// opens); once compiled, it is not asked again this launch.privatefunc trackersReady(_ id: String) async {guardSitesTrackers.list == nil, let answer = try? await book.trackers(id) else { return } _ = awaitSitesTrackers.prepare(rules: answer.rules) }privatefunc show(_ page: SitesPage) { sheet = nil place = nil finding = falseSitesLive.shared.showing = page.id withAnimation(.easeOut(duration: 0.22)) { self.page = page } UIAccessibility.post(notification: .screenChanged, argument: nil) }/// The page in front is left, never closed: its state goes to the book (a site that stays signed in) and its/// picture is kept in memory, so it comes back as it was even if the system lets it go.privatefunc leaveFront() async {guardlet page else { return }await page.takePicture()iflet row = page.row, row.stay, let state = page.state {try? await book.keepState(row.id, state.base64EncodedString()) }if page.isQuick {// A search or a quick visit lives only while it is in front: leaving it is closing it.SitesLive.shared.end(page.id) } }/// Back to sites: switching, not closing.func backToList() async {await leaveFront()SitesLive.shared.showing = nil finding = false withAnimation(.easeOut(duration: 0.22)) { page = nil } liveTick += 1await refresh() UIAccessibility.post(notification: .screenChanged, argument: nil) }/// The next or previous site in his order, from a swipe on the bar's name.func step(_ by: Int) async {guardlet current = page?.row, let at = rows.firstIndex(where: { $0.id == current.id }), !rows.isEmpty else { return }let next = rows[(at + by + rows.count) % rows.count]guard next.id != current.id else { return }awaitopen(next) }// MARK: Closing/// Close this page: the site stays signed in and opens at this address next time; a site that forgets asks first;/// a quick visit or a search ends.func closePage() async {guardlet page else { return }guardlet row = page.row else {SitesLive.shared.end(page.id)await backToList()return }do {let answer = tryawait book.close(row.id)iflet ask = answer.ask { sheet = .forget(row, ask, first: answer.first)return }SitesLive.shared.end(row.id)await backToList()iflet said = answer.said { tell(said) } } catch { refused(error) } }/// Close and forget, asked: the store goes, sign-in and all; the site stays in the list.func forget(_ row: SitesRow) async { sheet = nildefer { liveTick += 1 }SitesLive.shared.end(row.id)await clearStore(row)try? await book.left(row.id, url: nil, title: nil)if page?.row?.id == row.id {SitesLive.shared.showing = nil withAnimation(.easeOut(duration: 0.22)) { page = nil } }await refresh() }/// The asking a site that forgets puts before Close and forget, from More.func askForget() async {guardlet row = page?.row else { return }do {let answer = tryawait book.forget(row.id)iflet ask = answer.ask { sheet = .forget(row, ask, first: answer.first) } } catch { refused(error) } }/// WebKit started on the main thread before a store is removed: removing one before any WebKit object exists (a/// sweep at launch, before the first page) crashes inside WebKit's run loop (found in SitesRowsTests).staticfunc webKitStarted() { _ = started }privatestaticlet started: Void = { _ = WKWebsiteDataStore.nonPersistent() }()/// A site's store, deleted (its sign-in and everything it kept on this phone).func clearStore(_ row: SitesRow) async {guardlet id = UUID(uuidString: row.storeUUID) else { return }Self.webKitStarted()do { tryawait WKWebsiteDataStore.remove(forIdentifier: id) } catch {let store = WKWebsiteDataStore(forIdentifier: id)await store.removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: .distantPast) } }// MARK: Search and the chooser/// Where a link opens: the chooser, his sites at that address first. Nothing loads until he picks.func choose(_ url: String, moving: Bool = false, from: String? = nil) async {do {let choice = tryawait book.choose(url, from: from, moving: moving, unlocked: unlocked) withAnimation(.easeOut(duration: 0.22)) { sheet = .choose(choice, moving: moving, from: from) } } catch { refused(error) } }/// A quick visit: the search line first, so it opens where he types, never on a blank page.func startQuick() { quickNext = true sheet = nil place = .search }/// The search line's first line, tapped.func go(_ first: SitesFound.First) async {let quick = quickNext quickNext = falseswitch first.kind {case"search": await openQuick(first.url, search: true)case"address"where quick: await openQuick(first.url)case"address": iflet url = first.url { await choose(url) }default:// The clipboard is read only now, on his tap (`hasURLs` asked nothing before).iflet url = UIPasteboard.general.url?.absoluteString ?? UIPasteboard.general.string, (try? await book.plan(url)) != nil {await choose(url) } else { tell(SitesWords.line("search.copied_none")) } } }/// A pick in the chooser.func picked(_ row: SitesRow, in choice: SitesChoice, from: String?) async { sheet = nilawaitopen(row, url: choice.url, from: from) }/// Hidden sites shown: Face ID or the passcode, then the list (and the chooser) offer them.func unlock() async -> Bool { #if COTTON_DEV// `-sites-skip-face`: a walk on a simulator, where no face can be shown to it (never the real build).ifProcessInfo.processInfo.arguments.contains("-sites-skip-face") { unlocked = trueawait refresh()returntrue } #endififDeviceLock.isSet {guardawaitDeviceLock.ask(SitesWords.line("hidden.unlock")) else { returnfalse } } else { #if COTTON_DEV// The simulator has no passcode: Sites Dev shows them (never the real build). #elsereturnfalse #endif } unlocked = trueawait refresh()returntrue }/// Hide: hidden sites leave the list, and their live pages end.func hide() async {defer { liveTick += 1 } unlocked = falsefor row in home?.hidden.rows ?? [] { SitesLive.shared.end(row.id) }iflet row = page?.row, row.hidden {SitesLive.shared.showing = nil page = nil }await refresh() }// MARK: Sites leaving the screen/// Sites left the screen: hidden sites hide (unless he chose a minute), quick visits not in front end, and the/// page in front keeps its state in the book.func wentAway() async {iflet page, let row = page.row, row.stay, let state = page.state {try? await book.keepState(row.id, state.base64EncodedString()) }let minute = settings?.rows.first { $0.id == "hide_after" }?.text == "minute"if unlocked {if minute { hideTask = Task { @MainActor intry? awaitTask.sleep(for: .seconds(60))if !Task.isCancelled { await hide() } } } else {await hide() } } }privatevar hideTask: Task<Void, Never>?func cameBack() { hideTask?.cancel() hideTask = nil }// MARK: Adding, arranging, a site's settingsfunc add(label: String, home: String, stay: Bool, hidden: Bool, thenOpen: String?) async -> Bool {do {let (row, said) = tryawait book.add(label: label, home: home, stay: stay, hidden: hidden) sheet = nilawait refresh()iflet said { tell(said) }iflet thenOpen { awaitopen(rows.first { $0.id == row.id } ?? row, url: thenOpen) }returntrue } catch { refused(error)returnfalse } }func edit(_ row: SitesRow, _ fields: [String: SitesValue]) async -> SitesRow? {do {let (changed, _) = tryawait book.edit(row.id, fields)// A new home, or Stay signed in turned off: the live page ends, so it opens fresh.if fields["home"] != nil || (fields["stay"] != nil && !changed.stay) { SitesLive.shared.end(row.id) }await refresh()let full = rows.first { $0.id == row.id } ?? changedSitesLive.shared.page(row.id)?.update(full)return full } catch { refused(error)returnnil } }func arrange(order: [String], pinned: [String]) async {do {let said = tryawait book.arrange(order: order, pinned: pinned)await refresh() tell(said) } catch { refused(error) } }/// Sign out: what the site stored goes; the site stays.func signOut(_ row: SitesRow) async {defer { liveTick += 1 }SitesLive.shared.end(row.id)if page?.row?.id == row.id { SitesLive.shared.showing = nil; page = nil }await clearStore(row)try? await book.left(row.id, url: nil, title: nil) sheet = nilawait refresh() tell(SitesWords.line("said.signed_out", ["label": row.label])) }/// Remove: the site leaves the list at once and the core holds it for Undo; when the time is up the core erases it/// (never to the Bin) and owes its website store, removed by the next sweep.func remove(_ row: SitesRow) async {defer { liveTick += 1 }SitesLive.shared.end(row.id)if page?.row?.id == row.id { SitesLive.shared.showing = nil; page = nil }do {let answer = tryawait book.delete(row.id) sheet = nilawait refresh()let words = answer.said ?? SitesWords.line("said.removed", ["label": row.label])iflet undo = answer.undo { offerUndo([row.id], words: words, undo) } else { tell(words) } } catch { refused(error) } }/// Keep one of a twin group: every other site in it is removed, with one Undo for them all.func keepOne(_ keep: SitesRow, of twins: SitesHome.Twins) async {let drops = twins.ids.filter { $0 != keep.id }var dropped: [String] = []var undo: SitesUndo?for drop in drops {SitesLive.shared.end(drop)if page?.row?.id == drop { SitesLive.shared.showing = nil; page = nil }do { undo = tryawait book.keepOne(keep: keep.id, drop: drop).undo ?? undo dropped.append(drop) } catch { refused(error); break } } sheet = nil liveTick += 1await refresh()guard !dropped.isEmpty else { return }let words = SitesWords.line("said.removed", ["label": keep.label])iflet undo { offerUndo(dropped, words: words, undo) } else { tell(words) } }privatefunc offerUndo(_ ids: [String], words: String, _ undo: SitesUndo) { removingTask?.cancel() toastTask?.cancel() toast = nil withAnimation(.easeOut(duration: 0.2)) { removing = SitesRemoving(ids: ids, words: words, undo: undo.label) } removingTask = Task { @MainActor [weakself] intry? awaitTask.sleep(for: .seconds(undo.seconds))guard !Task.isCancelled, letselfelse { return } withAnimation(.easeOut(duration: 0.3)) { self.removing = nil }self.removingTask = nil// The core erases at its next look past the time; the list is read again so it does, and its stores go.try? awaitTask.sleep(for: .milliseconds(400))awaitself.refresh() } }/// Undo: the core puts the site back where it stood.func undoRemove() async {guardlet waiting = removing else { return } removingTask?.cancel() removingTask = nil withAnimation(.easeOut(duration: 0.2)) { removing = nil }do { for id in waiting.ids { tryawait book.undo(id) } } catch { refused(error) } liveTick += 1await refresh() }/// The earlier Sites' list that will not open on this phone: Leave them sets it aside here.func leaveBook() async {do {tryawait book.bookLeave()await refresh() } catch { refused(error) } }// MARK: Sign-ins for sites no longer in the list/// Remove asked for one of them, by name.func askOrphan(_ orphan: SitesHome.Orphan) { withAnimation(.easeOut(duration: 0.2)) { sheet = .orphan(orphan) } }/// He said Remove: that one sign-in goes (the core checks it again), and the store it frees is removed at once: his/// yes was for it, so it never waits behind other owed stores or raises the many-at-once ask.func removeOrphan(_ orphan: SitesHome.Orphan) async { withAnimation(.easeOut(duration: 0.2)) { sheet = nil } sweeping = truelet before = Set(((try? await book.storesGone()) ?? []).map(\.store))do {iftryawait book.orphanRemove(orphan.id) > 0 {let freed = ((try? await book.storesGone()) ?? []).filter { !before.contains($0.store) }await removeStores(freed) } } catch { refused(error) } sweeping = falseawait refresh() }// MARK: Settingsfunc readSettings() async {do { settings = tryawait book.settings() } catch { refused(error) } }func set(_ name: String, _ value: SitesValue) async {do { settings = tryawait book.set(name, value) } catch { refused(error) } }/// What each site keeps on this phone, measured here (WebKit's folder for its store), said by the core.func readStorage() async {let all = (home?.rows ?? []) + (home?.hidden.rows ?? [])var sizes: [String: Int] = [:]for row in all { sizes[row.id] = Self.size(of: row) }do { storage = tryawait book.storage(sizes) } catch { refused(error) } }/// What a site's store holds on disk: WebKit keeps each under Library/WebKit/<bundle id>/WebsiteDataStore/<uuid>.staticfunc size(of row: SitesRow) -> Int {guardlet library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else { return0 }let stores = library.appendingPathComponent("WebKit/\(Bundle.main.bundleIdentifier ?? "")/WebsiteDataStore", isDirectory: true)let names = (try? FileManager.default.contentsOfDirectory(atPath: stores.path)) ?? []return names.filter { $0.caseInsensitiveCompare(row.storeUUID) == .orderedSame } .reduce(0) { $0 + bytes(in: stores.appendingPathComponent($1, isDirectory: true)) } }privatestaticfunc bytes(in folder: URL) -> Int {guardlet walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]) else { return0 }var total = 0forcaselet file as URL in walk { total += (try? file.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize) ?? 0 }return total }/// Sign out of every site: each stays in the list and asks him to sign in again.func signOutAll() async {for row in rows {SitesLive.shared.end(row.id)await clearStore(row)try? await book.left(row.id, url: nil, title: nil) }await refresh()await readStorage() }// MARK: A site's numbers, for its settingsfunc keeps(_ row: SitesRow) -> String {let say = ByteCountFormatter() say.countStyle = .file say.allowsNonnumericFormatting = falsereturn say.string(fromByteCount: Int64(Self.size(of: row))) }}#if COTTON_DEV/// Sites Dev's launch words, for walks on a simulator with invented sites only.enumSitesAppDev {/// `-sites-fresh`: the key forgotten, so the list starts empty.staticvar fresh: Bool { ProcessInfo.processInfo.arguments.contains("-sites-fresh") }/// `-sites-seed`: invented sites, two at the invented club on this Mac (`scripts/invented-site.py`, port 8765).staticvar seed: Bool { ProcessInfo.processInfo.arguments.contains("-sites-seed") }/// `-sites-open <label>`: that site opened at launch.staticvaropen: String? {let args = ProcessInfo.processInfo.argumentsguardlet at = args.firstIndex(of: "-sites-open"), at + 1 < args.count else { returnnil }return args[at + 1] }/// `-sites-link <url> [-sites-from <app>]`: a link handed over as a Cotton app would, for the chooser's walk.staticvar link: (url: String, from: String?)? {let args = ProcessInfo.processInfo.argumentsguardlet at = args.firstIndex(of: "-sites-link"), at + 1 < args.count else { returnnil }let from = args.firstIndex(of: "-sites-from").flatMap { $0 + 1 < args.count ? args[$0 + 1] : nil }return (args[at + 1], from) } @MainActor staticfunc prepare(_ model: SitesModel) async {if fresh { SitesAppKey.forget() }guard seed else { return }await model.refresh()guard model.home?.rows.isEmpty ?? true, model.home?.hidden.locked ?? trueelse { return }let invented: [(String, String, Bool, Bool, Bool)] = [ ("Work mail", "http://localhost:8765/", true, false, true), ("Personal mail", "http://localhost:8765/", true, false, true), ("Quill, work", "quill.example", true, false, false), ("Orbit", "http://127.0.0.1:8766/", true, false, false), ("Family mail", "http://localhost:8765/", false, false, false), ("Shipyard", "shipyard.example", true, false, false), ("Clinic portal", "care.example", true, true, false),// Trackers measured: the invented site's page asks three tracker hosts and two that are not (IPHONE READY 1). ("Trackers", "http://localhost:8765/trackers", false, false, false), ]for (label, home, stay, hidden, pinned) in invented { _ = try? await model.book.add(label: label, home: home, stay: stay, hidden: hidden, pinned: pinned) }await model.refresh() }}#endif#endif