// The list: every record of one table as slips, with search, narrowed by the// current project, read a page at a time (rebuild note 7b95efa4, "Surfaces").// Two touches on a slip: its toggle flips the definition's toggle column, and// a long press drags it when the table has an order column — within its// section, when the definition splits the list by a choice column (`group`). A tap on a slip// hands the record to whoever holds the list — it opens that record's page.//// A list draws ONE layout, the one its definition names (`layout`; owner,// 15 Oct 2026): cards — each record as its cover (`CoverFace`), a polaroid, a// place's postcard or a small slip, `grid.columns` across — the borderless// contact sheet of pictures, or slips (absent). The person never switches it// and no device remembers one. A grid does not drag; the list does. Narrowing// is search's and voice's job: the list draws no menus of facets.//// A list split by day (`by_day`) heads each day by its name, counted only when// it holds more than one; a long list split by month (`by_month`) heads each// month by its name and count. A list of work still to do (`upcoming`) heads each// day it is next due by its name, soonest first, a day gone under Today, and// its slips say how late, the hour or when a snooze ends. A slip ticked stays// where it stands until the list is read again (`RecordListModel.sections`). A// definition naming `chips` draws its row of choice words over the records;// Save makes a record of them (`ChipRowHead`).//// A record the definition dims (`dimmed`: a closed shop) is drawn faded, and// other tables' lists the definition names (`lists`: every shop's recent// orders) follow the table's own records as sections (`RecordsSection`).//// A long list opens with "Recent" (`recent`): the records touched most// lately, typed quietly with their moment handwritten at the right, each// opening its page — only over the whole table, read to its end: not while a// search or a project narrows the list (`RecordListModel.recent`).//// A section the definition marks `closed` (`ListGroup.closed`) draws its// heading, the words "show" or "hide", and its count only, until the heading// is tapped. A search opens every shut section, so nothing it finds is hidden.//// Archived records (the definition's `archived` column) are left out unless// whoever holds the list asks for them. A slip's long press is ONE menu: the// acts its page's menu offers, in the same words, each asked first as the// page asks it (S8) and read back with its Undo — and none on a list that drags, whose long press is the drag. An empty list says the definition's own words// (`empty`) when it has them. And a list may be narrowed to the// records holding given column values — one conversation's messages, by its id.// A list asked for its archived records too draws them faded.//// A table whose slip numbers its records (`ordinal`) has each one's place in// its section written on its slip, and a section of a grouped list may carry// a note under its heading (`group` sections' `note`).//// A table naming `create` has the "+" on the title's line, opening a blank page// for a new record (today in its `dated` column) — the button its empty list// offers too, under its own `empty` words; a link may ask for that page as// the list arrives (`composeOnArrival`).//// Every write goes through the `Records` verbs in the environment and is read// back as the change receipt (`ChangeReceipt`) — a passing card at the list's// foot, above the one input, with its byline, lines and Undo, until it is// dismissed or the next write replaces it.//// The one input at the foot acts on this list (`OneInputModel`): "done milk"// ticks the matching record, "move milk to Allotment" moves it, words with no// verb add one. Its change lands on the model as the list's newest and wears// the same receipt; what it said beside it (asked, matched nothing) is the// note card under the receipt. Whoever holds the list may title it in place// of the table's plural ("Code" over the sessions).//// A list that asks its owner something (`QuestionKeys`) says its own words// when empty (`empty`); a row standing for another record opens THAT record// through `recordOpener` (`opens`); a slip's typed answers write their value// and a slip's reply opens the reply sheet, whose words are written the same// way — and a record answered leaves the list.//// A store that offers acts of its own (`ActingRecords`) has them drawn at the// list's head as plain typed buttons ("Connect Google"); the reason one was// not done is said under them. An act that opens a sign-in in the browser has// the list read itself again every two seconds while it is on screen, so what// the sign-in made appears; one that makes or picks a record opens its page.// An act the vault refused opens the vault (`\.keptFlow`) and is tried once// more (`KeptFlowRetry`). The store's one line about the table (`listNote`)// is typed over the acts. The head's acts are asked for with the list's// `where`, so one project's list can offer what only it can ("Start a session"// in that project). A slip's own acts (`slipActions`: Allow on a session// waiting for a permission) are drawn under it and run the same way, asking// first where the act asks — the one act path (`RecordActs`) a section of// another page runs its slips' acts through too. A table that is `live` reads// again on its cadence while it is on screen.//// A sealed table (`sealed`: Passwords) draws no capture bar: the one// input files its words as a thought, and a password said into it would land// unsealed (`TableDefinition.takesCapture`). Its empty list says the// definition's own words (`empty`), never "in the bar below".//// An engine may stand one view above its table's slips (`EngineListHead`):// the alarm engine's next-alarm line and its note saying whether this phone// will ring. Every other list has none.//// A table indexed by a column (`index`) has the A–Z rail at the list's right// edge, like Contacts (`IndexRail`): a finger on a letter lands on its first// record, a letter no record starts with is faint, and the rail is hidden// while a search narrows the list or when one letter holds everything. Such a// list reads to its end, so every letter is there to land on. A table whose// tile is the polaroid grid draws each record in its grid as its polaroid —// the print captioned with the first name, or the typed card with the whole// name — never a slip squeezed small. A `create` naming an app route// (`path`) opens that route from the "+" and the empty list's button, in// place of a blank page (people are brought in from the phone's contacts). A// slip that asks a question (`answers`) offers its answers under it, each// written with its receipt and Undo; an answered record leaves the list.// A table of pictures (its tile the polaroid grid) draws its records as// polaroids in the grid (`PolaroidFace`), and — where its `grid` names a// `sheet` — the toggle's other face is the contact sheet: the pictures as// plain squares, many across, in place of slips. A row that stands for// another record (`opens`) opens that one. A slip or a polaroid that asks// something carries its answers; an answered record leaves the list.//// A table may narrow its list by a row of typed words (`filter`: all · photos// · videos), shown once there is something to choose between or a word is// on; offer Select (`select`), whose ticks end in one Delete asked in the// table's words (`deletion`) and done one at a time, the refused staying// picked; and keep other lists in its menu with their counts (`links`), the// ones waiting on the owner summed in red beside the filter ("3 to review").// Months are counted in the table's words (`count_words`).//// A list that can be emptied in one act (`clear`: the Bin's "Empty the bin")// draws its red verb under the records with its line by hand, only while// nothing narrows the list; the list is read to its end so the question's// count is the table's, and every record goes through `delete_record`, one at// a time, the refused staying listed.//// A list may also be a PICK (`pick`): always selecting, its tick making one// record of another table per picked record (a picture put in an album), then// going back.//// A link with no route (`ListLink.isListLink`) is drawn on the list itself, in// the page's row of links (`SideLinksRow`): one that `lead`s alone under the// records, the rest after the other lists ("People 12 Statements 4"), each// counted from its read's total and left out at none unless its list takes an// add (R12). It opens the table's list narrowed by its `where`, titled by this// list (`FilteredListOpening`: "Settled · Ledgers"). The other lists// read with the list's search while it is searched, so what is typed finds// their records too.//// The one input's answer: a record it made wears its receipt, which no note// replaces; a question the store asked before making one ("From which// one?", `CreateQuestion`) stands above the bar with its answers, the// words staying in the bar until an answer makes the record.importCottonKitimportCottonValuesimportSwiftUI/// A list that picks: every record it shows can be ticked, and its tick/// makes one record of `table` per picked record, holding `preset` and the/// picked record's id in `column` — then `done` (the add screen goes back).publicstructListPick {publicenumAction: String {case add = "Add"case remove = "Remove"publicfunc label(count: Int) -> String { "\(rawValue) \(count)" }var completed: String { self == .add ? "added" : "removed" } }publicvar action: Actionpublicvar table: Stringpublicvar column: Stringpublicvar preset: [String: RecordValue]/// The picker title, kept while selections and search change ("Add photos").publicvar label: Stringpublicvar empty: EmptyWords?/// What the pick says once it is done, of how many ("3 photos added to/// Summer"); nil says "Added 3" and the made table's name — and nothing/// at all after an `act`, whose own change wears a receipt.publicvar said: ((Int) -> String)?/// What the tick does in place of making records — taking the picked/// records out of a group — answering the ids it could not do.publicvar act: (@MainActor ([String]) async -> [String])?/// Records the pick already holds (the people in the group being added/// to): drawn ticked in pencil, said as `heldWords`, and not picked again.publicvar held: Set<String>publicvar heldWords: String?publicvar done: @MainActor () -> Voidpublicinit( table: String, column: String, preset: [String: RecordValue], label: String, action: Action = .add, empty: EmptyWords? = nil, said: ((Int) -> String)? = nil, act: (@MainActor ([String]) async -> [String])? = nil, held: Set<String> = [], heldWords: String? = nil, done: @escaping @MainActor () -> Void ) {self.action = actionself.held = heldself.heldWords = heldWordsself.table = tableself.column = columnself.preset = presetself.label = labelself.empty = emptyself.said = saidself.act = actself.done = done }}/// A list drawn as one gathering of its table's records (a group's page):/// what its "+" and its empty words add, the lines its menu gains, and what/// becomes of a record the bar makes there.publicstructListScope {publicvar empty: EmptyWordspublicvar addLabel: Stringpublicvar add: @MainActor () -> Voidpublicvar menu: [PopoverMenuItem]/// The bar's words on this list ("Add to Family…").publicvar barWords: String?/// The newest change the gathering made of itself (records put in or/// taken out): the list wears it as its own receipt, with its Undo.publicvar received: ChangeRecord?/// A record the bar made on this list, by its id.publicvar made: @MainActor (String) async -> Void/// Runs one of the list's own acts the core put in its menu (a group's/// page: Add, Remove, Rename, Remove list); nil draws none of them.var runs: (@MainActor (ListAnswer.MenuItem) -> Void)? = nilpublicinit( empty: EmptyWords, addLabel: String, add: @escaping @MainActor () -> Void, menu: [PopoverMenuItem], barWords: String? = nil, received: ChangeRecord? = nil, made: @escaping @MainActor (String) async -> Void ) {self.empty = emptyself.addLabel = addLabelself.add = addself.menu = menuself.barWords = barWordsself.received = receivedself.made = made }}publicstructRecordListSurface: View {privatelet definition: TableDefinitionprivatelet archived: Boolprivatelet filter: [String: RecordValue]/// The one section of the table's day plan this list is ("earlier");/// nil, the whole list.privatelet section: String?/// The tool's view this list is (`ToolView`): read as it says and drawn/// as one list, its groups on the ring rather than in stacks.privatelet view: ToolView.Read?/// The day a day-split list opens on (`RecordListModel.opensOn`).privatelet opensOn: String?privatelet composeOnArrival: Boolprivatelet pick: ListPick?/// The list is one gathering of the table's records (a group's page).privatelet scope: ListScope?/// The title over the list in place of the table's plural; nil is the plural.privatelet titleOverride: String?/// The head act whose sheet is up as the list opens, asked once.privatelet askingOnOpen: String?privatelet onOpen: (TableRecord) -> Void/// What the holder draws above the list (the Mail folders), boxed so/// the list is one type, compiled once, whatever stands above it.privatelet leading: AnyView @Environment(\.theme) privatevar theme @Environment(\.linkTitles) privatevar links @Environment(\.records) privatevar store/// The ring's views over the fan, when this list is one (`ToolViews`). @Environment(ToolViews.self) privatevar toolViews: ToolViews? @Environment(\.cottonCore) privatevar core/// The editor over Home's fan, where one stands (`ExportFan`'s row). @Environment(\.deckEditor) privatevar deckEditor @Environment(\.currentProject) privatevar currentProject/// The project the rows are read in: the current one, for a table whose/// rows belong to projects; none for a table whose rows do not (the bin,/// an engine's view) — the core refuses a project filter on those, and a/// list that sent one read "could not be read" inside every project.privatevar project: String? { definition.projectScope(currentProject) } @Environment(\.recordsRevision) privatevar revision/// The database shown, which the list's seed is kept under. @Environment(DatabaseScene.self) privatevar databaseScene: DatabaseScene? @Environment(DatabasesModel.self) privatevar databasesModel: DatabasesModel? @Environment(\.keptFlow) privatevar keptFlow @Environment(\.nativeKeptFlow) privatevar nativeKeptFlow @Environment(\.rekeyThisDevice) privatevar rekeyThisDevice @Environment(\.readerPresenter) privatevar readerPresenter @Environment(\.openURL) privatevar openURL @Environment(PendingTaps.self) privatevar pendingTaps: PendingTaps? @Environment(\.recordOpener) privatevar opener/// Where a list link whose list is a screen of its own opens (the Code/// list's Runners, `/code/runners`); a table it does not open, the/// generic narrowed list. @Environment(\.listOpener) privatevar listOpener @Environment(\.tableDefinitions) privatevar definitions @Environment(Navigator.self) privatevar navigator: Navigator?/// Where a picture, a film or a document opens: the one viewer. @Environment(\.viewerPresenter) privatevar viewerPresenter/// This list is on the navigator's path (`FilteredListOpening.open`). @Environment(\.listsOnPath) privatevar listsOnPath/// This list's own route on that path, when it is a routed screen. @Environment(\.screenRoute) privatevar screenRoute @Environment(ToastCenter.self) privatevar toasts @State privatevar model: RecordListModel?/// Whether words this table does not take are kept as a thought said/// here (`ThoughtKeepingRecords`): the box then stands on the list anyway.privatevar keepsThoughts: Bool { (store as? any ThoughtKeepingRecords)?.keepsThoughts(table: definition.id) ?? false } @State privatevar localQuery = "" @Environment(\.cottonListSearch) privatevar toolbarQueryprivatevar query: String { toolbarQuery?.wrappedValue ?? localQuery }privatevar queryBinding: Binding<String> { toolbarQuery ?? $localQuery }/// The acts the store offers at the head and under each slip, the one/// asking first, why the last was not done, and the store's line about/// the table (`ActingRecords.listNote`). @State privatevar acts: RecordActs/// A value an act showed once, until "I've saved it". @State privatevar revealed: RevealedValue?/// A sign-in is open in the browser: the list reads again while it waits. @State privatevar signingIn = 0 @State privatevar searching = false/// What the one input said beside its change, until it is let go. @State privatevar note: OneInputNote?/// How many of the bar's answers were let go: each empties the bar. @State privatevar answersLetGo = 0/// The table each change the bar made was written to, when it is not the/// list's own (`capture`): its receipt reads "Added" by that table's title. @State privatevar receiptTables: [String: TableDefinition] = [:] @State privatevar dragging = false/// Whether `askingOnOpen` was put up, so a read again does not put it up again. @State privatevar asked = false/// A blank page for a new record is open over the list. @State privatevar composing = false/// A door's files being chosen in the system's picker (`DeckDoors`). @State privatevar choosingFiles: DefinitionCreateFiles?/// A door's pictures being chosen in the photo picker or taken with the camera (`DoorPictures`). @State privatevar pickingPictures: DefinitionCreatePick?/// The related list (or its blank record) the menu opened. @State privatevar relatedOpen: RelatedOpening?/// `composeOnArrival` is honoured once: coming back from the blank page/// must not open it again. @State privatevar composedOnArrival = false/// The closed sections (`ListGroup.closed`) opened by a tap, by heading. @State privatevar opened: Set<String> = []/// The letter the index rail last asked the list to show. @State privatevar scrollTarget: String?/// The record whose answer is on its way: its verbs wait. @State privatevar answering: String?/// The record whose reply sheet is up, or nil. @State privatevar replying: TableRecord? @State privatevar gridWidth: CGFloat = 0/// The filter row's chosen value; nil is all. @State privatevar chosen: String?/// The read the rows on screen were read for: a list returned to on the/// path appears again with the same one, and keeps its rows and place. @State privatevar readFor: Read?/// A failed first read is being tried again on a tick. @State privatevar retrying = false/// The list is drawn (a page pushed over it, or a tab away, is not). @State privatevar onScreen = false @Environment(\.scenePhase) privatevar scenePhase/// Ticking records, for Select (or always, on a pick). @State privatevar selecting = false/// The ticked records' ids, in the order ticked. @State privatevar picked: [String] = [] @State privatevar menuOpen = false/// The head's "+" opened the store's folded "New …" choices. @State privatevar headFanned = false/// Whether the store's head acts fold into one "+", drawn as the head's/// own circle at its full hit size, where every other list's "+" stands.privatevar headFolds: Bool { scope == nil && definition.create == nil && RecordActionButtons.folds(acts.head) } @State privatevar confirmingDelete = false/// Select's Delete as the core asked it: the records it takes, its question, its receipt. @State privatevar deletingAsked: ListDeleting?/// The long-press act waiting on its question, in the core's words (S8). @State privatevar asking: PressAsk?/// A long-press Bin of a record that repeats, waiting on how far it reaches. @State privatevar scoping: ScopeAsk?/// The `clear` question is open. @State privatevar confirmingClear = false/// A Select or a pick is being written. @State privatevar busy = false/// The narrowed list a list link opened. @State privatevar filteredOpen: FilteredListOpening?/// What the search found in the other lists (`lists`) drawn with it. @State privatevar sectionFinds = SectionFinds()/// The question the store asked before making the bar's record. @State privatevar question: CreateQuestion?/// "New group" is being asked (the stacks row's sheet). @State privatevar namingGroup = false/// "Add to group…" is up for the ticked records. @State privatevar addingToGroup = false/// - Parameters:/// - archived: list archived records too./// - filter: the column values every listed record holds (column key →/// value); empty lists the whole table./// - composeOnArrival: open the blank page for a new record as the/// list arrives (a link asking for "new", as `/todos?new=1` does)./// - filterValue: the filter row's value the list opens on (`/photos?show=videos`)./// - pick: the list picks records for another table instead of opening them./// - selecting: open already ticking (a section's "Select pictures")./// - title: the list's title in place of the table's plural./// - asking: the id of a head act to ask as the list opens — its/// sheet or question up once the head offers it, as a tap would.publicinit<Leading: View>( definition: TableDefinition, archived: Bool = false, where filter: [String: RecordValue] = [:], composeOnArrival: Bool = false, filterValue: String? = nil, pick: ListPick? = nil, selecting: Bool = false, title: String? = nil, asking: String? = nil, scope: ListScope? = nil, query: String = "", section: String? = nil, view: ToolView.Read? = nil, opensOn: String? = nil, @ViewBuilder leading: () -> Leading, onOpen: @escaping (TableRecord) -> Void ) {self.view = viewself.opensOn = opensOnself.scope = scope// A list opened searched (a section's "All" while its list was// searched) opens with the search open on the same words. _localQuery = State(initialValue: query) _searching = State(initialValue: !query.isEmpty)self.definition = definitionself.archived = archivedself.filter = filterself.section = sectionself.composeOnArrival = composeOnArrivalself.pick = pickself.titleOverride = titleself.askingOnOpen = askingself.onOpen = onOpenself.leading = AnyView(leading()) _acts = State(initialValue: RecordActs(table: definition.id, where: filter)) _chosen = State(initialValue: filterValue.flatMap { definition.filter?.words[$0] == nil ? nil : $0 }) _selecting = State(initialValue: pick != nil || (selecting && definition.select != nil)) }/// The list with nothing drawn above it — every list but the meetings'/// (whose recovery notes stand at its head).publicinit( definition: TableDefinition, archived: Bool = false, where filter: [String: RecordValue] = [:], composeOnArrival: Bool = false, filterValue: String? = nil, pick: ListPick? = nil, selecting: Bool = false, title: String? = nil, asking: String? = nil, scope: ListScope? = nil, query: String = "", section: String? = nil, view: ToolView.Read? = nil, opensOn: String? = nil, onOpen: @escaping (TableRecord) -> Void ) {self.init( definition: definition, archived: archived, where: filter, composeOnArrival: composeOnArrival, filterValue: filterValue, pick: pick, selecting: selecting, title: title, asking: asking, scope: scope, query: query, section: section, view: view, opensOn: opensOn, leading: { EmptyView() }, onOpen: onOpen) }/// Whether the records are drawn in a grid: the definition's cards or/// its contact sheet.privatevar showsGrid: Bool { definition.layout != .list }/// What every listed record holds: the route's narrowing and the filter/// row's word.privatevar narrowing: [String: RecordValue] { filter.merging(model?.filterWhere(chosen) ?? [:]) { _, word in word } }/// What a read depends on: a new project, search or filter word reads again./// What the list reads from page one: the project, search and filter/// word — never the records revision. A tick is `dataMoved`,/// which lets a read on its way answer and then reads again in place.privatestructRead: Equatable {var project: String?var query: Stringvar chosen: String?/// The tool's view: another view is another list.var view: ToolView.Read? }/// The title: the holder's, else the core's, or while ticking how many are.privatevar title: String {iflet pick { return pick.label }guard selecting else {iflet titleOverride, !titleOverride.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return titleOverride }return model?.answer?.title ?? definition.plural }return picked.isEmpty ? (pick?.label ?? "Select") : "\(picked.count) selected" }/// The list links the core answered (`lead` alone under the records,/// `above` in one row over them, or the row after its other lists).privatefunc listLinks(lead: Bool, above: Bool = false) -> [ListAnswer.Link] {guard pick == nil, !selecting, query.isEmpty else { return [] }return (model?.answer?.links ?? []).filter { $0.id.hasPrefix("link:") && $0.lead == lead && $0.above == above } }/// Opens what a link, a menu line or a group says it opens: a route, or a list.privatefuncopen(_ opens: ListAnswer.Opens) {iflet path = opens.path {iflet route = Route.parse(path) { navigator?.push(route) }return }guardlet table = opens.table else { return }let narrowed = opens.where ?? [:]iflet listOpener, narrowed.isEmpty, opens.section == nil, opens.archived != true, opens.query == nil, listOpener.names(table) { listOpener(table, nil)return }FilteredListOpening( table: table, filter: narrowed, title: opens.title ?? "", query: opens.query ?? "", archived: opens.archived ?? false, section: opens.section ) .open(on: navigator, onPath: listsOnPath, else: $filteredOpen) }/// The list's last line on a table that archives (S7): "Archived · n ›",/// as the core counts what this read finds put away. @ViewBuilder privatefunc archivedLink(_ model: RecordListModel) -> someView {if pick == nil, !selecting, let link = model.answer?.links.first(where: { $0.id == "archived" }) {PaperTypedButton("\(link.words) \u{203A}", size: 15) { open(link.opens) } .accessibilityIdentifier("list-\(definition.id)-archived") .frame(maxWidth: .infinity, alignment: .leading) .padding(.top, 22) } }/// A planned list's past (Calendar, Meetings, Calls): ONE link at its top,/// above Today — "Earlier · n ›" — opening the past as its own list. @ViewBuilder privatefunc earlierLink(_ model: RecordListModel) -> someView {if pick == nil, !selecting, let link = model.answer?.links.first(where: { $0.id == "earlier" }) {PaperTypedButton("\(link.words) \u{203A}", size: 15) { open(link.opens) } .accessibilityIdentifier("list-\(definition.id)-earlier") .frame(maxWidth: .infinity, alignment: .leading) .padding(.bottom, 18) } }/// Bring back, on each slip of a list of the archived (S7), where the core offers it. @ViewBuilder privatefunc bringBack(_ record: TableRecord, _ model: RecordListModel) -> someView {if archived, !selecting, let back = model.row(record.id)?.press.first(where: { $0.id == Self.bringBackAct }), let patch = back.write {PaperTypedButton(back.act.label, size: 14) { write { tryawait model.write(record, patch) } } .accessibilityIdentifier("list-\(definition.id)-bring-back-\(record.id)") } }/// One row of list links, drawn as a page's row of links — unless the/// list stands them as its link tiles. @ViewBuilder privatefunc listLinksRow(lead: Bool) -> someView {let links = !lead && definition.linkTiles != nil ? [] : listLinks(lead: lead)if !links.isEmpty {SideLinksRow(links: links.map { link inPageSideLink(id: "link-\(link.label)", label: link.words) { open(link.opens) } }, identifier: "list-\(definition.id)") .padding(.top, lead ? RecordListSurfaceKnobs.paperGap : 22) .padding(.bottom, lead ? 22 : 0) } }/// The list's link slips (`link_tiles`): each of its own links a slip at/// the top of the list — "Senders · 12". @ViewBuilder privatevar linkSlips: someView {let links = definition.linkTiles == nil ? [] : listLinks(lead: false)if !links.isEmpty { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {ForEach(links, id: \.id) { link inButton { open(link.opens) } label: {ObjectSlip(seed: "link-\(definition.id)-link-\(link.label)", dye: .cream, edge: .cut, title: link.words, titleLines: 1) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("list-\(definition.id)-link-\(link.label)") } } .padding(.bottom, RecordListSurfaceKnobs.paperGap) } }/// The row of `above` list links, over the records, after the lists drawn above them. @ViewBuilder privatevar aboveLinksRow: someView {let links = listLinks(lead: false, above: true)if !links.isEmpty { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {ForEach(links, id: \.id) { link inButton { open(link.opens) } label: {PaperSection(title: link.label, count: link.count.map(String.init)) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("list-\(definition.id)-above-link-\(link.label)") } } .padding(.bottom, 22) } }/// A menu line's id as the tray names it: `link-<table>`, `menu-<path>`.staticfunc menuID(_ id: String) -> String {guardlet colon = id.firstIndex(of: ":") else { return id }return id[..<colon] + "-" + id[id.index(after: colon)...] }/// The menu, as the core answered it: New, Select, the related lists,/// the links with their counts, the list's own screens, New group — and/// on a group's page, the page's own acts.privatevar menu: [PopoverMenuItem] {guard pick == nilelse { return [] }var items: [PopoverMenuItem] = []for item in model?.answer?.menu ?? [] {switch item.id {case"new":guard scope == nil, store != nil, acts.canCreate else { continue } items.append(PopoverMenuItem(id: "new", object: item.object, does: item.does, label: item.label) { compose() })case"select": items.append(PopoverMenuItem(id: "select", object: item.object, does: item.does, label: item.label) { selecting = true picked = [] })case"group-new":guard scope == nil, GroupRecords.grouping(store) != nilelse { continue } items.append(PopoverMenuItem(id: "group-new", object: item.object, does: item.does, label: item.label) { namingGroup = true })caselet id where id.hasPrefix("related:"):// A related list opens as the page opens it, its add beside it.let parts = id.split(separator: ":")guard parts.count >= 2, let at = Int(parts[1]), let related = definition.related, related.indices.contains(at) else { continue }let relation = related[at]let adding = parts.count == 3 items.append(PopoverMenuItem(id: "related-\(at)\(adding ? "-new" : "")", object: item.object, does: item.does, label: item.label) { relatedOpen = RelatedOpening(relation: relation, adding: adding) })default:// A group page's own acts, as the core answered them, run by the page (`scope.runs`).iflet act = item.act {guardlet runs = scope?.runs else { continue } items.append(PopoverMenuItem(id: Self.menuID(item.id), object: item.object, does: item.does, label: item.label, destructive: item.red) { runs(item) })continue }guardlet opens = item.opens else { continue }if item.id.hasPrefix("menu:"), scope != nil { continue } items.append(PopoverMenuItem(id: Self.menuID(item.id), object: item.object, does: item.does, label: item.label) { open(opens) }) } }// The page's own lines join ahead of what takes something away: the// core ranked those last.iflet scope { items.insert(contentsOf: scope.menu, at: items.firstIndex(where: \.isDestructive) ?? items.count) }return items }/// Whether this list draws its table's groups above it, as the core says.privatevar showsGroups: Bool { model?.answer?.groups != nil && scope == nil && keepsGroups }/// Whether the table gathers groups and the store keeps them.privatevar keepsGroups: Bool { definition.groups != nil && GroupRecords.grouping(store) != nil }publicvar body: someView {// The body is cut into stages, each built in a frame of its own and// handed on as `AnyView`, so no single frame holds the whole list.// Build 230 (October 2026) crashed on every list it opened: a stack// overflow on the phone's 1 MB main thread (`___chkstk_darwin` in// `closure #1 in RecordListSurface.body.getter`, under `ZStack.init`).// That one closure built the paper screen, everything in its scroll// and its modifiers as values of one 40 KB type nested 82 levels deep,// copied at every modifier. The simulator's 8 MB main stack hid it// from every walk; `SurfaceStackTests` holds what the list may use.let listed = column(AnyView(content))return reading(surrounded(screen(paper(listed)))) }/// The paper screen with the menu and the search field over it.privatefunc screen(_ paper: AnyView) -> AnyView {AnyView(ZStack(alignment: .top) { paperif searching {SearchPill(text: queryBinding, placeholder: (model?.searchWords ?? "")) { queryBinding.wrappedValue = "" searching = false } .padding(.top, 6 + (ScreenBarKnobs.chromeNavCircleTarget - 40) / 2) .accessibilityIdentifier("list-\(definition.id)-search-field") } } .preference(key: PageSearchingKey.self, value: searching) .menuTray(isOpen: $menuOpen, items: menu, title: title)) }/// The paper screen: the title line, and in its scroll the search slip,/// whatever the holder draws first and the list.privatefunc paper(_ column: AnyView) -> AnyView {// A search's answer opens at the top (sev 3): the place the whole// list was scrolled to is not where its matches stand.returnAnyView(PaperScreen(title: title, topOn: query, yielding: {// The circles that give way when the name needs the row: the// plus whose New is the tray's first card, and the magnifier,// whose search then stands as the slip under the name.if !selecting {if scope == nil, pick == nil, let create = definition.create, store != nil, acts.canCreate {NavCircle(symbol: "plus", label: create.label) { compose() } .accessibilityIdentifier("list-\(definition.id)-new") }if definition.searchesInHead, !searching {HeadSearchCircle { searching = true } .accessibilityIdentifier("list-\(definition.id)-search") } } }, trailing: {if selecting { selectCircles } else {iflet scope, store != nil {NavCircle(symbol: "plus", label: scope.addLabel) { scope.add() } .accessibilityIdentifier("list-\(definition.id)-scope-add") } elseif pick != nil, let create = definition.create, store != nil, acts.canCreate {NavCircle(symbol: "plus", label: create.label) { compose() } .accessibilityIdentifier("list-\(definition.id)-new") } elseif definition.create == nil || store == nil || !acts.canCreate, headFolds {NavCircle(symbol: headFanned ? "minus" : "plus", label: headFanned ? CottonStrings.close : ShellLines.line("lists", "new")) { headFanned.toggle() } .accessibilityIdentifier("list-\(definition.id)-action-new") }// The stack of cards raises the list's own acts, never the// databases (walker, 16 Oct 2026: a list's stack opened the// switcher; the caps arc's last cap opens Databases).if !menu.isEmpty {TrayStackButton { menuOpen = true } .accessibilityIdentifier("list-\(definition.id)-menu") } } }) {// Search is a slip under the list's name (owner, 6 Oct): the// first thing in the scroll, above the stacks row; it opens// the search field with the keyboard up and the box put away.if !searching, pick != nil || !selecting {ListSearchSlip( inHead: definition.searchesInHead, placeholder: (model?.searchWords ?? ""), identifier: "list-\(definition.id)-search" ) { searching = true } } leading column } .scrollDisabled(dragging) .refreshable { await reload() }// Back from a record's page, which may have changed or removed it:// read again in place, so the rows it had and its place stay. .reloadOnReturn {// Back returns to the place left (S2): the pages already read// are read again at their depth, so a list scrolled through// several pages keeps every slip above the one opened and// its scroll with them — never shrunk to the first page.iflet model, model.phase == .loaded { await model.refresh() } else { await reload() }await loadActions() }// The A–Z rail, outside the scroll view, level with the first row. .overlayPreferenceValue(PaperTrailingGap.self, alignment: IndexRail.anchor) { gap iniflet model, model.phase == .loaded, !searching, query.isEmpty, let index = model.answer?.index, index.count > 1 {IndexRail(present: index.map(\.letter)) { scrollTarget = $0 } .padding(.top, IndexRail.topAir)// Just outside the grid's own edge (`PaperTrailingGap`// is what a wide page leaves beyond it; a phone's is the// margin): letters never overprint the cards' names. .padding(.trailing, max(0, ContentMarginKnobs.chromeContentMargin + gap - IndexRail.width - IndexRail.edgeInset - 3)) .accessibilityIdentifier("list-\(definition.id)-index") } }) }/// What the scroll holds under the search slip: the acts, the filters,/// the engine's head, the chips, the records and the footer.privatefunc column(_ listed: AnyView) -> AnyView {AnyView(VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) { head filterRow// The view the table's ENGINE stands above its slips, if it// registered one (`EngineListHead`): the next alarm.EngineListHead.view(for: definition)if store != nil, definition.chips != nil {ChipRowHead(definition: definition) { data inawait create(data) } }if store != nil, let paste = definition.paste {ListPasteHead(paste: paste) { data inawait create(data) } } listedif query.isEmpty, let model, model.phase == .loaded {ForEach(model.answer?.notes ?? [], id: \.self) { note inText(note) .paperMeta() .fixedSize(horizontal: false, vertical: true) } }if scope == nil, pick == nil, AboutInfo.hasFooter(definition) {ToolsAboutFooter() } }) }/// The screen with what stands around it: the bar at its foot, the/// questions it asks, the pages it pushes./// The screen with what stands around it, each stage applied in a/// frame of its own (see `body`).privatefunc surrounded(_ screen: AnyView) -> AnyView { pushing(asking(barred(screen))) }/// The bar at the foot.privatefunc barred(_ screen: AnyView) -> AnyView {AnyView(screen .safeAreaInset(edge: .bottom, spacing: 0) { VStack(spacing: 8) {// ONE slip above the bar at a time: with the keyboard up, two// are taller than the room left and push the top bar under// the clock. The store's question first; then the bar's// answer. The receipt stands at the toast edge, the top// (the owner, 17 Nov 2026), while neither does — a record// made always wears its receipt (no note is kept beside one).iflet question {CreateQuestionCard(question: question, identifier: "list-\(definition.id)") { option inawait answerQuestion(question, option) } onDismiss: {self.question = nil } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) } elseiflet note {OneInputNoteCard(note: note) {self.note = nil answersLetGo += 1 } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) } } } .receiptAtToastEdge {if question == nil, note == nil { receipt } } .composerColumn()) }/// The questions the list asks before it writes.privatefunc asking(_ screen: AnyView) -> AnyView {AnyView(screen .scopeDecision( item: $scoping, question: { .delete($0.record, in: definition, bin: "") }, identifier: "list-\(definition.id)-scope" ) { ask, scope inguardlet model else { return } write { tryawait model.delete(ask.record, scope: scope) } }// A long press's act that asks first asks in the core's words. .confirmDecision( item: $asking, title: { $0.question.title }, message: { $0.question.message }, confirmLabel: { $0.question.confirm }, cancelLabel: asking?.question.cancel, identifier: "list-\(definition.id)-press", onConfirm: { ask inguardlet model else { return } perform(ask.press, on: ask.record, model) } ) .confirmDecision( isPresented: $confirmingDelete, title: deletingAsked?.question.title ?? "", message: deletingAsked?.question.message ?? "", confirmLabel: deletingAsked?.question.confirm ?? "", cancelLabel: deletingAsked?.question.cancel, identifier: "list-\(definition.id)-delete", onConfirm: { iflet deletingAsked { deletePicked(deletingAsked) } } ) .confirmDecision( isPresented: confirmingClear, title: clearQuestion?.title ?? "", message: clearQuestion?.message ?? "", confirmLabel: clearQuestion?.confirmLabel ?? "", cancelLabel: definition.clear?.cancel, isLoading: busy, identifier: "list-\(definition.id)-clear-dialog", onConfirm: { clearAll() }, onCancel: { confirmingClear = false } ) .onChange(of: scope?.received?.id) {iflet change = scope?.received { model?.received(change, foreign: true) } } .addingToGroup( isPresented: $addingToGroup, definition: definition, ids: picked, received: { model?.received($0, foreign: true) } ) { selecting = false picked = [] }) }/// The pages the list pushes.privatefunc pushing(_ screen: AnyView) -> AnyView {AnyView(screen .pageDestination(item: $relatedOpen) { opening inRelatedDestination(opening: opening, record: TableRecord(id: "", values: [:])) } .filteredList($filteredOpen, store: store, definitions: definitions, opener: opener) .doorFiles($choosingFiles, for: definition.id) .doorPictures($pickingPictures, for: definition.id) .pageDestination(isPresented: $composing) {// What narrows the list goes on the new record too, as the chips'// records hold it: a todo made from a project's own Todos is filed// under that project, as the old board's "+" filed it.let preset = RecordListModel.narrowed(definition.createPreset(), filter: filter, project: project, in: definition)// The page it becomes opens what the list's own pages open (a new// record offers its own "New" at once): a destination does not// inherit the list's opener by itself.RecordOpening(definition: definition, opens: .blank(preset)).cottonScreenFrame() .environment(\.recordOpener, opener) }) }/// The reads the list runs while it is on screen, and its sheets.privatefunc reading(_ screen: AnyView) -> AnyView {AnyView(screen #if COTTON_DEV .onAppear { DevTimings.shared.begin(definition.id) } #endif .task {guard composeOnArrival, definition.create != nil, !composedOnArrival else { return }await loadActions()guard acts.canCreate else { return } composedOnArrival = true compose() } .task(id: Read(project: project, query: query, chosen: chosen, view: view)) {guardlet store else { return }let read = Read(project: project, query: query, chosen: chosen, view: view)// Back on this list (a page pushed over it closed): the task runs// again for the read it already holds. The return reads in place// (`reloadOnReturn`); reading from the start here would drop every// page past the first and move the rows under the person.if readFor == read, let model, model.phase == .loaded { return } readFor = readlet wanted = narrowinglet model = RecordListModel.retaining(self.model, definition: definition, store: store, core: core, archived: archived, filter: wanted, section: section, view: view, pick: pick.map { (column: $0.column, held: $0.held.sorted()) }, database: databaseScene?.shownId, opensOn: opensOn)self.model = modelif !query.isEmpty {// Typing reads once the fingers pause, not on every letter.try? awaitTask.sleep(for: .milliseconds(250))guard !Task.isCancelled else { return } }// The head's acts draw at once, off the rows already known, and// are asked again once the read lands: an act never waits behind// a read (`SettingsRecords.listActions`).// The rows are read at once; the head's acts beside them.let acts = Task { await loadActions() }await withTaskCancellationHandler {await reload()await acts.value } onCancel: { acts.cancel() }await loadActions() }// A sync tick or a poll: the rows are read again in place once the// read on its way answers, never restarted (`RecordListModel.dataMoved`,// architect 12 Oct: during a sync a first read slower than one tick// was thrown away again and again, the skeleton up meanwhile). A list// whose first read failed tries it again. .onChange(of: revision) { _, _ inguardlet model else { return }if model.phase == .failed {guard !retrying else { return } retrying = trueTask {await reload()await loadActions() retrying = false } } else { model.dataMoved() } }// A table whose rows move with no sync saying so (`polled`: a device// asking to join) reads again in place on a beat, only while the list// is drawn and the app is in front; SwiftUI cancels it with either. .onAppear { onScreen = true } .onDisappear { onScreen = false } .task(id: pollBeat) {guardlet beat = pollBeat else { return }while !Task.isCancelled {do { tryawaitTask.sleep(for: beat) } catch { return } model?.dataMoved() } }// The head's acts follow the rows a tick re-read. .task(id: model?.settled ?? 0) {guard (model?.settled ?? 0) > 0else { return }await loadActions() } .task(id: signingIn) {// Every two seconds for up to three minutes, the old Google// card's cadence; cancelled when the list goes away.guard signingIn > 0else { return }// Until what the sign-in made appears — the rows change — and no// longer: every read here asks the network.let before = Set(model?.records.map(\.id) ?? [])for _ in0..<90 {do { tryawaitTask.sleep(for: .seconds(2)) } catch { return }await reload()ifSet(model?.records.map(\.id) ?? []) != before { break } }await loadActions() }// A live table reads again on its cadence while it is on screen, as// deep as it was scrolled, keeping its rows until the answer lands. .readingLive(definition.live) { await model?.refresh() } .askingFirst(acts, identifier: "list-\(definition.id)-confirm-action") { acts.perform($0.action, on: $0.record, store: store, surface: actSurface) } onAnswer: { asked, values inawait acts.answer(asked, values: values, store: store, surface: actSurface) }// A tool's view draws no stacks: its "New group" is asked here, and// the group made is a slip on the ring, chosen. .cottonCard(isPresented: view == nil ? .constant(false) : $namingGroup) {GroupNameSheet(title: ShellLines.line("lists", "group.new"), name: "", identifier: "list-\(definition.id)-group-name") { name inawait makeGroup(name) } } .cottonCard(item: $replying, detents: [.half]) { record iniflet reply = definition.replyOffered(record) {ReplySheet( definition: definition, record: record, reply: reply, onSend: { words inawait send(words, for: record) }, onClose: { replying = nil }) } }) }/// Makes a group from the tool's view and shows it, its slip chosen on/// the ring; the sentence why not when refused.privatefunc makeGroup(_ name: String) async -> String? {guardlet grouping = GroupRecords.grouping(store) else { returnShellLines.line("lists", "group.none_kept") }do {let made = tryawait grouping.createGroup(named: name, of: definition.id, records: [])let tool = definition.tool.map { $0.key ?? definition.id } ?? definition.iddo { tryawait toolViews?.reload(core: core) } catch { _ = toasts.show(ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]), tone: .error) }iflet id = made.group?.id { toolViews?.choose(ToolView.groupPrefix + id, of: tool) }returnnil } catch {returnActionRefused.words(for: error) } }/// The store's acts and a value one of them showed once; nothing for a/// store that offers none. @ViewBuilder privatevar head: someView {iflet model, model.phase == .loaded, CouldNotRead.isSaid(model.readStall, over: model.records.count),let problem = CouldNotRead.said(model.readStall, otherwise: model.readProblem, scene: databaseScene, databases: databasesModel, definitions: definitions) {Text(problem).paperMeta(13).accessibilityIdentifier("list-read-refusal") } elseiflet model, model.updating, store is any ConfirmingRecords {// A Settings list reads off the serving Mac: the last answer// stands while the next one comes, said quietly.Text(ShellLines.line("lists", "updating")).paperMeta(13).accessibilityIdentifier("list-updating") }iflet revealed {RevealedValueCard( revealed: revealed, identifier: "list-\(definition.id)", onCopy: {Task {guardlet store else { toasts.show(ShellLines.line("record", "unreadable"), tone: .error); return }do {let change = tryawaitSecretCopy.copy(revealed, definition: definition, store: store)self.revealed = niliflet change { model?.received(change) } toasts.show(ShellLines.line("record", "copied_expires"), tone: .success)iflet id = revealed.record { open(id) } } catch { toasts.show(SecretCopy.problem(error), tone: .error) } } }, onSaved: {self.revealed = niliflet id = revealed.record { open(id) } }) }RecordActionButtons( actions: acts.head, problem: acts.headProblem, identifier: "list-\(definition.id)", note: acts.note, headOpens: headFolds ? $headFanned : nil ) { action in tapped(action, on: nil) } }/// Asks first where the act asks, else runs it.privatefunc tapped(_ action: RecordAction, on record: TableRecord?) { acts.tapped(action, on: record, store: store, surface: actSurface) }/// The head's acts, for this list's scope; the first time the head/// offers the act the list opened to ask, it asks.privatefunc loadActions() async {await acts.loadHead(store)guard !asked, let act = RecordListSurface.asked(acts.head, id: askingOnOpen) else { return } asked = true tapped(act, on: nil) }/// What an act's outcome does to this list: a record it made opens, a/// value shows once at the head, a sign-in has the list read on, a change/// wears the receipt, and the list and its head's acts are read again.privatevar actSurface: RecordActSurface {RecordActSurface(open: { open($0) }, reveal: { revealed = $0 }, signingIn: { signingIn += 1 }, received: { model?.received($0) }, reread: { await reload() }, current: { id in model?.records.first { $0.id == id } }, keptFlow: keptFlow, navigator: navigator, openURL: openURL, toasts: toasts) }/// A table whose records open in the viewer (`viewer`): the record/// opens there over every record this list has read — the month, the/// album, the person's photos — and swipes through them.privatefunc openInViewer(_ record: TableRecord) -> Bool {guard definition.viewer != nil, let viewerPresenter, let model else { returnfalse }let items = model.records.compactMap { ViewerItem(record: $0, definition: definition) }guardlet start = items.firstIndex(where: { $0.id == "\(definition.id)/\(record.id)" }) else { returnfalse } viewerPresenter.open(ViewerSet(items: items, start: start))returntrue }/// Opens a record's page by its id, as a tap on its slip would.privatefuncopen(_ id: String) {Task {guardlet record = try? await store?.get(table: definition.id, id: id) else { return } onOpen(record) } }/// Reads the list again in place: every page already read, the rows/// swapped in one move (`RecordListModel.refresh`), so a list returned to/// keeps the rows it had loaded and the same row on top. A list not yet/// read reads from its start.privatefunc reread() async {guardlet model else { return }if model.phase == .loaded { await model.refresh() } else { await reload() } }/// Reads the list again — to its end, for a list with an index rail.privatefunc reload() async {guardlet model else { return }await model.reload(project: project, query: query)if definition.index != nil { await model.readToEnd() }// A `clear` states the table's count and erases the whole table: it// needs every record too.if definition.index == nil, definition.clear != nil { await model.readToEnd() } }/// The "+" and the empty list's button run the table's create as the/// deck's Plus does, as the core says (`shell.plus`): its doors' choice/// tier on the fan (Books' Find a book, Add a file, Bring Goodreads in),/// its act at the object, its own route, else a blank page. A route that/// is an instruction (`/capture`, a new thought) is OPENED, typing:/// pushed, it would only land on the thoughts list again.privatefunc compose() {guard acts.canCreate else { return }let editor = deckEditor ?? DeckEditor.sessionlet toasts = toastsTask {let plus: DeckAnswer.Plus?do { plus = tryawaitDeckAnswer.Plus.read(definition.id, core: core) } catch { toasts.show(error.localizedDescription, tone: .error)return }switch plus?.does {case"doors"?: editor.offer(plus?.offers(editor, table: definition.id, core: core, toasts: toasts, landed: landed, pick: { pickingPictures = $0 }) { choosingFiles = $0 } ?? [],for: .emptyDeck(of: definition.id))case"act"?:guard plus?.act != nilelse { return } editor.ask(table: definition.id, core: core, landed: landed)case"route"?:guardlet route = plus?.route.flatMap(Route.parse) else { toasts.show(ShellLines.line("reading", "list.this_version", ["plural": definition.plural]), tone: .error)return }if route.tier == .action { navigator?.open(route, start: .typing) } else { navigator?.push(route) }default: composing = true } } }/// The record an act at the object made or found (`CreateAct.lands`):/// once sync brings it, opened on its tool's deck at its card where the/// fan holds the table, else as its page (`Navigator.open`), as the/// deck's Plus lands it.privatefunc landed(_ id: String) {Task { @MainActor infor _ in0..<DeckKnobs.landingTries {iflet store, (try? await store.get(table: definition.id, id: id)) != nil { navigator?.open(table: definition.id, id: id, definition: definition)return }try? awaitTask.sleep(for: .milliseconds(DeckKnobs.landingEveryMs)) } } }/// How often an open list the core says is polled asks again: only while/// it is drawn and the app is in front, so no beat outlives the list.privatevar pollBeat: Duration? {guard onScreen, scenePhase == .active, let seconds = model?.answer?.polls else { returnnil }return .seconds(seconds) } @ViewBuilder privatevar content: someView {iflet model {switch model.phase {// A local read lands within a frame or two: the paper waits// bare for it, never behind a skeleton (owner, 15 Oct 2026: "we're// on the local database, everything should load instantly").case .loading:// A read still out past a moment says what this device is// doing (`StillReading`); before that, nothing.StillReading().accessibilityIdentifier("list-\(definition.id)-loading")// A list that could not be read says so in the tool's name and// the plain reason, and offers Try again (owner's ask, 22 Oct// 2026: "Documents could not be read" with no way out); it still// reads again by itself on the next change (291 words row 6).// A table mid-move says so in its one definition line, and draws// itself on the move's done signal (passivemove rule 3).case .failed where model.readStall?.waitsForMove == true:QuietState( title: CouldNotRead.said(model.readStall, otherwise: model.readProblem, scene: databaseScene, databases: databasesModel, definitions: definitions) ?? "", message: "")case .failed:QuietState( title: ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]), message: CouldNotRead.said(model.readStall, otherwise: model.readProblem, scene: databaseScene, databases: databasesModel, definitions: definitions) ?? ShellLines.line("empty", "unchanged"), actionLabel: CottonStrings.tryAgainAction, actionIdentifier: "list-\(definition.id)-read-again", action: { Task { await reload() } })// A first page `listed_when` emptied is not an empty table: the// slips' next-page marker reads on.// An empty-words card never shows while any group or link on the// list holds records (architect, 5 Oct): a planned group shut// with a count, a planned list's Earlier link (never "No meetings// yet" over a past), a side link's count.case .loaded where model.holdsNothing: emptyList(model)case .loaded: slips(model) .environment(\.linkTitles, model.linkTitles) .environment(\.paperSurfaceImages, true) } } elseif store == nil {QuietState(title: ShellLines.line("lists", "unreadable.title", ["plural": definition.plural]), message: ShellLines.line("lists", "unreadable.no_records")) } else {Color.clear.accessibilityIdentifier("list-\(definition.id)-loading") } }/// A list read to nothing: its words, and the other lists and links/// around them. Built in a frame of its own (see `body`).privatefunc emptyList(_ model: RecordListModel) -> AnyView {// One set of words, the definition's or the generic ones; a// table naming `create` adds its button under them.let said = model.answer?.emptylet words = pick?.empty.map { (title: $0.title, message: $0.message ?? "") } ?? (title: said?.title ?? "", message: said?.message ?? "")// The other lists the definition names (`lists`) are drawn// around the empty words too: a Code list with no session yet// still reaches its repositories.returnAnyView(VStack(alignment: .leading, spacing: 0) {// Searched, the other lists show what the search finds// in them — a name typed finds the entries it is in. otherLists(above: true) aboveLinksRow// Searched, and a section found it (or is still reading):// no "Nothing matches" over what it found.ifSelf.saysNothingMatches(query: query, sections: sectionFinds, hasSections: !definition.lists.isEmpty) {if query.isEmpty, let scope, store != nil, pick == nil {QuietState( title: scope.empty.title, message: scope.empty.message ?? "", actionLabel: scope.addLabel, actionIdentifier: "list-\(definition.id)-empty-add", picture: Self.emptyPicture(definition), name: definition.plural, action: { scope.add() }) } elseif query.isEmpty, let create = definition.create, store != nil, acts.canCreate {QuietState( title: words.title, message: words.message, actionLabel: create.label, actionIdentifier: "list-\(definition.id)-empty-new", picture: Self.emptyPicture(definition), name: definition.plural, action: { compose() }) } elseif query.isEmpty, store != nil, definition.listTakesCapture {// A table added to from the bar alone still shows its// one add act on the empty screen (S3): the act puts// the person in the bar.QuietState( title: words.title, message: words.message, actionLabel: ShellLines.line("lists", "add_first", ["kind": definition.name.lowercased()]), actionIdentifier: "list-\(definition.id)-empty-add", picture: Self.emptyPicture(definition), name: definition.plural, action: { NotificationCenter.default.post(name: .cottonFocusInput, object: nil) }) } else {QuietState( title: words.title, message: words.message, picture: Self.emptyPicture(definition), name: definition.plural) } } listLinksRow(lead: true) otherLists(above: false) listLinksRow(lead: false) archivedLink(model) } .onPreferenceChange(SectionFindsKey.self) { sectionFinds = $0 }) } @ViewBuilder privatefunc slips(_ model: RecordListModel) -> someView {ScrollViewReader { proxy in slipStack(model) .onChange(of: scrollTarget) { _, letter inguardlet letter, let id = model.answer?.index?.first(where: { $0.letter == letter })?.row else { return } scrollTarget = nilTask {// A letter past the pages read reads on to it.if model.row(id) == nil { await model.readToEnd() }// Just under the floating circles rather than behind them. proxy.scrollTo(id, anchor: UnitPoint(x: 0.5, y: 0.16)) } } } } @ViewBuilder privatefunc slipStack(_ model: RecordListModel) -> someView {let sections = model.sections VStack(alignment: .leading, spacing: 0) { recent(model) otherLists(above: true) aboveLinksRow linkSlips earlierLink(model)if definition.stories != nil, !selecting, pick == nil {StoriesPictureGrid( definition: definition, records: model.records, personNames: model.linkTitles.byID, strip: StoriesPresentation.isStrip(filter, personColumn: definition.group?.column ?? "person_id"), hasMore: model.hasMore, onLoadMore: { Task { await model.loadMore() } }, onOpenGroup: { group inifcase .unassigned = group.id, let record = group.records.first { tap(record)return }FilteredListOpening(table: definition.id, filter: group.filter, title: FilteredListOpening.title(definition.plural, of: group.title)) .open(on: navigator, onPath: listsOnPath, else: $filteredOpen) }, onOpenRecord: { tap($0) } ) } elseif showsGrid { sectionedGrid(model, sections: sections) } elseif model.canReorder {// The order is the person's: said once, where nothing on a// slip shows that it drags.if model.records.count > 1 {Text(ShellLines.line("lists", "reorder_hint", ["kind": definition.name.lowercased()])) .paperMeta(13) .frame(maxWidth: .infinity, alignment: .leading) .padding(.bottom, RecordListSurfaceKnobs.paperGap) .accessibilityIdentifier("list-\(definition.id)-reorder-hint") }ForEach(Array(sections.enumerated()), id: \.offset) { index, section in heading(section, first: index == 0, below: RecordListSurfaceKnobs.paperGap)ReorderableList( items: shown(section), onReorder: { from, to in write { tryawait model.move(section: index, from: from, to: to) } }, onDragActiveChange: { dragging = $0 } ) { record, _, _ in slip(record, model).padding(.bottom, RecordListSurfaceKnobs.paperGap) } }// A list that drags is laid out whole, so this marker shows at// once after every page and the whole table is read: the order// a drag writes names every record, not only the first page's. nextPage(model) } else {LazyVStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {ForEach(Array(sections.enumerated()), id: \.offset) { index, section in// The stack's own spacing is the gap under it. heading(section, first: index == 0, below: 0)ForEach(shown(section)) { record in slip(record, model) } allOfSection(section, model) }// Inside the lazy stack, so it is made only when the last// slip scrolls into view. nextPage(model) } }// The list link that leads, alone straight under the records;// the rest in one row after the other lists. listLinksRow(lead: true) otherLists(above: false) listLinksRow(lead: false) archivedLink(model) clearRow(model) } }// A paged grid shares one lazy layout across its section headers and records (guarded in sectioned-grid.test.ts).privatefunc sectionedGrid(_ model: RecordListModel, sections: [RecordSection]) -> someView {let sheet = definition.layout == .sheetlet base = PaperLayout.grid(columns: model.answer?.across ?? 1)let spacing: CGFloat = sheet ? 2 : (definition.grid == nil || definition.drawsPolaroids ? 16 : 14)let flowing = base.flowing(atWidth: gridWidth, in: theme.scale)// Sibling lazy grids estimate their heights independently. As each// month refines that estimate, the following grids move and prefetch// again. One grid owns placement across the whole paged collection.returnLazyVGrid( columns: Array(repeating: GridItem(.flexible(), spacing: spacing, alignment: .top), count: flowing.columns), alignment: .leading, spacing: spacing ) {ForEach(Array(sections.enumerated()), id: \.offset) { index, section inSection {ForEach(shown(section)) { record inGroup {if sheet { sheetCell(record) .modifier(UnreadUnderTheFan()) } elseif definition.tile.face == .polaroidGrid { polaroid(record, model) } elseif definition.grid == nil { cover(record, model) } else { slip(record, model, compact: true) } } .asksForMore(record, model) } } header: { heading(section, first: index == 0, below: 0) } } nextPage(model) } .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { measured inif gridWidth != measured { gridWidth = measured } } .preference( key: PaperTrailingGap.self, value: sections.map { base.trailingGap(atWidth: gridWidth, spacing: spacing, count: shown($0).count, in: theme.scale) }.max() ?? 0 ) }/// Whether an empty list says its empty words: always unsearched; when/// searched, only once every other list drawn with it has read the/// search and found nothing — a "Nothing matches" over the matches a/// section found was a contradiction (walk 3, shot 457).staticfunc saysNothingMatches(query: String, sections: SectionFinds, hasSections: Bool) -> Bool {guard !query.isEmpty, hasSections else { returntrue }return !sections.holds && !sections.pending }/// The other tables' records the definition lists beside its own/// (`lists`): those marked `above` before its slips (the Code list's/// repositories), the rest after them (a shop's recent orders). @ViewBuilder privatefunc otherLists(above: Bool) -> someView {// The table's groups, as a row of stacks, stand first of all// (`GroupStacksRow`): nothing until a group exists.if above, showsGroups, let groups = definition.groups, let model {GroupStacksRow( definition: definition, groups: groups, answered: model.answer?.groups ?? [], offersNew: model.answer?.offers_new_group == true, naming: $namingGroup, received: { model.received($0, foreign: true) }, asked: { await model.refresh() }) }ForEach(Array(definition.lists.enumerated()).filter { $0.element.above == above }, id: \.offset) { _, section inRecordsSection(section: section, parent: nil, top: above ? 0 : 22, query: query, openedFrom: title) .padding(.bottom, above ? 22 : 0) } }// ── Clear: the whole list in one act ───────────────────────────────────/// The red verb under the records and its line by hand, where the core offers it. @ViewBuilder privatefunc clearRow(_ model: RecordListModel) -> someView {iflet clear = model.answer?.clear, !selecting, pick == nil { VStack(spacing: 2) {PaperTypedButton(clear.label, destructive: true) { confirmingClear = true } .disabled(busy || model.hasMore) .accessibilityLabel(clear.label) .accessibilityIdentifier("list-\(definition.id)-clear")iflet note = clear.note {Text(note) .paperHand(17) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) } } .frame(maxWidth: .infinity) .padding(.top, 16) } }/// The `clear` question, as the core said it with the list's count.privatevar clearQuestion: WriteConfirmation? { model?.answer?.clear.map { WriteConfirmation(title: $0.question, message: $0.message, confirmLabel: $0.confirm) } }/// Erases every record the list holds, one at a time; the refused stay.privatefunc clearAll() {guardlet model, let clear = model.answer?.clear, !busy else { return }let ids = model.records.map(\.id) busy = trueTask {let outcome = await model.delete(ids: ids) busy = false confirmingClear = false// The receipt: the definition's words once all went, else how many stayed. toasts.show( outcome.failed.isEmpty ? clear.done ?? ShellLines.line("definitions", "clear.erased", ["n": String(outcome.deleted.count)]) : ShellLines.line("definitions", "clear.failed", ["failed": String(outcome.failed.count), "total": String(outcome.deleted.count + outcome.failed.count)]), tone: outcome.failed.isEmpty ? .success : .error) } }/// The records touched most lately, above the list; nothing while a/// search or a project narrows it (the field's own words hide it before/// the search is read), or when the list is too short to need it. @ViewBuilder privatefunc recent(_ model: RecordListModel) -> someView {let rows = query.isEmpty ? model.answer?.recent ?? [] : []if !rows.isEmpty { VStack(alignment: .leading, spacing: 10) {PaperSection(title: ShellLines.line("lists", "recent"))ForEach(rows, id: \.id) { row inTravellingPress(style: OpacityButtonStyle(), action: { onOpen(TableRecord(id: row.id, values: [:])) }) { HStack(alignment: .firstTextBaseline, spacing: 12) {Text(row.title ?? "") .font(CottonFonts.type(15)) .foregroundStyle(CottonColors.ink) .lineLimit(1)Spacer(minLength: 8)iflet when = row.when {Text(when) .font(CottonFonts.hand(17)) .foregroundStyle(CottonColors.inkSecondary) } } .padding(.horizontal, 2) .contentShape(Rectangle()) } .accessibilityIdentifier("list-\(definition.id)-recent-\(row.id)") } } .padding(.bottom, 24) } }/// Under an opened folded section that holds more than its first rows:/// ONE link "All n ›" (R12) opening that section as its own list, paged. @ViewBuilder privatefunc allOfSection(_ section: RecordSection, _ model: RecordListModel) -> someView {if query.isEmpty, section.closed, let id = section.id, opened.contains(id), model.holdsMore(id) {Button {FilteredListOpening( table: definition.id, filter: model.filter, title: FilteredListOpening.title(section.heading ?? "", of: title), section: id) .open(on: navigator, onPath: listsOnPath, else: $filteredOpen) } label: { HStack(spacing: 4) {Text(ShellLines.line("lists", "whole.other", ["n": section.said ?? ""])).paperBody(15)Image(systemName: "chevron.right").font(.system(size: 11, weight: .semibold)).foregroundStyle(theme.print(.pencil)) } .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 8) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("list-\(definition.id)-all-\(id)") } }/// A section's heading; nothing for a section without one. A folded/// section's heading is what opens it, and says the count the core said. @ViewBuilder privatefunc heading(_ section: RecordSection, first: Bool, below: CGFloat) -> someView {iflet title = section.heading {Group {if section.closed && query.isEmpty {let id = section.id ?? titleButton { opened = RecordListSurface.toggled(opened, id)if opened.contains(id), let model { Task { await model.opened(id) } } } label: {FoldingSectionHeading(title: title, count: section.said ?? "", shut: !opened.contains(id)) } .buttonStyle(OpacityButtonStyle()) .accessibilityValue(ShellLines.line("lists", opened.contains(id) ? "fold.open" : "fold.closed")) .accessibilityIdentifier("list-\(definition.id)-fold-\(title)") } elseif section.id == "today" {// Today is marked: the calendar's own month leaf beside its name.PaperSection(title: title, count: nil) {let now = Date()CardMonthLeaf( day: Calendar.current.component(.day, from: now), month: DayHeads.month(Calendar.current.component(.month, from: now)), side: 30) } .accessibilityAddTraits(.isSelected) } else {PaperSection(title: title, count: nil) } } .padding(.top, first ? 0 : 18) .padding(.bottom, section.note == nil ? below : 6) .accessibilityIdentifier("list-\(definition.id)-section-\(title)") }iflet note = section.note {Text(note) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) .padding(.bottom, below) .accessibilityIdentifier("list-\(definition.id)-note-\(section.heading ?? "")") }// A group's head lines, as the core said them over the whole group.if !section.lines.isEmpty { VStack(alignment: .leading, spacing: 2) {ForEach(Array(section.lines.enumerated()), id: \.offset) { _, line inText(line).paperMeta(13) } } .padding(.top, section.heading == nil && !first ? 18 : 0) .padding(.bottom, below) .accessibilityElement(children: .combine) .accessibilityIdentifier("list-\(definition.id)-group-head") } }/// A section's slips as drawn: none while it is folded and unopened — a/// search opens every section, so nothing it finds is hidden.privatefunc shown(_ section: RecordSection) -> [TableRecord] {guard query.isEmpty, section.closed else { return section.records }return opened.contains(section.id ?? section.heading ?? "") ? section.records : [] }/// Reads the next page when it appears. In a grid both this marker and/// the last cell ask, so a page boundary inside a section is reached even/// when the grid has not placed its footer yet. A new identity for every length/// of the list, so it appears again after each page lands, and a page that/// failed is asked for again the next time it scrolls into view. @ViewBuilder privatefunc nextPage(_ model: RecordListModel) -> someView {if model.hasMore {Color.clear .frame(height: 1) .id(model.records.count) .onAppear { Task { await model.loadMore() } } } }/// A record as its cover, opening its page.privatefunc cover(_ record: TableRecord, _ model: RecordListModel) -> someView {TravellingPress(style: MotionButtonStyle(), action: { tap(record) }) {Group {if definition.tile.face == .cardGrid {CardFace(definition: definition, record: record) } else {CoverFace(definition: definition, record: record) } } .overlay { pickMark(record) }// The whole card takes the tap, its margins and air included (S1). .contentShape(Rectangle()) }// A print has no words: the tile says what it is aloud. .accessibilityLabel((record.said?.slip.spoken ?? definition.name)) .spokenValue(heldWords(record)) .opacity(model.row(record.id)?.dimmed == true ? 0.6 : 1) .modifier(pressMenu(record, model) {AnyView(Group {if definition.tile.face == .cardGrid {CardFace(definition: definition, record: record) } else {CoverFace(definition: definition, record: record) } }) }) .accessibilityIdentifier("\(definition.id)-\(record.id)") .viewerSource("\(definition.id)/\(record.id)") }/// The long press's one menu: the acts the core answered for the row/// (`shell.list`'s `press`, the held card's own), each asked first where/// the core gave it a question and read back with its Undo. No menu at/// all where it offers nothing, so a list whose long press drags keeps its drag.privatefunc pressMenu(_ record: TableRecord, _ model: RecordListModel, face: @escaping () -> AnyView) -> SlipPressMenu {var menu = SlipPressMenu(acts: model.row(record.id)?.press ?? [], identifier: "list-\(definition.id)", record: record.id) { press in// A Bin of a record that repeats asks how far it reaches.if press.act.id == Self.binAct, record.repeats { scoping = ScopeAsk(record: record) } elseiflet question = press.question { asking = PressAsk(press: press, question: question, record: record) } else { perform(press, on: record, model) } } menu.face = face// Settings' Export row, held over the fan, turns it into the tables,// as its card does on the deck (`ExportFan`).iflet deckEditor, ExportFan.opens(table: definition.id, record: record.id) {let target = DeckEditTarget(table: definition.id, record: record.id, date: nil) menu.turnsFan = { deckEditor.openExports(target, record: record) } }return menu }/// Runs a long press's engine verb as the page runs it: a link it opened/// is opened, a change wears the list's receipt (`RecordListModel.run`).privatefunc run(_ command: RecordCommand, on record: TableRecord, _ model: RecordListModel) {Task {do {guardlet change = tryawait model.run(command, on: record) else { toasts.show(ShellLines.line("record", "engine_action"), tone: .error)return }switch change.opened {case .record(let target)?: navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table]))case .landed(let target)?:guardawaitRecordLanding.arrived(target, in: store) else { return } navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table]))case .address(let address)?:iflet url = URL(string: address) { openURL(url) }case .database(let shown)?:awaitDatabaseCapRow.show(shown, scene: databaseScene, in: databasesModel, navigator: navigator)iflet said = change.said?.said { toasts.show(said, tone: .success) }case .platform(.pickFile(let pick))?:guardlet imported = tryawaitRecordFileEffects.perform(pick, records: store) else { return } model.received(imported, foreign: pick.table != definition.id)await model.refresh()iflet target = imported.created { receiptTables[imported.id] = definitions[target.table] navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table])) }case .platform(let action)?:guardawaitRecordPlatformEffects.perform(action, nativeFlow: nativeKeptFlow, rekey: rekeyThisDevice, reader: readerPresenter) else { toasts.show(ShellLines.line("record", "platform_action"), tone: .error)return }await model.refresh()casenil:iflet target = change.created { receiptTables[change.id] = definitions[target.table] navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table])) }if command.kind == .delete, let said = change.said?.said { toasts.show(said) } } } catchlet asked asCreateQuestion { question = asked note = nil } catch { toasts.show(RecordCommand.refusal(error), tone: .error) } } }/// The core's Bin act (`card_actions`), and the archived list's Bring back.staticlet binAct = "bin"staticlet bringBackAct = "bring_back"/// Runs a long-press act as the core named it, after its question was/// answered yes: a command by the engine (`records.command`), an address/// opened by the OS, a tool's act by `tools.act` as the fan runs it, Bin by/// a delete and Bring back by its write, each wearing the list's receipt.privatefunc perform(_ press: ListAnswer.Press, on record: TableRecord, _ model: RecordListModel) {let act = press.actswitch act.kind {case"command":guardlet command = definition.commands?.first(where: { $0.id == act.id }) else { toasts.show(ShellLines.line("record", "engine_action"), tone: .error)return } run(command, on: record, model)case"address":guardlet address = act.url.flatMap(URL.init(string:)),RecordAddress.open(address, taps: pendingTaps, external: { openURL($0) })else { toasts.show(ShellLines.line("record", "address_failed"), tone: .error)return }case"tool":guardlet core else { return }Task {do {switchtryawaitDeckActs.ran(act, core: core) {case .opens(let page): openURL(page)case .platform(let effect): _ = awaitRecordPlatformEffects.perform(effect, nativeFlow: nativeKeptFlow, rekey: rekeyThisDevice, reader: readerPresenter)caselet outcome: DeckActs.say(outcome, toasts: toasts, core: core) }await model.refresh() } catch { toasts.show(ActionRefused.words(for: error), tone: .error) } }default:// Bin by a delete; Archive and Bring back by the write the core said.if act.id == Self.binAct { write { tryawait model.delete(record) } } elseiflet patch = press.write { write { tryawait model.write(record, patch) } } else { toasts.show(ShellLines.line("record", "engine_action"), tone: .error) } } }privatefunc slip(_ record: TableRecord, _ model: RecordListModel, compact: Bool = false) -> someView {// A read-only toggle column, or a record kept elsewhere, draws its// check without a control: a tap there is a write.// While ticking there is one control on a slip, the pick's: a todo's// check beside it completed the todo when the tap meant to pick it.let said = model.row(record.id)let toggle: (() -> Void)? = !selecting && said?.toggle != nil ? { write { tryawait model.toggle(record) } } : nil// The slip's own acts, under it: each acts on this record, never// opens it — the slip itself does that.return VStack(alignment: .trailing, spacing: 2) {ActedSlip( acts: acts, record: record, store: store, identifier: "list-\(definition.id)-\(record.id)", onTap: { action in tapped(action, on: record) } ) {// Bare: the check, answer and reply inside the label keep their own taps.TravellingPress(style: BareButtonStyle(), action: { tap(record) }) {SlipFace( definition: definition, record: record, onToggle: toggle, compact: compact, upcoming: definition.upcoming != nil, onAnswer: selecting ? nil : { value in answer(record, value, model) }, onReply: selecting ? nil : { replying = record }, answering: answering == record.id, row: said ) .overlay { pickMark(record) } }// The row is named by its words, never by the switch inside it:// an alarm card was read out "1, button" (walker pass 2). .accessibilityLabel(definition.spoken(record, links: model.linkTitles.byID)) .spokenValue(heldWords(record)) .accessibilityIdentifier("\(definition.id)-\(record.id)") } .opacity(said?.dimmed == true ? 0.6 : 1) bringBack(record, model) } .accessibilityElement(children: .contain) .accessibilityIdentifier("\(definition.id)-\(record.id)") .modifier(pressMenu(record, model) {AnyView(SlipFace(definition: definition, record: record, compact: compact, upcoming: definition.upcoming != nil, row: said)) }) }/// A record as its polaroid, opening its page (or what it stands for).privatefunc polaroid(_ record: TableRecord, _ model: RecordListModel) -> someView {TravellingPress(style: MotionButtonStyle(), action: { tap(record) }) {PolaroidFace( definition: definition, record: record, width: 140, fills: true, onAnswer: selecting ? nil : { value in answer(record, value, model) } ) .overlay(alignment: .topLeading) { pickMark(record).aspectRatio(1, contentMode: .fit) } .contentShape(Rectangle()) }// The print's own words are not the tile's: it says what it is aloud. .accessibilityLabel((record.said?.slip.spoken ?? definition.name)) .spokenValue(heldWords(record)) .opacity(model.row(record.id)?.dimmed == true ? 0.6 : 1) .modifier(pressMenu(record, model) {AnyView(PolaroidFace(definition: definition, record: record, width: 140, fills: true)) }) .accessibilityIdentifier("\(definition.id)-\(record.id)") .viewerSource("\(definition.id)/\(record.id)") }/// A record as a contact sheet's square: its picture, no frame and no/// tilt; the badge and the polaroid's caption small in its corner (a/// film's play mark and length).privatefunc sheetCell(_ record: TableRecord) -> someView {TravellingPress(style: MotionButtonStyle(), action: { tap(record) }) {Color.clear .aspectRatio(1, contentMode: .fit) .overlay {// Framed to the cell and centred on it: a filled picture// left unframed is laid out at its own aspect from the// reader's corner, over the next squares (`SheetTile`).GeometryReader { geo inRecordPicture(avatarKey: record[definition.slip.photo].text, edge: geo.size.width) .frame(width: geo.size.width, height: geo.size.height) } } .clipped() .overlay(alignment: .bottomLeading) {iflet badge = definition.slip.badge, record.said?.slip.badge != nil { HStack(spacing: 3) {Image(systemName: badge.symbol).font(.system(size: 8))iflet words = definition.polaroidCaption(of: record) { Text(words).font(CottonFonts.type(10)) } } .foregroundStyle(CottonColors.accentContrast) .shadow(color: CottonColors.ink.opacity(0.5), radius: 2) .padding(4) .accessibilityLabel(badge.spoken) } } .overlay { pickMark(record) }// The button is its cell, touched and read out (295 rows 91/94). .sheetTile() } .accessibilityLabel((record.said?.slip.spoken ?? definition.name)) .spokenValue(heldWords(record)) .accessibilityIdentifier("\(definition.id)-\(record.id)-sheet") .viewerSource("\(definition.id)/\(record.id)") }/// The tick on a picked record, while ticking. @ViewBuilder privatefunc pickMark(_ record: TableRecord) -> someView {if selecting {if pick?.held.contains(record.id) == true {PickMark(isPicked: true, isHeld: true, identifier: "list-\(definition.id)-held-\(record.id)") } else {PickMark( isPicked: picked.contains(record.id), identifier: picked.contains(record.id) ? "list-\(definition.id)-picked-\(record.id)" : nil) } } }/// What a record the pick already holds is read out with ("Already in/// Family"); nothing for any other.privatefunc heldWords(_ record: TableRecord) -> String? {guard selecting, let pick, pick.held.contains(record.id) else { returnnil }return pick.heldWords }/// A tap on a record: a tick while ticking; else the slip's copy/// (`slip.tap`); else the record it stands for (`opens`), through the/// opener; else its own page.privatefunc tap(_ record: TableRecord) {if selecting {// Already held by the pick: there is nothing to add it to.if pick?.held.contains(record.id) == true { return }iflet at = picked.firstIndex(of: record.id) { picked.remove(at: at) } else { picked.append(record.id) } } else {// The row this screen opened, so the page pushed over it leaves// out a link that would only lead back to it (`Navigator.rowOpened`).// A slip whose tap is a copy (a clip) copies and stays: the// value onto this device's clipboard, never through the core.iflet copied = definition.tapCopy(record) { toasts.show(RecordActionOutcomes.copy(copied.value, expiresAfter: copied.secret ? SecretClipboard.seconds : nil), tone: .success)return }iflet screenRoute { navigator?.rowOpened[screenRoute] = PathRecord(table: definition.id, record: record) }if openInViewer(record) { return }ifcase .address? = definition.slip.opens {guardlet address = definition.slipAddress(record) else { toasts.show(ShellLines.line("lists", "destination.unreadable"), tone: .error)return }iflet route = Route.parse(address), let navigator { navigator.push(route) }elseiflet url = URL(string: address), url.scheme != nil { openURL(url) }else { toasts.show(ShellLines.line("lists", "destination.cannot_open"), tone: .error) } } elseiflet target = definition.opening(record), let opener { opener(target.table, TableRecord(id: target.id, values: [:])) } else { onOpen(record) } } }/// Writes one of the record's answers, with its receipt and Undo; the/// record's verbs wait while it is on its way.privatefunc answer(_ record: TableRecord, _ value: String, _ model: RecordListModel) {guard answering == nilelse { return } answering = record.id write {defer { answering = nil }returntryawait model.answer(record, value) } }// ── Select, pick and the filter row ─────────────────────────────────────/// While ticking: the act (the trash, or the counted pick verb) and the way/// out (Select's; a pick goes back with the back arrow). @ViewBuilder privatevar selectCircles: someView {iflet pick {PaperTypedButton(pick.action.label(count: picked.count)) { addPicked(pick) } .disabled(picked.isEmpty || busy) .accessibilityIdentifier("list-\(definition.id)-pick") } else {if keepsGroups, model?.answer?.select.adds_to_group == true {NavCircle(symbol: "square.stack", label: ShellLines.line("lists", "group.add_picked"), disabled: picked.isEmpty || busy) { addingToGroup = true } .accessibilityIdentifier("list-\(definition.id)-select-group") }// Select's Delete wherever the table deletes (`selectDeletes`),// and not once the records picked hold none it may delete// (`delete_when`): those it may not are left as they are.iflet select = model?.answer?.select, select.deletes, picked.isEmpty || !deletable.isEmpty {NavCircle(symbol: "trash", label: select.word, disabled: picked.isEmpty || busy) { askDelete() } .accessibilityIdentifier("list-\(definition.id)-select-delete") }NavCircle(symbol: "xmark", label: ShellLines.line("lists", "done")) { selecting = false picked = [] } .accessibilityIdentifier("list-\(definition.id)-select-done") } }/// The picked records the core says Select's Delete may take, in the order picked.privatevar deletable: [TableRecord] {guardlet model else { return [] }return picked.compactMap { id in model.row(id).flatMap { $0.deletes ? $0.record : nil } } }/// Asks the core how Select's Delete goes over the records picked —/// those it takes, and its question in the table's words — then asks it,/// or deletes at once where the table asks nothing.privatefunc askDelete() {guardlet model, !busy else { return }let ids = picked busy = trueTask {do {let said = tryawait model.deleting(ids) busy = falseif said.asks { deletingAsked = said confirmingDelete = true } else { deletePicked(said) } } catch { busy = false toasts.show(ActionRefused.words(for: error), tone: .error) } } }/// Deletes the records the core said it takes, one at a time; the refused/// stay picked, and what is said after is the core's.privatefunc deletePicked(_ said: ListDeleting) {guardlet model, !busy else { return } busy = trueTask {let outcome = await model.delete(ids: said.ids) busy = false picked = picked.filter { !outcome.deleted.contains($0) }if picked.isEmpty { selecting = false }iflet words = outcome.said?.outcome { toasts.show(words, tone: outcome.failed.isEmpty ? .notice : .error) } } }/// Makes the pick's records, one per picked; the refused stay picked, and/// once all are made the pick goes back.privatefunc addPicked(_ pick: ListPick) {guardlet model, !busy else { return }let ids = picked busy = trueTask {let outcome: (made: [String], failed: [String])iflet act = pick.act {let failed = await act(ids) outcome = (ids.filter { !failed.contains($0) }, failed) } else { outcome = await model.create(in: pick.table, column: pick.column, preset: pick.preset, ids: ids) } busy = false picked = outcome.failedlet target = definitions[pick.table]let n = outcome.made.countlet noun = (n == 1 ? target?.name : target?.plural)?.lowercased() ?? (n == 1 ? "record" : "records")if outcome.failed.isEmpty {iflet said = pick.said?(n) ?? (pick.act == nil ? "Added \(n) \(noun)" : nil) { toasts.show(said) } pick.done() } else { toasts.show(TableDefinition.selectOutcome(deleted: n, failed: outcome.failed.count, verb: pick.action.completed), tone: .error) } } }/// The filter row, as the core answered it: all, then each value's word,/// the chosen in ink and the rest faint and underlined; at its end, what/// waits on the owner, in red, opening the menu. @ViewBuilder privatevar filterRow: someView {if !selecting, let row = model?.answer?.filter, (row.column != nil && !row.values.isEmpty) || row.reviews == true { HStack(alignment: .firstTextBaseline, spacing: 6) {if row.tabs, row.column != nil { filterWord(row.all ?? "", value: nil)ForEach(row.values, id: \.value) { value inText("\u{00B7}").font(CottonFonts.type(14)).foregroundStyle(CottonColors.inkTertiary) filterWord(value.word, value: value.value) } }Spacer(minLength: 8)iflet review = row.review {Button { menuOpen = true } label: {Text(review).paperHand(16, ink: .red) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("list-\(definition.id)-waiting") } elseif row.reviews == true {// The count's place, held until it lands.Text(ShellLines.line("lists", "to_review", ["n": "0"])).paperHand(16, ink: .red).hidden().accessibilityHidden(true) } } .padding(.bottom, 14) } }privatefunc filterWord(_ word: String, value: String?) -> someView {Button { chosen = value } label: {Text(word) .font(CottonFonts.type(14)) .foregroundStyle(chosen == value ? CottonColors.ink : CottonColors.inkTertiary) .underline(chosen != value, color: CottonColors.hairline) } .buttonStyle(OpacityButtonStyle()) .accessibilityAddTraits(chosen == value ? .isSelected : []) .accessibilityIdentifier("list-\(definition.id)-filter-\(value ?? "all")") }/// Makes a record from the chips — its change lands on the model, whose/// receipt shows it; false when it was not made.privatefunc create(_ data: [String: RecordValue]) async -> Bool {guardlet model else { returnfalse }do { _ = tryawait model.create(data)returntrue } catch { toasts.show(ActionRefused.words(for: error), tone: .error)returnfalse } }/// Writes the reply's words; `true` once they landed. Blank words send/// nothing, and a refused write keeps the sheet up with its words.privatefunc send(_ words: String, for record: TableRecord) async -> Bool {guardlet model, let patch = definition.replyPatch(words) else { returnfalse } answering = record.iddefer { answering = nil }do {// Its change lands on the model, whose receipt shows it. _ = tryawait model.write(record, patch)returntrue } catch { toasts.show(ActionRefused.words(for: error), tone: .error)returnfalse } }/// A change the bar made (or an answer to its question): its receipt,/// worded by the table it was written to, and the list read again.privatefunc wear(_ change: ChangeRecord, in table: TableDefinition?) {guardlet model else { return }let foreign = table.map { $0.id != definition.id } ?? falseiflet written = table, foreign { receiptTables[change.id] = written } model.received(change, foreign: foreign)// A record made on a group's page joins the group.let made = change.before == nil && (table?.id ?? definition.id) == definition.id ? change.after?.id : nilTask {iflet scope, let made { await scope.made(made) }await reload() } }/// Re-sends the create the store asked about, with the answer picked:/// the record it makes wears its receipt and the bar empties; another/// question takes this one's place; a refusal is said.privatefunc answerQuestion(_ asked: CreateQuestion, _ option: CreateQuestion.Option) async {guardlet store else { return }let result = awaitOneInputModel.answer(asked, option, records: store, definitions: definitions) question = result.question note = result.change == nil ? OneInputNote.of(result) : nilguardlet change = result.change else { return } answersLetGo += 1 wear(change, in: result.table)iflet target = change.created { navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table])) } }/// The newest write's receipt, at the toast edge over the top of the/// list — never over the one input at the foot. Its Undo reads the list/// again; Done lets it go. @ViewBuilder privatevar receipt: someView {iflet model, let change = model.lastChange {ChangeReceipt( change: change, table: receiptTables[change.id] ?? definition, undone: model.lastChangeUndone, onUndone: { _ inTask { await model.undone(change) } }, onDismiss: { model.dismissChange() }, performUndo: model.receiptUndo(for: change)) .id(change.id) .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) .transition(.move(edge: .top).combined(with: .opacity)) .accessibilityIdentifier("list-\(definition.id)-receipt") } }/// Runs one write — its change lands on the model, whose receipt shows/// it — or says it failed. Nil from `act`: the touch changed nothing.privatefunc write(_ act: @escaping () asyncthrows -> ChangeRecord?) {Task {do {// The model reads the list again, its counts with it, after// every write it makes (`RecordListModel.wrote`). _ = tryawait act() } catch { toasts.show(ActionRefused.words(for: error), tone: .error) } } }}/// A shut-able section's heading: the name in the serif, "show" or "hide"/// beside it as `/code`'s band headings said it, the hairline, and the whole/// count handwritten at its end.structFoldingSectionHeading: View { @Environment(\.theme) privatevar themelet title: Stringlet count: Stringlet shut: Boolvar body: someView { HStack(alignment: .center, spacing: 12) { HStack(alignment: .firstTextBaseline, spacing: 10) {Text(title) .font(CottonFonts.serif(theme.scale.sectionTitleSize)) .foregroundStyle(CottonColors.ink) .lineLimit(1)Text(ShellLines.line("lists", shut ? "fold.show" : "fold.hide")).paperMeta(12) } .layoutPriority(1)Rectangle() .fill(CottonColors.hairline) .frame(height: ComposerCardKnobs.chromeHairline) .frame(maxWidth: .infinity)Text(count) .paperHand(13) .lineLimit(1) } .padding(.horizontal, 2) .contentShape(Rectangle()) .accessibilityElement(children: .combine) .accessibilityAddTraits(.isHeader) }}/// A row's long press: when it offers something, the row lifts over the/// dimmed screen and its acts hang by it (`LiftedActs`, slipacts rule 5) —/// the acts the core answered for the row (`shell.list`'s `press`), in its/// order, the one that takes it away last and red. When it offers nothing/// the hold still takes the touch, so a list whose long press drags keeps its drag.structSlipPressMenu: ViewModifier { @Environment(\.theme) privatevar theme @Environment(\.actLift) privatevar lift @Environment(\.cottonHaptics) privatevar haptics/// The row's acts, as the core answered them.let acts: [ListAnswer.Press]let identifier: Stringlet record: Stringlet act: (ListAnswer.Press) -> Void/// The row as it lifts: its face, drawn without its taps.var face: () -> AnyView = { AnyView(EmptyView()) }/// A hold that opens the fan's own answer instead of lifting the row:/// Settings' Export row turns the fan into its tables (`ExportFan`).var turnsFan: (() -> Void)? = nil @State privatevar frame = RowFrame()func body(content: Content) -> someView {// The whole row — its press, its acts, Bring back — leaves the tree// under the bloomed fan, not only the face inside its button: a// button that names itself read on under the fan (walker 298). pressed(content).modifier(UnreadUnderTheFan()) } @ViewBuilder privatefunc pressed(_ content: Content) -> someView {iflet turnsFan { content.highPriorityGesture(LongPressGesture(minimumDuration: PressRule.longPressSeconds).onEnded { _ in haptics.press() turnsFan() }) } elseif acts.isEmpty {// Nothing to offer, and still a HOLD is not a tap: the hold takes// the touch (as `Pressable`'s does), so its release never opens// the row the way a tap would. content.highPriorityGesture(LongPressGesture(minimumDuration: PressRule.longPressSeconds).onEnded { _ in }) } else { content .opacity(lift?.lifted?.id == lifted ? 0 : 1) .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame.frame = $0 } .highPriorityGesture(LongPressGesture(minimumDuration: PressRule.longPressSeconds).onEnded { _ in hold() }) .accessibilityActions {ForEach(lifts) { act inButton(act.word) { act.perform() } } } } }privatevar lifted: String { identifier + "/" + record }/// The row's acts as the lifted card's rows: each its word, the object/// its picture names, red where it takes the record away.privatevar lifts: [LiftedAct] { acts.map { press inLiftedAct(id: "\(identifier)-\(press.act.id)-\(record)", word: press.act.label, object: Self.object(press.act), destroys: press.act.red == true) { act(press) } } }privatefunc hold() {guardlet lift, let frame = frame.frame else { return } haptics.press() lift.lift(Lifted(id: lifted, frame: frame, face: face(), acts: lifts)) }/// The enamel an act's picture names (`act-<object>`, `edit-act-<name>`),/// else the one its id names (Archive, Bring back); none for another.staticfunc object(_ act: CardAction) -> CardEnamel? {let named = act.icon.map { $0.replacingOccurrences(of: "edit-act-", with: "").replacingOccurrences(of: "act-", with: "") }let byID: CardEnamel? = act.id == RecordListSurface.bringBackAct ? .restore : CardEnamel(rawValue: act.id)return named.flatMap(CardEnamel.init(rawValue:)) ?? byID }}/// Where a row stands on the screen, kept out of the view's state: a scroll/// moves every row, and a lift reads it only on a hold.finalclassRowFrame {var frame: CGRect?}/// A long-press act held while its question, the core's, is asked.structPressAsk: Identifiable {let press: ListAnswer.Presslet question: ListAnswer.Questionlet record: TableRecordvar id: String { press.id + "/" + record.id }}/// A long-press Bin of a record that repeats, held while it asks how far it reaches.structScopeAsk: Identifiable {let record: TableRecordvar id: String { record.id }}extensionRecordListSurface {/// The head act the list opened to ask, once the head offers it.staticfunc asked(_ head: [RecordAction], id: String?) -> RecordAction? {guardlet id else { returnnil }return head.first { $0.id == id } }/// The picture an empty list stands over its words: the tool's own/// (walker294 rows 84, 108–110 — a blank grey card said nothing).staticfunc emptyPicture(_ definition: TableDefinition) -> ToolPicture? { definition.picture }/// `opened` with a folded section tapped: shut if it was open, open if shut.staticfunc toggled(_ opened: Set<String>, _ heading: String) -> Set<String> {var next = openedif next.contains(heading) { next.remove(heading) } else { next.insert(heading) }return next }}privatestructRecordsRevisionKey: EnvironmentKey {staticlet defaultValue = 0}extensionEnvironmentValues {/// Bumped by whoever holds a list when its records may have moved under/// it (a poll, a sync that named the table): the list reads again, in/// place, keeping what it shows until the answer lands.publicvar recordsRevision: Int { get { self[RecordsRevisionKey.self] } set { self[RecordsRevisionKey.self] = newValue } }}privatestructCottonListSearchKey: EnvironmentKey {staticlet defaultValue: Binding<String>? = nil}extensionEnvironmentValues {/// Optional host search, so Mac toolbars and phone search read the same list.var cottonListSearch: Binding<String>? { get { self[CottonListSearchKey.self] } set { self[CottonListSearchKey.self] = newValue } }}privateextensionView {/// The list's last record, drawn in a lazy grid, asks for the next page/// when it is scrolled into view.func asksForMore(_ record: TableRecord, _ model: RecordListModel) -> someView { onAppear {guard model.hasMore, record.id == model.records.last?.id else { return }Task { await model.loadMore() } } }}/// The sizes, counts and timings RecordListSurface draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enumRecordListSurfaceKnobs {staticlet paperGap: CGFloat = 12}/// A list's search slip under its name: always for a list that searches/// there, and for one whose magnifier gave way in a short head row.privatestructListSearchSlip: View {let inHead: Boollet placeholder: Stringlet identifier: Stringletopen: () -> Void @Environment(\.headCirclesGaveWay) privatevar gaveWayvar body: someView {if !inHead || gaveWay {SearchSlip(placeholder: placeholder, identifier: identifier, action: open) } }}