Cotton code
942 lines · 51.1 KB · SwiftRaw
// Which screen a route opens — ONE table, total over `Route`.//// Before I2 this was four dispatchers in three styles: a predicate plus a// builder for the work lane (`isWorkRoute` / `workDestination`, two lists held// equal by a test), an enum-value table for settings (`SettingsDestination`),// and a chain of five `@ViewBuilder` switches for everything else, each with a// `default:` handing to the next and the last drawing a placeholder — so a// route nobody drew fell quietly to "not built yet" and a route two lanes// drew went to whichever was asked first. Now there is one `switch route`// with NO `default`: a `Route` case without an arm does not compile, and the// compiler names it.//// **Every arm returns `AnyView`, on purpose.** A `@ViewBuilder` switch is a// nested `_ConditionalContent` tree, and the chain existed because forty arms// of it already cost minutes to type-check; a hundred and forty would not// type-check at all. `AnyView` here is one erasure per PUSH — the screen// inside is still a concrete view — and it is what makes a total table// possible. Nothing below this file may erase.//// The arms are the lanes' own, moved here unchanged: every one is `Hosted`// (the model built in `.task`, from `\.cottonCore`, never in a view's// `init`). There is no placeholder page: a route the app cannot draw is not a// route. Navigation is the environment's// `Navigator`: `back` pops, screens that push do it through `navigator` in// their own bodies, and a screen that is done may also say `dismiss()` —// `Chrome/ScreenBar.swift` already does when it is handed no `onBack`.import CottonKitimport CottonValuesimport SwiftUI/// What the arms need from the app around them that the environment does not/// carry: the gate, the sync facts, the staged chat export.@MainActorpublic struct RouteDeps {    let sync: SyncModel    let boot: BootModel    let workspaceId: String?    let chatExports: ChatExportHandoff    /// The share drain, which Settings › Bring in hands its files to.    let shares: ShareIntake    /// Home's model — the settings page draws its rows' figures and the    /// export off the read Home already keeps fresh.    let home: HomeModel    public init(        sync: SyncModel,        boot: BootModel,        workspaceId: String?,        chatExports: ChatExportHandoff,        shares: ShareIntake,        home: HomeModel    ) {        self.sync = sync        self.boot = boot        self.workspaceId = workspaceId        self.chatExports = chatExports        self.shares = shares        self.home = home    }}/// The pushed screen for a route. Worn at the stack's ONE/// `navigationDestination`, inside `cottonScreenFrame()`.public struct RouteScreen: View {    let route: Route    let deps: RouteDeps    @Environment(Navigator.self) private var navigator    @Environment(\.records) private var definitionStore    @Environment(\.paintsPicture) private var paintsPicture    @Environment(\.countsOpens) private var countsOpens    /// Which database this window shows — for the pages that belong to one    /// database rather than to the phone (People). Per window, never global.    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    public init(route: Route, deps: RouteDeps) {        self.route = route        self.deps = deps    }    /// **A screen's identity IS its route.**    ///    /// Every arm below is a `Hosted`, and a `Hosted` builds its model once and    /// keeps it in `@State` for as long as SwiftUI considers the view the same    /// view. On the phone that is exactly right: a screen is a PUSH, and a    /// second record is a second push at a new position in the stack.    ///    /// On the Mac a column's ROOT is not pushed — it is a value that changes in    /// place (`Boot/ColumnsHost.swift`: `ListColumn.listRoot`,    /// `PageColumn.pageRoot`). Same type, same position, so SwiftUI kept the    /// `@State` — and the model built for the first note answered for the    /// second. The Mac walk of 2026-09-15 pressed ↓ ↵ ↓ ↵ on the notes list    /// (walk-09): the path changed, the ring moved to the second note and the    /// page column went on showing the first. Nothing was wrong with the path;    /// what was wrong was that two different screens shared one identity.    ///    /// `.id(route)` is that identity, stated once, here, where the route    /// becomes a screen — rather than at each of the two column roots, which    /// would leave a third host to remember it. A push is unaffected: its    /// route never changes for the life of the push, so the id never changes    /// either.    public var body: some View {        screen(for: route)            // A narrowed list opened here goes on this same path, so the            // records opened inside it stack above it and Back walks them            // one level at a time (`FilteredListOpening.open`).            .environment(\.listsOnPath, true)            // The screen's own place on the path: a page deleted above it            // closes back here, and this screen wears the receipt.            .environment(\.screenRoute, route)            // Back on this screen, the row it last opened is forgotten: what            // opens from it next is reached some other way until a row is.            .onAppear { navigator.rowOpened[route] = nil }            .task(id: route) {                guard Self.countsOpen(route, paintsPicture: paintsPicture, countsOpens: countsOpens) else { return }                await definitionStore?.recordViewOpened(route)            }            .id(route)    }    /// The one erasure — see the header.    private func any<Screen: View>(_ screen: Screen) -> AnyView { AnyView(screen) }    private var moneyOpener: RecordOpener {        let navigator = navigator        // Under a transaction — its page, or its lines narrowed to it        // (`/lists/transaction_line?where={"transaction_id":…}`).        let onTransaction: Bool = {            if case .moneyTransaction = route { return true }            if case .tableList(_, let filter, _, _, _, _, _) = route,                let opening = FilteredListOpening(table: "", filter: filter, title: nil, query: nil) {                return opening.filter["transaction_id"] != nil            }            return false        }()        return RecordOpener { table, record in            if table == "money_account" { navigator.push(.moneyAccount(id: record.id)) }            else if table == "transaction" { navigator.push(.moneyTransaction(id: record.id)) }            else if table == "statement" { navigator.push(.moneyStatement(id: record.id)) }            // A movement opens what it is one side of: under an account its            // transaction, under a transaction the account it moved.            else if table == "transaction_line" {                if onTransaction {                    if let account = record["account_id"].text { navigator.push(.moneyAccount(id: account)) }                } else if let transaction = record["transaction_id"].text {                    navigator.push(.moneyTransaction(id: transaction))                }            }            // A statement's line opens the transaction it was recorded as;            // one not recorded yet has nothing to open.            else if table == "statement_line" {                if let transaction = record["transaction_id"].text { navigator.push(.moneyTransaction(id: transaction)) }            }            // A transaction's person, a statement's document: any other kind            // opens at its own route, as it does from every other page.            else if let kind = RecordKind(rawValue: table) { navigator.push(.record(kind, record.id)) }        }    }    /// What a narrowed list's records open through (`/lists/[table]`): the    /// opener whose routes hold the table's pages — the one the screen that    /// opened the list wore. Looked up, not switched on (no `default:` in    /// this file); a table no opener has a page for opens by its kind, and    /// one with no kind on the list's own stack.    private func tableListOpener(_ table: String) -> RecordOpener? {        let owners: [(tables: Set<String>, opener: RecordOpener)] = [            (["money_account", "transaction", "statement", "transaction_line", "statement_line"], moneyOpener),            (["photo", "video", "media", "album"], photosOpener),            (Set(Self.personSections.values.map(\.table)).union(["face", "thread", "person_note", "person_suggestion"]),             peopleOpener),        ]        if let owner = owners.first(where: { $0.tables.contains(table) }) { return owner.opener }        return RecordKind(rawValue: table) != nil ? kindOpener : nil    }    /// Where a record of any kind opens, by the kind's own route    /// (`Route.record`): pushed from a slip's link or a page's linked row,    /// and IN PLACE of the page when a record gives its place to the one it    /// became (`RecordOpener.move`) — the doorway never sits on the back stack.    /// A table with no kind of its own opens nothing.    private var kindOpener: RecordOpener {        let navigator = navigator        return RecordOpener(            moved: { to in                if to.table == "session" { navigator.replace(with: .sessionsId(id: to.id)) }                else if let kind = RecordKind(rawValue: to.table) { navigator.replace(with: .record(kind, to.id)) }            }        ) { table, record in            if table == "session" { navigator.push(.sessionsId(id: record.id)) }            else if let kind = RecordKind(rawValue: table) { navigator.push(.record(kind, record.id)) }        }    }    /// Where `/activity`'s slips open: a run's note (`opens`).    private var activityOpener: RecordOpener {        let navigator = navigator        return RecordOpener { table, record in            if table == "note" { navigator.push(.notesNote(id: record.id)) }            // Any other kind opens at its own route (S1); a call the            // assistant made has no page and opens nothing.            else if let kind = RecordKind(rawValue: table) { navigator.push(.record(kind, record.id)) }        }    }    /// A person's section screens (`/people/person/[id]/[section]`): the    /// table each lists and the column linking its records to the person.    /// Looked up, not switched on: the route table has no `default:`.    /// `/calendar?show=invites` — the calendar narrowed to the invites.    static let invites = "invites"    static let personSections: [String: (table: String, link: String)] = [        "todos": ("todo", "people"),        "notes": ("person_note", "person_id"),        "events": ("event", "people"),        "photos": ("photo", "people"),        "documents": ("document", "people"),        "money": ("owed", "counterparty_person_id"),    ]    /// Where a person's records open, listed under their page: each its own    /// page — a face the photo it was found in, an owed row its    /// transaction, a thread its conversation — and a person's note or a    /// question about them nowhere (both are answered where they stand). A    /// section's "All …" opens that kind whole for the person; calls their    /// call history. A merge that folded the page's person into another    /// shows the survivor's page in its place.    private var peopleOpener: RecordOpener {        let navigator = navigator        let sections = Dictionary(Self.personSections.map { ($0.value.table, $0.key) }, uniquingKeysWith: { first, _ in first })        return RecordOpener(            only: Set(RecordKind.allCases.map(\.rawValue)).union(["face", "owed", "thread", "person_note", "person_suggestion"]),            lists: Set(sections.keys).union(["call"]),            list: { table, filter in                let person = filter.values.first?.text ?? ""                if table == "call" { return navigator.push(.callsHistory(person: person)) }                if let section = sections[table] { navigator.push(.peoplePersonSection(id: person, section: section)) }            },            moved: { to in                if to.table == "person" { navigator.replace(with: .peoplePerson(id: to.id)) }            }        ) { table, record in            // Looked up rather than switched on (no `default:` in this file).            let through: [String: Route?] = [                "face": record["photo_id"].text.map { .photosPhoto(id: $0) },                "owed": .moneyTransaction(id: record.id),                "thread": .messagesThread(thread: record.id),                "person_note": nil,                "person_suggestion": nil,            ]            if let route = through[table] {                if let route { navigator.push(route) }            } else if let kind = RecordKind(rawValue: table) {                navigator.push(Route.record(kind, record.id))            }        }    }    /// Where the photo tables' records open: a picture or a film its page (a    /// library row by its kind), an album its page, a sighting's chat its    /// thread; an album's "Add photos" the add screen.    private var photosOpener: RecordOpener {        let navigator = navigator        return RecordOpener(            creates: ["album_item"],            create: { _, preset in navigator.push(.photosAlbumAdd(id: preset["album_id"]?.text ?? "")) }        ) { table, record in            // Looked up, not switched on: the route table has no `default:`.            let routes: [String: Route] = [                "photo": .photosPhoto(id: record.id),                "video": .videosVideo(id: record.id),                "media": Self.libraryRoute(record),                "album": .photosAlbum(id: record.id),                "message_thread": .messagesThread(thread: record.id),            ]            if let route = routes[table] { navigator.push(route) }            // A face on its picture opens the person it is thought to be            // (the picture is this page); a person named on a picture, or            // any other kind, opens at its own route (S1).            else if table == "face" {                if let person = record["suggested_person_id"].text { navigator.push(.peoplePerson(id: person)) }            } else if let kind = RecordKind(rawValue: table) { navigator.push(.record(kind, record.id)) }        }    }    /// A library row's page: a film's or a picture's, by its kind.    private static func libraryRoute(_ record: TableRecord) -> Route {        record["kind"].text == "video" ? .videosVideo(id: record.id) : .photosPhoto(id: record.id)    }    /// `/videos`: the video table's list; a film opens its page.    private var videosList: some View {        let navigator = navigator        return TableListRoute(table: "video") { navigator.push(.videosVideo(id: $0.id)) }            .environment(\.recordOpener, photosOpener)    }    /// The library — every picture and film, `show` narrowing it to the pictures.    private func library(_ show: PhotosShow) -> some View {        let navigator = navigator        return LibraryRoute(show: show) { navigator.push(Self.libraryRoute($0)) }            .environment(\.recordOpener, photosOpener)    }    /// `/code`, `/code/new` and `/projects/[slug]/code`: the session table's    /// list, titled Code, scoped to one project when a slug is given; a slip    /// opens its session's page.    private func codeList(project: String?) -> some View {        let navigator = navigator        let scope: [String: RecordValue] = project.map { ["project_slug": .text($0)] } ?? [:]        return TableListRoute(table: "session", title: CottonStrings.codeTitle, where: scope) {            navigator.push(.sessionsId(id: $0.id))        }        .environment(\.listOpener, codeLists)    }    /// Where the Code list's links open: the Code tool's other lists, each at    /// its own route (`SettingsTables.code`), the defaults straight onto their    /// one page.    private var codeLists: ListOpener {        let navigator = navigator        return ListOpener(only: Set(SettingsTables.code.map(\.table))) { table, _ in            if let route = SettingsTables.route(forTable: table) {                navigator.push(route)            }        }    }    /// One day's journal page, found by its date; `.id` so another day is a new lookup.    private func journalDay(_ day: String) -> some View {        TablePageRoute(table: "journal", where: "journal_date", equals: .text(day)).id(day)    }    // swiftlint:disable:next function_body_length    private func screen(for route: Route) -> AnyView {        @Bindable var navigator = navigator        let back: () -> Void = { navigator.pop() }        switch route {        // ── Home ──        // `/` and `/home` never reach a stack: on the phone the root IS the        // board and `Navigator` answers a push of either by going back to it;        // on the Mac they are launcher-tier and no window draws them. Should        // one arrive anyway it is the same board, over the same read.        case .root, .home:            return any(HomeBoard(home: deps.home, databaseName: deps.boot.serverName))        // ── mood, activity, the take (4d, 4k, phase 15) ──        // A mood's page has no route of its own: the list opens it on its        // own stack.        case .mood:            return any(TableListRoute(table: "mood"))        // What this database is, the assistant's runs and the connected        // assistants' calls: the `activity` record's page over its three        // tables (`Tables/ActivityTables.swift`); a run that wrote a note        // opens it.        case .activity:            return any(ActivityRoute().environment(\.recordOpener, activityOpener))        // The Camera tool's live surface. Built in `Hosted`'s `.task`: the        // capture session is constructed only after the gate, never in a View.        case .camera:            return any(                Hosted(unwired: { core, _ in                    CameraModel(core: core, capabilities: SystemCapabilityAuthority())                }) { model in                    CameraScreen(model: model) { navigator.pop() }                }            )        // Money as data: the engine supplies values; these are the shared surfaces.        case .money:            return any(TableListRoute(table: "money_account") { navigator.push(.moneyAccount(id: $0.id)) }                .environment(\.recordOpener, moneyOpener))        case .moneyAccount(let id):            return any(TablePageRoute(table: "money_account", id: id).environment(\.recordOpener, moneyOpener))        case .moneyStatement(let id):            return any(TablePageRoute(table: "statement", id: id).environment(\.recordOpener, moneyOpener))        case .moneyTransaction(let id):            return any(TablePageRoute(table: "transaction", id: id).environment(\.recordOpener, moneyOpener))        // One table's list narrowed by a link on a list or a page — on the        // path, so Back from a record opened in it returns to it.        case .tableList(let table, let filter, let title, let query, let archived, let section, let view):            guard let opening = FilteredListOpening(                table: table, filter: filter, title: title, query: query, archived: archived, section: section, view: view) else {                return any(PaperScreen {                    QuietState(title: ShellLines.line("boot", "link.unread_title"), message: ShellLines.line("boot", "link.unread_body"))                })            }            return any(FilteredListScreen(opening: opening)                .settingsKeptFlows(table: table, record: "new")                .environment(\.recordOpener, tableListOpener(table)))        // One record of a table no named route addresses — a data tool's row,        // an alarm, the database's own record on its page: its table's page,        // through the Settings source that holds the table when one does.        case .tableRecord(let table, let id):            // A source-answered table's page scopes its own store and runs the            // kept flows over it, and a person's own table reads their own            // database (`SourceTableStore`).            if SettingsRecords.sourceTables.contains(table) { return any(TablePageRoute(table: table, id: id)) }            return any(TablePageRoute(table: table, id: id)                .settingsKeptFlows(table: table, record: id)                .environment(\.recordOpener, tableListOpener(table)))        // ── messages and email (4g) ──        case .messages:            return any(TableListRoute(table: "thread") { navigator.push(.messagesThread(thread: $0.id)) })        // A conversation opens on its own chat (`ConversationRoute`); its        // info is its card on the Messages deck.        case .messagesThread(let id):            return any(ConversationRoute(table: "thread", id: id))        case .messagesInfo(let id):            return any(TablePageRoute(table: "thread", id: id))        case .messagesMedia(let id):            return any(TablePageRoute(table: "thread", id: id, mediaOnly: true))        case .messagesStarred:            return any(TableLinkedListRoute(table: "message", link: "thread_id", filter: ["kept": .bool(true)]))        case .messagesNew:            return any(ChatStartScreen())        case .messagesImport:            return any(TableFileImportRoute(table: "message_import", column: "file") { deps.chatExports.take() })        case .email:            return any(EmailArchiveSurface(id: nil))        case .emailId(let id, let at):            return any(EmailArchiveSurface(id: id, at: at))        // ── calls, photos, videos, storage (4g) ──        case .callsHistory(let person):            return any(TableListRoute(table: "call", where: person.flatMap { $0.isEmpty ? nil : ["person_id": RecordValue.text($0)] } ?? [:]) { record in                navigator.push(.callsCall(id: record.id))            })        case .callsCall(let id):            return any(TablePageRoute(table: "call", id: id))        // ── Photos ────────────────────────────────────────────────────────────        // The library is the media table's list (pictures and films as one,        // `show` its filter word), an album the album table's page, a picture        // the photo table's page; `photosOpener` says where each row opens.        // The faces to confirm are People's face table.        case .photos(let show):            // The films are their own list now; an old `?show=videos` link            // lands there rather than on the library narrowed to them.            if show == "videos" { return any(videosList) }            // The Photos tool's page: one grid, the view its ring chose (All            // by default; Albums, People, Places and each album — media.json's            // `tool.views` and the core's generated album views).            if show == nil {                return any(                    ToolViewRoute(of: "photos", table: "media") { navigator.push(Self.libraryRoute($0)) }                        .environment(\.recordOpener, photosOpener))            }            return any(library(PhotosShow(route: show)))        case .photosAlbums:            return any(                TableListRoute(table: "album") { navigator.push(.photosAlbum(id: $0.id)) }                    .environment(\.recordOpener, photosOpener))        case .photosDuplicates:            return any(TableListRoute(table: "duplicate").environment(\.recordOpener, photosOpener))        // The faces the Mac thinks it recognises, each asking "Is this …?"        // with Yes and Not them: People's question, listed here whole and        // under each person's page. A face opens the photo it was found in.        case .photosPeople:            return any(TableListRoute(table: "face") { face in                if let photo = face["photo_id"].text, !photo.isEmpty { navigator.push(.photosPhoto(id: photo)) }            }            .environment(\.recordOpener, peopleOpener))        case .photosAlbum(let id):            return any(TablePageRoute(table: "album", id: id).environment(\.recordOpener, photosOpener))        // The picker: the owner's pictures this album may still take, each        // ticked put in it, then back to the album.        case .photosAlbumAdd(let id):            return any(                TableListRoute(                    table: "photo", where: ["addable_to": .text(id)],                    pick: ListPick(                        table: "album_item", column: "record_id", preset: ["album_id": .text(id)], label: ShellLines.line("boot", "routes.add_photos"),                        empty: EmptyWords(                            title: ShellLines.line("empty", "album_full.title"),                            message: ShellLines.line("empty", "album_full.message")),                        done: { navigator.pop() })                ) { _ in })        case .photosPhoto(let id):            return any(TablePageRoute(table: "photo", id: id).environment(\.recordOpener, photosOpener))        // The Videos tool is the film table's own list — its own albums,        // counted in films — never the library filtered (walker 604bcce6);        // a film opens its page, whose print plays it.        case .videos:            return any(videosList)        // A film's page: its print plays it (the slip's `player`).        case .videosVideo(let id):            return any(TablePageRoute(table: "video", id: id).environment(\.recordOpener, photosOpener))        case .reader:            return any(TableListRoute(table: "page") { navigator.push(.readerPage(id: $0.id)) })        case .readerPage(let id):            return any(TablePageRoute(table: "page", id: id))        // ── Projects, memory and the briefing ─────────────────────────────────        // The projects are the project table's list, active then archived,        // with New project as its act; a row opens the project's page, which        // is the database page with that project chosen.        case .projects:            return any(                TableListRoute(table: "project") { record in                    // On the fan a card opens its project's page in place, on                    // the tile's own stack; choosing the project for Home's                    // page is Home's alone, which a fan tile never shows                    // (walker pass 4, 16 Oct 2026: the cards opened nothing).                    navigator.push(navigator.tile != nil                        ? .tableRecord(table: "project", id: record.id)                        : .projectsSlug(slug: record["slug"].text ?? record.id))                }            )        // A project's page is the database page with that project chosen:        // `Navigator` answers a push of this route by going there. Should one        // arrive in a path anyway it is the same board.        case .projectsSlug:            return any(HomeBoard(home: deps.home, databaseName: deps.boot.serverName))        // A project's section — procedures, each with the sentence that says        // when it applies, and every link group — is the project_item table's        // list cut to that project and section; a row opens the record it is.        case .projectsSlugSection(let slug, let section):            let named = ProjectSections.named(section)            return any(TableListRoute(table: "project_item", title: named?.label,                where: ["project": .text(slug), "section": .text(named?.key ?? section)]))        // Memory is the memory table the assistants write: a project's are        // its memory section (a memory's homes are project links); one        // memory's page; the archived.        case .projectsMemory(let slug):            return any(TableListRoute(table: "project_item", title: ShellLines.line("boot", "routes.memory"),                where: ["project": .text(slug), "section": .text("memory")]))        case .memory(let id):            return any(TablePageRoute(table: "memory", id: id))        case .memoryDropped:            return any(TableListRoute(table: "memory", title: ShellLines.line("boot", "routes.dropped"), where: ["status": .text("archived")]) { record in                navigator.push(.memory(id: record.id))            })        // A project's brand is its database's: the shown database's own page        // ("Name and picture"), where the kit and the logo files are columns.        case .projectsBrand:            return any(ShownDatabasePage())        case .projectsFeedback(let slug):            return any(TableListRoute(table: "project_feedback", title: ShellLines.line("boot", "routes.feedback"), where: ["project": .text(slug)]) { record in                navigator.push(.projectsFeedbackReport(slug: slug, id: record.id))            })        case .projectsFeedbackReport(_, let id):            return any(TablePageRoute(table: "project_feedback", id: id))        // The project's own Todos: the todo table's list with the project        // the slug names as the current one.        case .projectsTodos(let slug):            return any(ProjectListRoute(table: "todo", project: slug) { navigator.push(.todosTodo(id: $0.id)) })        case .briefing(let project):            if let project { return any(TablePageRoute(table: "briefing", id: project)) }            return any(TableListRoute(table: "briefing") { record in                navigator.push(.briefing(project: record.id))            })        // ── Sessions, history and the vault ───────────────────────────────────        // One session is the session table's page — its conversation, its        // columns behind "Details", its acts — the page Settings › Sessions        // opens too, re-read whenever a sync names the sessions.        case .sessionsId(let id):            return any(TablePageRoute(table: "session", id: id))        // Its terminal, pushed by the page's "Open the terminal". The pane        // streams; there is no read to repeat.        case .sessionsTerminal(let id):            return any(                Hosted(unwired: { core, _ in ScreenWriter(core: core) }) { writer in                    SessionTerminalScreen(id: id, writer: writer)                }            )        case .documents(let status):            return any(TableListRoute(table: "document", where: status.map { ["status": .text($0)] } ?? [:]) { navigator.push(.documentsDocument(id: $0.id)) })        case .documentsImport:            return any(DocumentImportRoute())        case .documentsDocument(let id), .documentsDocumentViewer(let id):            return any(TablePageRoute(table: "document", id: id))        // ── News ──────────────────────────────────────────────────────────────        case .news:            return any(TableListRoute(table: "news_edition") { navigator.push(.newsEdition(id: $0.id)) })        case .newsEdition(let id):            return any(TablePageRoute(table: "news_edition", id: id))        case .newsTopic(let id):            return any(TablePageRoute(table: "news_topic", id: id))        case .newsTopicNew:            return any(TableBlankRoute(table: "news_topic"))        case .newsSettings:            return any(TablePageRoute(table: "news_settings", where: "name", equals: .text("News settings")))        // ── Code ──────────────────────────────────────────────────────────────        // The session table's list, titled Code: its sections cut as the old        // queue cut them, a slip's one verb, Start a session at its head, re-read        // whenever a sync names the sessions. `/code/new` is that same list —        // Start is its head, the first instruction is typed on the page it        // opens — and one project's list is the table scoped by `project_slug`,        // which the session source reads as that project's sessions of all time.        case .code:            return any(codeList(project: nil))        case .codeNew(let project):            return any(codeList(project: project))        case .projectsCode(let slug):            return any(codeList(project: slug))        // The Code tool's defaults (was Settings › Code, Spec 9.3).        case .codeDefaults:            return any(CodeDefaultsCarried { TablePageRoute(table: "code_default", id: "defaults") })        // ── Meetings ──────────────────────────────────────────────────────────        case .meetings(let importing):            return any(Hosted(unwired: { core, _ in ScreenWriter(core: core) }) { writer in                MeetingListFlow(writer: writer, opensImporter: importing)            })        case .meetingsRecord:            // Meetings asked to record: the meeting table's list with the            // recorder as a sheet over it. Recording is a flow on the list; the            // meeting it files opens as the meeting table's page.            return any(Hosted(unwired: { core, _ in                MeetingRecorderModel(writer: ScreenWriter(core: core), capture: SystemMeetingRecorder(),                    authority: SystemCapabilityAuthority())            }) { recorder in MeetingListFlow(writer: recorder.writer, opensImporter: false, recorder: recorder) })        case .meetingsMeeting(let id):            return any(TablePageRoute(table: "meeting", id: id))        // ── the day and the person (4e) ──        case .calendar(_, let show) where show == Self.invites:            // Home's "invites to answer": someone else's events still asking            // for a reply (`asked_of_you::INVITE_SQL`), ahead; each opens its            // page, where Your reply accepts or declines it.            return any(TableListRoute(table: "event", where: [                "invited": .text("invited"), "my_response": .text("needs_action"),            ]) { record in                navigator.push(.calendarEvent(id: record.id, date: nil, at: nil))            })        // The Calendar tool's page: one list, the view its ring chose (Today        // by default; Upcoming, Recurring, All — event.json's `tool.views`).        case .calendar(let date, _) where date == nil:            return any(ToolViewRoute(of: "calendar", table: "event") { record in                navigator.push(.calendarEvent(id: record.id, date: nil, at: nil))            })        // A date opens its own day: the list is read from that day (a date        // slip's "captured · Yesterday" opened on Today, walker 298).        case .calendar(let date, _), .calendarMonth(let date):            return any(TableListRoute(table: "event", opensOn: RouteScreen.day(date)) { record in                navigator.push(.calendarEvent(id: record.id, date: nil, at: nil))            })        // An occurrence's page is that day's: `<series>@<start>`, which the        // core opens at the occurrence's own when.        case .calendarEvent(let id, _, let at):            return any(TablePageRoute(table: "event", id: at.map { "\(id)@\($0)" } ?? id))        case .calendarEventEdit(let id, let date, _):            if let id { return any(TablePageRoute(table: "event", id: id)) }            return any(NewEventRoute(day: date))        // The alarm table's list, under what its engine stands above it (the        // next alarm and the note that says whether this phone will ring:        // `EngineListHead`). A slip opens its alarm's page on the list's own        // stack (no /alarms/[id] route yet); its switch turns it on and off.        // The device's own alarms follow every write through        // `AlarmSyncModel`, which reconciles on the data event naming        // `cotton_alarms`.        case .alarms:            return any(TableListRoute(table: "alarm"))        // ── the lists ────────────────────────────────────────────────────        // The Todos tool's page: one list, the view its ring chose (Today        // by default; Done, Late, Upcoming, All and each group). `?new=1`        // opens a blank todo, due today, as the list arrives. The old Done        // and Dropped links open the table's list, under their project when        // they name one. A slip opens the todo's page, with its History.        case .todos(let new):            return any(ToolViewRoute(of: "todos", table: "todo", composeOnArrival: new) { navigator.push(.todosTodo(id: $0.id)) })        case .todosDone(let project), .todosDropped(let project):            if let project {                return any(ProjectListRoute(table: "todo", project: project) { navigator.push(.todosTodo(id: $0.id)) })            }            return any(TableListRoute(table: "todo") { navigator.push(.todosTodo(id: $0.id)) })        case .todosTodo(let id):            return any(TablePageRoute(table: "todo", id: id))        // Notes is its table's list, and a note is its page (`NoteRoute`:        // a journal page's id opens the journal's page, `new` a blank note).        case .notes:            return any(TableListRoute(table: "note") { navigator.push(.notesNote(id: $0.id)) })        case .notesNote(let id):            return any(NoteRoute(id: id))        // The journal is its table's list, and a day's page is the entry        // whose journal_date is that day — today's read from the phone's        // LOCAL calendar, never a UTC stamp.        case .notesJournalToday:            return any(journalDay(JournalStreak.dayKey(Date())))        case .journal:            return any(                TableListRoute(table: "journal") { record in                    if case .text(let day)? = record.values["journal_date"] { navigator.push(.journalDate(date: day)) }                })        case .journalDate(let date):            return any(journalDay(date))        // `/capture` is an ADDRESS, not a screen. It exists so a deep link, a        // notification or a Shortcut has a stable thing to point at for        // "capture something", and `Navigator.open` turns it into capture mode        // and pushes nothing (design 2026-09-13 §4.3).        //        // It cannot be resolved in the PARSER: `Route.parse("/capture")`        // answers `.capture` and `/capture` is in `allPatterns`, which        // `RouteTableTests` holds equal to the crate's `ROUTES`. So a PUSH of        // it — a screen saying `.capture` to a screen rather than to `open` —        // still needs a view, and it lands on the thoughts list, where every        // capture is. It landed on `/decide` while that queue held unfiled        // thoughts; since 2026-09-28 the queue holds only what someone asked        // the owner, and `/thoughts` is a list again.        //        // Since Thoughts became its table's list and page, a capture's slip        // names what it became under it and its page hands over to the one        // record it became (`hand_over`), both through `kindOpener`.        //        // `/take` and `/keyboard-take` are addresses of the same kind here:        // the Android input method's far side, which this phone has no        // keyboard to send anyone to; `open` raises capture mode listening,        // and a push lands where a take files.        case .capture, .take, .keyboardTake, .thoughts:            return any(                TableListRoute(table: "thought") { navigator.push(.thoughtsThought(id: $0.id)) }                    .environment(\.recordOpener, kindOpener))        case .thoughtsThought(let id):            return any(TablePageRoute(table: "thought", id: id).environment(\.recordOpener, kindOpener))        // ── the person ───────────────────────────────────────────────────        // Passwords is its table's list and a secret's page, over the vault's        // own verbs and never the root's fixture records (`PasswordsRoute`).        case .passwords:            return any(PasswordsRoute(id: nil) { navigator.push(.passwordsSecret(id: $0.id)) })        case .passwordsSecret(let id):            // The old screens' `new:<kind>` form is the list now, where the            // New acts are; no secret has such an id.            return any(PasswordsRoute(id: id.hasPrefix("new:") ? nil : id) { navigator.push(.passwordsSecret(id: $0.id)) })        // People is its table's list and page; the page's sections open        // through `peopleOpener`. The list's address-book act covers the        // screen over it (`PeopleListFlow`).        case .people:            return any(PeopleListFlow(table: "person"))        case .raised(let page, _):            return any(screen(for: page))        case .me:            return any(MeRoute().environment(\.recordOpener, peopleOpener))        case .peoplePerson(let id, let database):            return any(PersonPageRoute(id: id, database: database).environment(\.recordOpener, peopleOpener))        // One kind of a person's linked records, whole: that table's list        // narrowed to them. A section with no table of its own ("linked")        // is the person's card.        case .peoplePersonSection(let id, let section):            guard let target = Self.personSections[section] else {                return any(TablePageRoute(table: "person", id: id).environment(\.recordOpener, peopleOpener))            }            return any(                TableListRoute(table: target.table, where: [target.link: .text(id)]).environment(\.recordOpener, peopleOpener))        // People asked to import: the person table's list with the import        // covering the screen over it (`wholeScreen`). `unwired`: most of        // what the import reads is this phone's own address book, which no        // fold can move — `PeopleImportModel` carries the reason.        case .peopleImport:            return any(                Hosted(unwired: { core, _ in PeopleImportModel(core: core) }) { model in                    PeopleListFlow(table: "person", raising: .importing(model))                }            )        case .locations:            return any(TableListRoute(table: "location") { navigator.push(.locationsLocation(id: $0.id)) })        case .locationsLocation(let id):            return any(TablePageRoute(table: "location", id: id))        case .goals:            return any(TableListRoute(table: "goal") { navigator.push(.goalsGoal(id: $0.id)) })        case .goalsGoal(let id):            return any(TablePageRoute(table: "goal", id: id))        // ── devices ──        // The Devices table's list and a device's page, drawn from the device        // definition over the Records verbs (rebuild note 7b95efa4: "a device        // is a record with a slip and a page") — the same surfaces the        // settings sheet opens. The page approves, renames, orders and removes        // by its columns; a waiting device's digits are on it.        case .devices:            return any(                TableListRoute(table: "device") { record in                    navigator.push(.devicesId(id: record.id))                }            )        case .devicesId(let id):            return any(TablePageRoute(table: "device", id: id)                .settingsKeptFlows(table: "device", record: id))        // ── storage ──        // One native root holds this machine's Files choice and tool rules.        case .storage:            return any(TablePageRoute(table: "storage", id: StorageRecordID.current))        case .storageId(let id):            return any(TablePageRoute(table: "storage", id: id))        case .deviceStorage(let id):            return any(TablePageRoute(table: "storage", id: StorageRecordID.machine(id)))        // ── settings (4h) ──        case .settingsJoinRequest(let id):            return any(                Hosted(unwired: { core, toasts in                    JoinRequestModel(core: core, toasts: toasts, pairingId: id)                }) { model in                    JoinRequestScreen(model: model, onDone: back)                }            )        // The writes this device parked rather than folded. Reached from the        // join sheet's merge count and from Settings › Devices; `unwired`        // because the model owns no `data`-event family — `_parked` is        // device-local and never moves under it.        case .rejected:            return any(                Hosted(unwired: { core, toasts in                    RejectedModel(core: core, toasts: toasts)                }) { model in                    RejectedScreen(model: model)                }            )        // ── tools (Spec 9.1) ──        // The Tools screen, Home's fixed last entry: the `tools` board (every        // tool of this database, a tile on Home or not, and About), whose menu        case .tools:            return any(BoardRoute(board: BoardDefinition.tools.id, home: deps.home, fallbackName: deps.boot.serverName))        // A data tool of more than one table: its own board, a tile per table.        case .toolBoard(let id):            // Settings stands on its chips, each page the thing itself            // (`SettingsRing`); its list only where no ring stands (the Mac).            if id == SettingsRing.tool { return any(SettingsPage { screen(for: $0) }) }            return any(ToolBoardRoute(id: id))        // ── members (Spec 9.3) ──        // The Members tool: the member definition's list and page over the        // window's database, drawn by the shared surfaces like Devices.        case .membersAdmit:            let databaseId = scene?.shownId ?? deps.workspaceId ?? ""            return any(TableActsRoute(table: "member", title: ShellLines.line("boot", "routes.admit"), where: ["database": .text(databaseId)]))        case .members:            let databaseId = scene?.shownId ?? deps.workspaceId ?? ""            return any(                TableListRoute(table: "member", where: ["database": .text(databaseId)]) { record in                    navigator.push(.membersId(id: record.id))                }            )        case .membersId(let id):            let databaseId = scene?.shownId ?? deps.workspaceId ?? ""            return any(TablePageRoute(table: "member", id: id, within: ["database": .text(databaseId)]))        // The words dictation listens for (`read.voiceVocabulary`), read from        // the person's own database whichever is shown (Spec 9.5).        case .voiceWords:            return any(TableListRoute(table: "voice_word") { record in                navigator.push(.voiceWordsId(id: record.id))            })        case .voiceWordsId(let id):            return any(TablePageRoute(table: "voice_word", id: id))        // This device's own record page, and the shown database's (Spec 10):        // there is no settings screen.        case .device:            return any(ThisDeviceRoute())        // Settings › Backup and Cotton server: the personal object's two        // shell screens (`Join/BackupRoutes.swift`).        case .backup:            return any(BackupRoute())        case .server:            return any(ServerRoute())        // Settings › Bring in: files from Files, through the share drain.        case .bringIn:            return any(BringInRoute(shares: deps.shares))        // Settings › Export: tables into one Cotton package, to the share sheet.        case .export:            return any(ExportRoute())        // One of this device's host-drawn pages, opened from its own record        // page (`Platform/HostSettingsSlot.swift`).        case .hostPage(let id):            return any(HostPageScreen(id: id))        // The database page: the `database` board — its name, its record of        // the `database` table (whose whole page a tap opens), a section for        // every tool holding records, and its tools.        case .database:            return any(BoardRoute(board: BoardDefinition.database.id, home: deps.home, fallbackName: deps.boot.serverName))        case .bin:            // The one bin as its table's list (`bin.json`): sections by table,            // Restore under each row, "Empty the bin" under them all. A row's            // page opens on the list's own stack.            return any(TableListRoute(table: "bin"))        case .search:            return any(                Hosted(unwired: { core, toasts in SearchModel(core: core) }) { model in                    SearchScreen(model: model)                }            )        case .about:            return any(AboutScreen())        case .aboutWhatsNew:            return any(AboutWhatsNewScreen())        case .aboutHelp:            return any(AboutHelpScreen())        case .legalPrivacy:            return any(                PrivacyScreen()            )        case .legalTerms:            return any(                TermsScreen()            )        }    }}/// A read argument the route may or may not carry.private func only(_ name: String, _ value: String?) -> [String: JSONValue] {    value.map { [name: .string($0)] } ?? [:]}/// The library's list, named for what it was opened to show: the Videos card/// opens "Videos", never a screen headed "Photos" that happens to be narrowed/// to films. The whole library and the pictures keep the table's own name.private struct LibraryRoute: View {    let show: PhotosShow    let onOpen: (TableRecord) -> Void    /// The library narrowed to `kind` as its filter row narrows it; the    /// whole library for none, or a kind the row does not hold.    static func narrowed(_ definition: TableDefinition, to kind: String?) -> [String: RecordValue] {        guard let filter = definition.filter, let kind, filter.words[kind] != nil else { return [:] }        return [filter.column: .text(kind)]    }    @Environment(\.tableDefinitions) private var definitions    var body: some View {        if let definition = definitions["media"], DeckSwitch.draws(definition, view: nil, plain: true) {            // Photos' media have cards (package row 9): the library is their            // deck, narrowed to the kind it was opened for (door row 11).            DeckSurface(definition: definition, filter: Self.narrowed(definition, to: show.kind), view: nil)        } else if let definition = definitions["media"] {            RecordListSurface(                definition: definition, filterValue: show.kind, title: show.title,                leading: { LibraryStorageHead(kinds: show.kind.map { [$0] } ?? definition.column(definition.filter?.column)?.choices ?? []) }, onOpen: onOpen)        } else {            // No such table in this build: the route's own "unknown table".            TableListRoute(table: "media", filterValue: show.kind, onOpen: onOpen)        }    }}extension RouteScreen {    /// A route's date as the day a list is read from, YYYY-MM-DD; anything    /// else names no day and the list opens on this device's today.    static func day(_ date: String?) -> String? {        guard let date, date.count >= 10 else { return nil }        let day = String(date.prefix(10))        return day.range(of: #"^\d{4}-\d{2}-\d{2}$"#, options: .regularExpression) == nil ? nil : day    }}