// 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) import CottonKit import LocalAuthentication import SwiftUI import UIKit import WebKit /// A sheet over the list or a page. enum SitesRaised: Identifiable, Equatable { case more case switcher case choose(SitesChoice, moving: Bool, from: String?) case forget(SitesRow, SitesAsk, first: String?) case add(home: String?, thenOpen: String?) case site(SitesRow) case arrange case size case ask(SitesRow, kind: String, line: String, yes: String) case twins(SitesHome.Twins) case stores([SitesGoneStore]) case orphan(SitesHome.Orphan) var id: String { switch self { 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). enum SitesPlace: Equatable { case search case you case engine case storage case look case privacy case sync case hideAfter case help case about case hiddenLock } /// A removal the core holds for Undo (one site, or the extras Keep one dropped). struct SitesRemoving: Equatable { let ids: [String] let words: String let undo: String } @MainActor @Observable final class SitesModel { let core: any CottonCalling let book: SitesCalls private(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? private var toastTask: Task? /// A removal the core holds for Undo, as long as it says (SYNC-DESIGN, Remove). private(set) var removing: SitesRemoving? private var removingTask: Task? private var 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 = false var 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 = core var book = SitesCalls(core: core) if let key { book.key = key } self.book = book SitesLive.shared.core = core } // MARK: The list func refresh() async { do { home = try await 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 = true defer { sweeping = false } guard let owed = try? await book.storesOwed(), !owed.stores.isEmpty, !owed.kept else { return } let gone = owed.stores if gone.count > Self.askAbove { guard sheet == nil, page == nil else { 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. static let 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 = true defer { sweeping = false } await removeStores(gone) } private func 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 } } guard let id = UUID(uuidString: owed.storeUUID) else { removed.append(owed.store); continue } do { try await 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; return SitesLive.shared.isAlive(id) } func tell(_ words: String) { toastTask?.cancel() withAnimation(.easeOut(duration: 0.2)) { toast = words } toastTask = Task { @MainActor in try? await Task.sleep(for: .seconds(2.6)) guard !Task.isCancelled else { return } withAnimation(.easeOut(duration: 0.3)) { toast = nil } } } private func 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). func open(_ row: SitesRow, url: String? = nil, from: String? = nil) async { do { let opened = try await 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 in Task { try? await book.left(id, url: url.absoluteString, title: title) } } } show(page) await SitesLive.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 = try await 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). if let 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. private func trackersReady(_ id: String) async { guard SitesTrackers.list == nil, let answer = try? await book.trackers(id) else { return } _ = await SitesTrackers.prepare(rules: answer.rules) } private func show(_ page: SitesPage) { sheet = nil place = nil finding = false SitesLive.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. private func leaveFront() async { guard let page else { return } await page.takePicture() if let 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 += 1 await 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 { guard let 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 } await open(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 { guard let page else { return } guard let row = page.row else { SitesLive.shared.end(page.id) await backToList() return } do { let answer = try await book.close(row.id) if let ask = answer.ask { sheet = .forget(row, ask, first: answer.first) return } SitesLive.shared.end(row.id) await backToList() if let 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 = nil defer { 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 { guard let row = page?.row else { return } do { let answer = try await book.forget(row.id) if let 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). static func webKitStarted() { _ = started } private static let started: Void = { _ = WKWebsiteDataStore.nonPersistent() }() /// A site's store, deleted (its sign-in and everything it kept on this phone). func clearStore(_ row: SitesRow) async { guard let id = UUID(uuidString: row.storeUUID) else { return } Self.webKitStarted() do { try await 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 = try await 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 = false switch first.kind { case "search": await openQuick(first.url, search: true) case "address" where quick: await openQuick(first.url) case "address": if let url = first.url { await choose(url) } default: // The clipboard is read only now, on his tap (`hasURLs` asked nothing before). if let 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 = nil await open(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). if ProcessInfo.processInfo.arguments.contains("-sites-skip-face") { unlocked = true await refresh() return true } #endif if DeviceLock.isSet { guard await DeviceLock.ask(SitesWords.line("hidden.unlock")) else { return false } } else { #if COTTON_DEV // The simulator has no passcode: Sites Dev shows them (never the real build). #else return false #endif } unlocked = true await refresh() return true } /// Hide: hidden sites leave the list, and their live pages end. func hide() async { defer { liveTick += 1 } unlocked = false for row in home?.hidden.rows ?? [] { SitesLive.shared.end(row.id) } if let 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 { if let 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 in try? await Task.sleep(for: .seconds(60)) if !Task.isCancelled { await hide() } } } else { await hide() } } } private var hideTask: Task? func cameBack() { hideTask?.cancel() hideTask = nil } // MARK: Adding, arranging, a site's settings func add(label: String, home: String, stay: Bool, hidden: Bool, thenOpen: String?) async -> Bool { do { let (row, said) = try await book.add(label: label, home: home, stay: stay, hidden: hidden) sheet = nil await refresh() if let said { tell(said) } if let thenOpen { await open(rows.first { $0.id == row.id } ?? row, url: thenOpen) } return true } catch { refused(error) return false } } func edit(_ row: SitesRow, _ fields: [String: SitesValue]) async -> SitesRow? { do { let (changed, _) = try await 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 } ?? changed SitesLive.shared.page(row.id)?.update(full) return full } catch { refused(error) return nil } } func arrange(order: [String], pinned: [String]) async { do { let said = try await 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 = nil await 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 = try await book.delete(row.id) sheet = nil await refresh() let words = answer.said ?? SitesWords.line("said.removed", ["label": row.label]) if let 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 = try await book.keepOne(keep: keep.id, drop: drop).undo ?? undo dropped.append(drop) } catch { refused(error); break } } sheet = nil liveTick += 1 await refresh() guard !dropped.isEmpty else { return } let words = SitesWords.line("said.removed", ["label": keep.label]) if let undo { offerUndo(dropped, words: words, undo) } else { tell(words) } } private func 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 [weak self] in try? await Task.sleep(for: .seconds(undo.seconds)) guard !Task.isCancelled, let self else { 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? await Task.sleep(for: .milliseconds(400)) await self.refresh() } } /// Undo: the core puts the site back where it stood. func undoRemove() async { guard let waiting = removing else { return } removingTask?.cancel() removingTask = nil withAnimation(.easeOut(duration: 0.2)) { removing = nil } do { for id in waiting.ids { try await book.undo(id) } } catch { refused(error) } liveTick += 1 await refresh() } /// The earlier Sites' list that will not open on this phone: Leave them sets it aside here. func leaveBook() async { do { try await 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 = true let before = Set(((try? await book.storesGone()) ?? []).map(\.store)) do { if try await book.orphanRemove(orphan.id) > 0 { let freed = ((try? await book.storesGone()) ?? []).filter { !before.contains($0.store) } await removeStores(freed) } } catch { refused(error) } sweeping = false await refresh() } // MARK: Settings func readSettings() async { do { settings = try await book.settings() } catch { refused(error) } } func set(_ name: String, _ value: SitesValue) async { do { settings = try await 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 = try await book.storage(sizes) } catch { refused(error) } } /// What a site's store holds on disk: WebKit keeps each under Library/WebKit//WebsiteDataStore/. static func size(of row: SitesRow) -> Int { guard let library = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else { return 0 } 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)) } } private static func bytes(in folder: URL) -> Int { guard let walk = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.totalFileAllocatedSizeKey]) else { return 0 } var total = 0 for case let 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 settings func keeps(_ row: SitesRow) -> String { let say = ByteCountFormatter() say.countStyle = .file say.allowsNonnumericFormatting = false return 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. enum SitesAppDev { /// `-sites-fresh`: the key forgotten, so the list starts empty. static var 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). static var seed: Bool { ProcessInfo.processInfo.arguments.contains("-sites-seed") } /// `-sites-open