// Another table's records as one section of a page or a list: its heading// with the count, the records as their own table's slips, and the section's// empty sentence when there are none — a store's orders and its products under// its page, every shop's recent orders under the shops. Driven by the// definition (`PageSection.list`, `TableDefinition.lists`), never by a tool.//// A section linked to the page's record (`SectionList.link`) lists only the// records whose link column names it, and their slips leave that column off:// under a store, an order need not say which store. A blank page has no record// yet, so it draws none of its linked sections.//// A slip opens its record through `recordOpener`, which the route that holds// the page sets, since only it knows where another table's page lives; with// none, the slips are drawn and open nothing. The same opener says whether a// linked section offers "New <name>" — a blank page of that table holding the// link, so a record added from its parent's page belongs to it — and whether// the section's records open whole on a screen of their own ("Reorder// scenes", for an ordered table, where they drag).//// A section may draw its records as their own pages (`face: "page"`), one// after another, read straight through —// or list only the archived ones, faded (`archived`: the archived run under a// list). Its records are split by their table's `group` as its own list is,// each part under its heading and its note. A table whose slip numbers its// records has each one's place written on it.//// A section may draw only a few of its records (`limit`): its heading then// carries no count, and the row under them says the whole and opens it// ("All 2,120", or the section's own `whole` words).// It may draw them several across (`columns`), each as its table's grid cell —// a polaroid for a polaroid table, else a small slip — and merge in other// tables' records linked the same way (`with`), newest first by each table's// own date. A slip's check writes its record through the section's own list,// and its answers (`answers`) too, each read back with its receipt and Undo;// an answer that folds the page's record into another (`moved_to`) hands that// record to the opener, which shows its page instead. A section naming a table// this build has no definition for draws nothing at all — its heading appears// the day the definition lands.//// A section may name its new-row in its own words (`add`: "Add photos"), and// an empty one say a title and a sentence under it. A record that stands for// another (`opens`: an album's picture) opens that one. A table whose records// are ticked together (`select`) offers "Select <plural>": the section's// records whole on their own screen, already ticking.//// A table split by day (`by_day`: the assistant's calls) draws its days as// its list does (`daySections`). A table that opens another record (`opens`:// a run opens the note it wrote) hands the opener that one. A slip's button// is disabled only when it opens nothing AND offers no answer (`inert`): a// queued run has no note, and its Cancel must still be tapped. A refused// answer is said in the store's own words when it carried some (`refusal`),// and a change the store cannot take back offers no Undo. A change made here// wears its receipt over the section's slips.//// A section with a `limit` reads ONE page and counts the whole from the// store's `total` — never every page of a table that may hold thousands: its// heading counts the few against the whole, and when the whole is more, "All// 12" (`whole`) opens the rest as the table's list narrowed by the section's// filter (`FilteredListOpening`, "Orders · Corner Shop"), on a list and on a// page alike. A table split by a choice column (`group`) is drawn in its// sections' order first, then its own `sort` within a section — the order// its list draws — so its page is the store's own size, not the limit, and a// session waiting on the person stands before a newer ended one. A section// narrows by its own `where` too (a value, or an array meaning any of them),// beside the link to the page's record. Under a list it reads with the// list's search (`query`), and one holding nothing draws nothing at all — no// heading over an empty list it cannot add to (R12).//// A slip's own acts (`slipActions`: Allow on a session waiting for a// permission) are drawn under it and run as the list runs them// (`RecordActs`): asking first where the act asks, saying why one was not// done under the slip, and reading the section again after. A slip of a// table the opener has no page for (`RecordOpener(only:)`) is not a button.//// The heading opens the section's whole list through `listOpener`, set by the// same route for the same reason — the repository page's Pull requests open// that repository's pulls. With none, the heading is printed and opens nothing.// A screen that draws its own heading over the section says so (`headed`).importCottonKitimportCottonValuesimportSwiftUI/// Opens a record of any table: whoever holds a page or a list says where.publicstructRecordOpener: Sendable {publictypealiasValues = [String: RecordValue]/// The tables it has a page for; nil, every one. A slip of another table/// is drawn but not as a button, rather than one that opens nothing (a/// repository's branch rules have no page of their own).privatelet tables: Set<String>?privateletopen: @MainActor @Sendable (_ table: String, _ record: TableRecord) -> Void/// The tables a blank page can be opened for, and how.publiclet creates: Set<String>privatelet create: @MainActor @Sendable (_ table: String, _ preset: Values) -> Void/// The tables whose narrowed list opens on a screen of its own, and how.publiclet lists: Set<String>privatelet list: @MainActor @Sendable (_ table: String, _ filter: Values) -> Void/// Where a page goes when a write folded its record into another/// (`ChangeRecord.movedTo`): that record's page, in this one's place.privatelet moved: (@MainActor @Sendable (_ to: RecordRef) -> Void)?publicinit( only tables: Set<String>? = nil, creates: Set<String> = [], create: @escaping @MainActor @Sendable (_ table: String, _ preset: Values) -> Void = { _, _ in }, lists: Set<String> = [], list: @escaping @MainActor @Sendable (_ table: String, _ filter: Values) -> Void = { _, _ in }, moved: (@MainActor @Sendable (_ to: RecordRef) -> Void)? = nil, _ open: @escaping @MainActor @Sendable (_ table: String, _ record: TableRecord) -> Void ) {self.tables = tablesself.open = openself.creates = createsself.create = createself.lists = listsself.list = listself.moved = moved }/// Whether it has a page for `table`'s records.publicfunc opens(_ table: String) -> Bool { tables?.contains(table) ?? true }/// Whether a page can give its place to another record's (`move(to:)`).publicvar moves: Bool { moved != nil }/// Shows the page of the record a write folded the page's record into. @MainActor publicfunc move(to record: RecordRef) { moved?(record) } @MainActor publicfunc callAsFunction(_ table: String, _ record: TableRecord) {open(table, record) }/// Opens a blank page of `table` holding `preset`. @MainActor publicfunc new(_ table: String, _ preset: Values) {guard creates.contains(table) else { return } create(table, preset) }/// Opens `table`'s list narrowed to `filter` on its own screen. @MainActor publicfunc whole(_ table: String, _ filter: Values) {guard lists.contains(table) else { return } list(table, filter) }}privatestructRecordOpenerKey: EnvironmentKey {staticlet defaultValue: RecordOpener? = nil}extensionEnvironmentValues {/// Where a section's slip of another table opens; nil opens nothing.publicvar recordOpener: RecordOpener? { get { self[RecordOpenerKey.self] } set { self[RecordOpenerKey.self] = newValue } }}/// Opens a section's whole list: the table, and the record whose page the/// section is on (nil under a list). Whoever holds the page says where.publicstructListOpener: Sendable {/// The tables it has a list for; nil, every one. A section of another/// table prints its heading, rather than a chevron that opens nothing (a/// repository's branch rules have no list of their own).privatelet tables: Set<String>?privateletopen: @MainActor @Sendable (_ table: String, _ parent: String?) -> Voidpublicinit( only tables: Set<String>? = nil, _ open: @escaping @MainActor @Sendable (_ table: String, _ parent: String?) -> Void ) {self.tables = tablesself.open = open }/// Whether it has a list for `table`.publicfunc opens(_ table: String) -> Bool { tables?.contains(table) ?? true }/// Whether it NAMES `table` among the lists it has: an opener for every/// table does not, so a list link keeps its narrowed list unless the/// screen says it has that table's list (`RecordListSurface.listLinks`).publicfunc names(_ table: String) -> Bool { tables?.contains(table) ?? false } @MainActor publicfunc callAsFunction(_ table: String, _ parent: String?) {open(table, parent) }}privatestructListOpenerKey: EnvironmentKey {staticlet defaultValue: ListOpener? = nil}extensionEnvironmentValues {/// Where a section's heading opens its whole list; nil opens nothing.publicvar listOpener: ListOpener? { get { self[ListOpenerKey.self] } set { self[ListOpenerKey.self] = newValue } }}/// A section's newest change: the table it was made in, whether the store/// can take it back, and whether its receipt already did.structSectionChange {let change: ChangeRecordlet definition: TableDefinitionvar canUndo: Boolvar undone = false}structRecordsSection: View { @Environment(\.theme) privatevar themelet section: PageSection/// The id of the record whose page this is; nil under a list.let parent: String?/// The record whose page this is, for the `{first}` in the heading.var parentRecord: TableRecord? = nil/// The page's own table, which reads the `{first}` off its record.var parentDefinition: TableDefinition? = nil/// The room above the section when it draws; a section that draws/// nothing (no records, no empty sentence) takes none.var top: CGFloat = 0/// Whether the section draws its own heading; false where the screen/// holding it draws one that opens the whole list (a project's Sessions).var headed: Bool = true/// The list's search, under a list that is searched; the section reads/// with it.var query: String = ""/// The title of the list the section stands under (nil on a page): what/// names its whole list when opened ("Recent · Shops").var openedFrom: String? = nil/// What the records of a whole list opened from here open through:/// absent, the section's own opener; a page whose own opener only stands/// in (it pushes on the page) hands none, and the list opens them on its/// own stack.var wholeOpener: RecordOpener?? = nil/// A record page's list as slips (recordslips rule 4): its first rows,/// this many, then one slip saying how many more that opens the list.var slipRows: Int? = nil/// The words of that slip for the rows left ("and 12 more").var moreWords: (Int) -> String? = { _ innil }/// A row write can change the parent page's counts and facts too.var onWrite: (@MainActor () async -> Void)? = nil @Environment(\.tableDefinitions) privatevar definitions @Environment(DatabaseScene.self) privatevar scene: DatabaseScene? @Environment(DatabasesModel.self) privatevar databases: DatabasesModel? @Environment(\.records) privatevar store @Environment(\.cottonCore) privatevar core @Environment(\.recordOpener) privatevar opener @Environment(\.listOpener) privatevar listOpener @Environment(\.recordsRevision) privatevar revision/// The page's own link titles: a section's slips draw these under the/// titles their own list read (`slipTitles`). @Environment(\.linkTitles) privatevar pageTitles @Environment(\.keptFlow) privatevar keptFlow @Environment(\.openURL) privatevar openURL @Environment(ToastCenter.self) privatevar toasts @Environment(Navigator.self) privatevar navigator: Navigator?/// The screen's place on the path, where the row opened is noted. @Environment(\.screenRoute) privatevar screenRoute/// The screen it is on is on the navigator's path (`FilteredListOpening.open`). @Environment(\.listsOnPath) privatevar listsOnPath @State privatevar model: RecordListModel?/// The section's records whole on their own screen, ticking (`select`). @State privatevar selectingWhole = false/// A blank page for a new record of the section's table is open. @State privatevar composing = false/// The lists of the tables merged in (`with`), each its own read. @State privatevar others: [RecordListModel] = []/// The record whose answer is on its way: its verbs wait. @State privatevar answering: String?/// The acts under the slips, the one asking first, and why one was not done. @State privatevar acts: RecordActs?/// A value an act showed once, until "I've saved it". @State privatevar revealed: RevealedValue?/// The newest change a slip here made — a tick, an answer, an act — on/// its receipt over the slips, until it is let go or the next replaces it. @State privatevar landed: SectionChange?/// The whole of a capped section, opened as its table's narrowed list. @State privatevar filteredOpen: FilteredListOpening?/// The whole of a capped section that merges other tables into its own/// (`with`), on a screen of its own: every record it counts, merged. @State privatevar mergedWhole = false/// The search the section's last read answered; nil before one landed. @State privatevar readQuery: String?/// The column values every listed record holds: the link naming the/// page's record, or nothing for an unlinked section. Nil when the/// section is linked and there is no record to name (a blank page).staticfunc filter(_ list: SectionList, parent: String?) -> [String: RecordValue]? {guardlet link = list.link else { return list.where }guardlet parent, !parent.isEmpty else { returnnil }return list.where.merging([link: .text(parent)]) { _, link in link } }/// How many records a page of the section asks for: its few when it is/// capped and its table draws in the store's order; the store's own page/// for a table it groups itself (a later part's newer record must not/// push an earlier part's off), and for a section that is not capped.staticfunc pageSize(_ list: SectionList, of definition: TableDefinition) -> Int? {guardlet limit = list.limit, definition.group == nilelse { returnnil }return max(1, limit) }/// The heading's count: how many are drawn, with a "+" while more are/// still to be read; nothing for none.staticfunc count(shown: Int, more: Bool) -> String? {guard shown > 0else { returnnil }return more ? "\(shown)+" : "\(shown)" }/// The slips a section draws: the first `limit`, or every one.staticfunc drawn(_ records: [TableRecord], limit: Int?) -> [TableRecord] {guardlet limit else { return records }returnArray(records.prefix(max(0, limit))) }/// The heading's count as a board's section says it: how many are read,/// with a "+" while more are still to be read, and the few drawn against/// them where a limit drew fewer ("3 of 40"); nothing for none.staticfunc count(drawn: Int, read: Int, more: Bool) -> String? {guard read > 0else { returnnil }let whole = more ? "\(read)+" : "\(read)"return drawn < read ? ShellLines.line("lists", "drawn_of", ["drawn": "\(drawn)", "whole": whole]) : whole }/// Reads the section: ONE page, of the size the model asks for/// (`pageSize`) — the whole is counted from the store's total, never by/// reading every page. A section that is not capped reads its later/// pages as its last slip scrolls into view.staticfunc read(_ model: RecordListModel, limit: Int?, query: String = "") async {await model.reload(project: nil, query: query) }/// How many records the section holds in all: the store's totals of its/// own table and the merged ones, or nil when one did not say.staticfunc total(_ models: [RecordListModel]) -> Int? {var sum = 0for model in models {guardlet total = model.total else { returnnil } sum += total }return sum }/// Whether a capped section draws the row that opens its whole: its/// whole holds more than it draws.staticfunc opensWhole(_ list: SectionList, total: Int?, recordPage: Bool = false) -> Bool {guardlet limit = list.limit, let total, !list.archived else { returnfalse }return total > (recordPage ? 0 : limit) }/// The row's words: the section's own (`whole`), else the core's/// `lists.whole` for the total ("All 2,120"). @MainActorstaticfunc wholeLabel(_ list: SectionList, total: Int) -> String { list.whole ?? CountLines.shared.line("lists", "whole", n: total) ?? "" }/// What the heading does when pressed: open the section's whole list,/// or nothing where no list opener is set or it has no list for the/// section's table. @MainActorstaticfunc opensList(_ list: SectionList, parent: String?, with opener: ListOpener?) -> (@MainActor () -> Void)? {guardlet opener, opener.opens(list.table) else { returnnil }return { opener(list.table, parent) } }privatestructRead: Equatable {var parent: String?var revision: Intvar query: String }/// The tables a section draws records of, each with the filter that/// narrows it: its own, then each `with` table this build has a/// definition for — one it has none for adds nothing. Nil when the/// section's own table has no definition (the section draws nothing) or/// it is linked and there is no record to name.staticfunc sources( _ list: SectionList, parent: String?, in definitions: TableDefinitions ) -> [(definition: TableDefinition, filter: [String: RecordValue])]? {guardlet table = definitions[list.table], let filter = filter(list, parent: parent) else { returnnil }let own = (table, filter)let merged = list.with.compactMap { link -> (TableDefinition, [String: RecordValue])? inguardlet other = definitions[link.table], let parent, !parent.isEmpty else { returnnil }return (other, [link.link: .text(parent)]) }return [own] + merged }var body: someView {iflet list = section.drawnList, let sources = Self.sources(list, parent: parent, in: definitions),let own = sources.first {let (definition, filter) = (own.definition, own.filter) VStack(alignment: .leading, spacing: 0) {// Something on screen before the first read lands, so the// read below has a view to run on.Color.clear.frame(height: 0) content(definition, list) } .frame(maxWidth: .infinity, alignment: .leading)// What the search found here, for the list it stands on: its// "nothing matches" waits for every section's read to land. .preference(key: SectionFindsKey.self, value: finds(list, definition)) .task(id: Read(parent: parent, revision: revision, query: query)) {guardlet store else { return }if !query.isEmpty {// Typing reads once the fingers pause, as the list does.try? awaitTask.sleep(for: .milliseconds(250))guard !Task.isCancelled else { return } }let model = self.model.flatMap { $0.filter == filter ? $0 : nil } ?? RecordListModel( definition: definition, store: store, core: core, archived: list.archived, where: filter, pageSize: Self.pageSize(list, of: definition))self.model = modelif acts?.filter != filter { acts = RecordActs(table: definition.id, where: filter) }let others = sources.dropFirst().map { source inself.others.first { $0.definition.id == source.definition.id && $0.filter == source.filter } ?? RecordListModel( definition: source.definition, store: store, core: core, where: source.filter, pageSize: Self.pageSize(list, of: source.definition)) }self.others = othersawaitSelf.read(model, limit: list.limit, query: query)for other in others { awaitSelf.read(other, limit: list.limit, query: query) }guard !Task.isCancelled else { return } readQuery = query }// Back from one of its records, which may have moved on. .reloadOnReturn { await reloadAll(list) } .pageDestination(isPresented: $composing) {iflet table = definitions[list.table], let link = list.link, let parent {RecordOpening(definition: table, opens: .blank([link: .text(parent)])).cottonScreenFrame() } } .pageDestination(isPresented: $selectingWhole) {TableListRoute(table: list.table, where: filter, selecting: true).cottonScreenFrame() } .pageDestination(isPresented: $mergedWhole) {// "All n" of a merged section holds the same n it counts// (S6): the section itself, uncapped, under its own title.PaperScreen(title: wholeTitle(definition, list)) {RecordsSection( section: Self.uncapped(section), parent: parent, parentRecord: parentRecord, parentDefinition: parentDefinition, headed: false) } .cottonScreenFrame() .environment(\.records, store) .environment(\.tableDefinitions, definitions) .environment(\.recordOpener, opener) } .filteredList($filteredOpen, store: store, definitions: definitions, opener: wholeOpener ?? opener) } }/// Whether the section holds records for the search it is showing, and/// whether that search's read is still on its way.privatefunc finds(_ list: SectionList, _ definition: TableDefinition) -> SectionFinds {let pending = readQuery != query || model.map { $0.phase == .loading } ?? truelet holds = model.map { !Self.shown($0.records, of: definition, list).isEmpty } == true || others.contains { !$0.records.isEmpty }returnSectionFinds(holds: holds && !pending, pending: pending) }privatefunc reloadAll(_ list: SectionList) async {iflet model { awaitSelf.read(model, limit: list.limit, query: query) }for other in others { awaitSelf.read(other, limit: list.limit, query: query) } }/// The section's heading as drawn: its own words (the page's `{first}`/// filled), else its table's plural.privatefunc title(_ definition: TableDefinition) -> String {let heading = parentDefinition?.words(section.heading, for: parentRecord) ?? section.heading ?? definition.pluralreturnSelf.heading(heading, of: section.drawnList, topLevel: parent == nil, query: query) }/// A list's own section, searched, finds in the whole table rather than/// its few: it is headed by its `whole` words ("Movements", not/// "Recent") while the search is on; else by its heading.staticfunc heading(_ heading: String, of list: SectionList?, topLevel: Bool, query: String) -> String {guard topLevel, !query.isEmpty, let list else { return heading }returnFilteredListOpening.wholeTitle(list, heading: heading) }/// Opens the whole of a capped section: the opener's own screen for the/// table where it has one (a person's todos), else the table's list/// narrowed by the section's filter, named by the section's `whole` words/// (else its heading) and the words heading the page's record — or the/// list it stands under ("Movements · Accounts") — carrying the list's/// search.privatefunc openWhole(_ definition: TableDefinition, _ list: SectionList, _ filter: [String: RecordValue]) {// A merged section's whole is every table it counts, never its own// table's list alone — that list would hold fewer than "All n" says.if !list.with.isEmpty { mergedWhole = truereturn }iflet opener, opener.lists.contains(list.table) { opener.whole(list.table, filter)return }FilteredListOpening(table: list.table, filter: filter, title: wholeTitle(definition, list), query: query) .open(on: navigator, onPath: listsOnPath, else: $filteredOpen) }/// What the whole of the section is called on its own screen: its `whole`/// words (else its heading) and the words heading the page's record.privatefunc wholeTitle(_ definition: TableDefinition, _ list: SectionList) -> String {let name = parentRecord?.said?.slip.heading ?? openedFromreturnFilteredListOpening.title(FilteredListOpening.wholeTitle(list, heading: title(definition)), of: name) }/// The section with no cap: what its "All n" opens when it merges tables.staticfunc uncapped(_ section: PageSection) -> PageSection {var whole = section whole.list?.limit = nilreturn whole }/// What an act's outcome does to this section: a record it made opens/// through the opener, a value shows once over the slips, a change wears/// the section's receipt, and the section is read again.privatefunc actSurface(_ definition: TableDefinition, _ list: SectionList) -> RecordActSurface {RecordActSurface(open: { id inTask {guardlet record = try? await store?.get(table: definition.id, id: id) else { return } opener?(definition.id, record) } }, reveal: { revealed = $0 }, received: { change in landed = SectionChange(change: change, definition: definition, canUndo: true) }, reread: {await reloadAll(list)await onWrite?() }, current: { id in model?.records.first { $0.id == id } }, keptFlow: keptFlow, navigator: navigator, openURL: openURL, toasts: toasts) }/// The section's rows in the order drawn: its own records in the order/// the core answered them (`shell.list`) — a todo's open ones, soonest/// first, before its done — merged with the `with` tables' newest first/// when it has any.privatefunc rows(_ definition: TableDefinition, _ shown: [TableRecord]) -> [SectionRow] {let own = shown.map { SectionRow(definition: definition, record: $0) }guard !others.isEmpty else { return own }let more = others.filter { $0.phase == .loaded }.flatMap { other in other.records.map { SectionRow(definition: other.definition, record: $0) } }returnSectionRow.merged(own + more) }/// The records the section draws: only the archived ones on an archived/// run, else every one its list holds.staticfunc shown(_ records: [TableRecord], of definition: TableDefinition, _ list: SectionList) -> [TableRecord] { list.archived ? records.filter { $0.said?.archived == true } : records }/// "New scene", on a linked section of a table the opener can open a/// blank page for: the page holds the link to the record this page is of. @ViewBuilder privatefunc newRow(_ definition: TableDefinition, _ list: SectionList) -> someView {iflet opener, let link = list.link, let parent, !list.archived, opener.creates.contains(list.table) {TypedRow(symbol: "plus", label: list.add ?? model?.sectionWords?.new ?? "", chevron: false) { opener.new(list.table, [link: .text(parent)]) } .accessibilityIdentifier("section-\(list.table)-new") } elseif definition.create != nil || list.add != nil, let link = list.link, let parent, !parent.isEmpty, !list.archived,let held = definitions[list.table]?.column(link), !held.multiple {// A declared table or section add opens a blank page holding// its parent link, even when the table takes no standalone add.TypedRow(symbol: "plus", label: list.add ?? model?.sectionWords?.create ?? "", chevron: false) { composing = true } .accessibilityIdentifier("section-\(list.table)-new") } }/// The narrowed list on its own screen: "Reorder scenes" for a table/// with an order (it drags there), else "All <plural>". @ViewBuilder privatefunc wholeRow(_ definition: TableDefinition, _ list: SectionList, _ filter: [String: RecordValue]) -> someView {if list.limit != nil { cappedRow(definition, list, filter) } elseif !list.with.isEmpty {// A merged section drawn whole is already every record it holds:// no row to its own table's list, which would hold fewer.EmptyView() } elseif definition.select != nil, list.link != nil, !list.archived, opener?.lists.contains(list.table) != true {// A table whose records are ticked and acted on together (an// album's pictures, removed from it): the section's records whole// on their own screen, already ticking.TypedRow(symbol: "checkmark.circle", label: model?.sectionWords?.select ?? "") { selectingWhole = true } .accessibilityIdentifier("section-\(list.table)-select") } elseiflet opener, opener.lists.contains(list.table), list.face == .slip, !list.archived {let label = (definition.order != nil ? model?.sectionWords?.reorder : model?.sectionWords?.all) ?? ""TypedRow(symbol: definition.order != nil ? "arrow.up.arrow.down" : "list.bullet", label: label) { opener.whole(list.table, filter) } .accessibilityIdentifier("section-\(list.table)-whole") } }/// Under a capped section: "Reorder <plural>" for an ordered table the/// opener drags on its own screen; else, when its whole holds more than/// it draws, the row that opens the whole ("All 12"). @ViewBuilder privatefunc cappedRow(_ definition: TableDefinition, _ list: SectionList, _ filter: [String: RecordValue]) -> someView {let total = Self.total([model].compactMap { $0 } + others)if list.with.isEmpty, definition.order != nil, let opener, opener.lists.contains(list.table), list.face == .slip, !list.archived {TypedRow(symbol: "arrow.up.arrow.down", label: model?.sectionWords?.reorder ?? "") { opener.whole(list.table, filter) } .accessibilityIdentifier("section-\(list.table)-whole") } elseifSelf.opensWhole(list, total: total, recordPage: parent != nil), let total {TypedRow(symbol: "list.bullet", label: Self.wholeLabel(list, total: total)) { openWhole(definition, list, filter) } .accessibilityIdentifier("section-\(list.table)-whole") } } @ViewBuilder privatefunc content(_ definition: TableDefinition, _ list: SectionList) -> someView {iflet model, let acts, model.phase == .loaded { loaded(model, definition, list) .askingFirst(acts, identifier: "section-\(list.table)-confirm-action") { acts.perform($0.action, on: $0.record, store: store, surface: actSurface(definition, list)) } onAnswer: { asked, values inawait acts.answer(asked, values: values, store: store, surface: actSurface(definition, list)) } } elseiflet model, model.phase == .failed {// A read that failed is said under the heading, never drawn as a// list that holds nothing: "none" is only ever said of a read// that answered. VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {if headed { heading(title(definition), count: nil, list) }Text(CouldNotRead.said(model.readStall, otherwise: model.readProblem, scene: scene, databases: databases, definitions: definitions) ?? ShellLines.line("lists", "unreadable.said", ["plural": definition.plural])) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("section-\(list.table)-refusal") } .padding(.top, top) } } @ViewBuilder privatefunc loaded( _ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList ) -> someView {let title = self.title(definition)let read = Self.shown(model.records, of: definition, list)let shown = slipRows.map { Array(read.prefix($0)) } ?? readlet all = rows(definition, shown)let more = model.hasMore || others.contains { $0.hasMore }let gathers = list.limit != nil || list.columns != nil || !list.with.isEmptyif all.isEmpty && !more {// Under a list, none is nothing: no heading over an empty list// the section cannot add to (R12).if parent != nil, let empty = list.empty { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {if headed { heading(title, count: nil, list) } VStack(alignment: .leading, spacing: 4) {// `{title}` in the words is the page's own name.Text(parentDefinition?.words(empty, for: parentRecord) ?? empty) .paperMeta(13) .fixedSize(horizontal: false, vertical: true)iflet message = parentDefinition?.words(list.emptyMessage, for: parentRecord) ?? list.emptyMessage {Text(message) .paperHand(15, ink: .pencil) .fixedSize(horizontal: false, vertical: true) } } .accessibilityIdentifier("section-\(list.table)-empty") receipt(list)if slipRows == nil { newRow(definition, list) } } .padding(.top, top) } } else { VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {if headed { heading( title, count: gathers ? Self.gatheredCount(list, all, more: more, total: Self.total([model] + others), recordPage: parent != nil) : Self.count(shown: shown.count, more: model.hasMore), list ) .accessibilityIdentifier("section-\(list.table)") }iflet revealed {RevealedValueCard( revealed: revealed, identifier: "section-\(list.table)", onCopy: { toasts.show(RecordActionOutcomes.copy(revealed.value, expiresAfter: SecretClipboard.seconds), tone: .success) }, onSaved: { self.revealed = nil }) } receipt(list)if gathers { gathered(definition, list, all) } else { whole(model, definition, list, shown) } moreRow(model, definition, list, read: read.count) } .padding(.top, top) } }/// Every record the section holds, part by part. Lazy, so the next-page/// marker is made only when the last slip scrolls into view: in a plain/// stack it would appear at once after every page and read the whole/// table ("Recent orders" every order ever), and the "+" would never stand. @ViewBuilder privatefunc whole( _ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList, _ shown: [TableRecord] ) -> someView {LazyVStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {ForEach(Array(Self.parts(model.sections, shown: shown).enumerated()), id: \.offset) { _, part iniflet heading = part.heading {// A part of the section, under the section's own heading:// printed, never a door to the list.self.heading(heading, count: part.said ?? "\(part.records.count)", list, opens: false) .padding(.top, 8) .accessibilityIdentifier("section-\(list.table)-part-\(heading)") }iflet note = part.note {Text(note) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) }ForEach(part.records) { record inif slipRows != nil { listSlip(definition, record) } else {switch list.face {case .slip: slip(definition, record, ordinal: model.row(record.id)?.place, faded: list.archived)case .page: page(definition, record, ordinal: model.row(record.id)?.place) } } } }if model.hasMore, slipRows == nil {Color.clear .frame(height: 1) .id(model.records.count) .onAppear { Task { await model.loadMore() } } }// A record page's list adds on its own page and in the tray's// Edit, and says "and N more" instead of "All N" (R3).if !model.hasMore, slipRows == nil, let filter = Self.filter(list, parent: parent) { newRow(definition, list) wholeRow(definition, list, filter) } } }/// The parts the core answered the section's list in (`shell.list`'s/// sections, each with its heading, count and note), each holding only/// the records drawn (`shown`: the archived run's, a page's first few); a/// part left with none is not drawn.staticfunc parts(_ sections: [RecordSection], shown: [TableRecord]) -> [RecordSection] {let drawn = Set(shown.map(\.id))return sections.compactMap { section invar part = section part.records = section.records.filter { drawn.contains($0.id) }return part.records.isEmpty ? nil : part } }/// Under a record page's first rows: one slip saying how many more, that/// opens the list (recordslips rule 4) — its words the slips table's. @ViewBuilder privatefunc moreRow(_ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList, read: Int) -> someView {iflet rows = slipRows, let filter = Self.filter(list, parent: parent) {let total = Self.total([model] + others) ?? readif total > rows, let words = moreWords(total - rows) {ListSlip(title: words) { openWhole(definition, list, filter) } .accessibilityIdentifier("section-\(list.table)-more") } } }/// The section's heading: with a list opener, a button that opens the/// whole list, wearing the chevron a project page's heading wears; else/// the printed heading alone. A part's heading (`opens: false`) is/// printed only. @ViewBuilder privatefunc heading(_ title: String, count: String?, _ list: SectionList, opens: Bool = true) -> someView {if opens, letopen = Self.opensList(list, parent: parent, with: listOpener) {Button(action: open) { HStack(alignment: .center, spacing: 3) {PaperSection(title: title, count: count)Image(systemName: "chevron.right") .font(.system(size: 9, weight: .semibold)) .foregroundStyle(theme.print(.pencil)) .padding(.trailing, 2) } .frame(minHeight: 32) .contentShape(Rectangle()) } .buttonStyle(OpacityButtonStyle()) .accessibilityAddTraits(.isHeader) } else {PaperSection(title: title, count: count) } }/// The newest change a slip here made, read back as its receipt; its Undo/// reads the section again, Done lets it go. @ViewBuilder privatefunc receipt(_ list: SectionList) -> someView {iflet landed {ChangeReceipt( change: landed.change, table: landed.definition, canUndo: landed.canUndo, undone: landed.undone, onUndone: { _ inself.landed?.undone = trueTask {await reloadAll(list)await onWrite?() } }, onDismiss: { self.landed = nil }) .id(landed.change.id) .accessibilityIdentifier("section-\(list.table)-receipt") } }/// Opens a record: what it stands for (`opens`), else its own page.privatefuncopen(_ definition: TableDefinition, _ record: TableRecord) {// The row this screen opened, so the page pushed over it leaves out// a link that would only lead back to it (`Navigator.rowOpened`).iflet screenRoute { navigator?.rowOpened[screenRoute] = PathRecord(table: definition.id, record: record) }iflet target = definition.opening(record) { opener?(target.table, TableRecord(id: target.id, values: [:])) } else { opener?(definition.id, record) } }/// A section drawing a few of its records (`limit`), several across/// (`columns`) or merged with other tables' (`with`): one run, no parts,/// under a heading that counts what it shows against the whole. @ViewBuilder privatefunc gathered( _ definition: TableDefinition, _ list: SectionList, _ all: [SectionRow] ) -> someView {let drawn = list.limit.map { Array(all.prefix(max(0, $0))) } ?? all VStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) {// A record page's list is link slips one under another, whatever// the list lays out on its own page (R3: a person's Todos drew// coloured slips several across).switch slipRows == nil ? Self.gatheredLayout(list, definition: definition) : .stack {case .grid(let across):PaperCollection(drawn, layout: .grid(columns: across), spacing: 12) { row, _ in cell(row) }case .row(let across):// Slips several across are a row: they share the column but// never go below a slip's own width, and scroll when they do// not fit (`PaperRow`).PaperRow(drawn, across: across, spacing: 12) { row in cell(row) }case .stack:ForEach(drawn) { row inif slipRows != nil { listSlip(row.definition, row.record) } else { slip(row.definition, row.record, ordinal: nil, faded: false) } } }// Uncapped (a merged section's whole): the next pages are read as// its last slip shows, each table's own.if list.limit == nil, model?.hasMore == true || others.contains(where: \.hasMore) {Color.clear.frame(height: 1) .id(all.count) .onAppear {Task {await model?.loadMore()for other in others { await other.loadMore() } } } }// A record page's capped list says "and N more" and adds on its// own page (R3).if slipRows == nil, let filter = Self.filter(list, parent: parent) { newRow(definition, list) wholeRow(definition, list, filter) } } }/// How a gathered section lays its records out: one under another; prints/// several across in a grid; or slips several across in a row.enumGatheredLayout: Equatable {case stackcase grid(across: Int)case row(across: Int) }staticfunc gatheredLayout(_ list: SectionList, definition: TableDefinition) -> GatheredLayout {guardlet across = list.columns, across > 1else { return .stack }return definition.drawsPolaroids ? .grid(across: across) : .row(across: across) }/// A gathered section's count: what it draws where nothing limits it;/// nothing over a capped one — its whole is said by the row that opens/// it ("All 2,120"), never as "10 / 2120" in the heading (R7(e)). @MainActorstaticfunc gatheredCount(_ list: SectionList, _ all: [SectionRow], more: Bool, total: Int? = nil, recordPage: Bool = false) -> String? {if recordPage { return total.flatMap { CountLines.shared.line("lists", "count", n: $0) } }guard list.limit == nilelse { returnnil }return count(shown: all.count, more: more) }/// One record as its table's grid cell: its polaroid, or a small slip. @ViewBuilder privatefunc cell(_ row: SectionRow) -> someView {let definition = StoriesPresentation.pictureDefinition(row.definition)let record = StoriesPresentation.displayed(row.record, definition: definition)if row.definition.tile.face == .polaroidGrid {Button { open(row.definition, row.record) } label: {PolaroidFace(definition: definition, record: record, width: 120, fills: true) } .buttonStyle(MotionButtonStyle()) .disabled(!(opener?.opens(row.definition.id) ?? false)) .accessibilityIdentifier("\(row.definition.id)-\(row.record.id)") } else { slip(row.definition, row.record, ordinal: nil, faded: false, compact: true) } }/// A record page's list row: a link slip of the page's paper, the row's/// title over its line, that opens the row (R3).privatefunc listSlip(_ definition: TableDefinition, _ record: TableRecord) -> someView {let links = Self.slipTitles(page: pageTitles, list: list(of: definition)?.linkTitles).byIDlet title = record.said?.slip.title ?? ""let line = record.said?.slip.subtitlereturnListSlip(title: title, line: line == title ? nil : line) { open(definition, record) } .accessibilityIdentifier("section-\(definition.id)-\(record.id)") .modifier(UnreadUnderTheFan()) }privatefunc slip( _ definition: TableDefinition, _ record: TableRecord, ordinal: Int?, faded: Bool, compact: Bool = false ) -> someView {let model = list(of: definition)// The check writes through the list the record was read in, unless// the column or the record is read-only — then it is drawn, not a control.let toggle: (() -> Void)? = definition.column(definition.slip.toggle) .flatMap { !$0.readonly && record.said?.readOnly != true ? model : nil } .map { model in { write(definition) { tryawait model.toggle(record) } } }let answer: ((String) -> Void)? = model.map { model in { value inself.answer(definition, model, record, value) } }// The slip's own acts, under it: each acts on this record, never// opens it — the slip itself does that. A merged table's slip (`with`)// has none: the section reads the acts of its own table only.let acts = self.acts.flatMap { $0.table == definition.id ? $0 : nil } ?? RecordActs(table: definition.id)let list = section.drawnList ?? SectionList(table: definition.id)returnActedSlip( acts: acts, record: record, store: store, identifier: "section-\(definition.id)-\(record.id)", onTap: { action in acts.tapped(action, on: record, store: store, surface: actSurface(definition, list)) } ) { HStack(alignment: .center, spacing: 10) {Button {open(definition, record) } label: {SlipFace( definition: definition, record: record, onToggle: toggle, compact: compact, ordinal: ordinal, upcoming: definition.upcoming != nil, onAnswer: answer, answering: answering == record.id) .environment(\.linkTitles, Self.slipTitles(page: pageTitles, list: model?.linkTitles)) } .buttonStyle(.plain) .disabled(Self.inert( canOpen: (opener?.opens(definition.id) ?? false) || toggle != nil, offersAnswer: definition.slip.answers != nil))iflet key = parentDefinition?.resolvedParts.lists.first(where: { $0.matches(list, parent: parentRecord) })?.mainAct,let command = definition.commands?.first(where: { $0.id == key && $0.applies(to: record) && !$0.needsPick }) {RecordRowCommandChip(command: command, identifier: "section-\(definition.id)-\(record.id)-command-\(command.id)") {guardlet engine = store as? any RecordCommandselse { throwActionRefused(ShellLines.line("lists", "action_unavailable")) }let change = tryawait engine.command(table: definition.id, id: record.id, command: command)var canUndo = change.undoableiflet confirming = store as? any ConfirmingRecords { canUndo = await confirming.canUndo(change: change.id) } landed = SectionChange(change: change, definition: definition, canUndo: canUndo)await reloadAll(list)await onWrite?() } } } } .opacity(record.said?.dimmed == true || faded ? 0.6 : 1) .accessibilityElement(children: .contain) .accessibilityIdentifier("\(definition.id)-\(record.id)") .modifier(UnreadUnderTheFan()) }/// The titles a section's slip draws its link columns with: the page's/// (which name only the page record's own links) under the titles the/// section's list read for its rows — a store's orders name their/// customers, a project's todos their goals. The list's reading wins, as/// `RecordListSurface`'s title merges it.staticfunc slipTitles(page: LinkTitles, list: LinkTitles?) -> LinkTitles { page.merging(list ?? LinkTitles()) }/// The list a record of `definition` was read in: the section's own, or/// a merged table's.privatefunc list(of definition: TableDefinition) -> RecordListModel? { model?.definition.id == definition.id ? model : others.first { $0.definition.id == definition.id } }/// Writes one of a slip's answers, its verbs waiting while it is on its/// way; an answer that folded the page's record into another shows that/// record's page.privatefunc answer(_ definition: TableDefinition, _ model: RecordListModel, _ record: TableRecord, _ value: String) {guard answering == nilelse { return } answering = record.id write(definition) {defer { answering = nil }let change: ChangeRecord?do { change = tryawait model.answer(record, value) } catch {// Refused (a run no longer queued): the section reads again,// so the slip shows the state the store found.await model.reload(project: nil, query: "")throw error }iflet to = change?.movedTo, to.id != parent { opener?.move(to: to) }return change } }/// Runs one write and reads its change back on the section's receipt,/// or says it failed.privatefunc write( _ definition: TableDefinition, _ act: @escaping () asyncthrows -> ChangeRecord? ) {Task {do {guardlet change = tryawait act() else { return }// A change the store cannot take back (a cancelled run is// gone) is shown without an Undo.var undoes = trueiflet confirming = store as? any ConfirmingRecords { undoes = await confirming.canUndo(change: change.id) } landed = SectionChange(change: change, definition: definition, canUndo: undoes)await onWrite?() } catch { toasts.show(Self.refusal(error), tone: .error) } } }/// The record as its own card, read in place; a tap opens it.privatefunc page(_ definition: TableDefinition, _ record: TableRecord, ordinal: Int?) -> someView {Button { opener?(definition.id, record) } label: {RecordCardFace(definition: definition, record: record) } .buttonStyle(.plain) .disabled(!(opener?.opens(definition.id) ?? false)) .accessibilityIdentifier("\(definition.id)-\(record.id)-page") .modifier(UnreadUnderTheFan()) }/// Whether a slip's own button is disabled: it opens nothing AND offers/// no answer. `.disabled` reaches every button drawn inside the slip, so/// a queued run (no note to open) must stay enabled or its Cancel is dead.staticfunc inert(canOpen: Bool, offersAnswer: Bool) -> Bool { !canOpen && !offersAnswer }/// A refused write in its own words when it carried some — the engine/// names the state it found — else the generic sentence.staticfunc refusal(_ error: any Error) -> String {iflet refused = error as? ActionRefused { return refused.sentence }iflet said = (error as? CottonCallError)?.message, !said.isEmpty { return said }returnShellLines.line("lists", "change_not_saved") }}/// What the sections a list stands on found, together: whether any holds a/// record, and whether any read is still on its way.structSectionFinds: Equatable {var holds = falsevar pending = false}structSectionFindsKey: PreferenceKey {staticlet defaultValue = SectionFinds()staticfunc reduce(value: inoutSectionFinds, nextValue: () -> SectionFinds) {let next = nextValue() value = SectionFinds(holds: value.holds || next.holds, pending: value.pending || next.pending) }}