// 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`). import CottonKit import CottonValues import SwiftUI /// 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. public struct TableListRoute: View { private let table: String private let title: String? private let archived: Bool private let filter: [String: RecordValue] private let composeOnArrival: Bool private let filterValue: String? private let pick: ListPick? private let selecting: Bool /// The list act whose sheet is up as the list opens (`/repos/[id]/pulls/new`). private let asking: String? private let onOpen: ((TableRecord) -> Void)? /// What stands above the list (the meetings' recovery notes). private let leading: Leading /// The day a day-split list opens on (`/calendar?date=`). private let opensOn: String? /// The tool's view the list is (`ToolViewRoute`). private let 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`). private let tool: String? @Environment(\.tableDefinitions) private var definitions @Environment(\.toolDefinitions) private var tools @Environment(ToolViews.self) private var toolViews: ToolViews? @Environment(\.cottonCore) private var core @Environment(Navigator.self) private var navigator: Navigator? @Environment(ToastCenter.self) private var toasts: ToastCenter? /// The record whose page is open on the list's own stack. @State private var 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. public init( 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 = view self.tool = tool self.opensOn = opensOn self.table = table self.title = title self.archived = archived self.filter = filter self.composeOnArrival = composeOnArrival self.filterValue = filterValue self.pick = pick self.selecting = selecting self.asking = asking self.onOpen = onOpen self.leading = leading() } /// The list with nothing drawn above it. public init( 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 ) where Leading == 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. private var ringView: ToolView? { guard view == nil, filter.isEmpty, pick == nil, !archived, !selecting, filterValue == nil, asking == nil, let toolViews, let key = toolKey else { return nil } 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. private func storyCard(_ card: ToolView?) -> AnyView? { #if os(iOS) guard let card else { return nil } if let notes = card.notes { return AnyView(NotesHome(view: notes)) } if let chat = card.chat { return AnyView(ChatHome(filter: chat)) } #endif return nil } /// The tool the list is a view of (`ListTool.key`). private var 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). private var rolls: Bool { guard pick == nil, !archived, !selecting, filterValue == nil, asking == nil, let toolViews, let key = toolKey else { return false } if ringView != nil { return true } guard let current = toolViews.current(of: key), let view else { return false } return view.name == current.drawnRead(of: key).name } public var body: some View { // 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 = ringView if let ringView, let id = ringView.group, let definition = definitions[table] { groupPage(definition, id: id, ringView) } else if let story = storyCard(ringView) { story } else { tableList(ringView) } } /// A group the core made a view of: the group's own page, its acts. @inline(never) private func 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) { _ in Task { do { try await 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) private func tableList(_ ringView: ToolView?) -> AnyView { let listed = ringView?.read.table ?? table let filter = ringView?.read.filter ?? filter let key = toolKey ?? table let view = ringView?.drawnRead(of: key) ?? view return AnyView(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. private func rollover(forward: Bool) -> String? { guard let toolViews, let key = toolKey else { return nil } guard let next = toolViews.neighbour(of: key, step: forward ? 1 : -1) else { return nil } 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. private var plain: Bool { pick == nil && !selecting && !archived && filterValue == nil && asking == nil } @ViewBuilder private func list(_ listed: String, where filter: [String: RecordValue], view: ToolView.Read?) -> some View { 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")) } else if 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 private func surface(_ listed: String, where filter: [String: RecordValue], view: ToolView.Read?, onOpen: ((TableRecord) -> Void)?) -> some View { if let 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) } else if let 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. if let navigator { navigator.push(BoardRecord.route(table: definition.id, id: row.id, definition: definition)) } else { opened = row } }) .pageDestination(item: $opened) { record in RecordOpening(definition: definition, opens: .record(record.id, record)) .cottonScreenFrame() } } else { UnknownTable() } } } extension TableListRoute { /// 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). static func drawn(_ definition: TableDefinition, as view: ToolView.Read?) -> TableDefinition { var drawn = definition if 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. if let slip = view?.slip { drawn.slip = slip drawn.slipBy = nil } if let 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). if let card = view?.card { drawn.card = card } if let search = view?.search { drawn.searchPlaceholder = search } switch view?.face { case "list": drawn.layout = .list case "grid" where definition.layout == .list: drawn.layout = .cards default: 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). enum ListTool { static func key(handed tool: String?, table: TableDefinition?, tools: [ToolDefinition]) -> String? { if let tool { return tool } guard let table else { return nil } if let 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). public struct ToolViewRoute: View { private let tool: String private let table: String private let composeOnArrival: Bool private let onOpen: ((TableRecord) -> Void)? @Environment(ToolViews.self) private var views: ToolViews? @Environment(\.tableDefinitions) private var definitions @Environment(\.toolDefinitions) private var tools @Environment(\.cottonCore) private var core @Environment(ToastCenter.self) private var toasts: ToastCenter? public init(of tool: String, table: String, composeOnArrival: Bool = false, onOpen: ((TableRecord) -> Void)? = nil) { self.tool = tool self.table = table self.composeOnArrival = composeOnArrival self.onOpen = onOpen } public var body: some View { page } @ViewBuilder private var page: some View { let definition = definitions[table] let view = views?.current(of: tool) #if os(iOS) if let notes = view?.notes { // A card of Cotton Notes' fan: its list. NotesHome(view: notes) } else if let 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 private func listPage(_ view: ToolView?, definition: TableDefinition?) -> some View { if let 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 { try await 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 ?? table TableListRoute( 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. public struct TablePageRoute: View { private enum Target: Hashable { case id(String) case columns([String: RecordValue]) case blank([String: RecordValue]) } private enum Found { case record(TableRecord) case none case failed } private let table: String private let target: Target private let mediaOnly: Bool /// The values a source-answered table's record is read within (a member /// of one database); nothing for any other table. private var within: [String: RecordValue] = [:] /// The record as its opener already read it, drawn on the first frame /// while the page reads it again. private var seen: TableRecord? @Environment(\.tableDefinitions) private var definitions @Environment(Navigator.self) private var navigator: Navigator? @Environment(\.records) private var store @State private var found: Found? public init(newIn table: String, preset: [String: RecordValue] = [:]) { self.init(table: table, blankWith: preset) } public init(table: String, id: String, mediaOnly: Bool = false) { self.mediaOnly = mediaOnly self.table = table self.target = .id(id) } /// One record its opener has already read: drawn at once. public init(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). public init(table: String, id: String, within scope: [String: RecordValue]) { self.init(table: table, id: id) self.within = scope } public init(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. public init(table: String, blankWith preset: [String: RecordValue]) { self.mediaOnly = false self.table = table self.target = .blank(preset) } /// The page of the record whose columns hold every value in `filter`. public init(table: String, where filter: [String: RecordValue]) { self.mediaOnly = false self.table = table self.target = .columns(filter) } public var body: some View { SourceTableStore(table: table, id: recordID, filter: within) { page } } private var recordID: String? { if case .id(let id) = target { return id } return nil } @ViewBuilder private var page: some View { if let 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 private func lookedUp(_ definition: TableDefinition, _ filter: [String: RecordValue]) -> some View { 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 }) } case nil: PaperScreen { EmptyView() } // no loader: the rows are local and land next frame .task(id: target) { guard let store else { return found = .failed } do { let hit = try await 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). public struct TableActsRoute: View { private let table: String private let title: String? private let filter: [String: RecordValue] private let onOpen: (TableRecord) -> Void @Environment(\.tableDefinitions) private var definitions /// - Parameter filter: the values the acts are offered within (the /// database a person is admitted to). public init( table: String, title: String? = nil, where filter: [String: RecordValue] = [:], onOpen: @escaping (TableRecord) -> Void = { _ in } ) { self.table = table self.title = title self.filter = filter self.onOpen = onOpen } public var body: some View { SourceTableStore(table: table, filter: filter) { if let definition = definitions[table] { TableActs(definition: definition, title: title ?? definition.plural, filter: filter, onOpen: onOpen) } else { UnknownTable() } } } } private struct TableActs: View { let definition: TableDefinition let title: String let filter: [String: RecordValue] let onOpen: (TableRecord) -> Void @Environment(\.records) private var store var body: some View { RecordActionChooser(definition: definition, title: title, where: filter, asking: nil) { id in Task { if let 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. struct SourceTableStore: View { let table: String var id: String? = nil var filter: [String: RecordValue] = [:] @ViewBuilder let content: () -> Content @Environment(\.tableDefinitions) private var definitions var body: some View { let personal = definitions[table]?.isPersonal == true if SettingsRecords.sourceTables.contains(table) { SourceScoped(table: table, id: id, filter: filter, personal: personal, content: content) } else if personal { PersonalRecordScope(plural: definitions[table]?.plural ?? table) { content() } } else { content() } } } private struct SourceScoped: View { let table: String let id: String? let filter: [String: RecordValue] let personal: Bool let content: () -> Content @Environment(\.cottonCore) private var screenCore @Environment(\.records) private var definitionStore @Environment(DatabasesModel.self) private var databases: DatabasesModel? @Environment(DatabaseScene.self) private var scene: DatabaseScene? @Environment(SettingsTableStores.self) private var stores @Environment(\.tableDefinitions) private var definitions @State private var kept = KeptStore() /// 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. private var core: (any CottonCalling)? { guard let screenCore else { return nil } guard personal, let own = databases?.held.first(where: \.isPersonal) else { return DatabaseScopedCore(underlying: screenCore, database: scene?.shownId) } return DatabaseScopedCore(underlying: screenCore, database: own.databaseId) } var body: some View { Group { if let records = kept.store { content() .id(ObjectIdentifier(records)) .environment(\.records, records) .settingsKeptFlows(table: table, record: id) } else if 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) { guard let core else { return } let buildingFor = identity let 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 } } } private var 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. struct KeptStore { private(set) var store: Store? private var builtFor: SettingsTableStoreIdentity? mutating func keep(for identity: SettingsTableStoreIdentity, make: () -> Store) { guard store == nil || builtFor != identity else { return } store = make() builtFor = identity } } struct SettingsTableStoreIdentity: Hashable { let corePresent: Bool let 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? = nil var 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). struct UnknownTable: View { @Environment(\.tableDefinitions) private var definitions var body: some View { PaperScreen { if Self.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. static func 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. struct NewEventRoute: View { let day: String? @Environment(\.cottonCore) private var core @State private var preset: [String: RecordValue]? @State private var unread = false private struct Blank: Decodable { let values: [String: RecordValue] } var body: some View { // 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.clear if let preset { TablePageRoute(newIn: "event", preset: preset) } else if 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)] if let day { ask["day"] = .string(day) } do { guard let core else { throw CancellationError() } preset = try await core.call(CottonMethod.shellDraft, JSONValue.object(ask), as: Blank.self).values } catch { unread = true } } } }