// 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 " — 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 ": 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`). import CottonKit import CottonValues import SwiftUI /// Opens a record of any table: whoever holds a page or a list says where. public struct RecordOpener: Sendable { public typealias Values = [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). private let tables: Set? private let open: @MainActor @Sendable (_ table: String, _ record: TableRecord) -> Void /// The tables a blank page can be opened for, and how. public let creates: Set private let create: @MainActor @Sendable (_ table: String, _ preset: Values) -> Void /// The tables whose narrowed list opens on a screen of its own, and how. public let lists: Set private let 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. private let moved: (@MainActor @Sendable (_ to: RecordRef) -> Void)? public init( only tables: Set? = nil, creates: Set = [], create: @escaping @MainActor @Sendable (_ table: String, _ preset: Values) -> Void = { _, _ in }, lists: Set = [], 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 = tables self.open = open self.creates = creates self.create = create self.lists = lists self.list = list self.moved = moved } /// Whether it has a page for `table`'s records. public func opens(_ table: String) -> Bool { tables?.contains(table) ?? true } /// Whether a page can give its place to another record's (`move(to:)`). public var moves: Bool { moved != nil } /// Shows the page of the record a write folded the page's record into. @MainActor public func move(to record: RecordRef) { moved?(record) } @MainActor public func callAsFunction(_ table: String, _ record: TableRecord) { open(table, record) } /// Opens a blank page of `table` holding `preset`. @MainActor public func 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 public func whole(_ table: String, _ filter: Values) { guard lists.contains(table) else { return } list(table, filter) } } private struct RecordOpenerKey: EnvironmentKey { static let defaultValue: RecordOpener? = nil } extension EnvironmentValues { /// Where a section's slip of another table opens; nil opens nothing. public var 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. public struct ListOpener: 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). private let tables: Set? private let open: @MainActor @Sendable (_ table: String, _ parent: String?) -> Void public init( only tables: Set? = nil, _ open: @escaping @MainActor @Sendable (_ table: String, _ parent: String?) -> Void ) { self.tables = tables self.open = open } /// Whether it has a list for `table`. public func 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`). public func names(_ table: String) -> Bool { tables?.contains(table) ?? false } @MainActor public func callAsFunction(_ table: String, _ parent: String?) { open(table, parent) } } private struct ListOpenerKey: EnvironmentKey { static let defaultValue: ListOpener? = nil } extension EnvironmentValues { /// Where a section's heading opens its whole list; nil opens nothing. public var 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. struct SectionChange { let change: ChangeRecord let definition: TableDefinition var canUndo: Bool var undone = false } struct RecordsSection: View { @Environment(\.theme) private var theme let 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? = { _ in nil } /// A row write can change the parent page's counts and facts too. var onWrite: (@MainActor () async -> Void)? = nil @Environment(\.tableDefinitions) private var definitions @Environment(DatabaseScene.self) private var scene: DatabaseScene? @Environment(DatabasesModel.self) private var databases: DatabasesModel? @Environment(\.records) private var store @Environment(\.cottonCore) private var core @Environment(\.recordOpener) private var opener @Environment(\.listOpener) private var listOpener @Environment(\.recordsRevision) private var revision /// The page's own link titles: a section's slips draw these under the /// titles their own list read (`slipTitles`). @Environment(\.linkTitles) private var pageTitles @Environment(\.keptFlow) private var keptFlow @Environment(\.openURL) private var openURL @Environment(ToastCenter.self) private var toasts @Environment(Navigator.self) private var navigator: Navigator? /// The screen's place on the path, where the row opened is noted. @Environment(\.screenRoute) private var screenRoute /// The screen it is on is on the navigator's path (`FilteredListOpening.open`). @Environment(\.listsOnPath) private var listsOnPath @State private var model: RecordListModel? /// The section's records whole on their own screen, ticking (`select`). @State private var selectingWhole = false /// A blank page for a new record of the section's table is open. @State private var composing = false /// The lists of the tables merged in (`with`), each its own read. @State private var others: [RecordListModel] = [] /// The record whose answer is on its way: its verbs wait. @State private var answering: String? /// The acts under the slips, the one asking first, and why one was not done. @State private var acts: RecordActs? /// A value an act showed once, until "I've saved it". @State private var 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 private var landed: SectionChange? /// The whole of a capped section, opened as its table's narrowed list. @State private var 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 private var mergedWhole = false /// The search the section's last read answered; nil before one landed. @State private var 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). static func filter(_ list: SectionList, parent: String?) -> [String: RecordValue]? { guard let link = list.link else { return list.where } guard let parent, !parent.isEmpty else { return nil } 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. static func pageSize(_ list: SectionList, of definition: TableDefinition) -> Int? { guard let limit = list.limit, definition.group == nil else { return nil } return max(1, limit) } /// The heading's count: how many are drawn, with a "+" while more are /// still to be read; nothing for none. static func count(shown: Int, more: Bool) -> String? { guard shown > 0 else { return nil } return more ? "\(shown)+" : "\(shown)" } /// The slips a section draws: the first `limit`, or every one. static func drawn(_ records: [TableRecord], limit: Int?) -> [TableRecord] { guard let limit else { return records } return Array(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. static func count(drawn: Int, read: Int, more: Bool) -> String? { guard read > 0 else { return nil } 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. static func 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. static func total(_ models: [RecordListModel]) -> Int? { var sum = 0 for model in models { guard let total = model.total else { return nil } sum += total } return sum } /// Whether a capped section draws the row that opens its whole: its /// whole holds more than it draws. static func opensWhole(_ list: SectionList, total: Int?, recordPage: Bool = false) -> Bool { guard let limit = list.limit, let total, !list.archived else { return false } 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"). @MainActor static func 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. @MainActor static func opensList(_ list: SectionList, parent: String?, with opener: ListOpener?) -> (@MainActor () -> Void)? { guard let opener, opener.opens(list.table) else { return nil } return { opener(list.table, parent) } } private struct Read: Equatable { var parent: String? var revision: Int var 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. static func sources( _ list: SectionList, parent: String?, in definitions: TableDefinitions ) -> [(definition: TableDefinition, filter: [String: RecordValue])]? { guard let table = definitions[list.table], let filter = filter(list, parent: parent) else { return nil } let own = (table, filter) let merged = list.with.compactMap { link -> (TableDefinition, [String: RecordValue])? in guard let other = definitions[link.table], let parent, !parent.isEmpty else { return nil } return (other, [link.link: .text(parent)]) } return [own] + merged } var body: some View { if let 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)) { guard let store else { return } if !query.isEmpty { // Typing reads once the fingers pause, as the list does. try? await Task.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 = model if acts?.filter != filter { acts = RecordActs(table: definition.id, where: filter) } let others = sources.dropFirst().map { source in self.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 = others await Self.read(model, limit: list.limit, query: query) for other in others { await Self.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) { if let 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. private func finds(_ list: SectionList, _ definition: TableDefinition) -> SectionFinds { let pending = readQuery != query || model.map { $0.phase == .loading } ?? true let holds = model.map { !Self.shown($0.records, of: definition, list).isEmpty } == true || others.contains { !$0.records.isEmpty } return SectionFinds(holds: holds && !pending, pending: pending) } private func reloadAll(_ list: SectionList) async { if let model { await Self.read(model, limit: list.limit, query: query) } for other in others { await Self.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. private func title(_ definition: TableDefinition) -> String { let heading = parentDefinition?.words(section.heading, for: parentRecord) ?? section.heading ?? definition.plural return Self.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. static func heading(_ heading: String, of list: SectionList?, topLevel: Bool, query: String) -> String { guard topLevel, !query.isEmpty, let list else { return heading } return FilteredListOpening.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. private func 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 = true return } if let 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. private func wholeTitle(_ definition: TableDefinition, _ list: SectionList) -> String { let name = parentRecord?.said?.slip.heading ?? openedFrom return FilteredListOpening.title(FilteredListOpening.wholeTitle(list, heading: title(definition)), of: name) } /// The section with no cap: what its "All n" opens when it merges tables. static func uncapped(_ section: PageSection) -> PageSection { var whole = section whole.list?.limit = nil return 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. private func actSurface(_ definition: TableDefinition, _ list: SectionList) -> RecordActSurface { RecordActSurface( open: { id in Task { guard let 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. private func 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) } } return SectionRow.merged(own + more) } /// The records the section draws: only the archived ones on an archived /// run, else every one its list holds. static func 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 private func newRow(_ definition: TableDefinition, _ list: SectionList) -> some View { if let 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") } else if 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 ". @ViewBuilder private func wholeRow(_ definition: TableDefinition, _ list: SectionList, _ filter: [String: RecordValue]) -> some View { if list.limit != nil { cappedRow(definition, list, filter) } else if !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() } else if 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") } else if let 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 " 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 private func cappedRow(_ definition: TableDefinition, _ list: SectionList, _ filter: [String: RecordValue]) -> some View { 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") } else if Self.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 private func content(_ definition: TableDefinition, _ list: SectionList) -> some View { if let 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 in await acts.answer(asked, values: values, store: store, surface: actSurface(definition, list)) } } else if let 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 private func loaded( _ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList ) -> some View { let title = self.title(definition) let read = Self.shown(model.records, of: definition, list) let shown = slipRows.map { Array(read.prefix($0)) } ?? read let all = rows(definition, shown) let more = model.hasMore || others.contains { $0.hasMore } let gathers = list.limit != nil || list.columns != nil || !list.with.isEmpty if 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) if let 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)") } if let 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 private func whole( _ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList, _ shown: [TableRecord] ) -> some View { LazyVStack(alignment: .leading, spacing: RecordListSurfaceKnobs.paperGap) { ForEach(Array(Self.parts(model.sections, shown: shown).enumerated()), id: \.offset) { _, part in if let 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)") } if let note = part.note { Text(note) .paperMeta(13) .fixedSize(horizontal: false, vertical: true) } ForEach(part.records) { record in if 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. static func parts(_ sections: [RecordSection], shown: [TableRecord]) -> [RecordSection] { let drawn = Set(shown.map(\.id)) return sections.compactMap { section in var 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 private func moreRow(_ model: RecordListModel, _ definition: TableDefinition, _ list: SectionList, read: Int) -> some View { if let rows = slipRows, let filter = Self.filter(list, parent: parent) { let total = Self.total([model] + others) ?? read if 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 private func heading(_ title: String, count: String?, _ list: SectionList, opens: Bool = true) -> some View { if opens, let open = 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 private func receipt(_ list: SectionList) -> some View { if let landed { ChangeReceipt( change: landed.change, table: landed.definition, canUndo: landed.canUndo, undone: landed.undone, onUndone: { _ in self.landed?.undone = true Task { 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. private func open(_ 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`). if let screenRoute { navigator?.rowOpened[screenRoute] = PathRecord(table: definition.id, record: record) } if let 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 private func gathered( _ definition: TableDefinition, _ list: SectionList, _ all: [SectionRow] ) -> some View { 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 in if 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. enum GatheredLayout: Equatable { case stack case grid(across: Int) case row(across: Int) } static func gatheredLayout(_ list: SectionList, definition: TableDefinition) -> GatheredLayout { guard let across = list.columns, across > 1 else { 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)). @MainActor static func 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 == nil else { return nil } return count(shown: all.count, more: more) } /// One record as its table's grid cell: its polaroid, or a small slip. @ViewBuilder private func cell(_ row: SectionRow) -> some View { 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). private func listSlip(_ definition: TableDefinition, _ record: TableRecord) -> some View { let links = Self.slipTitles(page: pageTitles, list: list(of: definition)?.linkTitles).byID let title = record.said?.slip.title ?? "" let line = record.said?.slip.subtitle return ListSlip(title: title, line: line == title ? nil : line) { open(definition, record) } .accessibilityIdentifier("section-\(definition.id)-\(record.id)") .modifier(UnreadUnderTheFan()) } private func slip( _ definition: TableDefinition, _ record: TableRecord, ordinal: Int?, faded: Bool, compact: Bool = false ) -> some View { 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) { try await model.toggle(record) } } } let answer: ((String) -> Void)? = model.map { model in { value in self.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) return ActedSlip( 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)) if let 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)") { guard let engine = store as? any RecordCommands else { throw ActionRefused(ShellLines.line("lists", "action_unavailable")) } let change = try await engine.command(table: definition.id, id: record.id, command: command) var canUndo = change.undoable if let 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. static func 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. private func 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. private func answer(_ definition: TableDefinition, _ model: RecordListModel, _ record: TableRecord, _ value: String) { guard answering == nil else { return } answering = record.id write(definition) { defer { answering = nil } let change: ChangeRecord? do { change = try await 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 } if let 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. private func write( _ definition: TableDefinition, _ act: @escaping () async throws -> ChangeRecord? ) { Task { do { guard let change = try await act() else { return } // A change the store cannot take back (a cancelled run is // gone) is shown without an Undo. var undoes = true if let 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. private func page(_ definition: TableDefinition, _ record: TableRecord, ordinal: Int?) -> some View { 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. static func 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. static func refusal(_ error: any Error) -> String { if let refused = error as? ActionRefused { return refused.sentence } if let said = (error as? CottonCallError)?.message, !said.isEmpty { return said } return ShellLines.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. struct SectionFinds: Equatable { var holds = false var pending = false } struct SectionFindsKey: PreferenceKey { static let defaultValue = SectionFinds() static func reduce(value: inout SectionFinds, nextValue: () -> SectionFinds) { let next = nextValue() value = SectionFinds(holds: value.holds || next.holds, pending: value.pending || next.pending) } }