// A table definition: the record the interpreter draws every face, list and // page from (rebuild note 7b95efa4, "Table definitions as data"). // // Wire storage and keys are generated in CottonKit from the Rust serde types. // These native wrappers keep presentation behavior and the table's copy-on-write // box; the catalogue is already resolved by the core before it reaches them. import CottonValues import Foundation import CottonKit /// The shared column types. Changes belong to the core definition format. /// `url` is a web address: its value opens /// on tap, its name opens the text editor. public typealias ColumnType = DefinitionColumnType public struct ColumnDefinition: Codable, Hashable, Sendable, Identifiable { typealias Storage = DefinitionColumn private var storage: Storage public var key: String { get { storage.key } set { storage.key = newValue } } public var name: String? { get { storage.name } set { storage.name = newValue } } public var type: ColumnType { get { storage.`type` } set { storage.`type` = newValue } } /// A `place` column's companions: the picked place's id, its country, its time zone. public var place: DefinitionPlaceColumns? { get { storage.place } set { storage.place = newValue } } public var required: Bool { get { storage.required } set { storage.required = newValue } } public var choices: [String]? { get { storage.choices } set { storage.choices = newValue } } public var objects: [String: String]? { get { storage.objects } set { storage.objects = newValue } } public var choicesFrom: String? { get { storage.choicesFrom } set { storage.choicesFrom = newValue } } public var computed: ColumnComputed? { get { storage.computed } set { storage.computed = newValue } } public var markdown: Bool? { get { storage.markdown } set { storage.markdown = newValue } } public var linkTo: String? { get { storage.linkTo } set { storage.linkTo = newValue } } public var indexed: Bool { get { storage.indexed } set { storage.indexed = newValue } } public var stamps: [String: String]? { get { storage.stamps } set { storage.stamps = newValue } } public var pastName: String? { get { storage.pastName } set { storage.pastName = newValue } } public var readonly: Bool { get { storage.readonly } set { storage.readonly = newValue } } public var live: Bool? { get { storage.live } set { storage.live = newValue } } public var fact: Bool? { get { storage.fact } set { storage.fact = newValue } } public var reading: String? { get { storage.reading } set { storage.reading = newValue } } public var factJoin: String? { get { storage.factJoin } set { storage.factJoin = newValue } } public var toggleOn: [String]? { get { storage.toggleOn } set { storage.toggleOn = newValue } } public var currency: String? { get { storage.currency } set { storage.currency = newValue } } public var signed: Bool? { get { storage.signed } set { storage.signed = newValue } } public var pair: String? { get { storage.pair } set { storage.pair = newValue } } public var presentation: String? { get { storage.presentation } set { storage.presentation = newValue } } public var units: ColumnUnits? { get { storage.units } set { storage.units = newValue } } public var moves: [String: [String]]? { get { storage.moves } set { storage.moves = newValue } } public var hints: [String: String]? { get { storage.hints } set { storage.hints = newValue } } public var shownWhen: ShownWhen? { get { storage.shownWhen } set { storage.shownWhen = newValue } } public var secret: Bool? { get { storage.secret } set { storage.secret = newValue } } public var reveal: ColumnReveal? { get { storage.reveal } set { storage.reveal = newValue } } public var redWhen: [String]? { get { storage.redWhen } set { storage.redWhen = newValue } } public var multiple: Bool { get { storage.multiple } set { storage.multiple = newValue } } public var edges: Bool? { get { storage.edges } set { storage.edges = newValue } } public var media: Bool? { get { storage.media } set { storage.media = newValue } } public var placeholder: String? { get { storage.placeholder } set { storage.placeholder = newValue } } public var week: Bool { get { storage.week } set { storage.week = newValue } } public var month: Bool { get { storage.month } set { storage.month = newValue } } public var choiceNames: [String: String]? { get { storage.choiceNames } set { storage.choiceNames = newValue } } public var format: ColumnFormat? { get { storage.format } set { storage.format = newValue } } public var labels: [String: String]? { get { storage.labels } set { storage.labels = newValue } } public var until: String? { get { storage.until } set { storage.until = newValue } } public var size: [String]? { get { storage.size } set { storage.size = newValue } } public var caption: String? { get { storage.caption } set { storage.caption = newValue } } public var captionFallback: String? { get { storage.captionFallback } set { storage.captionFallback = newValue } } public var plainBefore: String? { get { storage.plainBefore } set { storage.plainBefore = newValue } } public var plainAfter: String? { get { storage.plainAfter } set { storage.plainAfter = newValue } } public var opens: RecordOpens? { get { storage.opens } set { storage.opens = newValue } } public var poster: String? { get { storage.poster } set { storage.poster = newValue } } public var zone: Bool { get { storage.zone } set { storage.zone = newValue } } public var yearly: Bool { get { storage.yearly } set { storage.yearly = newValue } } public var reach: ColumnReach? { get { storage.reach } set { storage.reach = newValue } } public var provenance: ColumnProvenance? { get { storage.provenance } set { storage.provenance = newValue } } public var signs: AmountSigns? { get { storage.signs } set { storage.signs = newValue } } public var defaultValue: RecordValue? { get { storage.defaultValue } set { storage.defaultValue = newValue } } public var hidden: Bool? { get { storage.hidden } set { storage.hidden = newValue } } public var unavailable: [String]? = nil public var unavailableNote: String? = nil public var id: String { key } public init( key: String, name: String? = nil, type: ColumnType, required: Bool = false, choices: [String]? = nil, linkTo: String? = nil, indexed: Bool = false, stamps: [String: String]? = nil, pastName: String? = nil, readonly: Bool = false, live: Bool? = nil, fact: Bool? = nil, reading: String? = nil, factJoin: String? = nil, toggleOn: [String]? = nil, pair: String? = nil, units: ColumnUnits? = nil, moves: [String: [String]]? = nil, hints: [String: String]? = nil, shownWhen: ShownWhen? = nil, secret: Bool? = nil, reveal: ColumnReveal? = nil, multiple: Bool = false, placeholder: String? = nil, week: Bool = false, month: Bool = false, choiceNames: [String: String]? = nil, format: ColumnFormat? = nil, zone: Bool = false, yearly: Bool = false, reach: ColumnReach? = nil, provenance: ColumnProvenance? = nil, signs: AmountSigns? = nil, labels: [String: String]? = nil, until: String? = nil, size: [String]? = nil, caption: String? = nil, opens: RecordOpens? = nil, poster: String? = nil, presentation: String? = nil, redWhen: [String]? = nil, captionFallback: String? = nil, currency: String? = nil, signed: Bool? = nil ) { storage = Storage(_generated: (), key: key, type: type) self.key = key self.name = name self.type = type self.required = required self.choices = choices self.linkTo = linkTo self.indexed = indexed self.stamps = stamps self.pastName = pastName self.readonly = readonly self.live = live self.fact = fact self.reading = reading self.factJoin = factJoin self.toggleOn = toggleOn self.pair = pair self.presentation = presentation self.format = format self.units = units self.moves = moves self.hints = hints self.shownWhen = shownWhen self.secret = secret self.currency = currency self.signed = signed self.reveal = reveal self.multiple = multiple self.placeholder = placeholder self.week = week self.month = month self.choiceNames = choiceNames self.labels = labels self.until = until self.size = size self.caption = caption self.captionFallback = captionFallback self.opens = opens self.poster = poster self.zone = zone self.yearly = yearly self.reach = reach self.provenance = provenance self.signs = signs self.redWhen = redWhen } typealias CodingKeys = Storage.CodingKeys public init(from decoder: Decoder) throws { storage = try Storage(from: decoder) if storage.computed != nil { storage.readonly = true } } public func encode(to encoder: Encoder) throws { try storage.encode(to: encoder) } /// Whether the value is written blind (`secret`). public var isSecret: Bool { secret == true } /// What every column a person adds to a shipped table is keyed under /// (the core's `owner::OWN_COLUMN_PREFIX`); no shipped column is. public static let ownPrefix = "own_" /// Whether the owner added this column (his namespace). public var isOwn: Bool { key.hasPrefix(Self.ownPrefix) } /// The name a person reads, as the core said it. public var label: String { name ?? "" } } /// A count's words: the number, then `one` or `other` after it; a zero reads /// as `zero` alone when there is one ("No orders yet", "Sold out"). public typealias ColumnUnits = DefinitionColumnUnits extension DefinitionColumnUnits { public init(one: String, other: String, zero: String? = nil) { self.init(_generated: (), one: one, other: other) self.zero = zero } } /// A column drawn only while another column holds one of `values`. public typealias ShownWhen = DefinitionValueMatch /// Which columns a slip shows. Every slot is a column key or nil; a slot the /// JSON leaves out is nil. /// A slip opens either its declared URL column or its linked record target. public typealias SlipOpening = DefinitionSlipOpens public typealias SlipStock = DefinitionSlipStock public typealias SlipStockBy = DefinitionSlipStockBy public typealias SlipLayout = DefinitionSlipLayout public typealias SlipEdge = DefinitionSlipEdge extension DefinitionSlipLayout { public init( title: String, subtitle: String? = nil, trailing: String? = nil, photo: String? = nil, toggle: String? = nil, player: String? = nil, trailingPicture: String? = nil, toggleOn: [String]? = nil, caption: SlipCaption? = nil, figure: String? = nil, stub: String? = nil, subtitleFallback: String? = nil, titleFallback: String? = nil, byline: SlipByline? = nil, toggleStyle: SlipToggleStyle = .check, ordinal: Bool = false, badge: SlipBadge? = nil, answers: SlipAnswers? = nil, links: LinkedSection? = nil, reply: SlipReply? = nil, unread: String? = nil, edge: SlipEdge? = nil, status: String? = nil, object: String? = nil, photoName: String? = nil, titleLines: Int? = nil, opens: SlipOpening? = nil, stock: SlipStock? = nil, stockBy: SlipStockBy? = nil, tap: String? = nil ) { self.init(_generated: (), title: title) self.tap = tap self.opens = opens self.stock = stock self.stockBy = stockBy self.object = object self.unread = unread self.edge = edge self.status = status self.links = links self.answers = answers self.ordinal = ordinal self.titleFallback = titleFallback self.subtitles = subtitle.map { [$0] } ?? [] self.subtitleFallback = subtitleFallback self.trailing = trailing self.photo = photo self.photoName = photoName self.toggle = toggle self.player = player self.trailingPicture = trailingPicture self.toggleOn = toggleOn self.caption = caption self.figure = figure self.stub = stub self.byline = byline self.toggleStyle = toggleStyle self.badge = badge self.reply = reply self.titleLines = titleLines } /// The subtitle columns in order, however the definition spells them. public var subtitles: [String] { get { DefinitionSlipSubtitle.columns(subtitleKeys) } set { subtitleKeys = DefinitionSlipSubtitle.spelled(newValue) } } /// The first subtitle column. public var subtitle: String? { subtitles.first } public func titleLines(otherwise: Int) -> Int { guard let titleLines else { return otherwise } return titleLines == 0 ? Int.max : titleLines } } /// A slip's foot as a sentence rather than one column: some columns as they /// read, a status word, then the first of some date columns that holds a day, /// read with its column's name — "Paused \u{00B7} By Wed 31 Dec", "Reached Tue /// 2 Sep", "6 orders \u{00B7} last Tue 2 Sep". /// A slip drawn by a choice column's value (`slip_by`, Records slips typed by /// kind, 11 Oct 2026): a record holding one of `slips`' values is drawn with /// that variant's words — title, subtitles, trailing, caption — in place of /// the slip's; any other value draws the slip as declared. The definition /// chooses, never the app. public typealias SlipBy = DefinitionSlipBy extension DefinitionSlipBy { public init(column: String, slips: [String: SlipVariant]) { self.init(_generated: (), column: column, slips: slips) } } /// One value's words on a `SlipBy` slip. public typealias SlipVariant = DefinitionSlipVariant extension DefinitionSlipSubtitle { /// The subtitle columns in order: one, several, or none. static func columns(_ subtitle: Self?) -> [String] { switch subtitle { case .one(let column)?: return [column] case .several(let columns)?: return columns case nil: return [] } } /// The spelling the core writes: one column alone, several as a list. static func spelled(_ columns: [String]) -> Self? { columns.count > 1 ? .several(columns) : columns.first.map(Self.one) } } extension DefinitionSlipVariant { public init(title: String, subtitles: [String] = [], trailing: String? = nil, caption: SlipCaption? = nil) { self.init(_generated: (), title: title) self.subtitles = subtitles self.trailing = trailing self.caption = caption } public var subtitles: [String] { get { DefinitionSlipSubtitle.columns(subtitle) } set { subtitle = DefinitionSlipSubtitle.spelled(newValue) } } } public typealias SlipCaption = DefinitionSlipCaption extension DefinitionSlipCaption { public init(columns: [String] = [], status: String? = nil, dates: [String], fields: [String]? = nil) { self.init(_generated: ()) self.columns = columns self.status = status self.dates = dates self.fields = fields } } /// The face a table's tile wears at tile size. public typealias TileFace = DefinitionTileFace public typealias TileLayout = DefinitionTileLayout extension DefinitionTileLayout { public init(face: TileFace, summary: [TileSummary] = [], current: TileCurrent? = nil, sparkline: TileSparkline? = nil, chart: TileChart? = nil) { self.init(_generated: (), face: face) self.summary = summary self.current = current self.sparkline = sparkline self.chart = chart } } /// A chart of the table's records by period — the crate's `ChartFace`: /// `{ "kind": "bar", "x": "occurred_on", "y": "amount_minor", "by": "month" }`, /// `y` an amount or number column summed or `"count"`; the core works out the /// series (`records::chart`), a face only draws it. public typealias TileChart = DefinitionChartFace extension DefinitionChartFace { public typealias Kind = DefinitionChartKind public typealias Period = DefinitionChartPeriod public init(kind: Kind, x: String, y: String, by: Period, periods: Int? = nil, filter: [String: RecordValue]? = nil, hour: String? = nil, timezone: String? = nil) { self.init(_generated: (), kind: kind, x: x, y: y, by: by) self.hour = hour self.timezone = timezone self.periods = periods self.filter = filter } } /// A line of one number over time — the crate's `Sparkline`: `value` of each /// record of `table`, placed by its `at` date, over the last `days` (7 absent); /// on a page, `link` is the column of `table` that holds the page's record. public typealias TileSparkline = DefinitionSparkline extension DefinitionSparkline { public init(table: String, value: String, at: String, days: Int? = nil, link: String? = nil) { self.init(_generated: (), table: table, value: value, at: at) self.days = days self.link = link } } /// A record is current while the date in `column` is no more than `days` days /// behind today — the crate's `TileCurrent`. public typealias TileCurrent = DefinitionTileCurrent extension DefinitionTileCurrent { public init(column: String, days: Int) { self.init(_generated: (), column: column, days: days) } } /// What a tile figure does with its rows — the crate's `SummaryOp`. public typealias SummaryOp = DefinitionSummaryOp /// One figure on a board tile: `{ "op": "sum", "column": "amount", /// "where": { "status": "active" }, "label": "a month" }`. public typealias TileSummary = DefinitionTileSummary extension DefinitionTileSummary { public init(op: SummaryOp, column: String? = nil, filter: [String: RecordValue]? = nil, label: String? = nil) { self.init(_generated: (), op: op) self.column = column self.filter = filter self.label = label } } /// The cover face's words: the title is the table's, and the footer line is /// the first of these columns' values joined ("example.org \u{00B7} Essay"). /// Absent, the footer is the slip's subtitle. public typealias CoverLayout = DefinitionCoverLayout extension DefinitionCoverLayout { public init(footer: [String], bound: Bool = false) { self.init(_generated: ()) self.footer = footer self.bound = bound } } /// A thread's messages, for the conversation page style: the table they are /// records of, the link columns that name the thread (any of them), the words /// and the moment, which of them are the owner's, and what a message sent /// from the page's input is written with besides its words and the thread. public typealias ConversationLayout = DefinitionConversationLayout extension DefinitionConversationLayout { public init( table: String, links: [String], body: String, at: String, mine: ConversationMine, status: String? = nil, ended: String? = nil, sends: [String: RecordValue] = [:], anchor: String? = nil, canSend: Bool = true, colorBy: String? = nil, header: [String] = [], footer: MessageColumns? = nil, media: String? = nil, system: String? = nil, headerColumns: [String] = [], started: ConversationStarted? = nil, placeholder: String? = nil, also: [ConversationSource] = [], photo: String? = nil, folds: Bool = false, blankBody: String? = nil ) { self.init(_generated: (), table: table, links: links, body: body, at: at, mine: mine) self.blankBody = blankBody self.photo = photo self.folds = folds self.status = status self.ended = ended self.sends = sends self.anchor = anchor self.colorBy = colorBy self.sendGate = .allowed(canSend) self.header = header self.footer = footer self.media = media self.system = system self.headerColumns = headerColumns self.started = started self.placeholder = placeholder self.also = also } /// Whether words may be sent, as a fixed answer (a column's live fact reads as false). public var canSend: Bool { get { sendGate == .allowed(true) } set { sendGate = .allowed(newValue) } } } /// A fixed permission or a live boolean fact on the thread. Column facts /// fail closed when absent, rather than guessing that an archive can send. /// The part a table plays that the app asks for by name (`role`): where the /// board's sentence goes by what it guesses, the people and the projects a /// sentence's names are matched against, and where a sentence filed nowhere /// is kept. The app asks for the table playing a role, never for a table by /// its id. public typealias TableRole = DefinitionTableRole /// What a bin's rows hold (`binned`): the column naming each record's own /// table, and the values a Restore writes to the row. public typealias BinnedRows = DefinitionBinnedRows /// How a record of this table says its date where it is listed outside its /// own tool (`linked_when`): the words around `{when}` for a day it is due or /// starts (`scheduled`) and for the day it was made (`made`). public typealias LinkedWhen = DefinitionLinkedWhen /// A list drawn as people's stories (`stories`): the print's words on the /// list and on the page, and the rows whose picture plays. public typealias StoriesLayout = DefinitionStoriesLayout /// The read that answers a record's projects (`projects_read`): the kind /// the link verbs name it by, the read, and the screen families it draws. public typealias ProjectsRead = DefinitionProjectsRead extension DefinitionCanSend { public func allows(_ thread: TableRecord?) -> Bool { switch self { case .allowed(let value): return value case .column(let key): return thread?[key].bool == true } } } /// A conversation's message columns: one, or several (the crate's /// `MessageColumns`). Each form is written back as it was read. public typealias MessageColumns = DefinitionMessageColumns extension DefinitionMessageColumns: ExpressibleByStringLiteral, ExpressibleByArrayLiteral { public init(stringLiteral value: String) { self = .one(value) } public init(arrayLiteral elements: String...) { self = .several(elements) } public var columns: [String] { switch self { case .one(let key): return [key] case .several(let keys): return keys } } } /// The thread's opening line: its start column, and the thread columns read /// before the time ("mac-b", "owner@\u{2026}"). public typealias ConversationStarted = DefinitionConversationStarted extension DefinitionConversationStarted { public init(at: String, words: [String] = []) { self.init(_generated: (), at: at) self.words = words } } /// A second table read into a conversation beside its messages: its link /// columns, words, moment and whose, and how its records are drawn in the /// stream — as notes, whose footer is their time alone, or as their own /// table's slips (a session's runs between its turns). A slip source needs /// no `body` or `mine`: the slip says what its table's definition says, and /// is nobody's side of the chat. public typealias ConversationSource = DefinitionConversationSource extension DefinitionConversationSource { public init( table: String, links: [String], body: String? = nil, at: String, mine: ConversationMine? = nil, face: ConversationFace = .note ) { self.init(_generated: (), table: table, links: links, at: at) self.body = body self.mine = mine self.face = face } } /// A view the app stands above a table's list (`list_head`). public typealias ListHead = DefinitionListHead /// How an `also` table's records are drawn in a conversation's stream. public typealias ConversationFace = DefinitionConversationFace /// Which messages are the owner's: those whose `column` holds one of `values`. public typealias ConversationMine = DefinitionValueMatch /// The tool a home table belongs to (`tool`): its name, and the tables it /// holds, the home table first. public typealias TableTool = DefinitionToolHome extension DefinitionToolHome { public init( name: String, tables: [String] = [], key: String? = nil, icon: String? = nil, cardStock: ToolCardTint? = nil, route: String? = nil, figures: [TableToolFigure] = [], heldOnly: Bool = false ) { self.init(_generated: (), name: name) self.tables = tables self.key = key self.icon = icon self.cardStock = cardStock self.route = route self.figures = figures self.heldOnly = heldOnly } } /// One figure on a tool's card: the read it counts, said as `many` (`{n}` /// for the count; plain words for a flag) or `one` when the count is one. public typealias TableToolFigure = DefinitionToolFigure extension DefinitionToolFigure { public init(read: String, one: String? = nil, many: String) { self.init(_generated: (), read: read, many: many) self.one = one } /// The figure for a count: silence at zero, `one` at one when it is /// said, otherwise `many` with the count for `{n}` (a flag reads as 1). public func words(_ n: Int) -> String? { guard n > 0 else { return nil } if n == 1, let one { return one } return many.replacingOccurrences(of: "{n}", with: String(n)) } } /// A list split into sections by one choice column's value, each with its /// heading and count; a drag moves a slip only within its section. public typealias ListGrouping = DefinitionListGrouping extension DefinitionListGrouping { public init(column: String, sections: [ListGroup]) { self.init(_generated: (), column: column) self.sections = sections } } /// One section of a grouped list: the choice values it holds, in the order /// its slips are drawn, under an optional heading. public typealias ListGroup = DefinitionListGroup extension DefinitionListGroup { public init(heading: String?, values: [String], note: String? = nil, closed: Bool = false) { self.init(_generated: (), values: values) self.heading = heading self.note = note self.closed = closed } /// Whether the list opens with this section shut. public var opensClosed: Bool { closed } } /// The order a table's list reads in when nothing is dragged into place: one /// column, largest first when `descending` (a journal's newest day first). public typealias ListSort = DefinitionListSort extension DefinitionListSort { public init(column: String, descending: Bool = false, tie: String? = nil) { self.init(_generated: (), column: column) self.descending = descending self.tie = tie } } /// A table whose records move while they are on screen: its list and its /// pages read again every `every` seconds, keeping what they show until the /// answer lands, for as long as they are on screen and the app is in front. /// A cadence under a second reads as one second and one over a day as a /// day: a definition is data anyone can write, and no table asks the store /// more often than that (nor overflows a clock asking less). public typealias LiveReading = DefinitionLiveReading extension DefinitionLiveReading { /// The fastest a table may ask to be read again, in seconds. public static let floor: Double = 1 /// The slowest, in seconds: a day. public static let ceiling: Double = 86_400 public init(every: Double) { self.init(_generated: (), every: every) } /// How long the list and its pages wait between reads: `every`, held /// between a second and a day. public var interval: Duration { let seconds = every.isNaN ? Self.floor : min(max(every, Self.floor), Self.ceiling) return .milliseconds(Int((seconds * 1000).rounded())) } } /// One section of a record's page: an optional heading over the columns it /// shows — or over another table's records (`list`), drawn under the page. public typealias PageSection = DefinitionPageSection extension DefinitionPageSection { public init( heading: String?, columns: [String] = [], list: SectionList? = nil, above: Bool = false, picture: String? = nil, web: String? = nil, links: LinkedSection? = nil, when: SectionWhen? = nil, note: String? = nil, ink: SectionInk? = nil, hand: PageHand? = nil, answers: SlipAnswers? = nil, actions: [SectionAction] = [], figure: String? = nil, role: SectionRole? = nil, commands: [String] = [] ) { self.init(_generated: ()) self.heading = heading self.columns = columns self.list = list self.above = above self.picture = picture self.web = web self.links = links self.when = when self.note = note self.ink = ink self.hand = hand self.answers = answers self.actions = actions self.figure = figure self.role = role self.commands = commands } } /// A page section's part: `main` is what the page is for (a script, a /// transcript), at most one a page; `facts` are a few values said in one /// line under the title; `side` is a list reached from the page's row of /// links, or columns kept behind its Details link. public typealias SectionRole = DefinitionSectionRole /// What an empty list says in its own words, in place of the generic "No /// yet": a table whose records arrive some other way than the bar /// names that way ("Share a link to Cotton"). public typealias EmptyWords = DefinitionEmptyWords extension DefinitionEmptyWords { public init(title: String, message: String? = nil, search: NoMatchWords? = nil) { self.init(_generated: (), title: title) self.message = message self.search = search } } /// A title and the sentence under it, said when a search finds nothing. public typealias NoMatchWords = DefinitionNoMatchWords extension DefinitionNoMatchWords { public init(title: String, message: String? = nil) { self.init(_generated: (), title: title) self.message = message } } /// The records touched most lately, as a short section above a long list: /// the `count` records latest in `column`, each typed with its moment /// handwritten, once the list holds more than `over` — with fewer, the rows /// would name the slips right under them. public typealias RecentLayout = DefinitionRecentLayout extension DefinitionRecentLayout { public init(column: String, count: Int = 2, over: Int = 3) { self.init(_generated: (), column: column) self.count = count self.over = over } } /// One act under the list that erases every record it holds. public typealias ListClear = DefinitionListClear extension DefinitionListClear { public init( label: String, note: String? = nil, title: String? = nil, message: String = "", confirm: String = "Delete", cancel: String? = nil, done: String? = nil ) { self.init(_generated: (), label: label) self.note = note self.title = title self.message = message self.confirm = confirm self.cancel = cancel self.done = done } } /// Another table's records as a section: those whose `link` column names the /// record the page is of (a store's orders), or, with no link, the whole /// table's (every shop's recent orders, under the shops). A section with no /// records says `empty`, or, without one, is left out. public typealias SectionList = DefinitionSectionList extension DefinitionSectionList { public init( table: String, link: String? = nil, empty: String? = nil, face: ListSectionFace = .slip, archived: Bool = false, limit: Int? = nil, columns: Int? = nil, with: [SectionLink] = [], add: String? = nil, emptyMessage: String? = nil, where filter: [String: RecordValue] = [:], whole: String? = nil ) { self.init(_generated: (), table: table) self.link = link self.emptyWords = empty.map { title in emptyMessage.map { .titled(DefinitionSectionEmptyWords(title: title, message: $0)) } ?? .sentence(title) } self.face = face self.archived = archived self.limit = limit self.columns = columns self.with = with self.add = add self.where = filter self.whole = whole } /// What the list says while it holds none: the sentence, or the title. public var empty: String? { switch emptyWords { case .sentence(let words)?: return words case .titled(let words)?: return words.title case nil: return nil } } /// The line under an empty list's title, when its words carry one. public var emptyMessage: String? { guard case .titled(let words)? = emptyWords else { return nil } return words.message } public var drawingFace: SectionListFace { face } } extension DefinitionSectionEmptyWords { public init(title: String, message: String?) { self.init(_generated: (), title: title) self.message = message } } /// How a list section draws its records. A face this build has not learned /// draws slips. public typealias ListSectionFace = DefinitionSectionFace /// The code stack's name for the same face (`SectionList.drawingFace`). public typealias SectionListFace = ListSectionFace /// A long text column the page menu hands out of the app as a file: /// "Export Fountain" writes the column's text to ".fountain" and opens /// the share sheet. The engine answers the column (a screenplay's assembled /// script); a record whose column holds nothing has nothing to export. public typealias RecordExport = DefinitionRecordExport extension DefinitionRecordExport { public init(label: String, column: String, extension: String) { self.init(_generated: (), label: label, column: column, extension: `extension`) } } /// The records whose `column` holds one of `values`. public typealias ValueMatch = DefinitionValueMatch extension DefinitionValueMatch { public init(column: String, values: [String]) { self.init(_generated: (), column: column, values: values) } } extension DefinitionCardOpens { /// Whether `record` opens into its parts: its `when` holds of it, or it /// names none (a film is no series: its card plays, it has no seasons). public func opens(_ record: TableRecord) -> Bool { guard let when else { return true } return record[when.column].text.map(when.values.contains) ?? false } } /// Who keeps a record in step from outside the person's hands (`kept_by`): /// `when` names the column that, holding a value, marks such a record, and /// `says` is the pencil line its page wears. public typealias KeptBy = DefinitionKeptBy extension DefinitionKeptBy { public init(when: String, says: String) { self.init(_generated: (), when: when, says: says) } } /// A table's definition. Copy-on-write: its fields live in one heap box, so /// a surface, a face and every closure that captures one carry a pointer, not /// the kilobytes — builds 227, 230 and 231 overflowed the phone's 1 MB main /// stack partly on copies of this struct (2.7 KB inline) in every frame that /// held one. A write to a shared definition copies the box first. public struct TableDefinition: Codable, Hashable, Sendable, Identifiable { /// The fields, as the format's JSON has them. typealias Stored = DefinitionTableDefinition final class Box: @unchecked Sendable { var stored: Stored /// The page the core resolved for `stored`, when the core handed it over. var page: DrawnPage? /// What the core says of the table, when the core handed it over. var said: TableSaid? init(_ stored: Stored, page: DrawnPage? = nil, said: TableSaid? = nil) { self.stored = stored self.page = page self.said = said } } private var box: Box typealias CodingKeys = Stored.CodingKeys /// The box to write into: this definition's own, copied first when another /// definition shares it. private mutating func own() -> Box { if !isKnownUniquelyReferenced(&box) { box = Box(box.stored, page: box.page, said: box.said) } return box } public var id: String { get { box.stored.id } set { own().stored.id = newValue } } public var name: String { get { box.stored.name } set { own().stored.name = newValue } } public var plural: String { get { box.stored.plural } set { own().stored.plural = newValue } } /// The card's picture: an object the app ships, or a photo record. public var picture: ToolPicture? { get { box.stored.picture?.drawn } set { own().stored.picture = DefinitionToolPicture(newValue, linkObject: box.stored.picture?.linkObject) } } /// The picture the owner set on this table (`update_definition`, said in /// the row's `edited`): a photo naming no object this app ships. Nil when /// the table's picture is its definition's own. public var ownersPicture: ToolPicture? { guard box.stored.edited.contains(where: { $0 == "picture" || $0.hasPrefix("picture.") }), case .photo? = picture else { return nil } return picture } /// How a card draws a link to one of this table's records: its cap, its /// face, or — absent — the tool's own enamel. public var linkObject: LinkObject? { box.stored.picture?.linkObject } /// The record drawn alone as a card above the strip (`Deck`); nil, the /// table's tool keeps its list and a record opens on the plain card /// (`DeckCard.plain`). public var card: DefinitionCardFace? { get { box.stored.card } set { own().stored.card = newValue } } /// The marks drawn over a card at rest that run one of the table's /// commands on its record, by the mark's name (`InkMarks`): a check on a /// todo runs `done`. public var marks: [String: String]? { get { box.stored.marks } set { own().stored.marks = newValue } } public var builtin: Bool { get { box.stored.shipped } set { own().stored.shipped = newValue } } /// False when the engine owns removal; absent keeps the generic page action. public var delete: Bool? { get { deletes } set { deletes = newValue ?? true } } public var engine: String? { get { box.stored.engine } set { own().stored.engine = newValue } } public var columns: [ColumnDefinition] { get { box.stored.columns } set { own().stored.columns = newValue } } public var title: String { get { box.stored.title } set { own().stored.title = newValue } } public var voiceWords: [String]? { get { box.stored.voiceWords } set { own().stored.voiceWords = newValue } } public var date: String? { get { box.stored.date } set { own().stored.date = newValue } } public var project: String? { get { box.stored.project } set { own().stored.project = newValue } } public var order: String? { get { box.stored.order } set { own().stored.order = newValue } } /// Independent native permission to move records in their manual order; /// a derived position may stay read-only as an individual field. public var reorder: Bool? { get { box.stored.reorder } set { own().stored.reorder = newValue } } public var slip: SlipLayout { get { box.stored.slip } set { own().stored.slip = newValue } } /// A slip per value of one choice column (`slip_by`), chosen per record /// by `slip(for:)`. public var slipBy: SlipBy? { get { box.stored.slipBy } set { own().stored.slipBy = newValue } } public var tile: TileLayout { get { box.stored.tile } set { own().stored.tile = newValue } } public var page: [PageSection] { get { box.stored.page } set { own().stored.page = newValue } } public var parts: PageParts? { get { box.stored.parts } set { own().stored.parts = newValue } } /// The page the core resolved for this definition (`definitions.catalogue`'s /// `pages`), or nil for one that did not come from the core. public var drawnPage: DrawnPage? { box.page } /// The page's parts in order: the core's resolved list; for a definition /// the core did not hand over, the list it names, else the plain page. /// The app derives no page of its own. public var pageParts: [PagePart] { get { if let page = box.page { return page.pageParts } guard let named = box.stored.pageParts else { return PagePart.plain } return named } set { own().stored.pageParts = newValue } } /// Absent: the list is one section. public var group: ListGrouping? { get { box.stored.group } set { own().stored.group = newValue } } /// The list's order when the table has no drag order (`order`); absent /// means the order the store answers in. public var sort: ListSort? { get { box.stored.sort } set { own().stored.sort = newValue } } /// A column a record must hold a value in to be listed — a journal page /// nobody wrote on is not a day. Absent means every record is listed. public var listedWhen: String? { get { box.stored.listedWhen } set { own().stored.listedWhen = newValue } } /// The cover face's footer columns; absent, the slip's subtitle. public var cover: CoverLayout? { get { box.stored.cover } set { own().stored.cover = newValue } } /// A date or yes-no column that, once set, archives the record: a list /// leaves it out unless it is asked for archived records. public var archived: String? { get { box.stored.archived } set { own().stored.archived = newValue } } /// A column that, holding a value, makes the whole record read-only — a /// note kept in step with a file outside Cotton. The page opens no editor. public var readonlyWhen: String? { get { box.stored.readonlyWhen } set { own().stored.readonlyWhen = newValue } } /// Who keeps a record in step, and the one line its page says of it /// ("Kept in step with Gmail", "Kept by your assistant"). A record that /// is only read-only names no keeper and its page says nothing. public var keptBy: KeptBy? { get { box.stored.keptBy } set { own().stored.keptBy = newValue } } /// False on a table nothing is added to by typing (chats, email, calls, /// duplicates, imports): its list draws no bar. public var add: Bool? { get { box.stored.add } set { own().stored.add = newValue } } /// Whether the table's records are secrets (`sealed`): never said into /// the bar nor kept as a thought, never cached on a device's disk. public var isSealed: Bool { box.stored.sealed == true } /// The view the list stands above its slips (`list_head`), by its kind /// from the fixed vocabulary — never by the engine's name. public var listHead: ListHead? { box.stored.listHead } /// The column whose value is the project scope a link to one of this /// table's records opens (`scope_by`); nil for a table whose links open /// a page. /// The table is the person's own (`scope: personal`): read from their own /// database whichever one is shown. public var isPersonal: Bool { box.stored.scope == .personal } public var scopeBy: String? { get { box.stored.scopeBy } set { own().stored.scopeBy = newValue } } /// Present on a bin (`binned`): its rows stand for records put in the /// bin — the column naming each one's table, and what Restore writes. public var binned: BinnedRows? { box.stored.binned } /// Present on a table whose list is drawn as people's stories, grouped /// by who posted them (`stories`). public var stories: StoriesLayout? { box.stored.stories } /// The screen a record of this table opens at when it is not the table's /// page (`record_route`, an app route pattern filled with the record's id). public var recordRoutePattern: String? { box.stored.recordRoute } /// The words a record of this table says its date in where it is listed /// outside its own tool (`linked_when`). public var linkedWhen: LinkedWhen? { box.stored.linkedWhen } /// The kind the core's record read and comments know this table's /// records by (`record_kind`); nil where the generic read does not answer. public var recordKind: String? { get { box.stored.recordKind } set { own().stored.recordKind = newValue } } /// A shell setup table, never a destination for filing a thought. public var setup: Bool? { get { box.stored.setup } set { own().stored.setup = newValue } } /// Where the table stands among those a thought is filed into /// (`filing_rank`): the ranked first, lowest first. public var filingRank: Int? { get { box.stored.filingRank } set { own().stored.filingRank = newValue } } /// True on a table a thought is made into by its own verb /// (`made_by_verb`), whatever links its record carries. public var madeByVerb: Bool { get { box.stored.madeByVerb == true } set { own().stored.madeByVerb = newValue ? true : nil } } /// Its rows are the person's face choices, one per table its `rowKey` /// names (`face_choices`). public var faceChoices: Bool { get { box.stored.faceChoices == true } set { own().stored.faceChoices = newValue ? true : nil } } /// The column naming the one row a create keys (`row_key`). public var rowKey: String? { get { box.stored.rowKey } set { own().stored.rowKey = newValue } } /// The part this table plays that the app asks for by name (`role`). public var role: TableRole? { get { box.stored.role } set { own().stored.role = newValue } } /// True on a list whose records ARE the files the "+" picks /// (`takes_files`: Photos, Videos, Documents). public var takesFiles: Bool { get { box.stored.takesFiles == true } set { own().stored.takesFiles = newValue ? true : nil } } /// The screen family a sync names when this table's rows move /// (`screen_family`), by its name. public var screenFamilyName: String? { box.stored.screenFamily } /// True on a table whose rows move under an open list without a sync /// saying so (`polled`). public var isPolled: Bool { box.stored.polled == true } /// The read that answers a record's projects (`projects_read`). public var projectsRead: ProjectsRead? { get { box.stored.projectsRead } set { own().stored.projectsRead = newValue } } /// True on a Settings table whose put-away records are the core's /// archived read (`archived_in_core`). public var archivedInCore: Bool { box.stored.archivedInCore == true } /// True on a Settings table a link to which may hold the core's own /// record id (`core_links`). public var coreLinks: Bool { box.stored.coreLinks == true } /// True on a table whose create with a record's day adds to that record /// (a journal day): a plain sentence in the page's bar is added to it. public var append: Bool? { get { box.stored.append } set { own().stored.append = newValue } } /// The messages a `conversation` page draws; nil on any other style. public var conversation: ConversationLayout? { get { box.stored.conversation } set { own().stored.conversation = newValue } } /// The page carries a composer of its own: while it is open on the /// phone the fan, the caps and the record button are put away /// (`FanComposerPage`). public var composer: Bool { get { box.stored.composer } set { own().stored.composer = newValue } } public var actions: [PageAction]? { get { box.stored.actions } set { own().stored.actions = newValue } } public var related: [RelatedRecords]? { get { box.stored.related } set { own().stored.related = newValue } } public var acts: [RecordCommand]? { get { box.stored.acts } set { own().stored.acts = newValue } } public var commands: [RecordCommand]? { get { let commands = (box.stored.commands ?? []) + (box.stored.acts ?? []) return commands.isEmpty ? nil : commands } set { own().stored.commands = newValue own().stored.acts = nil } } /// Existing non-destructive read-stamp command after a successful page read. public var onOpen: String? { get { box.stored.onOpen } set { own().stored.onOpen = newValue } } /// A date column grouping a chronological list by local day. public var dayGrouping: String? { get { box.stored.dayGrouping } set { own().stored.dayGrouping = newValue } } /// Records drawn faded on a list (a closed shop, a hidden product): /// still there, and read as set aside. public var dimmed: ValueMatch? { get { box.stored.dimmed } set { own().stored.dimmed = newValue } } /// Other tables' lists drawn under this table's list, each a section /// with a `list` (every shop's recent orders under the shops). public var lists: [PageSection] { get { box.stored.lists } set { own().stored.lists = newValue } } /// The table's records can be gathered into named groups, drawn as a row /// of stacks above its list (`TableGroups`); absent, the table has none. public var groups: TableGroups? { get { box.stored.groups } set { own().stored.groups = newValue } } /// The "Recent" section above the list; absent, none. public var recent: RecentLayout? { get { box.stored.recent } set { own().stored.recent = newValue } } /// A date column the list is split by, one section per day under its /// day's name ("Today", "Tuesday 9 September"), days newest first. public var byDay: String? { get { box.stored.byDay } set { own().stored.byDay = newValue } } /// A date column a long list is split by, one section per month under /// its name ("September", "September 2025"), once it holds more than a /// dozen records over more than one month (`monthSections`). public var byMonth: String? { get { box.stored.byMonth } set { own().stored.byMonth = newValue } } /// The one layout the list draws in; absent is the slips. public var layout: ListLayout { get { box.stored.layout } set { own().stored.layout = newValue } } /// How many records stand across the cards or the contact sheet; absent, /// the cards' own count (`CoverFace.columns`). public var grid: ListGrid? { get { box.stored.grid } set { own().stored.grid = newValue } } /// A row of a several-choice column's words over the list: tap some and /// save, and a record holding them is made — no typing, no assistant. public var chips: ChipRow? { get { box.stored.chips } set { own().stored.chips = newValue } } /// The system's Paste button at the list's head: a pasted text becomes a /// record with it in `column` (a clip), as the crate's `paste` says. public var paste: ListPaste? { get { box.stored.paste } set { own().stored.paste = newValue } } /// A date column the page stamps with the moment it is first opened, /// once. While it holds nothing the record is unread: its slip and its /// cover wear the red ink dot. public var opened: String? { get { box.stored.opened } set { own().stored.opened = newValue } } /// What the list says when it holds nothing; absent, the generic words. public var empty: EmptyWords? { get { box.stored.empty } set { own().stored.empty = newValue } } /// The list's "+" (and the empty list's button): a blank page for a new /// record, under these words. public var create: ListCreate? { get { box.stored.create } set { own().stored.create = newValue } } /// The table the list's one input writes into, when it is not this one: /// on the Accounts list what is typed is a movement of money. public var capture: ListCapture? { get { box.stored.capture } set { own().stored.capture = newValue } } /// What the page menu hands out of the app as a file. public var exports: [RecordExport] { get { box.stored.exports } set { own().stored.exports = newValue } } /// A link column naming a record's siblings: the page offers the previous /// and next record, in the table's order, among those holding the same /// value in it (a screenplay's scenes, one after another). public var pager: String? { get { box.stored.pager } set { own().stored.pager = newValue } } /// The list (or its group's first section) split by the day each record /// is next due, soonest first, a day gone under Today. public var upcoming: ListUpcoming? { get { box.stored.upcoming } set { own().stored.upcoming = newValue } } /// A text column the list is indexed by: the A\u{2013}Z rail at the /// list's right edge, a finger on a letter landing on its first record. public var index: String? { get { box.stored.index } set { own().stored.index = newValue } } /// The columns a search reads, by any part of a word ("kar" finds /// Karaka, "board" a whiteboard); empty, the store's own search. public var search: [String] { get { box.stored.search } set { own().stored.search = newValue } } /// Whether a record may be deleted: false on a table its engine only /// archives (a person), whose page and slips then offer no Delete. public var deletes: Bool { get { box.stored.deletes } set { own().stored.deletes = newValue } } /// Where a table deletes only some of its records: the delete holds for /// a record only while this holds for it, as the engine answers it on the /// record ("can_delete" present — a movement typed by hand, never one a /// statement made). Nil, every record (`deletes(_:)`). public var deleteWhen: SectionWhen? { get { box.stored.deleteWhen } set { own().stored.deleteWhen = newValue } } /// On a tool's home table only: the tool it is the home of — its name /// and every table it holds, this one first. Its unnarrowed list is /// called by the tool's name where the tool holds more than one table. public var tool: TableTool? { get { box.stored.tool } set { own().stored.tool = newValue } } /// The column whose words head the record's page, in place of its title /// ("September 2026 \u{00B7} Everyday" over a statement its slip calls /// "September 2026"). Only the page's heading: a list opened from the page /// is still named by the title. Its own row is not drawn again. public var heads: String? { get { box.stored.heads } set { own().stored.heads = newValue } } /// A row of another record: a tap opens the record its column names /// (an album's picture opens the photo), not this one (`RecordOpens`). public var opens: RecordOpens? { get { box.stored.opens } set { own().stored.opens = newValue } } /// The polaroid face's words; absent, a person's first name. public var polaroid: PolaroidLayout? { get { box.stored.polaroid } set { own().stored.polaroid = newValue } } /// A row of typed words over the list narrowing it by one column (all /// \u{00B7} photos \u{00B7} videos). public var filter: ListFilter? { get { box.stored.filter } set { own().stored.filter = newValue } } /// How a count of records is said, by one column's value ("40 photos /// \u{00B7} 2 videos"); absent, the number alone. public var countWords: CountWords? { get { box.stored.countWords } set { own().stored.countWords = newValue } } /// When `by_month` splits the list, and what heads the undated. public var months: ListMonthsLayout? { get { box.stored.months } set { own().stored.months = newValue } } /// Records never listed, whatever else the list shows: an album the /// owner said "not this" to. Its page still opens. public var hidden: ValueMatch? { get { box.stored.hidden } set { own().stored.hidden = newValue } } /// The values the core narrows the table's own list to when a read names /// no `where` on those columns (the list's own few among many). The /// core applies it; the app only carries it, and never narrows by it. public var shows: [String: RecordValue]? { get { box.stored.shows } set { own().stored.shows = newValue } } /// The list's Select: records ticked, then deleted together. public var select: ListSelect? { get { box.stored.select } set { own().stored.select = newValue } } /// The words Delete asks with, on the page and on the list's Select. public var deletion: DeletionWords? { get { box.stored.deletion } set { own().stored.deletion = newValue } } /// Other lists the list's menu opens, each with its count. public var links: [ListLink] { get { box.stored.links } set { own().stored.links = newValue } } /// The list's own links as one row of tiles after its first records. public var linkTiles: LinkTiles? { get { box.stored.linkTiles } set { own().stored.linkTiles = newValue } } /// Lines of the list's menu that open an app screen, uncounted. public var menu: [MenuLine] { get { box.stored.menu } set { own().stored.menu = newValue } } /// The list's search field's words. public var searchPlaceholder: String? { get { box.stored.searchPlaceholder } set { own().stored.searchPlaceholder = newValue } } /// How the list offers its search (`search_face`, fan3 part 6). public var searchFace: DefinitionSearchFace? { get { box.stored.searchFace } set { own().stored.searchFace = newValue } } /// The list's search is the head's magnifier: every list whose /// definition does not ask for the field on the page. var searchesInHead: Bool { searchFace != .field } /// The record button's lines (`voice`); the thought table carries them. public var voice: VoiceWords? { get { box.stored.voice } set { own().stored.voice = newValue } } /// Lines about a database's own reads (`words.could_not_read`); the /// database table carries them. public var words: DefinitionTableWords? { get { box.stored.words } set { own().stored.words = newValue } } /// The record page's slips table (`slips`): each kind's width and held /// acts, and their words; the database table carries it. public var slips: DefinitionSlipsLayout? { get { box.stored.slips } set { own().stored.slips = newValue } } /// The table's records open in the full-screen viewer (`viewer`). public var viewer: TableViewer? { get { box.stored.viewer } set { own().stored.viewer = newValue } } /// A record that opens as the one record it became (`HandingKeys`). public var handOver: RecordHandOver? { get { box.stored.handOver } set { own().stored.handOver = newValue } } /// The strip under the page, written from the page (`HandingKeys`). public var attachments: AttachmentsLayout? { get { box.stored.attachments } set { own().stored.attachments = newValue } } /// How often the table's list and pages read again while on screen — /// records something outside the app keeps moving (a session's turns, a /// device's last word). Absent: they read when opened and when told to. public var live: LiveReading? { get { box.stored.live } set { own().stored.live = newValue } } /// The engine's one live reading for a page. The native boundary resolves /// and authorizes its method and bindings; Swift only draws its fields. public var liveRead: LiveRecordRead? { get { box.stored.liveRead } set { own().stored.liveRead = newValue } } /// One act under the list that erases every record it holds, after one /// question in the table's words (the Bin's "Empty the bin"). public var clear: ListClear? { get { box.stored.clear } set { own().stored.clear = newValue } } public var instructions: String? { get { box.stored.instructions } set { own().stored.instructions = newValue } } public init( id: String, name: String, plural: String, picture: ToolPicture? = nil, builtin: Bool = false, engine: String? = nil, columns: [ColumnDefinition], title: String, date: String? = nil, project: String? = nil, order: String? = nil, slip: SlipLayout, tile: TileLayout, page: [PageSection], parts: PageParts? = nil, pageParts: [PagePart]? = nil, group: ListGrouping? = nil, sort: ListSort? = nil, listedWhen: String? = nil, cover: CoverLayout? = nil, archived: String? = nil, readonlyWhen: String? = nil, conversation: ConversationLayout? = nil, dimmed: ValueMatch? = nil, lists: [PageSection] = [], live: LiveReading? = nil, liveRead: LiveRecordRead? = nil, recent: RecentLayout? = nil, byDay: String? = nil, byMonth: String? = nil, layout: ListLayout = .list, grid: ListGrid? = nil, chips: ChipRow? = nil, opened: String? = nil, empty: EmptyWords? = nil, create: ListCreate? = nil, capture: ListCapture? = nil, exports: [RecordExport] = [], pager: String? = nil, upcoming: ListUpcoming? = nil, index: String? = nil, search: [String] = [], deletes: Bool = true, opens: RecordOpens? = nil, polaroid: PolaroidLayout? = nil, filter: ListFilter? = nil, countWords: CountWords? = nil, months: ListMonthsLayout? = nil, hidden: ValueMatch? = nil, select: ListSelect? = nil, deletion: DeletionWords? = nil, links: [ListLink] = [], menu: [MenuLine] = [], searchPlaceholder: String? = nil, clear: ListClear? = nil, handOver: RecordHandOver? = nil, attachments: AttachmentsLayout? = nil, related: [RelatedRecords]? = nil, commands: [RecordCommand]? = nil, instructions: String? = nil, onOpen: String? = nil, dayGrouping: String? = nil, actions: [PageAction]? = nil, delete: Bool? = nil, keptBy: KeptBy? = nil, add: Bool? = nil, append: Bool? = nil, groups: TableGroups? = nil ) { box = Box(Stored( id: id, name: name, plural: plural, picture: picture, builtin: builtin, engine: engine, columns: columns, title: title, date: date, project: project, order: order, slip: slip, tile: tile, page: page, parts: parts, pageParts: pageParts, group: group, sort: sort, listedWhen: listedWhen, cover: cover, archived: archived, readonlyWhen: readonlyWhen, conversation: conversation, dimmed: dimmed, lists: lists, live: live, liveRead: liveRead, recent: recent, byDay: byDay, byMonth: byMonth, layout: layout, grid: grid, chips: chips, opened: opened, empty: empty, create: create, capture: capture, exports: exports, pager: pager, upcoming: upcoming, index: index, search: search, deletes: deletes, opens: opens, polaroid: polaroid, filter: filter, countWords: countWords, months: months, hidden: hidden, select: select, deletion: deletion, links: links, menu: menu, searchPlaceholder: searchPlaceholder, clear: clear, handOver: handOver, attachments: attachments, related: related, commands: commands, instructions: instructions, onOpen: onOpen, dayGrouping: dayGrouping, actions: actions, delete: delete, keptBy: keptBy, add: add, append: append, groups: groups )) } public init(from decoder: Decoder) throws { box = Box(try Stored(from: decoder)) } public func encode(to encoder: Encoder) throws { try box.stored.encode(to: encoder) } public static func == (a: TableDefinition, b: TableDefinition) -> Bool { a.box === b.box || a.box.stored == b.box.stored } public func hash(into hasher: inout Hasher) { box.stored.hash(into: &hasher) } public func column(_ key: String?) -> ColumnDefinition? { guard let key else { return nil } return columns.first { $0.key == key } } /// This definition carrying `page`, the page the core resolved for it /// (read off the catalogue by `DefinitionCatalogue`). func drawing(_ page: DrawnPage) -> TableDefinition { var table = self table.own().page = page return table } /// This definition carrying what the core said of it (`said`): its /// columns read by the names the core gave them. func saying(_ said: Data?) throws -> TableDefinition { guard let said else { return self } let answer = try JSONDecoder().decode(TableSaid.self, from: said) var table = self table.own().said = answer table.columns = table.columns.map { column in var named = column named.name = answer.labels[column.key] return named } return table } /// Whether the list draws the capture bar, as the core says it; a shell /// that opens a list as read-only turns it off. public var listTakesCapture: Bool { get { box.said?.listTakesCapture ?? false } set { if box.said != nil { own().said?.listTakesCapture = newValue } } } /// Whether the table's name takes "an". public var takesAn: Bool { box.said?.takesAn ?? false } } /// Secret Copy's policy. The row declares reveal_count (number) and /// last_revealed (date); one reveal is shared by the row's secret columns. public typealias ColumnReveal = DefinitionSecretReveal extension DefinitionSecretReveal { public static let countColumn = "reveal_count" public static let lastRevealedColumn = "last_revealed" public init(once: Bool, expires: Int) { self.init(_generated: (), once: once, expires: expires) } } // Native construction choices; the wire storage itself is generated. extension TableDefinition.Stored { init( id: String, name: String, plural: String, picture: ToolPicture? = nil, builtin: Bool = false, engine: String? = nil, columns: [ColumnDefinition], title: String, date: String? = nil, project: String? = nil, order: String? = nil, slip: SlipLayout, tile: TileLayout, page: [PageSection], parts: PageParts? = nil, pageParts: [PagePart]? = nil, group: ListGrouping? = nil, sort: ListSort? = nil, listedWhen: String? = nil, cover: CoverLayout? = nil, archived: String? = nil, readonlyWhen: String? = nil, conversation: ConversationLayout? = nil, dimmed: ValueMatch? = nil, lists: [PageSection] = [], live: LiveReading? = nil, liveRead: LiveRecordRead? = nil, recent: RecentLayout? = nil, byDay: String? = nil, byMonth: String? = nil, layout: ListLayout = .list, grid: ListGrid? = nil, chips: ChipRow? = nil, opened: String? = nil, empty: EmptyWords? = nil, create: ListCreate? = nil, capture: ListCapture? = nil, exports: [RecordExport] = [], pager: String? = nil, upcoming: ListUpcoming? = nil, index: String? = nil, search: [String] = [], deletes: Bool = true, opens: RecordOpens? = nil, polaroid: PolaroidLayout? = nil, filter: ListFilter? = nil, countWords: CountWords? = nil, months: ListMonthsLayout? = nil, hidden: ValueMatch? = nil, select: ListSelect? = nil, deletion: DeletionWords? = nil, links: [ListLink] = [], menu: [MenuLine] = [], searchPlaceholder: String? = nil, clear: ListClear? = nil, handOver: RecordHandOver? = nil, attachments: AttachmentsLayout? = nil, related: [RelatedRecords]? = nil, commands: [RecordCommand]? = nil, instructions: String? = nil, onOpen: String? = nil, dayGrouping: String? = nil, actions: [PageAction]? = nil, delete: Bool? = nil, keptBy: KeptBy? = nil, add: Bool? = nil, append: Bool? = nil, groups: TableGroups? = nil ) { self.init(_generated: (), id: id, name: name, plural: plural, columns: columns, slip: slip, tile: tile) self.keptBy = keptBy self.groups = groups self.add = add self.append = append self.handOver = handOver self.attachments = attachments self.id = id self.name = name self.plural = plural self.picture = DefinitionToolPicture(picture, linkObject: nil) self.shipped = builtin self.engine = engine self.columns = columns self.title = title self.date = date self.project = project self.order = order self.slip = slip self.tile = tile self.page = page self.parts = parts self.pageParts = pageParts self.group = group self.sort = sort self.listedWhen = listedWhen self.cover = cover self.archived = archived self.readonlyWhen = readonlyWhen self.conversation = conversation self.related = related self.commands = commands self.onOpen = onOpen self.dimmed = dimmed self.lists = lists self.live = live self.liveRead = liveRead self.recent = recent self.byDay = byDay self.byMonth = byMonth self.layout = layout self.grid = grid self.chips = chips self.opened = opened self.empty = empty self.create = create self.capture = capture self.exports = exports self.pager = pager self.upcoming = upcoming self.index = index self.search = search self.deletes = deletes self.opens = opens self.polaroid = polaroid self.filter = filter self.countWords = countWords self.months = months self.hidden = hidden self.select = select self.deletion = deletion self.menu = menu self.links = links self.searchPlaceholder = searchPlaceholder self.clear = clear self.instructions = instructions self.dayGrouping = dayGrouping self.actions = actions if let delete { self.deletes = delete } } } // ── What a shell asks of a definition itself ───────────────────────────────── extension TableDefinition { /// The definition `record`'s slip is drawn by: the layout the core said /// for its `slip_by` variant, else itself. public func slip(for record: TableRecord) -> TableDefinition { guard let layout = record.said?.layout else { return self } var typed = self typed.slip = layout return typed } /// The project a list or page over this table reads in: `current` when /// the table's rows belong to projects, else none. The bin and an /// engine's view hold every project's rows at once, and the core refuses /// a project filter on them rather than narrowing to nothing. public func projectScope(_ current: String?) -> String? { project == nil ? nil : current } } /// One section of a list as drawn: its heading, or none, its records, and /// whether it opens shut (`ListGroup.closed`). public struct RecordSection: Hashable, Sendable { /// The section's id as the core answered it (`today`, `late`, `day:<d>`, `all`). public var id: String? public var heading: String? public var records: [TableRecord] /// Whether a heading over one record says "1": a day of one moment does /// not count it. public var countsOne = true /// Drawn closed until its heading is tapped (`ListGroup.closed`). public var closed: Bool = false /// What the slips under this heading say of their date column: the time /// alone under a day, the day alone under a month (R7 b, c). public var dayWords: DayWords = .full /// How many the whole section holds when more than are loaded (a planned /// read's count); nil counts the records here. public var count: Int? = nil /// What the group's head says over the whole group (`group.summary`): /// the core's lines — "₹1,200 in", "₹300 out" — drawn as they are. public var lines: [String] = [] /// The whole section's count in words, as the core says it on a folded heading. public var said: String? = nil /// The line under the heading, as the definition gives it. public var note: String? = nil } extension TableDefinition { /// The date column a card's When writes, as the core names it /// (`card_actions::date_column`): the card's date place, else its first /// corner, else the table's date. A card naming its date by its place /// alone (a trip's `starts`) once had its When dropped here without a /// word: the target held no date (13 Nov 2026). public var whenColumn: String? { card?.fields.first { $0.slot == .date }?.column ?? card?.corner.first?.column ?? date } }