// 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. import CottonKit import CottonValues import SwiftUI /// 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). public struct ListPick { public enum Action: String { case add = "Add" case remove = "Remove" public func label(count: Int) -> String { "\(rawValue) \(count)" } var completed: String { self == .add ? "added" : "removed" } } public var action: Action public var table: String public var column: String public var preset: [String: RecordValue] /// The picker title, kept while selections and search change ("Add photos"). public var label: String public var 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. public var 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. public var 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. public var held: Set public var heldWords: String? public var done: @MainActor () -> Void public init( 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 = [], heldWords: String? = nil, done: @escaping @MainActor () -> Void ) { self.action = action self.held = held self.heldWords = heldWords self.table = table self.column = column self.preset = preset self.label = label self.empty = empty self.said = said self.act = act self.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. public struct ListScope { public var empty: EmptyWords public var addLabel: String public var add: @MainActor () -> Void public var menu: [PopoverMenuItem] /// The bar's words on this list ("Add to Family…"). public var 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. public var received: ChangeRecord? /// A record the bar made on this list, by its id. public var 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)? = nil public init( empty: EmptyWords, addLabel: String, add: @escaping @MainActor () -> Void, menu: [PopoverMenuItem], barWords: String? = nil, received: ChangeRecord? = nil, made: @escaping @MainActor (String) async -> Void ) { self.empty = empty self.addLabel = addLabel self.add = add self.menu = menu self.barWords = barWords self.received = received self.made = made } } public struct RecordListSurface: View { private let definition: TableDefinition private let archived: Bool private let filter: [String: RecordValue] /// The one section of the table's day plan this list is ("earlier"); /// nil, the whole list. private let 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. private let view: ToolView.Read? /// The day a day-split list opens on (`RecordListModel.opensOn`). private let opensOn: String? private let composeOnArrival: Bool private let pick: ListPick? /// The list is one gathering of the table's records (a group's page). private let scope: ListScope? /// The title over the list in place of the table's plural; nil is the plural. private let titleOverride: String? /// The head act whose sheet is up as the list opens, asked once. private let askingOnOpen: String? private let 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. private let leading: AnyView @Environment(\.theme) private var theme @Environment(\.linkTitles) private var links @Environment(\.records) private var store /// The ring's views over the fan, when this list is one (`ToolViews`). @Environment(ToolViews.self) private var toolViews: ToolViews? @Environment(\.cottonCore) private var core /// The editor over Home's fan, where one stands (`ExportFan`'s row). @Environment(\.deckEditor) private var deckEditor @Environment(\.currentProject) private var 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. private var project: String? { definition.projectScope(currentProject) } @Environment(\.recordsRevision) private var revision /// The database shown, which the list's seed is kept under. @Environment(DatabaseScene.self) private var databaseScene: DatabaseScene? @Environment(DatabasesModel.self) private var databasesModel: DatabasesModel? @Environment(\.keptFlow) private var keptFlow @Environment(\.nativeKeptFlow) private var nativeKeptFlow @Environment(\.rekeyThisDevice) private var rekeyThisDevice @Environment(\.readerPresenter) private var readerPresenter @Environment(\.openURL) private var openURL @Environment(PendingTaps.self) private var pendingTaps: PendingTaps? @Environment(\.recordOpener) private var 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) private var listOpener @Environment(\.tableDefinitions) private var definitions @Environment(Navigator.self) private var navigator: Navigator? /// Where a picture, a film or a document opens: the one viewer. @Environment(\.viewerPresenter) private var viewerPresenter /// This list is on the navigator's path (`FilteredListOpening.open`). @Environment(\.listsOnPath) private var listsOnPath /// This list's own route on that path, when it is a routed screen. @Environment(\.screenRoute) private var screenRoute @Environment(ToastCenter.self) private var toasts @State private var 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. private var keepsThoughts: Bool { (store as? any ThoughtKeepingRecords)?.keepsThoughts(table: definition.id) ?? false } @State private var localQuery = "" @Environment(\.cottonListSearch) private var toolbarQuery private var query: String { toolbarQuery?.wrappedValue ?? localQuery } private var queryBinding: Binding { 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 private var acts: RecordActs /// A value an act showed once, until "I've saved it". @State private var revealed: RevealedValue? /// A sign-in is open in the browser: the list reads again while it waits. @State private var signingIn = 0 @State private var searching = false /// What the one input said beside its change, until it is let go. @State private var note: OneInputNote? /// How many of the bar's answers were let go: each empties the bar. @State private var 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 private var receiptTables: [String: TableDefinition] = [:] @State private var dragging = false /// Whether `askingOnOpen` was put up, so a read again does not put it up again. @State private var asked = false /// A blank page for a new record is open over the list. @State private var composing = false /// A door's files being chosen in the system's picker (`DeckDoors`). @State private var choosingFiles: DefinitionCreateFiles? /// A door's pictures being chosen in the photo picker or taken with the camera (`DoorPictures`). @State private var pickingPictures: DefinitionCreatePick? /// The related list (or its blank record) the menu opened. @State private var relatedOpen: RelatedOpening? /// `composeOnArrival` is honoured once: coming back from the blank page /// must not open it again. @State private var composedOnArrival = false /// The closed sections (`ListGroup.closed`) opened by a tap, by heading. @State private var opened: Set = [] /// The letter the index rail last asked the list to show. @State private var scrollTarget: String? /// The record whose answer is on its way: its verbs wait. @State private var answering: String? /// The record whose reply sheet is up, or nil. @State private var replying: TableRecord? @State private var gridWidth: CGFloat = 0 /// The filter row's chosen value; nil is all. @State private var 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 private var readFor: Read? /// A failed first read is being tried again on a tick. @State private var retrying = false /// The list is drawn (a page pushed over it, or a tab away, is not). @State private var onScreen = false @Environment(\.scenePhase) private var scenePhase /// Ticking records, for Select (or always, on a pick). @State private var selecting = false /// The ticked records' ids, in the order ticked. @State private var picked: [String] = [] @State private var menuOpen = false /// The head's "+" opened the store's folded "New …" choices. @State private var 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. private var headFolds: Bool { scope == nil && definition.create == nil && RecordActionButtons.folds(acts.head) } @State private var confirmingDelete = false /// Select's Delete as the core asked it: the records it takes, its question, its receipt. @State private var deletingAsked: ListDeleting? /// The long-press act waiting on its question, in the core's words (S8). @State private var asking: PressAsk? /// A long-press Bin of a record that repeats, waiting on how far it reaches. @State private var scoping: ScopeAsk? /// The `clear` question is open. @State private var confirmingClear = false /// A Select or a pick is being written. @State private var busy = false /// The narrowed list a list link opened. @State private var filteredOpen: FilteredListOpening? /// What the search found in the other lists (`lists`) drawn with it. @State private var sectionFinds = SectionFinds() /// The question the store asked before making the bar's record. @State private var question: CreateQuestion? /// "New group" is being asked (the stacks row's sheet). @State private var namingGroup = false /// "Add to group…" is up for the ticked records. @State private var 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. public init( 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 = view self.opensOn = opensOn self.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 = definition self.archived = archived self.filter = filter self.section = section self.composeOnArrival = composeOnArrival self.pick = pick self.titleOverride = title self.askingOnOpen = asking self.onOpen = onOpen self.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). public init( 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. private var showsGrid: Bool { definition.layout != .list } /// What every listed record holds: the route's narrowing and the filter /// row's word. private var 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. private struct Read: Equatable { var project: String? var query: String var 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. private var title: String { if let pick { return pick.label } guard selecting else { if let 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). private func 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. private func open(_ opens: ListAnswer.Opens) { if let path = opens.path { if let route = Route.parse(path) { navigator?.push(route) } return } guard let table = opens.table else { return } let narrowed = opens.where ?? [:] if let 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 private func archivedLink(_ model: RecordListModel) -> some View { 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 private func earlierLink(_ model: RecordListModel) -> some View { 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 private func bringBack(_ record: TableRecord, _ model: RecordListModel) -> some View { 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 { try await 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 private func listLinksRow(lead: Bool) -> some View { let links = !lead && definition.linkTiles != nil ? [] : listLinks(lead: lead) if !links.isEmpty { SideLinksRow(links: links.map { link in PageSideLink(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 private var linkSlips: some View { let links = definition.linkTiles == nil ? [] : listLinks(lead: false) if !links.isEmpty { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) { ForEach(links, id: \.id) { link in Button { 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 private var aboveLinksRow: some View { let links = listLinks(lead: false, above: true) if !links.isEmpty { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) { ForEach(links, id: \.id) { link in Button { 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-`, `menu-`. static func menuID(_ id: String) -> String { guard let colon = id.firstIndex(of: ":") else { return id } return id[..= 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`). if let act = item.act { guard let 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 } guard let 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. if let 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. private var showsGroups: Bool { model?.answer?.groups != nil && scope == nil && keepsGroups } /// Whether the table gathers groups and the store keeps them. private var keepsGroups: Bool { definition.groups != nil && GroupRecords.grouping(store) != nil } public var body: some View { // 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. private func screen(_ paper: AnyView) -> AnyView { AnyView(ZStack(alignment: .top) { paper if 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. private func 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. return AnyView(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 { if let scope, store != nil { NavCircle(symbol: "plus", label: scope.addLabel) { scope.add() } .accessibilityIdentifier("list-\(definition.id)-scope-add") } else if pick != nil, let create = definition.create, store != nil, acts.canCreate { NavCircle(symbol: "plus", label: create.label) { compose() } .accessibilityIdentifier("list-\(definition.id)-new") } else if 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. if let 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 in if let 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. private func 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 in await create(data) } } if store != nil, let paste = definition.paste { ListPasteHead(paste: paste) { data in await create(data) } } listed if query.isEmpty, let model, model.phase == .loaded { ForEach(model.answer?.notes ?? [], id: \.self) { note in Text(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`). private func surrounded(_ screen: AnyView) -> AnyView { pushing(asking(barred(screen))) } /// The bar at the foot. private func 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). if let question { CreateQuestionCard(question: question, identifier: "list-\(definition.id)") { option in await answerQuestion(question, option) } onDismiss: { self.question = nil } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) } else if let 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. private func asking(_ screen: AnyView) -> AnyView { AnyView(screen .scopeDecision( item: $scoping, question: { .delete($0.record, in: definition, bin: "") }, identifier: "list-\(definition.id)-scope" ) { ask, scope in guard let model else { return } write { try await 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 in guard let 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: { if let 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) { if let 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. private func pushing(_ screen: AnyView) -> AnyView { AnyView(screen .pageDestination(item: $relatedOpen) { opening in RelatedDestination(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. private func 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)) { guard let 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 = read let wanted = narrowing let 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 = model if !query.isEmpty { // Typing reads once the fingers pause, not on every letter. try? await Task.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) { _, _ in guard let model else { return } if model.phase == .failed { guard !retrying else { return } retrying = true Task { 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) { guard let beat = pollBeat else { return } while !Task.isCancelled { do { try await Task.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) > 0 else { 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 > 0 else { 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 _ in 0..<90 { do { try await Task.sleep(for: .seconds(2)) } catch { return } await reload() if Set(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 in await 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 in await makeGroup(name) } } .cottonCard(item: $replying, detents: [.half]) { record in if let reply = definition.replyOffered(record) { ReplySheet( definition: definition, record: record, reply: reply, onSend: { words in await 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. private func makeGroup(_ name: String) async -> String? { guard let grouping = GroupRecords.grouping(store) else { return ShellLines.line("lists", "group.none_kept") } do { let made = try await grouping.createGroup(named: name, of: definition.id, records: []) let tool = definition.tool.map { $0.key ?? definition.id } ?? definition.id do { try await toolViews?.reload(core: core) } catch { _ = toasts.show(ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]), tone: .error) } if let id = made.group?.id { toolViews?.choose(ToolView.groupPrefix + id, of: tool) } return nil } catch { return ActionRefused.words(for: error) } } /// The store's acts and a value one of them showed once; nothing for a /// store that offers none. @ViewBuilder private var head: some View { if let 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") } else if let 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") } if let revealed { RevealedValueCard( revealed: revealed, identifier: "list-\(definition.id)", onCopy: { Task { guard let store else { toasts.show(ShellLines.line("record", "unreadable"), tone: .error); return } do { let change = try await SecretCopy.copy(revealed, definition: definition, store: store) self.revealed = nil if let change { model?.received(change) } toasts.show(ShellLines.line("record", "copied_expires"), tone: .success) if let id = revealed.record { open(id) } } catch { toasts.show(SecretCopy.problem(error), tone: .error) } } }, onSaved: { self.revealed = nil if let 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. private func 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. private func 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. private var 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. private func openInViewer(_ record: TableRecord) -> Bool { guard definition.viewer != nil, let viewerPresenter, let model else { return false } let items = model.records.compactMap { ViewerItem(record: $0, definition: definition) } guard let start = items.firstIndex(where: { $0.id == "\(definition.id)/\(record.id)" }) else { return false } viewerPresenter.open(ViewerSet(items: items, start: start)) return true } /// Opens a record's page by its id, as a tap on its slip would. private func open(_ id: String) { Task { guard let 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. private func reread() async { guard let 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. private func reload() async { guard let 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. private func compose() { guard acts.canCreate else { return } let editor = deckEditor ?? DeckEditor.session let toasts = toasts Task { let plus: DeckAnswer.Plus? do { plus = try await DeckAnswer.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 != nil else { return } editor.ask(table: definition.id, core: core, landed: landed) case "route"?: guard let 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. private func landed(_ id: String) { Task { @MainActor in for _ in 0.. 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?.empty let 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. return AnyView(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. if Self.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() }) } else if 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() }) } else if 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 private func slips(_ model: RecordListModel) -> some View { ScrollViewReader { proxy in slipStack(model) .onChange(of: scrollTarget) { _, letter in guard let letter, let id = model.answer?.index?.first(where: { $0.letter == letter })?.row else { return } scrollTarget = nil Task { // 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 private func slipStack(_ model: RecordListModel) -> some View { 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 in if case .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) } ) } else if showsGrid { sectionedGrid(model, sections: sections) } else if 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 { try await 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). private func sectionedGrid(_ model: RecordListModel, sections: [RecordSection]) -> some View { let sheet = definition.layout == .sheet let 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. return LazyVGrid( columns: Array(repeating: GridItem(.flexible(), spacing: spacing, alignment: .top), count: flowing.columns), alignment: .leading, spacing: spacing ) { ForEach(Array(sections.enumerated()), id: \.offset) { index, section in Section { ForEach(shown(section)) { record in Group { if sheet { sheetCell(record) .modifier(UnreadUnderTheFan()) } else if definition.tile.face == .polaroidGrid { polaroid(record, model) } else if 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 in if 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). static func saysNothingMatches(query: String, sections: SectionFinds, hasSections: Bool) -> Bool { guard !query.isEmpty, hasSections else { return true } 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 private func otherLists(above: Bool) -> some View { // 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 in RecordsSection(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 private func clearRow(_ model: RecordListModel) -> some View { if let 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") if let 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. private var 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. private func clearAll() { guard let model, let clear = model.answer?.clear, !busy else { return } let ids = model.records.map(\.id) busy = true Task { 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 private func recent(_ model: RecordListModel) -> some View { 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 in TravellingPress(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) if let 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 private func allOfSection(_ section: RecordSection, _ model: RecordListModel) -> some View { 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 private func heading(_ section: RecordSection, first: Bool, below: CGFloat) -> some View { if let title = section.heading { Group { if section.closed && query.isEmpty { let id = section.id ?? title Button { 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)") } else if 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)") } if let 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 in Text(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. private func 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 private func nextPage(_ model: RecordListModel) -> some View { 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. private func cover(_ record: TableRecord, _ model: RecordListModel) -> some View { 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. private func 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) } else if let 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`). if let 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`). private func run(_ command: RecordCommand, on record: TableRecord, _ model: RecordListModel) { Task { do { guard let change = try await 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)?: guard await RecordLanding.arrived(target, in: store) else { return } navigator?.open(BoardRecord.route(table: target.table, id: target.id, definition: definitions[target.table])) case .address(let address)?: if let url = URL(string: address) { openURL(url) } case .database(let shown)?: await DatabaseCapRow.show(shown, scene: databaseScene, in: databasesModel, navigator: navigator) if let said = change.said?.said { toasts.show(said, tone: .success) } case .platform(.pickFile(let pick))?: guard let imported = try await RecordFileEffects.perform(pick, records: store) else { return } model.received(imported, foreign: pick.table != definition.id) await model.refresh() if let 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)?: guard await RecordPlatformEffects.perform(action, nativeFlow: nativeKeptFlow, rekey: rekeyThisDevice, reader: readerPresenter) else { toasts.show(ShellLines.line("record", "platform_action"), tone: .error) return } await model.refresh() case nil: if let 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) } } } catch let asked as CreateQuestion { 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. static let binAct = "bin" static let 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. private func perform(_ press: ListAnswer.Press, on record: TableRecord, _ model: RecordListModel) { let act = press.act switch act.kind { case "command": guard let 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": guard let 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": guard let core else { return } Task { do { switch try await DeckActs.ran(act, core: core) { case .opens(let page): openURL(page) case .platform(let effect): _ = await RecordPlatformEffects.perform(effect, nativeFlow: nativeKeptFlow, rekey: rekeyThisDevice, reader: readerPresenter) case let 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 { try await model.delete(record) } } else if let patch = press.write { write { try await model.write(record, patch) } } else { toasts.show(ShellLines.line("record", "engine_action"), tone: .error) } } } private func slip(_ record: TableRecord, _ model: RecordListModel, compact: Bool = false) -> some View { // 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 { try await 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). private func polaroid(_ record: TableRecord, _ model: RecordListModel) -> some View { 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). private func sheetCell(_ record: TableRecord) -> some View { 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 in RecordPicture(avatarKey: record[definition.slip.photo].text, edge: geo.size.width) .frame(width: geo.size.width, height: geo.size.height) } } .clipped() .overlay(alignment: .bottomLeading) { if let badge = definition.slip.badge, record.said?.slip.badge != nil { HStack(spacing: 3) { Image(systemName: badge.symbol).font(.system(size: 8)) if let 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 private func pickMark(_ record: TableRecord) -> some View { 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. private func heldWords(_ record: TableRecord) -> String? { guard selecting, let pick, pick.held.contains(record.id) else { return nil } 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. private func 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 } if let 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. if let copied = definition.tapCopy(record) { toasts.show(RecordActionOutcomes.copy(copied.value, expiresAfter: copied.secret ? SecretClipboard.seconds : nil), tone: .success) return } if let screenRoute { navigator?.rowOpened[screenRoute] = PathRecord(table: definition.id, record: record) } if openInViewer(record) { return } if case .address? = definition.slip.opens { guard let address = definition.slipAddress(record) else { toasts.show(ShellLines.line("lists", "destination.unreadable"), tone: .error) return } if let route = Route.parse(address), let navigator { navigator.push(route) } else if let url = URL(string: address), url.scheme != nil { openURL(url) } else { toasts.show(ShellLines.line("lists", "destination.cannot_open"), tone: .error) } } else if let 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. private func answer(_ record: TableRecord, _ value: String, _ model: RecordListModel) { guard answering == nil else { return } answering = record.id write { defer { answering = nil } return try await 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 private var selectCircles: some View { if let 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. if let 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. private var deletable: [TableRecord] { guard let 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. private func askDelete() { guard let model, !busy else { return } let ids = picked busy = true Task { do { let said = try await model.deleting(ids) busy = false if 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. private func deletePicked(_ said: ListDeleting) { guard let model, !busy else { return } busy = true Task { let outcome = await model.delete(ids: said.ids) busy = false picked = picked.filter { !outcome.deleted.contains($0) } if picked.isEmpty { selecting = false } if let 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. private func addPicked(_ pick: ListPick) { guard let model, !busy else { return } let ids = picked busy = true Task { let outcome: (made: [String], failed: [String]) if let 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.failed let target = definitions[pick.table] let n = outcome.made.count let noun = (n == 1 ? target?.name : target?.plural)?.lowercased() ?? (n == 1 ? "record" : "records") if outcome.failed.isEmpty { if let 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 private var filterRow: some View { 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 in Text("\u{00B7}").font(CottonFonts.type(14)).foregroundStyle(CottonColors.inkTertiary) filterWord(value.word, value: value.value) } } Spacer(minLength: 8) if let review = row.review { Button { menuOpen = true } label: { Text(review).paperHand(16, ink: .red) } .buttonStyle(OpacityButtonStyle()) .accessibilityIdentifier("list-\(definition.id)-waiting") } else if 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) } } private func filterWord(_ word: String, value: String?) -> some View { 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. private func create(_ data: [String: RecordValue]) async -> Bool { guard let model else { return false } do { _ = try await model.create(data) return true } catch { toasts.show(ActionRefused.words(for: error), tone: .error) return false } } /// Writes the reply's words; `true` once they landed. Blank words send /// nothing, and a refused write keeps the sheet up with its words. private func send(_ words: String, for record: TableRecord) async -> Bool { guard let model, let patch = definition.replyPatch(words) else { return false } answering = record.id defer { answering = nil } do { // Its change lands on the model, whose receipt shows it. _ = try await model.write(record, patch) return true } catch { toasts.show(ActionRefused.words(for: error), tone: .error) return false } } /// 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. private func wear(_ change: ChangeRecord, in table: TableDefinition?) { guard let model else { return } let foreign = table.map { $0.id != definition.id } ?? false if let 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 : nil Task { if let 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. private func answerQuestion(_ asked: CreateQuestion, _ option: CreateQuestion.Option) async { guard let store else { return } let result = await OneInputModel.answer(asked, option, records: store, definitions: definitions) question = result.question note = result.change == nil ? OneInputNote.of(result) : nil guard let change = result.change else { return } answersLetGo += 1 wear(change, in: result.table) if let 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 private var receipt: some View { if let model, let change = model.lastChange { ChangeReceipt( change: change, table: receiptTables[change.id] ?? definition, undone: model.lastChangeUndone, onUndone: { _ in Task { 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. private func write(_ act: @escaping () async throws -> ChangeRecord?) { Task { do { // The model reads the list again, its counts with it, after // every write it makes (`RecordListModel.wrote`). _ = try await 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. struct FoldingSectionHeading: View { @Environment(\.theme) private var theme let title: String let count: String let shut: Bool var body: some View { 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. struct SlipPressMenu: ViewModifier { @Environment(\.theme) private var theme @Environment(\.actLift) private var lift @Environment(\.cottonHaptics) private var haptics /// The row's acts, as the core answered them. let acts: [ListAnswer.Press] let identifier: String let record: String let 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 private var frame = RowFrame() func body(content: Content) -> some View { // 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 private func pressed(_ content: Content) -> some View { if let turnsFan { content.highPriorityGesture(LongPressGesture(minimumDuration: PressRule.longPressSeconds).onEnded { _ in haptics.press() turnsFan() }) } else if 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 in Button(act.word) { act.perform() } } } } } private var 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. private var lifts: [LiftedAct] { acts.map { press in LiftedAct(id: "\(identifier)-\(press.act.id)-\(record)", word: press.act.label, object: Self.object(press.act), destroys: press.act.red == true) { act(press) } } } private func hold() { guard let 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-`, `edit-act-`), /// else the one its id names (Archive, Bring back); none for another. static func 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. final class RowFrame { var frame: CGRect? } /// A long-press act held while its question, the core's, is asked. struct PressAsk: Identifiable { let press: ListAnswer.Press let question: ListAnswer.Question let record: TableRecord var id: String { press.id + "/" + record.id } } /// A long-press Bin of a record that repeats, held while it asks how far it reaches. struct ScopeAsk: Identifiable { let record: TableRecord var id: String { record.id } } extension RecordListSurface { /// The head act the list opened to ask, once the head offers it. static func asked(_ head: [RecordAction], id: String?) -> RecordAction? { guard let id else { return nil } 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). static func emptyPicture(_ definition: TableDefinition) -> ToolPicture? { definition.picture } /// `opened` with a folded section tapped: shut if it was open, open if shut. static func toggled(_ opened: Set, _ heading: String) -> Set { var next = opened if next.contains(heading) { next.remove(heading) } else { next.insert(heading) } return next } } private struct RecordsRevisionKey: EnvironmentKey { static let defaultValue = 0 } extension EnvironmentValues { /// 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. public var recordsRevision: Int { get { self[RecordsRevisionKey.self] } set { self[RecordsRevisionKey.self] = newValue } } } private struct CottonListSearchKey: EnvironmentKey { static let defaultValue: Binding? = nil } extension EnvironmentValues { /// Optional host search, so Mac toolbars and phone search read the same list. var cottonListSearch: Binding? { get { self[CottonListSearchKey.self] } set { self[CottonListSearchKey.self] = newValue } } } private extension View { /// 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) -> some View { 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`). enum RecordListSurfaceKnobs { static let 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. private struct ListSearchSlip: View { let inHead: Bool let placeholder: String let identifier: String let open: () -> Void @Environment(\.headCirclesGaveWay) private var gaveWay var body: some View { if !inHead || gaveWay { SearchSlip(placeholder: placeholder, identifier: identifier, action: open) } } }