// A converted tool's routes: its list and its page opened by table id, the// definition read from the environment the root publishes (`RootView`). A// table the app has no definition for says so instead of drawing nothing.//// A table an app source answers (`SettingsRecords.sources`: the tables the// owner kept in Swift, 14 Oct, and a repository's own) is drawn by these same// routes; only the store under them differs (`SourceTableStore`).importCottonKitimportCottonValuesimportSwiftUI/// One table's list, by table id; its archived records too when `archived`,/// and narrowed, when `where` names columns, to the records holding those values.////// A slip always opens its record's page. Whoever holds the list says where/// that page lives (`onOpen`, pushing the table's own route); a table whose/// page has no route of its own (a mood) opens it on the list's own stack —/// never a slip that opens nothing. Such a page offers no History, which the/// app's history screen reads by route.publicstructTableListRoute<Leading: View>: View {privatelet table: Stringprivatelet title: String?privatelet archived: Boolprivatelet filter: [String: RecordValue]privatelet composeOnArrival: Boolprivatelet filterValue: String?privatelet pick: ListPick?privatelet selecting: Bool/// The list act whose sheet is up as the list opens (`/repos/[id]/pulls/new`).privatelet asking: String?privatelet onOpen: ((TableRecord) -> Void)?/// What stands above the list (the meetings' recovery notes).privatelet leading: Leading/// The day a day-split list opens on (`/calendar?date=`).privatelet opensOn: String?/// The tool's view the list is (`ToolViewRoute`).privatelet view: ToolView.Read?/// The tool whose view the list is, where its page handed one in/// (`ToolViewRoute`): what the ring and the deck's rollover are keyed/// by. Nil, the table's own tool block or the tool that lists it names/// it (`ListTool.key`).privatelet tool: String? @Environment(\.tableDefinitions) privatevar definitions @Environment(\.toolDefinitions) privatevar tools @Environment(ToolViews.self) privatevar toolViews: ToolViews? @Environment(\.cottonCore) privatevar core @Environment(Navigator.self) privatevar navigator: Navigator? @Environment(ToastCenter.self) privatevar toasts: ToastCenter?/// The record whose page is open on the list's own stack. @State privatevar opened: TableRecord?/// - Parameter composeOnArrival: open the blank page for a new record/// as the list arrives (`/todos?new=1`), once./// - filterValue: the filter row's word the list opens on./// - pick: the list picks records for another table (`ListPick`)./// - selecting: the list opens already ticking./// - asking: the list act whose sheet is up as the list opens./// - leading: drawn above the list's slips.publicinit( table: String, title: String? = nil, archived: Bool = false, where filter: [String: RecordValue] = [:], composeOnArrival: Bool = false, filterValue: String? = nil, pick: ListPick? = nil, selecting: Bool = false, asking: String? = nil, opensOn: String? = nil, view: ToolView.Read? = nil, tool: String? = nil, @ViewBuilder leading: () -> Leading, onOpen: ((TableRecord) -> Void)? = nil ) {self.view = viewself.tool = toolself.opensOn = opensOnself.table = tableself.title = titleself.archived = archivedself.filter = filterself.composeOnArrival = composeOnArrivalself.filterValue = filterValueself.pick = pickself.selecting = selectingself.asking = askingself.onOpen = onOpenself.leading = leading() }/// The list with nothing drawn above it.publicinit( table: String, title: String? = nil, archived: Bool = false, where filter: [String: RecordValue] = [:], composeOnArrival: Bool = false, filterValue: String? = nil, pick: ListPick? = nil, selecting: Bool = false, asking: String? = nil, opensOn: String? = nil, view: ToolView.Read? = nil, tool: String? = nil, onOpen: ((TableRecord) -> Void)? = nil ) whereLeading == EmptyView {self.init( table: table, title: title, archived: archived, where: filter, composeOnArrival: composeOnArrival, filterValue: filterValue, pick: pick, selecting: selecting, asking: asking, opensOn: opensOn, view: view, tool: tool, leading: { EmptyView() }, onOpen: onOpen) }/// The view this list reads when it is a tool's own list under a ring of/// two or more views (the ring over the fan chose it, else the tool's/// default): every tool's list reads its chosen view, the routes that/// draw it unchanged. A list narrowed, picking, ticking, archived or/// asked for a view of its own reads what it was asked.privatevar ringView: ToolView? {guard view == nil, filter.isEmpty, pick == nil, !archived, !selecting, filterValue == nil, asking == nil,let toolViews, let key = toolKey else { returnnil }return toolViews.current(of: key) }/// The fan cards whose page is the app's own list (Cotton Notes, Cotton/// Chat). Nil for any other view.privatefunc storyCard(_ card: ToolView?) -> AnyView? { #if os(iOS)guardlet card else { returnnil }iflet notes = card.notes {returnAnyView(NotesHome(view: notes)) }iflet chat = card.chat {returnAnyView(ChatHome(filter: chat)) } #endifreturnnil }/// The tool the list is a view of (`ListTool.key`).privatevar toolKey: String? { ListTool.key(handed: tool, table: definitions[table], tools: tools.all) }/// Does this list stand for the ring's chosen view, so its deck rolls/// over into the neighbouring one: it resolves the view itself/// (`ringView`), or it was handed exactly that view by the tool's page/// (`ToolViewRoute`, which every tool's fan tile opens — the rollover had/// stood unwired there, the deck stopping at either end).privatevar rolls: Bool {guard pick == nil, !archived, !selecting, filterValue == nil, asking == nil,let toolViews, let key = toolKey else { returnfalse }if ringView != nil { returntrue }guardlet current = toolViews.current(of: key), let view else { returnfalse }return view.name == current.drawnRead(of: key).name }publicvar body: someView {// Each branch handed on as AnyView: the body's value is a pointer,// never the widest branch copied at every step of the chain, which// put Home → album's list → its page past half the phone's stack// (RouteSurfaceStackTests).let ringView = ringViewiflet ringView, let id = ringView.group, let definition = definitions[table] { groupPage(definition, id: id, ringView) } elseiflet story = storyCard(ringView) { story } else { tableList(ringView) } }/// A group the core made a view of: the group's own page, its acts. @inline(never) privatefunc groupPage(_ definition: TableDefinition, id: String, _ ringView: ToolView) -> AnyView {AnyView(GroupPage(definition: definition, group: RecordGroup(id: id, name: ringView.label, of: table, count: ringView.count), tool: toolKey) { _ inTask {do { tryawait toolViews?.reload(core: core) } catch { _ = toasts?.show(ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]), tone: .error) } } } .id(ringView.id)) }/// A view may read another of the tool's tables (Messages' Agents over/// sessions, Starred over messages): that table's list, its rows opened/// as that table opens them, never this table asked for a view it has/// none of. @inline(never) privatefunc tableList(_ ringView: ToolView?) -> AnyView {let listed = ringView?.read.table ?? tablelet filter = ringView?.read.filter ?? filterlet key = toolKey ?? tablelet view = ringView?.drawnRead(of: key) ?? viewreturnAnyView(SourceTableStore(table: listed, filter: filter) { list(listed, where: filter, view: view) }) }/// The deck rolled past its end: the ring's neighbouring view is chosen,/// its label said; nil past the ring's ends.privatefunc rollover(forward: Bool) -> String? {guardlet toolViews, let key = toolKey else { returnnil }guardlet next = toolViews.neighbour(of: key, step: forward ? 1 : -1) else { returnnil } toolViews.choose(next.id, of: key)return next.label }/// A tool's plain list — not picking, ticking, archived or opened on a/// value or an act — which a card draws as a deck.privatevar plain: Bool { pick == nil && !selecting && !archived && filterValue == nil && asking == nil } @ViewBuilder privatefunc list(_ listed: String, where filter: [String: RecordValue], view: ToolView.Read?) -> someView {let onOpen = listed == table ? onOpen : nil #if os(iOS)if listed == "note", NotesBooks.isNotes, plain {// Cotton Notes: the writing app's list, never the note deck.NotesHome(view: NotesListAsk(view: "all")) } elseif view?.face == "meetings", plain, core != nil {// Cotton Meetings' first screen: record in one tap, every// meeting's card with where it stands.MeetingsHome() } else { surface(listed, where: filter, view: view, onOpen: onOpen) } #else surface(listed, where: filter, view: view, onOpen: onOpen) #endif } @ViewBuilder privatefunc surface(_ listed: String, where filter: [String: RecordValue], view: ToolView.Read?, onOpen: ((TableRecord) -> Void)?) -> someView {iflet definition = definitions[listed].map({ Self.drawn($0, as: view) }),DeckSwitch.draws(definition, view: view, plain: plain) {DeckSurface(definition: definition, filter: filter, view: view, rollover: rolls ? { forward in rollover(forward: forward) } : nil, composesOnArrival: composeOnArrival, opensOn: opensOn) } elseiflet definition = definitions[listed].map({ Self.drawn($0, as: view) }) {RecordListSurface( definition: definition, archived: archived, where: filter, composeOnArrival: composeOnArrival, filterValue: filterValue, pick: pick, selecting: selecting, title: title ?? view?.title, asking: asking, view: view, opensOn: opensOn, leading: { leading }, onOpen: onOpen ?? { row in// A record is opened through the navigator, by its own// route or its table's deck, so it rises over Home's fan// opens in place on the phone (`PageOpening`); a Bin row// on its card in the Bin's deck, as every record.iflet navigator { navigator.push(BoardRecord.route(table: definition.id, id: row.id, definition: definition)) } else { opened = row } }) .pageDestination(item: $opened) { record inRecordOpening(definition: definition, opens: .record(record.id, record)) .cottonScreenFrame() } } else {UnknownTable() } }}extensionTableListRoute {/// The table as a view draws it: a view whose face is "list" draws its/// records as slips even where the table's own face is a grid (Birthdays/// over People's polaroids, which keeps its grid), "grid" as cards; a/// view naming no face leaves the table's layout. A view with its own/// order keeps the order the core read it in (`ToolView::over`: Birthdays/// by the next birthday), never the table's sort (People's by name).staticfunc drawn(_ definition: TableDefinition, as view: ToolView.Read?) -> TableDefinition {var drawn = definitionif view?.ordersItself == true { drawn.sort = nil// Its letters would jump about a list not in name order. drawn.index = nil }// The view's own slip and tile: the core resolved the slip's lines// by them (`ToolView::over`), so the list draws the same slots —// Web pages' relative caption, never Documents' kind and date.iflet slip = view?.slip { drawn.slip = slip drawn.slipBy = nil }iflet tile = view?.tile { drawn.tile = tile }// The view's own card: Birthdays draws People as birthdays, Money's// views draw movements and accounts (cards row 6).iflet card = view?.card { drawn.card = card }iflet search = view?.search { drawn.searchPlaceholder = search }switch view?.face {case"list": drawn.layout = .listcase"grid"where definition.layout == .list: drawn.layout = .cardsdefault: break }return drawn }}/// The tool a list is a view of: the one its page handed in; else the one/// the table's own tool block is keyed to, its own id where the block names/// no key; else the tool that lists the table — the one whose home it is/// before any other (`BoardLayout.ownsHome`'s rule: Music, Books, Films and/// Money declare their views in their manifests and their tables carry no/// tool block); nil for a table no tool owns. The ring's views and the/// deck's rollover into them are read by it — a list or a record's deck/// keyed by the table's block alone read no view at all: Films' landing deck/// stood whole, three of three, over every view the tier chose (the Cinemas/// walk, 5 Nov 2026).enumListTool {staticfunc key(handed tool: String?, table: TableDefinition?, tools: [ToolDefinition]) -> String? {iflet tool { return tool }guardlet table else { returnnil }iflet block = table.tool { return block.key ?? table.id }return (tools.first { $0.tables.first == table.id } ?? tools.first { $0.tables.contains(table.id) })?.id }}/// A tool's page: ONE list, drawn from the view its ring over the fan chose/// (`ToolViews`), or the tool's default where no ring stands (the page pushed/// on its own). A fixed view is the table read as the view says; a group the/// core generated is the group's own page, with its acts. The page has no/// stacks and no sections of its own: the ring is how a person moves/// between them (views programme, 58th amendment).publicstructToolViewRoute: View {privatelet tool: Stringprivatelet table: Stringprivatelet composeOnArrival: Boolprivatelet onOpen: ((TableRecord) -> Void)? @Environment(ToolViews.self) privatevar views: ToolViews? @Environment(\.tableDefinitions) privatevar definitions @Environment(\.toolDefinitions) privatevar tools @Environment(\.cottonCore) privatevar core @Environment(ToastCenter.self) privatevar toasts: ToastCenter?publicinit(of tool: String, table: String, composeOnArrival: Bool = false, onOpen: ((TableRecord) -> Void)? = nil) {self.tool = toolself.table = tableself.composeOnArrival = composeOnArrivalself.onOpen = onOpen }publicvar body: someView { page } @ViewBuilder privatevar page: someView {let definition = definitions[table]let view = views?.current(of: tool) #if os(iOS)iflet notes = view?.notes {// A card of Cotton Notes' fan: its list.NotesHome(view: notes) } elseiflet chat = view?.chat {// A card of Cotton Chat's fan: its conversations.ChatHome(filter: chat) } else { listPage(view, definition: definition) } #else listPage(view, definition: definition) #endif } @ViewBuilder privatefunc listPage(_ view: ToolView?, definition: TableDefinition?) -> someView {iflet view, let id = view.group, let definition {GroupPage(definition: definition, group: RecordGroup(id: id, name: view.label, of: table, count: view.count), tool: tool) { _ in// Deleted: the ring reads its views again and stands on the default.Task {do { tryawait views?.reload(core: core) } catch { _ = toasts?.show(ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]), tone: .error) } } } .id(view.id) } else {// A view may read another of the tool's tables (Photos' Albums// and People): its own table's list, its rows opened as that// table opens them.let read = view?.read.table ?? tableTableListRoute( table: read, where: view?.read.filter ?? [:], composeOnArrival: composeOnArrival, view: view?.drawnRead(of: tool), tool: tool, onOpen: read == table ? onOpen : nil) } }}/// One record's page, by table id and record id — or by the values of its/// columns, as the journal's day routes name a page by its date; values no/// record holds yet open a blank page holding them.////// Its History is the app's history screen for the record, read by the table/// id as the change log's kind — only for a table an engine keeps, whose/// changes that log holds. BAND-AID until the Records verbs carry a history of/// their own: a user table's page offers none.publicstructTablePageRoute: View {privateenumTarget: Hashable {case id(String)case columns([String: RecordValue])case blank([String: RecordValue]) }privateenumFound {case record(TableRecord)case nonecase failed }privatelet table: Stringprivatelet target: Targetprivatelet mediaOnly: Bool/// The values a source-answered table's record is read within (a member/// of one database); nothing for any other table.privatevar within: [String: RecordValue] = [:]/// The record as its opener already read it, drawn on the first frame/// while the page reads it again.privatevar seen: TableRecord? @Environment(\.tableDefinitions) privatevar definitions @Environment(Navigator.self) privatevar navigator: Navigator? @Environment(\.records) privatevar store @State privatevar found: Found?publicinit(newIn table: String, preset: [String: RecordValue] = [:]) {self.init(table: table, blankWith: preset) }publicinit(table: String, id: String, mediaOnly: Bool = false) {self.mediaOnly = mediaOnlyself.table = tableself.target = .id(id) }/// One record its opener has already read: drawn at once.publicinit(table: String, record: TableRecord) {self.init(table: table, id: record.id)self.seen = record }/// One record of a source-answered table, read within `scope` (a member/// of the database the route names).publicinit(table: String, id: String, within scope: [String: RecordValue]) {self.init(table: table, id: id)self.within = scope }publicinit(table: String, where column: String, equals value: RecordValue) {self.init(table: table, where: [column: value]) }/// A blank page for a new record holding `preset` until its first value/// creates it — a record added from its parent's page belongs to it.publicinit(table: String, blankWith preset: [String: RecordValue]) {self.mediaOnly = falseself.table = tableself.target = .blank(preset) }/// The page of the record whose columns hold every value in `filter`.publicinit(table: String, where filter: [String: RecordValue]) {self.mediaOnly = falseself.table = tableself.target = .columns(filter) }publicvar body: someView {SourceTableStore(table: table, id: recordID, filter: within) { page } }privatevar recordID: String? {ifcase .id(let id) = target { return id }returnnil } @ViewBuilder privatevar page: someView {iflet definition = definitions[table] {switch target {case .id(let id):// A conversation opens its chat, a deck tool's record its deck// at the card (`RecordOpening`); the page only for the rest.RecordOpening( definition: definition, opens: .record(id, seen ?? navigator?.openedRow(table: table, id: id)), within: within, mediaOnly: mediaOnly)case .columns(let filter): lookedUp(definition, filter)case .blank(let preset):RecordOpening(definition: definition, opens: .blank(preset)) } } else {UnknownTable() } } @ViewBuilder privatefunc lookedUp(_ definition: TableDefinition, _ filter: [String: RecordValue]) -> someView {switch found {case .record(let record)?:RecordOpening(definition: definition, opens: .record(record.id, record))case .none?:// Nothing holds that value yet: a blank page holding it, whose// first word creates the record — a day not yet written is a page// to write on, never a dead end.RecordOpening(definition: definition, opens: .blank(filter))case .failed?:PaperScreen {QuietState( title: ShellLines.line("record", "unreadable_kind", ["kind": definition.name.lowercased()]), message: ShellLines.line("empty", "unchanged"), actionLabel: ShellLines.line("record", "try_again"), action: { found = nil }) }casenil:PaperScreen { EmptyView() } // no loader: the rows are local and land next frame .task(id: target) {guardlet store else { return found = .failed }do {let hit = tryawait store.first(table: definition.id, where: filter) found = hit.map(Found.record) ?? Found.none } catch { found = .failed } } } }}/// What a source-answered table offers at once, without its list: the acts/// its list's head would hold (`/members/admit`: Admit someone).publicstructTableActsRoute: View {privatelet table: Stringprivatelet title: String?privatelet filter: [String: RecordValue]privatelet onOpen: (TableRecord) -> Void @Environment(\.tableDefinitions) privatevar definitions/// - Parameter filter: the values the acts are offered within (the/// database a person is admitted to).publicinit( table: String, title: String? = nil, where filter: [String: RecordValue] = [:], onOpen: @escaping (TableRecord) -> Void = { _ in } ) {self.table = tableself.title = titleself.filter = filterself.onOpen = onOpen }publicvar body: someView {SourceTableStore(table: table, filter: filter) {iflet definition = definitions[table] {TableActs(definition: definition, title: title ?? definition.plural, filter: filter, onOpen: onOpen) } else {UnknownTable() } } }}privatestructTableActs: View {let definition: TableDefinitionlet title: Stringlet filter: [String: RecordValue]let onOpen: (TableRecord) -> Void @Environment(\.records) privatevar storevar body: someView {RecordActionChooser(definition: definition, title: title, where: filter, asking: nil) { id inTask { iflet row = try? await store?.get(table: definition.id, id: id) { onOpen(row) } } } }}/// The store a table's list and page read through. A table an app source/// answers (`SettingsRecords`) gets one per shown database, kept while that/// holds so Back never rebuilds the list under the person, with the kept flows/// run over it. A table that is the person's own (`scope: personal`, Spec 9.5)/// reads their own database whichever is shown. Every other table reads the/// root's records untouched.structSourceTableStore<Content: View>: View {let table: Stringvar id: String? = nilvar filter: [String: RecordValue] = [:] @ViewBuilder let content: () -> Content @Environment(\.tableDefinitions) privatevar definitionsvar body: someView {let personal = definitions[table]?.isPersonal == trueifSettingsRecords.sourceTables.contains(table) {SourceScoped(table: table, id: id, filter: filter, personal: personal, content: content) } elseif personal {PersonalRecordScope(plural: definitions[table]?.plural ?? table) { content() } } else { content() } }}privatestructSourceScoped<Content: View>: View {let table: Stringlet id: String?let filter: [String: RecordValue]let personal: Boollet content: () -> Content @Environment(\.cottonCore) privatevar screenCore @Environment(\.records) privatevar definitionStore @Environment(DatabasesModel.self) privatevar databases: DatabasesModel? @Environment(DatabaseScene.self) privatevar scene: DatabaseScene? @Environment(SettingsTableStores.self) privatevar stores @Environment(\.tableDefinitions) privatevar definitions @State privatevar kept = KeptStore<SettingsRecords>()/// The core this table's reads and writes go through: the shown/// database's, or the person's own for a table that is theirs. While the/// held list is unread the shown database is the personal one/// (`DatabaseScene` opens there), so the screen's core is already right.privatevar core: (any CottonCalling)? {guardlet screenCore else { returnnil }guard personal, let own = databases?.held.first(where: \.isPersonal)else { returnDatabaseScopedCore(underlying: screenCore, database: scene?.shownId) }returnDatabaseScopedCore(underlying: screenCore, database: own.databaseId) }var body: someView {Group {iflet records = kept.store { content() .id(ObjectIdentifier(records)) .environment(\.records, records) .settingsKeptFlows(table: table, record: id) } elseif screenCore == nil {// No core will come to build the store with: say so rather// than stand blank.PaperScreen {QuietState(title: ShellLines.line("record", "unreadable_plural", ["plural": "\(definitions[table]?.plural ?? table)"]), message: PersonalScopeWait.Words.noRecords) } } else {PaperScreen { EmptyView() } // no loader: the store is local and lands next frame } }// Core arrival and a replacement backend both rebuild the store; its// identity above also replaces list/page models holding the old one.// Only those: `.task` restarts on every appear, a Back included, and a// store made again there gave the subtree a new `.id`, so the list or// page came back rebuilt at its top (S2). .task(id: identity) {guardlet core else { return }let buildingFor = identitylet records = stores.records(for: buildingFor) { SettingsRecords.bundled(core: core) }try? await records.selectScope(table: table, where: filter)guard !Task.isCancelled, identity == buildingFor else { return } kept.keep(for: buildingFor) { records } } }privatevar identity: SettingsTableStoreIdentity {SettingsTableStoreIdentity( corePresent: screenCore != nil, records: definitionStore.map { ObjectIdentifier($0) }, personal: personal ? databases?.held.first(where: \.isPersonal)?.databaseId : nil, database: scene?.shownId) }}/// A store made once per identity and kept while the identity holds. The/// screen draws under `.id(ObjectIdentifier(store))`, so a store made again for/// the same identity throws away everything under it — the list's scroll, the/// page's kept place, their models.structKeptStore<Store: AnyObject> {private(set) var store: Store?privatevar builtFor: SettingsTableStoreIdentity?mutatingfunc keep(for identity: SettingsTableStoreIdentity, make: () -> Store) {guard store == nil || builtFor != identity else { return } store = make() builtFor = identity }}structSettingsTableStoreIdentity: Hashable {let corePresent: Boollet records: ObjectIdentifier?/// The person's own database, which a `.personal` table reads: the store/// is made again once the held list names it.var personal: String? = nilvar database: String? = nil}/// A table the definitions in hand do not draw. The refusal is said only/// once the shown database's catalogue has answered and it IS the answer:/// while that read is in flight (`TableDefinitions.isRead` false — the set a/// window holds until then, or the empty default) the screen draws nothing,/// as a store still being made does. Messages and Notebook flashed the/// refusal for one frame before their empty state (Rigby walk, 22 Oct 2026).structUnknownTable: View { @Environment(\.tableDefinitions) privatevar definitionsvar body: someView {PaperScreen {ifSelf.refuses(definitions) {QuietState(title: ShellLines.line("record", "unknown_table.title"), message: ShellLines.line("record", "unknown_table.body")) } } }/// Whether the screen says the refusal: only on the answer of a read.staticfunc refuses(_ definitions: TableDefinitions) -> Bool { definitions.isRead }}/// A new event's blank page: the day it stands on is the core's/// (`shell.draft {blank}`), the route's day or today.structNewEventRoute: View {let day: String? @Environment(\.cottonCore) privatevar core @State privatevar preset: [String: RecordValue]? @State privatevar unread = falseprivatestructBlank: Decodable { let values: [String: RecordValue] }var body: someView {// A ZStack and never a Group: a Group holding nothing draws nothing,// and a task on it never starts — Plus on Calendar stood blank. ZStack {Color.cleariflet preset {TablePageRoute(newIn: "event", preset: preset) } elseif unread {PaperScreen {QuietState(title: ShellLines.line("boot", "link.unread_title"), message: ShellLines.line("boot", "link.unread_body")) } } } .task {var ask: [String: JSONValue] = ["table": "event", "blank": .bool(true), "timezone": .string(TimeZone.current.identifier)]iflet day { ask["day"] = .string(day) }do {guardlet core else { throwCancellationError() } preset = tryawait core.call(CottonMethod.shellDraft, JSONValue.object(ask), as: Blank.self).values } catch { unread = true } } }}