// THE SHELL EDITS (cardtrial, images 4 and 4b; owner, 28 Oct 2026: a face// has one state, view). Tap what the card shows and the shell answers: the// date corner turns the fan into one row of days; a long press turns it// into the card's acts; a tap on a value saves at once — the card's corner,// paper and animal change, a small ink mark is left, and the fan returns to// its tools. No confirmation, no Save, nothing flies. A card's words are// written in the shell's one short-text input or, a long text, on the whole// screen (`writing`); nothing is typed on the card.//// One editor stands over Home's fan (`FanHome`), so the deck above and the// fan below read the same state: the deck circles its corner and fades its// floating line, the fan draws the row and the strip fades.importCottonFacesimportCottonKitimportCottonPaperimportCottonValuesimport osimportSwiftUI/// What the fan answers while a card is being edited.publicenumDeckEditing: Equatable, Sendable {/// The days a date can be given in one tap (`shell.opened {step: when}`), No/// date first.case days(DeckEditTarget)/// The times the chosen day can be given, No time first/// (`shell.opened {step: time}`): a day chosen goes straight on to them.case times(DeckEditTarget)/// Pick a date: every day of the coming weeks, one card each — no sheet/// (door row 7: bottom sheets are out of the design).case pickDays(DeckEditTarget)/// Pick a time: every half hour of the day, one card each.case pickTimes(DeckEditTarget)/// The held card's acts as the core answers them (`shell.opened`).case acts(DeckEditTarget)/// The table's groups, the record's own marked.case groups(DeckEditTarget)/// The status verbs the record can take now (`shell.opened {step: status}`).case statuses(DeckEditTarget)/// A choice column's values, as its definition orders and words them:/// the column the card's picture chooses (`card.fields[].chooses` — an/// event's kind); a tap writes the value.case options(DeckEditTarget, column: String)/// How often it comes round (`shell.opened {step: repeat}`).case repeats(DeckEditTarget)/// The faces the opened card's table offers (`card.offers`), each by its/// title, the one worn where the row rests; a tap wears it (`FaceChoices`).case faces(DeckEditTarget)/// Settings' Export card held: every table, Everything first, a tap/// writes its package (`ExportFan`, the owner, 23 Oct 2026).case exports(DeckEditTarget)/// A card whose acts are not its definition's: a business's row held on/// a customer's phone (`CustomerDeck`), whose acts are the customer's/// calls to the business's server (Book, Cancel booking) — handed to/// the editor whole (`offer`), never read from `shell.opened`.case offered(DeckEditTarget)/// An act's picks, one after another (`DeckPicks`): a customer, then how/// many; the last answer runs the act.case picks(DeckEditTarget)/// A deck holding no card, its empty placeholder held: its tool's own/// acts alone (`tools.acts`: Connect Google Calendar) — there is no/// record, so none of a card's acts (edit, Bin, Export) stand.case toolActs(DeckEditTarget)/// Send: the person's people, one of whom a tap sends a copy to/// (`shell.opened {step: send}`); a hold on one offers their trust.case sends(DeckEditTarget)}/// One act a card's caller hands the fan (`DeckEditor.offer`): its word,/// as the caller says it, what it asks first, and what a tap does.structDeckOffer: Identifiable {let id: Stringlet word: Stringvar picture: String? = nil/// The picks it asks on the fan before it runs (`DeckPicks`): a/// customer's Take an order, how many. Nil runs it at once.var asks: DeckOfferPicks? = nil/// The fan's primary act, printed on a business look's fill: a/// customer's Book or Order, as the caller says.var primary = false/// Its kit pictogram, by reference (`shell.plus`' door's `pictogram`),/// and the fan tile of the tool its tier is dealt under (`FanTileLook`).var pictogram: String? = nilvar tile: FanTileLook? = nil/// The act, handed its picks' answers in their order (none when it asks none).let perform: @MainActor ([String]) async -> Void}/// What an offered act asks on the fan: the act the core asks its picks/// for (`DeckPicking`), and where they are read.structDeckOfferPicks {let act: Stringvar record: TableRecord?var place: DeckPickPlace}/// The card being edited: its table, its record and, for a date, the column/// the corner says.publicstructDeckEditTarget: Equatable, Hashable, Sendable, Identifiable {publicvar id: String { "\(table)|\(record)" }publicvar table: Stringpublicvar record: String/// The date column the corner (or the When act) sets.publicvar date: String?publicinit(table: String, record: String, date: String?) {self.table = tableself.record = recordself.date = date }/// A deck of `table` that holds no card: the table alone, no record/// (`DeckEditing.toolActs`), so nothing on its fan writes a record.publicstaticfunc emptyDeck(of table: String) -> DeckEditTarget {DeckEditTarget(table: table, record: "", date: nil) }}/// Words the shell writes (owner, 28 Oct 2026: editing is the shell's,/// never the card's), in the one short-text input (`DeckLineInput`) or, a/// long text, on the whole screen (`DeckLongTextEditor`) — as the core/// answered the ask (`shell.input {op: ask}`): the editor, the words it/// opens on, and what a commit writes (`writes`), handed back whole on/// commit. The shell decides none of it.publicstructDeckWriting: Equatable, Sendable, Identifiable {publicenumEditor: String, Equatable, Sendable, Decodable {/// One line of text over the dimmed deck: a title, a line.case line/// The whole screen: a longtext column.case page/// One line of figures over the dimmed deck: a money row's amount/// (`shell.input`'s `amount` editor, Money's Add a spend), typed on/// the number keyboard and written in the currency's minor units by/// the core.case amount }publiclet id = UUID()publiclet editor: Editor/// The words as the record holds them.publiclet words: String/// The record's title, over the full-screen editor.publiclet title: String?/// The words in pencil while nothing is typed (a new record's).publiclet hint: String?/// Written away, its column keeps its words: a card's title.publiclet keepsWords: Bool/// What a commit writes, as the core answered it (`shell.input`'s/// `writes`): `kind` names it (`column`, `new`, `act`, `group`,/// `tool_act`, `pick_words`, `pick_search`).publiclet writes: JSONValue/// Written from the reader (`ReadPage`), which stands as its own cover/// over the stack: the reader presents the editor, not the stack's/// writing layer (`DeckWritingLayer`), and Done returns to its page.publicvar overReader = false/// The keyboard the words are typed on, as the core named it: `phone`/// for a number (Send's Add a person); nil for words.publicvar keyboard: String?publicinit(editor: Editor, words: String, title: String?, hint: String?, keepsWords: Bool, writes: JSONValue) {self.editor = editorself.words = wordsself.title = titleself.hint = hintself.keepsWords = keepsWordsself.writes = writes }init(_ asked: InputAsk) {self.init(editor: asked.editor, words: asked.words, title: asked.title, hint: asked.hint, keepsWords: asked.keeps_words, writes: asked.writes) keyboard = asked.keyboard }/// The kind of write the core named.publicvar kind: String? { writes["kind"]?.string }/// The card a column write is for: its record, or its draft.publicvar record: String? {guard kind == "column"else { returnnil }return writes["id"]?.string ?? writes["draft"]?.string }}/// `shell.input {op: ask}`'s answer: the editor a write stands in.structInputAsk: Decodable, Equatable, Sendable {let editor: DeckWriting.Editorlet words: Stringlet hint: String?let title: String?let keeps_words: Boollet writes: JSONValue/// `phone` where the words are a number.var keyboard: String?}/// `shell.input {op: commit}`'s answer: what the commit wrote, or why not.structInputCommitted: Decodable, Sendable {let change: CoreRecords.WireChange?let record: CoreRecords.WireRecord?/// The record a new card's create made.let made: String?/// A tool act's receipt and the change that undoes it.let said: String?let undo: String?/// The record an object act's answer names (`CreateAct.lands`).let lands: Lands?/// A pick's search, committed.let query: String?/// A pick answered: the next one due, or the act run.let step: PickStep?let ran: CommandOutcome?/// A customer's picks, every one answered, for the shell to post.let answers: [String]?/// The draft as it stands once a choice was staged on it.let draft: DraftSaid?/// The next words to write: a new note's body on the whole screen.let next: InputAsk?let refusal: String?/// The core asks this device's vault key lent for the same commit/// (a password door's act on a locked vault).let lend: Bool?structLands: Decodable, Sendable {let id: String }/// The store's own write, where the commit made one.var written: ChangeRecord? { change.map { CoreRecords.change(CoreRecords.WireWrite(change: $0, record: record)) } }}/// `shell.draft`'s answer: a card not yet made as the core holds it.structDraftSaid: Decodable, Sendable {let id: Stringlet table: Stringlet values: [String: RecordValue]let card: RecordValue?let made: String?}/// `shell.opened {step: pick}`'s step: the pick now due.structPickStep: Decodable, Equatable, Sendable {let label: Stringlet index: Int/// What a row's value is committed with (`shell.input`).let writes: JSONValuelet rows: [Row]?/// The row the arc rests on (a number's count).let rest: Int?/// A moment's pick: drawn on the days' row.let moment: Bool?/// A record pick's table: letters written over it narrow it.let table: String?/// What to say where it offers nothing.let nothing: String?/// Free words, asked in the shell's writer.let words: InputAsk?/// A file, asked of the platform's picker (`step.file`, SUBTITLE FILE): the copy's path is committed with/// its own `writes`.let file: FileAsk?structFileAsk: Decodable, Equatable, Sendable {let accept: [String]let hint: String?let writes: JSONValue }structRow: Decodable, Equatable, Sendable {let value: Stringlet words: Stringlet detail: String?let picture: String?let initials: String?/// `answer`, `count`, `day` or `search`.let does: Stringlet count: Double?let day: String?let search: InputAsk? }}privatestructPickAnswer: Decodable, Sendable { let step: PickStep }@MainActor@ObservablepublicfinalclassDeckEditor {/// The run's one editor over Home's fan: the fan's arc and the record/// button under it read the same state, so while a card is in action/// mode the button is its close (`FanRecord`).publicstaticlet session = DeckEditor()/// What the fan answers; nil while it shows tools.publicprivate(set) var editing: DeckEditing?/// Close restores the tier beneath; replacements (days → times) do not add one. @ObservationIgnored privatevar sharedTiers: FanTiers?/// The tiers the editor's choices stand on: the fan's, connected by/// FanSurface, or an editor's own (`standing()`). A choice put up before/// either would stand on a stack no fan draws: said loudly/// (`unconnected`), never quietly. Closing reads `shown`, and with no/// stack there is nothing to close.var navigation: FanTiers {iflet sharedTiers { return sharedTiers }Self.unconnected()let stack = Self.rootedTiers() sharedTiers = stackreturn stack }func connect(_ tiers: FanTiers) { sharedTiers = tiers }/// An editor standing on tiers of its own, rooted as the fan's: a/// test's, a preview's.staticfunc standing() -> DeckEditor {let editor = DeckEditor() editor.sharedTiers = rootedTiers()return editor }privatestaticfunc rootedTiers() -> FanTiers {let stack = FanTiers() stack.setRoot(FanTier(id: "editor-root", cards: []))return stack }/// What an editor asked for its tiers before any were connected does: a/// debug build stops there; a release one says it in the log.staticvar unconnected: () -> Void = { assertionFailure("DeckEditor asked for its tiers before FanSurface connected the fan's")Logger(subsystem: "com.cottondb.cotton", category: "deck").error("deck editor used before the fan connected its tiers") }/// The stack choices stand on, where one is connected.privatevar shown: FanTiers? { sharedTiers }privatefunc clearEditorTiers() {guardlet shown else { return }while shown.open?.editorState != nil { shown.pop() } } @ObservationIgnored privatevar closeOpened: (() -> Void)?publicprivate(set) var openedTarget: DeckEditTarget?/// The faces the opened card may be worn in, worn one first, as the/// core's face step answers them (`shell.opened {step: face}`): the/// faces tier Face opens offers these (`openFaces`).publicprivate(set) var faces: [OpenedChoice] = []/// A card not yet made, as the core keeps it (`shell.draft`): its id/// is the draft's until its create lands, and every choice made on it is/// staged there — one create per draft.private(set) var draft: DeckDraft? @ObservationIgnored privatevar draftStore: (any Records)?/// The core the draft is kept by (`shell.draft`). @ObservationIgnored privatevar draftCore: (any CottonCalling)? @ObservationIgnored privatevar draftMade: ((TableRecord) -> Void)?/// The last write the deck could not make, said by its writer layer.publicprivate(set) var refusal: DeckRefusal?/// `worn`: the face the card wears now, where the database keeps face/// choices: the core offers Face where the table offers another of its/// family, and its face step says which (`faces`).func presentOpened(_ target: DeckEditTarget, record: TableRecord, worn: String? = nil, view: String? = nil, core: (any CottonCalling)? = nil, close: @escaping () -> Void) { closeOpened = nil clearEditorTiers() closeOpened = close openedTarget = target faces = [] openActs(target, record: record, view: view, face: worn, core: core)guardlet worn, let core else { return }Task { @MainActor inlet ask: JSONValue = .object(["step": "face", "table": .string(target.table), "face": .string(worn)])let rows = (try? await core.call(CottonMethod.shellOpened, ask, as: OpenedStep<OpenedChoice>.self))?.step.rows ?? []guard openedTarget == target else { return } faces = rows } }func dismissOpened() { closeOpened = nil draft = nil draftStore = nil draftCore = nil draftMade = nil openedTarget = nil faces = [] clearEditorTiers() editing = nil picking = nil dismissWriting() }privatefunc push(_ next: DeckEditing) {guard editing != next || navigation.open?.editorState == nilelse { return } editing = nextlet tier = FanTier(id: "editor-\(String(describing: next))", cards: [], editorState: next) navigation.push(tier, onPop: { [weakself] inguardletselfelse { return }self.picking = nilself.editing = self.navigation.open?.editorStateifself.editing == nil { self.closeOpened?() } }) { _ in } }privatefunc replace(_ next: DeckEditing) {guard navigation.open?.editorState != nilelse { return push(next) } editing = next navigation.replaceOpen(FanTier(id: "editor-\(String(describing: next))", cards: [], editorState: next)) { _ in } }/// An act finishes by popping its choices through the shared navigation.privatefunc finish() {iflet openedTarget {whilelet shown, let state = shown.open?.editorState, state != .acts(openedTarget) { shown.pop() } editing = .acts(openedTarget) } else { clearEditorTiers(); editing = nil } picking = nil }/// The days on offer, as the core said them for today.publicprivate(set) var days: [DateChoice] = []/// How often a record can come round, as the core said it.publicprivate(set) var repeats: [RepeatChoice] = []/// The held card's acts as the core answered them (`shell.opened`), or/// an empty deck's tool acts alone (`tools.acts`). Empty until read.publicprivate(set) var actions: [CardAction] = []/// The fan tile of the tool the open tier is dealt under (`FanTileLook`):/// the held card's tool's, the empty deck's, Plus's.publicprivate(set) var tile: FanTileLook?/// The card `actions` were read for, so another card never wears them.publicprivate(set) var actsTarget: DeckEditTarget?/// The Status step's verbs, as the core said them for the held card.publicprivate(set) var statuses: [OpenedChoice] = []/// The Group step's row (`shell.opened {step: group}`): New list, then the lists.publicprivate(set) var groupRows: [GroupChoice] = []/// The Send step (`shell.opened {step: send}`): the people, or why there are none.publicprivate(set) var sendStep: SendStep?/// The core the held card was asked of: its steps, and its acts again/// once a new card is made, are asked of it too. @ObservationIgnored privatevar asked: (any CottonCalling)?/// What the held card was asked with (`view`, `face`): asked again with/// it once a new card is made. @ObservationIgnored privatevar askedWith: (view: String?, face: String?) = (nil, nil)/// The times on offer, as the core said them; empty while the core does/// not offer them, and then a day chosen is the whole edit.publicprivate(set) var times: [TimeChoice] = []/// The day the days row just wrote: the time is written onto it.publicprivate(set) var chosenDay: String?/// The record the last saved edit left its ink mark on, and when.publicprivate(set) var marked: DeckInkMark?/// The record as the card showed it when the fan opened: what a status/// verb's `when` and the date picker read.publicprivate(set) var held: TableRecord?/// The acts a card's caller handed the fan (`offer`), in its order.private(set) var offered: [DeckOffer] = []/// The act whose picks the fan asks (`DeckPicks`); nil while none is.private(set) var picking: DeckPicking?/// A file pick's platform picker: the person's file copied under its own name, nil on Cancel (`PickedFile`). @ObservationIgnored var chooseFile: @MainActor ([String]) asyncthrows -> URL? = { tryawaitPickedFile.choose($0) }/// The column the shell's input or full-screen editor writes; nil while/// neither stands.publicprivate(set) var writing: DeckWriting?/// Nothing under the shell's writer moves for the keyboard it raises:/// true from the moment the input or the full-screen editor opens until/// that keyboard has gone, and every page host under it lays its page/// out as though no keyboard stood (`deckStillUnderWriter`).publicprivate(set) var holdsKeyboard = false/// The keyboard stands on screen (`DeckWritingLayer` hears it). @ObservationIgnored privatevar keyboardShown = false/// What a new record's commit hands its deck: the record made. @ObservationIgnored privatevar made: ((TableRecord) -> Void)?/// The record as written, handed back to the reader that opened the/// editor, so its pages are cut again from the new words. @ObservationIgnored privatevar rewritten: ((TableRecord) -> Void)?/// The records the writing card's deck reads: what a commit writes to. @ObservationIgnored privatevar writingStore: (any Records)?/// The last write the shell made that its store took, as it took it:/// the deck it was made on reads itself again (`DeckSurface`), so its/// card stands as written and a record made stands where the deck's/// order puts it. Never left for a sync event, which a write to a served/// database need not raise: the ship walk (29 Oct 2026) saw a new note's/// body written and its card, its reader and the fan's Body still on the/// title alone, and the note itself only after a search.publicprivate(set) var landed: DeckLanded?public nonisolated init() {}/// The card a fan answers for, whichever way it was opened.publicvar target: DeckEditTarget? {switch editing {case .days(let target), .times(let target), .pickDays(let target), .pickTimes(let target), .acts(let target), .groups(let target), .statuses(let target), .repeats(let target), .faces(let target), .exports(let target), .offered(let target), .picks(let target), .toolActs(let target), .options(let target, _), .sends(let target): targetcasenil: nil } }/// Whether `record`'s date corner is open (circled)./// Which of a card's date places opened the days (its corner or its/// footer date): only that one is circled.publicprivate(set) var corner: String?publicfunc circles(_ record: String, at place: String? = nil) -> Bool {switch editing {case .days(let target), .times(let target), .pickDays(let target), .pickTimes(let target): target.record == record && holds(place)default: false } }/// Whether `place` is the date place the days were opened from.publicfunc holds(_ place: String?) -> Bool { corner == nil || place == nil || corner == place }/// The fan answers for a card: the floating line and the strip fade.publicvar isEditing: Bool { editing != nil || writing != nil }/// The part a tap last opened an editor from, and the record it is on/// (`DeckFaceParts`).privatevar tapped: (part: FacePart, record: String)?/// A tap on `record`'s `part`, which opens that part's editor.publicfunc select(_ part: FacePart, record: String) { tapped = (part, record) }/// The part of `record` whose editor stands open — its date's days, its/// statuses, its groups, the input or full-screen editor writing its/// words — which the face rings (`selectedFacePart`); nil while none is.publicfunc selected(on record: String) -> FacePart? {guardlet tapped, tapped.record == record else { returnnil }letopen: Bool = switch (tapped.part, editing) {case (.corner, _), (.when, _): circles(record)case (.state, .statuses(let target)?), (.group, .groups(let target)?), (.picture, .options(let target, _)?), (.seal, .options(let target, _)?), (.weather, .options(let target, _)?): target.record == recordcase (.state, _), (.group, _), (.picture, _), (.seal, _), (.weather, _): falsedefault: writing?.record == record }returnopen ? tapped.part : nil }/// The fan holds what a hold opened — the card's acts (When, Group,/// Repeat, Status, Bin) or the Export card's tables — not one of the/// value rows an act opens.publicvar holdsActs: Bool {switch editing {case .acts, .exports, .offered, .toolActs: returntruedefault: returnfalse } }// MARK: Opening and closing/// The corner tapped: the fan becomes the row of days. Opening changes/// nothing; a second tap on the same corner puts the fan back.publicfunc openDays(_ target: DeckEditTarget, record: TableRecord?, core: (any CottonCalling)?, at place: String? = nil) {guard target.date != nilelse { return }if editing == .days(target) { return close() } corner = place held = record chosenDay = niliflet core { asked = core } push(.days(target))Task { await readDays(target, core: core) }Task { await readTimes(target, core: core) } }func hold(_ record: TableRecord) { held = record }/// A choice put on the draft (`shell.draft {id, stage}`): staged by the/// core until its create lands, written onto its record once it has. The/// draft stands as the core answers it, its card in words.privatefunc stage(_ stage: JSONValue) {guardlet draft, let core = draftCore else { return }let id = draft.id// One after another, in the order chosen: a later day staged never// lands before an earlier one.let before = staging staging = Task { @MainActor inawait before?.valuedo {let said = tryawait core.call(CottonMethod.shellDraft, JSONValue.object(["id": .string(id), "stage": stage, "timezone": .string(TimeZone.current.identifier)]),as: DraftSaid.self)self.took(said, asked: id) } catch { say((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } } }/// The draft's last stage asked, which the next waits on. @ObservationIgnored privatevar staging: Task<Void, Never>?/// The draft as the core answered it: its values and its card, while it/// is still the draft asked about.privatefunc took(_ said: DraftSaid, asked id: String) {guardvar now = draft, now.id == id else { return }if now.isNew { now.record.values = said.values } now.said = said.card.flatMap { said inswitchDeckCard.read(said) {case .success(let card)?: return cardcase .failure(let failure)?: DeckCardLog.unreadable(id, failure); returnnilcasenil: returnnil } } draft = nowif now.isNew { held = now.record } }/// The card held: the fan becomes its acts as the core answers them/// (`shell.opened`), its tools' among them as they stand on the deck of/// `view` (`<tool>/<id>`); Face where it wears `face` and may wear another.publicfunc openActs(_ target: DeckEditTarget, record: TableRecord?, view: String? = nil, face: String? = nil, core: (any CottonCalling)? = nil) { held = record actions = [] parts = [:] actsTarget = niliflet core { asked = core } askedWith = (view, face) push(.acts(target))Task { await readActs(target) } }/// The Export card held: the fan becomes the tables (`ExportFan`), read/// by the fan as it opens.publicfunc openExports(_ target: DeckEditTarget, record: TableRecord?) { held = record push(.exports(target)) }/// A card held whose acts its caller holds (a customer's card on the/// business's server): the fan becomes those acts, in the caller's/// order; a tap does one and the fan goes back to its tools.func offer(_ acts: [DeckOffer], for target: DeckEditTarget) { held = nil offered = acts tile = acts.lazy.compactMap(\.tile).first push(.offered(target)) }/// A deck's empty placeholder held: the fan becomes its tool's acts/// (`tools.acts`, read by the placeholder as it stands), only the tool's/// — a tap runs one as it runs from a card (`EditingFan.runTool`).func openToolActs(_ acts: [CardAction], for target: DeckEditTarget, tile: FanTileLook? = nil) {let acts = acts.filter { Self.runsAsTool($0) || Self.sends($0) != nil }guard !acts.isEmpty else { return } held = nil actions = actsself.tile = tile actsTarget = nil push(.toolActs(target)) }/// `tools.acts`: the acts of the tools owning `table` that stand now on/// the deck of `view` (`<tool>/<id>`: Books' On this phone carries Sign/// in, Back up now and Sign out), resolved as a card's are, each one the/// fan can run; none when the core cannot say.staticfunc toolActs(of table: String, view: String? = nil, core: (any CottonCalling)?) async -> [CardAction] {await toolActsAnswer(of: table, view: view, core: core).actions }/// What is held where `tools.acts` is asked by more than its deck.enumToolActsHeld: String {/// A list's tile on the fan's lists tier: the list's own acts alone.case list }/// `tools.acts` whole: the acts, and their tool's fan tile.staticfunc toolActsAnswer(of table: String, view: String? = nil, held: ToolActsHeld? = nil, core: (any CottonCalling)?) async -> CardActions {var ask = ["table": table]iflet view { ask["view"] = view }iflet held { ask["held"] = held.rawValue }guardlet core,let answer = try? await core.call(CottonMethod.toolsActs, ask, as: CardActions.self)else { returnCardActions(actions: []) }returnCardActions(actions: answer.actions.filter(runsAsTool), tile: answer.tile) }/// A door's act at the object (`create.doors`): on a phone not signed in/// the object cannot be asked, so where the act says so in its own words/// (`signed_out`: "Sign in to find books by name") they are said until/// the next tap and the fan offers the Account card's acts as they/// stand (`shell.account`: Sign in alone, signed out); else its words/// are asked in the shell's input (`ask`).publicfunc askDoor(_ act: DefinitionCreateAct, door: String, table: String, core: (any CottonCalling)?, toasts: ToastCenter?, landed: (@MainActor (String) -> Void)? = nil) {guardlet words = act.signedOut else { return ask(table: table, door: door, core: core, landed: landed) }Task { @MainActor inguardlet core,let account = try? await core.call(CottonMethod.shellAccount, as: AccountAnswer.self), account.stand != "connected", account.actions.contains(where: Self.runsAsTool)else { return ask(table: table, door: door, core: core, landed: landed) } openToolActs(account.actions, for: .emptyDeck(of: table), tile: account.tile) toasts?.show(words, window: ToastWindow.untilTap) } }/// A tool's act (`tools.act`) the fan can run: it names its tool.staticfunc runsAsTool(_ action: CardAction) -> Bool { action.kind == "tool" && action.tool != nil }/// A held tile's Send (a list's): its own record, which Send's step is asked of.staticfunc sends(_ action: CardAction) -> DeckEditTarget? {guard action.step == EditingAct.send.rawValue, let table = action.table, let record = action.record else { returnnil }returnDeckEditTarget(table: table, record: record, date: nil) }/// `shell.opened`: the held card's acts, kept for this card alone. A/// card not yet made is asked by its values (`draft`).privatefunc readActs(_ target: DeckEditTarget) async {guardlet core = asked,let answer = try? await core.call(CottonMethod.shellOpened, openedAsk(target), as: OpenedActs.self), editing == .acts(target) else { return } actions = answer.acts tile = answer.tile parts = answer.parts ?? [:] actsTarget = target }/// The held card's tap map (`shell.opened`'s `parts`), for the card the/// acts were read for.publicprivate(set) var parts: [String: CardPart] = [:]/// What a tap on `slot` of `record` opens while it is held; nil where/// the place is the card's own tap.publicfunc part(_ slot: String, on record: String) -> CardPart? {guard actsTarget?.record == record else { returnnil }return parts[slot] }/// What the held card is asked by: its id, or a new card's values.privatefunc openedAsk(_ target: DeckEditTarget, step: String? = nil) -> OpenedAsk {let draft = self.draft.flatMap { $0.isNew && $0.record.id == target.record ? $0.record.values : nil }returnOpenedAsk(table: target.table, id: draft == nil ? target.record : nil, draft: draft, view: askedWith.view, face: askedWith.face, step: step, timezone: TimeZone.current.identifier) }/// One step's rows (`shell.opened {step}`); none when the core cannot say.privatefunc readStep<Row: Decodable & Sendable>(_ step: String, of target: DeckEditTarget, core: (any CottonCalling)?, all: Bool = false, column: String? = nil) async -> [Row]? {iflet core { asked = core }guardlet core = asked ?? draftCore else { returnnil }var ask = openedAsk(target, step: step) ask.all = all ? true : nil ask.column = columnreturntry? await core.call(CottonMethod.shellOpened, ask, as: OpenedStep<Row>.self).step.rows }/// A step row's write committed as the core said it (`shell.input`):/// why it was refused, nil where it landed.staticfunc commitRow(_ writes: JSONValue, core: any CottonCalling) async -> String? {let ask: JSONValue = .object(["op": "commit", "writes": writes, "words": "", "timezone": .string(TimeZone.current.identifier)])do {returntryawait core.call(CottonMethod.shellInput, ask, as: InputCommitted.self).refusal } catch {return (error as? CottonCallError)?.message ?? ActionRefused.words(for: error) } }/// The faces a table may be worn in, as a choice tier at the hub: one/// card per face, a tap wears it (`EditingFan`)./// The opened card's Face act opens it; the deck's hand cycles the faces/// instead (`FaceChoiceControl`), through the same `choose`.publicfunc openFaces(for target: DeckEditTarget) {guard faces.count > 1else { return } push(.faces(target)) }/// The footer's status word tapped: the fan becomes the statuses.publicfunc openStatuses(_ target: DeckEditTarget, record: TableRecord?, core: (any CottonCalling)? = nil) { held = record push(.statuses(target))Task { await readStatuses(target, core: core) } }/// The card's picture tapped where it chooses a column (an event's/// kind): the fan becomes that column's values. A second tap on the same/// picture puts the fan back.publicfunc openOptions(_ target: DeckEditTarget, column: String, record: TableRecord?) {if editing == .options(target, column: column) { return close() } held = record optionRows = [] push(.options(target, column: column))Task { optionRows = await readStep("options", of: target, core: nil, column: column) ?? [] } }/// An act that opens a further row: When's days, Group's groups, Status's values.publicfuncopen(_ next: DeckEditing, core: (any CottonCalling)?) { push(next)ifcase .days(let target) = next { chosenDay = nilTask { await readDays(target, core: core) }Task { await readTimes(target, core: core) } }ifcase .repeats(let target) = next, repeats.isEmpty { Task { await readRepeats(target, core: core) } }ifcase .statuses(let target) = next { Task { await readStatuses(target, core: core) } }ifcase .groups(let target) = next { Task { await readGroups(target, core: core) } }ifcase .sends(let target) = next { sendStep = nilTask { await readSend(target, core: core) } } }/// The Send step as the core answers it; a refusal (signed out, the/// object unreachable) is the step's own words.privatefunc readSend(_ target: DeckEditTarget, core: (any CottonCalling)?) async {iflet core { asked = core }guardlet core = asked ?? draftCore else { return }do { sendStep = tryawait core.call(CottonMethod.shellOpened, openedAsk(target, step: "send"), as: SendStepAnswer.self).step } catch { sendStep = SendStep(refused: ActionRefused.words(for: error)) } }/// The fan returns to its tools. An act whose picks were being asked/// is dropped: nothing runs.publicfunc close() {if writing != nil { dismissWriting(); return } picking = niliflet shown, shown.open?.editorState != nil { shown.pop() }else { editing = nil; closeOpened?() } }// MARK: Acts/// One of the card's commands tapped on its fan. One that picks nothing/// runs at once: its mark, the tools, the core's change. One that picks/// turns the fan into its first pick's answers, as the core answers them/// (`shell.opened {step: pick}`); one that asks free words asks them in/// the shell's writer.func act(_ command: RecordCommand, on target: DeckEditTarget, definition: TableDefinition, place: DeckPickPlace) async -> DeckActOutcome {if command.kind == .copy, command.copies == RecordCommand.copySealed {returnawait copySealed(on: target, core: place.core ?? asked ?? draftCore) }guard command.needsPick else { mark(target)returnawait run(command, on: target, store: place.store) }var place = placeif place.core == nil { place.core = asked ?? draftCore }let draft = self.draft.flatMap { $0.isNew && $0.record.id == target.record ? $0.id : nil } picking = DeckPicking(act: command.id, target: target, draft: draft, place: place)returnawait ask(opening: target) }/// A mark drawn over the card at rest (the core's `check`): the command/// its table binds to the mark (`marks`) run on the card's record as the/// card's acts run it — its ink mark, the core's change, the stamp its/// face lands. A mark the table binds nothing to, or whose command the/// record is past (a todo already done), runs nothing (owner, 3 Nov/// 2026: "marking a todo as done is just having a check mark").func act(mark: String, on record: TableRecord, definition: TableDefinition, place: DeckPickPlace) async -> DeckActOutcome {guardlet command = definition.command(forMark: mark, on: record) else { return .none }let target = DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn)returnawait act(command, on: target, definition: definition, place: place) }/// An offered act tapped on its fan (a customer's Take an order): one/// that asks nothing runs at once; one that asks turns the fan into its/// picks, over the rows the business served, and the last answer hands/// every answer to the act. The close runs nothing.func act(_ offer: DeckOffer, on target: DeckEditTarget) async -> DeckActOutcome {guardlet asks = offer.asks else { finish()await offer.perform([])return .none } held = asks.record picking = DeckPicking(act: asks.act, target: target, draft: nil, place: asks.place, perform: offer.perform)returnawait ask(opening: target) }/// The answers the fan's picks offer now.var pickOptions: [DeckPickOption] { picking?.options ?? [] }/// The card the picks' arc rests on.var pickRest: Int { picking?.rest ?? 0 }/// A pick's card tapped: a stepper moves its count, a day turns the fan/// to its times, a search asks its words, an answer is committed — the/// core answers the next pick, or runs the act with every answer.func answer(_ option: DeckPickOption) async -> DeckActOutcome {guardvar picking, editing == .picks(picking.target), let step = picking.step else { return .none }switch option.does {case .search(let asked):guardlet asked else { return .none } holdsKeyboard = true writing = DeckWriting(asked)return .askingcase .count(let count): picking.count = countself.picking = pickingreturnawait ask()case .day(let day): picking.day = dayself.picking = pickingreturnawait ask()case .answer(let value):returnawait committed(value, writes: step.writes) } }/// A pick's answer committed (`shell.input`): the next pick due, or the/// act run — staged on a draft until its create lands.privatefunc committed(_ value: String, writes: JSONValue) async -> DeckActOutcome {guardlet picking, let core = picking.place.core else { return .none }let answer: InputCommitteddo { answer = tryawait core.call(CottonMethod.shellInput, commitAsk(writes, words: value), as: InputCommitted.self) } catch { close()return .refused((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) }iflet answers = answer.answers, let perform = picking.perform {self.picking = nil finish()await perform(answers)return .none }return picked(answer, in: picking) }/// A file pick (Give subtitles): the platform's picker, nothing else drawn. The copy's path is committed as the/// words and the copy removed once the commit has answered; Cancel closes the step and sends nothing.privatefunc pickFile(_ file: PickStep.FileAsk, step: PickStep) async -> DeckActOutcome {guardvar picking else { return .none } picking.step = stepself.picking = pickinglet copy: URL?do { copy = tryawait chooseFile(file.accept) } catch {if editing == .picks(picking.target) { close() }self.picking = nilreturn .refused((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) }guardlet copy else {if editing == .picks(picking.target) { close() }self.picking = nilreturn .none }let outcome = await committed(copy.path(percentEncoded: false), writes: file.writes)PickedFile.remove(copy)return outcome }/// What a pick's commit came to, on the fan.privatefunc picked(_ answer: InputCommitted, in asked: DeckPicking) -> DeckActOutcome {iflet refusal = answer.refusal { close()return .refused(refusal) }iflet step = answer.step {var next = asked next.query = "" next.ink = InkLetters() next.inkSurface = "pick:\(UUID().uuidString)" next.count = nil next.day = nil picking = next// Words were asked in the writer, over the card's acts: the next// pick turns the fan into its answers.return show(step, opening: editing == .picks(asked.target) ? nil : asked.target) } picking = niliflet draft = answer.draft { mark(asked.target) took(draft, asked: draft.id)return .none }iflet ran = answer.ran { mark(asked.target)do {let change = try ran.change(table: asked.target.table, record: asked.target.record) land(change, on: asked.target.table)return .ran(change) } catch {return .refused(ActionRefused.words(for: error)) } } finish()return .none }/// A record pick stands on the fan: letters written above it narrow/// its answers rather than the deck (`InkGround`).var picksRecords: Bool {guardlet picking, editing == .picks(picking.target) else { returnfalse }return picking.step?.table != nil }/// The letters the core holds for the record pick on the fan, after a/// letter written over it or one taken back: its answers narrowed by the/// core to the rows a word of whose name starts with them. A letter is/// always taken: one that leaves no answer leaves the pick with none/// (owner, 4 Nov 2026).func narrowPick(to ink: InkLetters) async {guardvar asked = picking, picksRecords else { return }// The same letters (a backspace on none): the answers stand.guard ink.letters != asked.ink.letters else { picking?.ink = inkreturn } asked.ink = ink picking = asked _ = await ask() }/// The pick now due, read onto the fan (`shell.opened {step: pick}`). One/// with nothing to offer closes the fan and says so. The first pick of/// an act (`opening`) turns the fan into the picks only once its answers/// are read, in one change: a fan turned into its picks with none yet/// unmounted the arc for that moment, and the answers then dealt onto it/// stood unprinted (the walk of 24 Oct 2026).privatefunc ask(opening: DeckEditTarget? = nil) async -> DeckActOutcome {guardlet picking, let core = picking.place.core else { return .none }let asked = picking.askedlet step: PickStepdo { step = tryawait core.call(CottonMethod.shellOpened, asked, as: PickAnswer.self).step } catch { close()return .refused((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) }// Closed, moved on, or asked again while the answers were read: a// slower read for older letters never stands over newer ones.guardlet now = self.picking, now.asked == asked, opening != nil || editing == .picks(now.target) else { return .none }iflet file = step.file { returnawait pickFile(file, step: step) }return show(step, opening: opening) }/// The pick the core answered, on the fan — or, where it asks free/// words, in the shell's writer over the card's acts.privatefunc show(_ step: PickStep, opening: DeckEditTarget?) -> DeckActOutcome {guardvar picking else { return .none } picking.step = stepiflet words = step.words {self.picking = picking holdsKeyboard = true writing = DeckWriting(words)return .asking }let options = (step.rows ?? []).map { DeckPickOption($0, index: step.index) }guard !options.isEmpty || step.table != nil && !picking.ink.isEmpty else { close()self.picking = nilreturn .refused(step.nothing ?? ShellLines.line("editing", "command.the_choices_could_not")) } picking.options = optionsself.picking = pickingiflet opening { push(.picks(opening)) }return .asking }/// A password's Copy (`copies: "$sealed"`): the device's own act, never/// the core's `records.command` (it refuses a copy: the value must not/// pass through a write). `password.reveal` opens the row on the/// five-minute unlock, or — locked — with this device's vault key read/// once (the read IS Face ID) and lent for this one call, and answers/// `copies`, the value Copy takes; it goes on the clipboard set to/// expire. A row the Worker sealed refuses in the core's words.privatefunc copySealed(on target: DeckEditTarget, core: (any CottonCalling)?, clipboard: any Clipboard = SystemClipboard(), keyring: VaultKeyring = VaultKeyring()) async -> DeckActOutcome {guardlet core else { return .refused(ShellLines.line("record", "unreadable")) }let id = target.recordvar answer: JSONValuedo { answer = tryawait core.callJSON(CottonMethod.passwordReveal, ["id": id]) } catchlet refusal asCottonCallErrorwhere refusal.code == "vault_locked" {let read = awaitTask.detached(priority: .userInitiated) { () -> Result<String, Error> indo { return .success(try keyring.privateKey()) } catch { return .failure(error) } }.valueguardcase .success(let key) = read else {ifcase .failure(let error) = read, case .cancelled? = error as? VaultKeyError { return .none }return .refused(ShellLines.line("passwords", "vault.phone_own_key")) }do { answer = tryawait core.callJSON(CottonMethod.passwordReveal, ["id": id, "privateKey": key]) } catch {return .refused(SecretCopy.problem(error)) } } catch {return .refused(SecretCopy.problem(error)) }guardlet value = answer["copies"]?.string, !value.isEmpty else {return .refused(ShellLines.line("record", "unreadable")) }guard clipboard.put(value, expiringAfter: SecretClipboard.seconds) else {return .refused(ShellLines.line("record", "copy.no_expiry")) }return .ran(ChangeRecord( id: "copy-\(UUID().uuidString.lowercased())", byline: "You", before: nil, after: nil, undoable: false, reason: nil, said: ChangeSaid(kind: "command", said: ShellLines.line("record", "copied_expires")))) }/// A command that picks nothing, run by the core — staged on a draft/// until its create lands.privatefunc run(_ command: RecordCommand, on target: DeckEditTarget, store: (any Records)?) async -> DeckActOutcome {iflet draft, draft.isNew, draft.record.id == target.record { stage(.object(["act": .string(command.id)]))return .none }guardlet engine = store as? any RecordCommandselse { return .none }do {let change = tryawait engine.command(table: target.table, id: target.record, command: command, picked: nil) land(change, on: target.table)return .ran(change) } catch {return .refused(ActionRefused.words(for: error)) } }// MARK: Saving/// A day chosen: written at once, keeping the time the card had, and the/// fan goes straight on to the times (No time first). Where the core/// offers no times the day is the whole edit: the mark, the tools./// A choice that sets no day (Pick a date) is the caller's to open.publicfunc choose(_ choice: DateChoice, store: (any Records)?, core: (any CottonCalling)?) {guardlet target = dayTarget, let day = choice.day else { return } writeWhen(target, day: .set(day), time: .keep, store: store, core: core)guard !times.isEmpty else { return mark(target) } chosenDay = day replace(.times(target)) }/// No date: the card's when is cleared, its time with it.publicfunc chooseNoDate(store: (any Records)?, core: (any CottonCalling)?) {guardcase .days(let target) = editing else { return } writeWhen(target, day: .clear, time: .clear, store: store, core: core) mark(target) }/// A time chosen (or No time): written onto the day, keeping it.publicfunc choose(_ choice: TimeChoice?, store: (any Records)?, core: (any CottonCalling)?) {guardlet target = timeTarget else { return }let day: WhenHalf = chosenDay.map(WhenHalf.set) ?? .keep writeWhen(target, day: day, time: choice?.time.map(WhenHalf.set) ?? .clear, store: store, core: core) mark(target) }/// The card a day is chosen for: the days row or the picked days.privatevar dayTarget: DeckEditTarget? {switch editing {case .days(let target), .pickDays(let target): targetdefault: nil } }/// The card a time is chosen for: the times row or the picked times.privatevar timeTarget: DeckEditTarget? {switch editing {case .times(let target), .pickTimes(let target): targetdefault: nil } }/// Pick a date (or a time): the row opens on every day of the coming/// weeks (every half hour), on the fan, in the sheet's place, as the/// core says them (`shell.opened {step: when|time, all: true}`).publicfunc openPick() {switch editing {case .days(let target): push(.pickDays(target))Task { pickedDays = await readStep("when", of: target, core: nil, all: true) ?? [] }case .times(let target): push(.pickTimes(target))Task { pickedTimes = await readStep("time", of: target, core: nil, all: true) ?? [] }default: break } }/// Pick a date's every day, as the core said them.publicprivate(set) var pickedDays: [DateChoice] = []/// Pick a time's every half hour, as the core said them.publicprivate(set) var pickedTimes: [TimeChoice] = []/// A choice column's values, as the core says them (`{step: options}`).publicprivate(set) var optionRows: [OpenedChoice] = []// MARK: The when's two halves/// One half of a card's when: kept as it is, cleared, or set.publicenumWhenHalf: Equatable, Sendable {case keep, clearcase set(String) }/// THE ONE WRITE OF A CARD'S WHEN (`cards.when`): the half it is not/// given is kept by the core — a day keeps the record's time, a time its/// day (today's, on a record with none). A core that refuses it is said,/// in the core's own line, by the deck's writer layer; nothing is/// written another way (6 Nov 2026: a silent second write hid a When/// that never landed).publicfunc writeWhen(_ target: DeckEditTarget, day: WhenHalf, time: WhenHalf, store: (any Records)?, core: (any CottonCalling)?) {guard target.date != nilelse { return }if draft?.isNew == true {// The draft's when is the core's to work out (`shell.draft`'s// `when` stage): the half not given is kept.var when: [String: JSONValue] = [:]for (key, half) in [("date", day), ("time", time)] {switch half {case .keep: breakcase .clear: when[key] = .nullcase .set(let value): when[key] = .string(value) } } stage(.object(["when": .object(when)]))return }guardlet core else { return }Task {var request: [String: JSONValue] = ["table": .string(target.table), "id": .string(target.record),"timezone": .string(TimeZone.current.identifier)]for (key, half) in [("date", day), ("time", time)] {switch half {case .keep: breakcase .clear: request[key] = .nullcase .set(let value): request[key] = .string(value) } }do { _ = tryawait core.callJSON(CottonMethod.cardsWhen, JSONValue.object(request)) land(nil, on: target.table) } catch {Self.acts.error("\(CottonMethod.cardsWhen, privacy: .public) refused: \(String(describing: error), privacy: .public)") say((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } } }/// One value written to the record the fan answers for, then the fan/// returns. The card is drawn again from the core's re-read, so its/// corner, paper and animal are the core's for the new value.publicfunc save(_ target: DeckEditTarget, patch: [String: RecordValue], store: (any Records)?) { mark(target)if draft?.isNew == true { stage(.object(["values": Self.json(patch)])); return }guardlet store else { return }Task {guardlet change = try? await store.update(table: target.table, id: target.record, patch: patch) else { return } land(change, on: target.table) } }/// A write the store took: said to the deck it was made on (`landed`).privatefunc land(_ change: ChangeRecord?, on table: String) { landed = DeckLanded(table: table, change: change)// A write to the opened card asks its acts again: what holds of it// now is the core's to say (Start reading run, Finished stands).iflet target = openedTarget, target.table == table, change?.after.map({ $0.id == target.record }) ?? true {Task { await readActs(target) } }guardlet draft, !draft.isNew, draft.definition.id == table else { return }// A change's row is the stored values alone, without the card the// core resolves on a read (`@card`): taken as it is, the made card// fell back to its pre-title draft card, a blank strip (Rigby 11// walk, 8 Nov 2026). Without a card it is read again.iflet after = change?.after, after.id == draft.record.id, DeckCard(after) != nil {self.draft?.record = after held = after } elseiflet store = draftStore {Task {guardlet after = try? await store.get(table: table, id: draft.record.id),self.draft?.record.id == after.id else { return }self.draft?.record = after held = after } } }// MARK: Writing/// A card's words tapped: the shell writes their column — a longtext on/// the whole screen, any other in the short-text input — as the core/// answers the ask (`shell.input {op: ask, kind: column}`). A new card's/// title is its create's. The fan returns.publicfunc write(_ target: DeckEditTarget, column: String, store: (any Records)?, core: (any CottonCalling)?) {if openedTarget == nil { finish() } writingStore = store ?? draftStoreif draft?.isNew == true { made = draftMade }var ask: [String: JSONValue] = ["op": "ask", "kind": "column", "table": .string(target.table), "column": .string(column)]iflet draft, draft.isNew, draft.record.id == target.record { ask["draft"] = .string(draft.id) } else { ask["id"] = .string(target.record) }open(ask, core: core ?? asked ?? draftCore) }/// The reader's page held (`ReadPage`): the column the page shows written/// on the whole screen, over the reader; Done hands the record as written/// to `rewritten`, and the reader stands on, cut again from it.func write(_ target: DeckEditTarget, column: String, store: (any Records)?, core: (any CottonCalling)?, overReader rewritten: @escaping (TableRecord) -> Void) {if openedTarget == nil { finish() } writingStore = storeself.rewritten = rewrittenopen(["op": "ask", "kind": "column", "table": .string(target.table), "id": .string(target.record), "column": .string(column)], core: core ?? asked, overReader: true) }/// The shell's writer opened on what the core answered for `ask`; a/// write the core refuses is said by the deck's writer layer.privatefuncopen(_ ask: [String: JSONValue], core: (any CottonCalling)?, overReader: Bool = false) {guardlet core else { return say(ShellLines.line("record", "acting.that_change_was_not")) } writingCore = core holdsKeyboard = truelet token = UUID() asking = tokenTask { @MainActor indo {let asked = tryawait core.call(CottonMethod.shellInput, JSONValue.object(ask), as: InputAsk.self)// Put away, or asked again, while the core answered: the// writer the person no longer waits for never stands.guard asking == token else { return } asking = nilvar writing = DeckWriting(asked) writing.overReader = overReaderself.writing = writing } catch {guard asking == token else { return } asking = nilifself.writing == nil, !keyboardShown { holdsKeyboard = false }// Over the reader, a body the core says nobody writes here// opens nothing: the long press does nothing.if overReader, (error as? CottonCallError)?.code == "refused" { return } say((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } } }/// A deck's "+" on a kind made by its title: the core begins its draft/// (`shell.draft`, the view's `preset` its values) and the short-text/// input asks the title, the record made on commit and handed to `made`./// On a face that tags no part (a note's torn page) the card's body is/// written next, on the whole screen, as the core answers (`next`).publicfunc create(_ definition: TableDefinition, preset: [String: RecordValue], store: (any Records)?, core: (any CottonCalling)? = nil, made: @escaping (TableRecord) -> Void) {guardlet core else { return } dismissOpened()Task { @MainActor inlet said: DraftSaiddo { said = tryawait core.call(CottonMethod.shellDraft, JSONValue.object(["table": .string(definition.id), "values": Self.json(preset),"timezone": .string(TimeZone.current.identifier)]),as: DraftSaid.self) } catch {return say((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) }let record = TableRecord(id: said.id, values: said.values) draft = DeckDraft(id: said.id, definition: definition, record: record) took(said, asked: said.id) draftStore = store draftCore = corelet target = DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn) presentOpened(target, record: record, core: core) { [weakself] inself?.dismissOpened() } writingStore = store follows = DeckFace.tagsNoPart(definition)self.made = made draftMade = madeopen(["op": "ask", "kind": "new", "table": .string(definition.id), "draft": .string(said.id)], core: core) } }/// A group act's "New group": the short-text input under the group's/// name, the group made on commit with the card's record in it.func nameGroup(_ target: DeckEditTarget, store: (any Records)?) { writingStore = storeopen(["op": "ask", "kind": "group", "table": .string(target.table), "id": .string(target.record)], core: asked) }/// Add a person (Account's Your people, and Send's last row, the one/// add): their number in the shell's short-text input. Once committed,/// the Send tier it was asked over is read again, and Account hears it/// (`cottonPeopleChanged`): the person stands there, waiting until they/// add this person back.func addPerson(_ add: SendAdd? = nil, core: (any CottonCalling)?) {var ask: [String: JSONValue] = ["kind": .string(DeckEditor.addPersonKind)]ifcase .object(let said)? = add?.ask { ask = said } ask["op"] = "ask"open(ask, core: core ?? asked) }/// The input's kind for Add a person where the core named none.staticlet addPersonKind = "people_add"/// The core the shell's writer commits through. @ObservationIgnored privatevar writingCore: (any CottonCalling)?/// The ask the writer waits on (`open`): a writer put away before the/// core answers drops it. @ObservationIgnored privatevar asking: UUID?/// Where a tool's act run from the input says its receipt (`askToolWords`). @ObservationIgnored privatevar actingToasts: ToastCenter?/// Who stands on the record an act at the object lands (`CreateAct.lands`). @ObservationIgnored privatevar actingLands: (@MainActor (String) -> Void)?/// A new card's face tags no part: its body is written next (`next`). @ObservationIgnored privatevar follows = false/// A deck's "+" whose definition hands the words to an act at the/// person's object (`create.act`, or its `door`'s): the short-text input/// under the create's label, and the act run on commit. Nothing is made/// on the phone: the object writes, and the deck takes it by sync. An/// act that `lands` hands the record its answer names to `landed`,/// which stands on it (Books' Find a book: the new card).publicfunc ask(table: String, door: String? = nil, core: (any CottonCalling)?, landed: (@MainActor (String) -> Void)? = nil) { dismissOpened() actingLands = landedvar ask: [String: JSONValue] = ["op": "ask", "kind": "act", "table": .string(table)]iflet door { ask["door"] = .string(door) }open(ask, core: core) }/// A Plus door that writes a new record (`accepts.draft`): the core/// begins it with the door's values (`shell.input {kind: door}`) and asks/// each part in turn in the shell's input, the next part handed back on/// each commit (`next`), the record made by the last.publicfunc askDraftDoor(table: String, door: String, core: (any CottonCalling)?) { dismissOpened()open(["op": "ask", "kind": "door", "table": .string(table), "door": .string(door),"timezone": .string(TimeZone.current.identifier)], core: core) }/// A tool's act that asks its words first (a list's Rename): the shell's/// short-text input under the act's hint, holding the words the core/// gave it (the list's name); committed, the act runs with them.func askToolWords(_ action: CardAction, core: (any CottonCalling)?, toasts: ToastCenter?) {guardlet words = action.words, let tool = action.tool else { return } dismissOpened() actingToasts = toastsvar ask: [String: JSONValue] = ["op": "ask", "kind": "tool_act", "tool": .string(tool), "act": .string(action.id),"words": .object(["prefill": words.prefill.map(JSONValue.string) ?? .null,"hint": words.hint.map(JSONValue.string) ?? .null])]for (key, value) in [("account", action.account), ("group", action.group), ("record", action.record)] {iflet value { ask[key] = .string(value) } }open(ask, core: core) }privatestaticlet acts = Logger(subsystem: "com.cottondb.deck", category: "acts")/// A value as the core takes it.staticfunc json(_ value: someEncodable) -> JSONValue { (try? JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value))) ?? .null }/// `shell.input {op: commit}`'s request for `writes` and the words typed.privatefunc commitAsk(_ writes: JSONValue, words: String) -> JSONValue {var ask: [String: JSONValue] = ["op": "commit", "writes": writes, "words": .string(words),"timezone": .string(TimeZone.current.identifier)]if follows, writes["kind"]?.string == "new" { ask["follows"] = .bool(true) }return .object(ask) }/// The words committed: the core writes what the ask said they write/// (`shell.input {op: commit}`) — the column, the record made, the act/// run, the list made, a pick answered — and answers it, or why not.publicfunc commit(_ text: String) {guardlet writing else { return }let made = self.madelet rewritten = self.rewritten// A pick's words are its act's, asked of the core the pick was read from.let core = (writing.kind?.hasPrefix("pick") == true ? picking?.place.core : nil) ?? writingCore ?? asked ?? draftCorelet toasts = actingToastslet lands = actingLandslet picking = self.picking// The pick's words keep its picks: dismissing them is a commit's.if writing.kind == "pick_words" || writing.kind == "pick_search" { self.picking = nil } dismissWriting()self.picking = pickingguardlet core else { return say(ShellLines.line("record", "acting.that_change_was_not")) }// An edit's mark goes on at once, as the edit is made.if writing.kind == "column" || writing.kind == "group", let record = writing.record ?? writing.writes["id"]?.string { mark(DeckEditTarget(table: writing.writes["table"]?.string ?? "", record: record, date: nil)) }Task { @MainActor invar answer: InputCommittedlet ask = commitAsk(writing.writes, words: text)do { answer = tryawait core.call(CottonMethod.shellInput, ask, as: InputCommitted.self)// The core asks a lend (Passwords' New password on a locked// vault): this device's vault key, read once — the read IS// Face ID — and the same words committed again with it.if answer.lend == true, case .object(var lent) = ask {guardlet key = awaitSelf.lentKey() else { return } lent["privateKey"] = .string(key) answer = tryawait core.call(CottonMethod.shellInput, JSONValue.object(lent), as: InputCommitted.self) } } catch {Self.acts.error("\(CottonMethod.shellInput, privacy: .public) refused: \(String(describing: error), privacy: .public)")return say((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) }await committed(answer, writing: writing, made: made, rewritten: rewritten, toasts: toasts, lands: lands, core: core) } }/// This device's vault key for one lent call; nil when the person/// cancelled Face ID or the phone has no key.privatestaticfunc lentKey(keyring: VaultKeyring = VaultKeyring()) async -> String? {awaitTask.detached(priority: .userInitiated) { try? keyring.privateKey() }.value }/// What a commit came to, on the deck.privatefunc committed(_ answer: InputCommitted, writing: DeckWriting, made: ((TableRecord) -> Void)?, rewritten: ((TableRecord) -> Void)?, toasts: ToastCenter?, lands: (@MainActor (String) -> Void)?, core: any CottonCalling) async {let table = writing.writes["table"]?.string ?? ""iflet query = answer.query, var asked = picking { asked.query = query picking = askedifcase .refused(let words) = await ask() { say(words) }return }if answer.step != nil || answer.ran != nil || (writing.kind == "pick_words" && answer.draft != nil), let asked = picking {ifcase .refused(let words) = picked(answer, in: asked) { say(words) }return }iflet id = answer.made {await madeDraft(id, answer: answer, made: made) } elseiflet change = answer.written { land(change, on: table)iflet after = change.after { rewritten?(after) } }iflet draft = answer.draft { took(draft, asked: draft.id) }iflet id = answer.lands?.id { lands?(id) }iflet said = answer.said {iflet undo = answer.undo { DeckActs.say(.receipt(said, undo: undo), toasts: toasts, core: core) }else { DeckActs.say(.said(said), toasts: toasts, core: core) } }iflet refusal = answer.refusal { say(refusal) }// A person added: the Send tier it was asked over is read again, and Account hears it.if writing.kind == DeckEditor.addPersonKind {NotificationCenter.default.post(name: .cottonPeopleChanged, object: nil)ifcase .sends(let target)? = editing { await readSend(target, core: core) } }iflet next = answer.next { holdsKeyboard = trueself.writing = DeckWriting(next) } }/// The draft's record made by the core's one create: the card stands as/// the record made, its acts asked by its id now, and the deck learns/// what it made before it reads (`DeckOrder.kept`).privatefunc madeDraft(_ id: String, answer: InputCommitted, made: ((TableRecord) -> Void)?) async {guardvar draft = self.draft else { return }let table = draft.definition.idvar after = answer.record?.record ?? TableRecord(id: id, values: draft.record.values)if after.id != id { after = TableRecord(id: id, values: after.values) }if draft.isNew { draft.record = after draft.isNew = falseself.draft = draftlet target = DeckEditTarget(table: table, record: id, date: draft.definition.whenColumn)// Close choices against the draft's old identity before// replacing its acts with the newly stored record. finish() openedTarget = target held = after actions = [] actsTarget = nil replace(.acts(target))Task { await readActs(target) } }iflet store = draftStore, let read = try? await store.get(table: table, id: id) { after = read }ifself.draft?.record.id == id {self.draft?.record = after held = after } made?(after) land(answer.written, on: table) }/// A write the deck could not make, said once by its writer layer.privatefunc say(_ sentence: String) { refusal = DeckRefusal(sentence: sentence) }/// The input dismissed: nothing is written, and an act asking its words/// there runs nothing.publicfunc dismissWriting() {if writing?.kind == "pick_words" { picking = nil } writing = nil asking = nil made = nil rewritten = nil writingStore = nil// The page under it stands still until the keyboard has gone, not// only the writer: let go as the keyboard goes, the page rose to// it and fell back in the keyboard's last frames.if !keyboardShown { holdsKeyboard = false } }/// The keyboard came up or has gone (`DeckWritingLayer`): once it has/// gone with no writer standing, the pages answer the keyboard again.publicfunc keyboard(shown: Bool) { keyboardShown = shownif !shown, writing == nil { holdsKeyboard = false } }/// The edit is made: its mark is left and the fan returns to its tools.publicfunc mark(_ target: DeckEditTarget) { marked = DeckInkMark(record: target.record, at: .now) finish() }/// The mark fades: it was a reward, not a state.publicfunc unmark(_ mark: DeckInkMark) {if marked == mark { marked = nil } }// MARK: The days/// The When step's row (`shell.opened {step: when}`): No date, then the days.privatefunc readDays(_ target: DeckEditTarget, core: (any CottonCalling)?) async {guardlet rows: [DateChoice] = await readStep("when", of: target, core: core) else { return } days = rows }/// The record's times on offer (`shell.opened {step: time}`): No time,/// the hours, its own time among them marked, Pick a time. None when the/// core does not answer, and then a day chosen is the whole edit.privatefunc readTimes(_ target: DeckEditTarget, core: (any CottonCalling)?) async { times = [] times = await readStep("time", of: target, core: core) ?? [] }privatefunc readRepeats(_ target: DeckEditTarget, core: (any CottonCalling)?) async {guardlet rows: [RepeatChoice] = await readStep("repeat", of: target, core: core) else { return } repeats = rows }/// The Status step's verbs (`shell.opened {step: status}`).privatefunc readStatuses(_ target: DeckEditTarget, core: (any CottonCalling)?) async { statuses = [] statuses = await readStep("status", of: target, core: core) ?? [] }/// The Group step's row (`shell.opened {step: group}`), in the core's order.privatefunc readGroups(_ target: DeckEditTarget, core: (any CottonCalling)?) async { groupRows = [] groupRows = await readStep("group", of: target, core: core) ?? [] }/// A repeat chosen: the record comes round by it (or stops), at once.publicfunc choose(_ choice: RepeatChoice, core: (any CottonCalling)?) {guardcase .repeats(let target) = editing else { return } mark(target)if draft?.isNew == true { stage(.object(["repeat": .string(choice.key)])); return }Task { await writeRepeat(choice, on: target, core: core) } }privatefunc writeRepeat(_ choice: RepeatChoice, on target: DeckEditTarget, core: (any CottonCalling)?) async {guardlet core else { return }let request = ["id": target.record, "preset": choice.key, "timezone": TimeZone.current.identifier]guard (try? await core.callJSON(CottonMethod.cardsRepeat, request)) != nilelse { return } land(nil, on: target.table) }/// The days handed in whole (a specimen's fixture, a test).publicfunc show(days: [DateChoice]) {self.days = days }/// The times handed in whole (a specimen's fixture, a test).publicfunc show(times: [TimeChoice]) {self.times = times }/// Opens straight onto a row, for a specimen.publicfunc stand(_ editing: DeckEditing?) {iflet editing { push(editing) } else { clearEditorTiers(); self.editing = nil } }}/// A write the shell's editor made that its store took (`DeckEditor.landed`):/// the table it wrote and the change as the store answered it — none for a/// write the core made without one (`cards.when`, `cards.repeat`). Each/// landing is its own, however alike two are.publicstructDeckLanded: Equatable, Sendable {publiclet id = UUID()publiclet table: Stringpubliclet change: ChangeRecord?}/// The small ink mark a saved edit leaves on the card.publicstructDeckInkMark: Equatable, Sendable {publicvar record: Stringpublicvar at: Date}/// `shell.opened`'s request: the held card by its id, or a new card by/// its values (`draft`); a step's rows where it names one.structOpenedAsk: Encodable, Sendable {let table: Stringlet id: String?let draft: [String: RecordValue]?let view: String?let face: String?let step: String?let timezone: String/// Pick a date's, Pick a time's: every day, every half hour.var all: Bool? = nil/// The choice column whose values are asked (`step: options`).var column: String? = nil}/// `tools.acts`' answer: an empty deck's tool acts, and the fan tile of/// their tool (`FanTileLook`).structCardActions: Decodable, Sendable {publicvar actions: [CardAction]publicvar tile: FanTileLook? = nil}/// `shell.opened`'s answer for a held card: its acts, ranked and flagged,/// and the fan tile of the tool owning its table (`FanTileLook`).structOpenedActs: Decodable, Sendable {var acts: [CardAction]var tile: FanTileLook?/// The face's tap map while the card is held, by card place.var parts: [String: CardPart]?}/// What a tap on one of a held card's places opens (`shell.opened`'s/// `parts`): the days, the statuses, the lists, a choice column's values,/// the viewer, the line or the whole screen, and the column it writes.publicstructCardPart: Decodable, Equatable, Hashable, Sendable {/// `days`, `statuses`, `groups`, `options`, `viewer`, `line` or `page`.publicvar does: Stringpublicvar column: String?publicinit(does: String, column: String? = nil) {self.does = doesself.column = column }}/// `shell.opened {step}`'s answer: the step's rows, in order.structOpenedStep<Row: Decodable & Sendable>: Decodable, Sendable {structStep: Decodable, Sendable {var kind: Stringvar rows: [Row] }var step: Step}/// One row of a step as the core said it: its value and its words (a/// status verb's command id and label).publicstructOpenedChoice: Decodable, Equatable, Hashable, Sendable {publicvar value: Stringpublicvar words: String/// It takes the record away (Drop): drawn red.publicvar red: Bool?/// The picture the core names for it (`act-stamp`), where it names one.publicvar picture: String?/// Its kit pictogram, by reference, where its tool's fan tile names one.publicvar pictogram: String?/// The one the record stands on now (the face it wears).publicvar chosen: Bool?/// What `shell.input` commits to choose it, where the core says.publicvar writes: JSONValue?}/// One row of the Group step as the core said it: New list (`new`), or a/// list by its id, how many it holds and whether the held card is in it.publicstructGroupChoice: Decodable, Equatable, Hashable, Sendable {publicvar value: Stringpublicvar words: Stringpublicvar new: Bool?publicvar detail: String?publicvar holds: Bool?/// The picture the core names for it (`act-plus`, `edit-act-group`).publicvar picture: String?/// Its kit pictogram, by reference, where its tool's fan tile names one.publicvar pictogram: String?/// The one the record stands on now (the face it wears).publicvar chosen: Bool?/// What `shell.input` commits to join or leave this list.publicvar writes: JSONValue?}/// How often a record comes round (`shell.opened {step: repeat}`): Never,/// then the presets.publicstructRepeatChoice: Decodable, Equatable, Hashable, Sendable, Identifiable {/// The preset (`none`, `daily`, `weekly` …).publicvar key: Stringpublicvar label: String/// The picture the core names for it (`act-cross`, `act-cycle`).publicvar picture: String?publicvar id: String { key }enumCodingKeys: String, CodingKey { case key = "value", label = "words", picture }}/// One act of a held card as the core answered it (`shell.opened`): a/// command of the record's definition, a handoff (`address`), a chooser/// that opens a step (when, group, repeat, status, face) or Bin, or an act/// of the card's tool (`tools.act`: Connect Google Calendar) — ranked,/// primary and red as the core said. An empty deck's tool acts/// (`tools.acts`) come in the same shape, unranked.publicstructCardAction: Decodable, Equatable, Hashable, Sendable, Identifiable {publicvar id: Stringpublicvar label: String/// `command`, `chooser`, `address` or `tool`.publicvar kind: String/// `main`, `more` or `away`.publicvar rank: String?/// The one act a business look prints on its brand's fill.publicvar primary: Bool?/// Drawn red: it takes the record away, and stands last.publicvar red: Bool?/// The picture the fan draws it with (`act-stamp`, `edit-act-when`),/// where it has one.publicvar icon: String?/// The column a chooser sets (`due_at`, `recurrence_id`, `status`).publicvar column: String?/// The step a tap opens instead of running (`when`, `repeat`, `status`…).publicvar step: String?/// A handoff's address, opened by the OS.publicvar url: String?/// A tool's act: the tool it is, whether it asks first (Disconnect), and/// the account it is for.publicvar tool: String?publicvar asks: Bool?publicvar account: String?/// A list's own act (Set picture from Photos, Remove picture, Play): the/// list it is for, and the song its Play starts from.publicvar group: String?publicvar record: String?/// The table `record` is of, where an act names a record of its own (a list's Send).publicvar table: String?/// The words it asks before it runs (a list's Rename), in the shell's/// one short-text input: what the input holds, and its hint.publicvar words: CardActionWords?/// Its kit pictogram, by reference (`photo:<sha256>`), where its tool's/// fan tile names one (`FanTileLook`).publicvar pictogram: String?publicinit(id: String, label: String, kind: String, rank: String? = nil, primary: Bool? = nil, red: Bool? = nil, icon: String? = nil, column: String? = nil, step: String? = nil, url: String? = nil, tool: String? = nil, asks: Bool? = nil, account: String? = nil, group: String? = nil) {self.id = idself.label = labelself.kind = kindself.rank = rankself.primary = primaryself.red = redself.icon = iconself.column = columnself.step = stepself.url = urlself.tool = toolself.asks = asksself.account = accountself.group = group }}/// What a tool's act asks in the short-text input (`CardAction.words`).publicstructCardActionWords: Decodable, Equatable, Hashable, Sendable {publicvar prefill: String?publicvar hint: String?publicinit(prefill: String? = nil, hint: String? = nil) {self.prefill = prefillself.hint = hint }}/// What a tool's act answers (`tools.act`): the page to open, the flow this/// device's own row runs (an account act's Sign in or Sign out), or the/// words it says (Back up now).structToolActAnswer: Decodable, Sendable {var opens: String?var said: String?/// The change that undoes what it wrote (a list's move, its removal).var undo: String?var platform: RecordPlatformAction?/// The document the act wrote, to share once it is here (Export OPML).var document: String?enumCodingKeys: String, CodingKey { case opens, said, undo, document }init(from decoder: Decoder) throws {let c = try decoder.container(keyedBy: CodingKeys.self) opens = try c.decodeIfPresent(String.self, forKey: .opens) said = try c.decodeIfPresent(String.self, forKey: .said) undo = try c.decodeIfPresent(String.self, forKey: .undo) document = try c.decodeIfPresent(String.self, forKey: .document) platform = tryRecordPlatformAction.fromAnswer(decoder) }}/// What a tool's act came to (`DeckActs.ran`).enumToolActOutcome: Equatable {case opens(URL)case platform(RecordPlatformAction)case said(String)/// Its receipt, and the change that undoes it.case receipt(String, undo: String)/// A document it wrote, shared once it has come; its words meanwhile.case document(String, said: String?)case nothing}/// `tools.act`'s request.structToolActAsk: Encodable, Sendable {let tool: Stringlet act: Stringlet account: String?var group: String? = nilvar record: String? = nilvar words: String? = nil}/// One time on offer (`shell.opened {step: time}`): its words as the core/// said them, and the time it sets.publicstructTimeChoice: Decodable, Equatable, Hashable, Sendable, Identifiable {/// `none` (No time), `HH:MM`, or `pick` (Pick a time).publicvar key: Stringpublicvar label: String/// `HH:MM`; none for No time and Pick a time.publicvar time: String?/// The record's own time.publicvar chosen: Bool?/// The picture the core names for it (`act-clock`, `act-cross`).publicvar picture: String?publicvar id: String { key }enumCodingKeys: String, CodingKey { case key = "value", label = "words", time, chosen, picture }publicinit(key: String, label: String, time: String? = nil, chosen: Bool? = nil, picture: String? = nil) {self.key = keyself.label = labelself.time = timeself.chosen = chosenself.picture = picture }}/// One day on offer (`shell.opened {step: when}`): its words as the core/// said them, and the day it sets.publicstructDateChoice: Decodable, Equatable, Hashable, Sendable, Identifiable {/// Stable from day to day ("today", "weekday-2", "month-1", "pick").publicvar key: String/// `none` (No date), `today`, `day`, `week`, `month` or `pick`: what it does.publicvar kind: Stringpublicvar label: Stringpublicvar detail: String?/// `YYYY-MM-DD`; none for Pick a date.publicvar day: String?/// The picture the core names for it (`edit-value-today`, `act-cross`).publicvar picture: String?publicvar id: String { key }enumCodingKeys: String, CodingKey { case key = "value", kind, label = "words", detail, day, picture }publicinit(key: String, kind: String, label: String, detail: String? = nil, day: String? = nil, picture: String? = nil) {self.key = keyself.kind = kindself.label = labelself.detail = detailself.day = dayself.picture = picture }}privatestructDeckEditorKey: EnvironmentKey {staticlet defaultValue: DeckEditor? = nil}privatestructDeckViewNameKey: EnvironmentKey {staticlet defaultValue: String? = nil}extensionEnvironmentValues {/// The view the deck shows, as `<tool>/<id>` (`ToolView.Read.name`): the/// tool acts its cards and its empty placeholder offer are that view's.var deckViewName: String? { get { self[DeckViewNameKey.self] } set { self[DeckViewNameKey.self] = newValue } }}extensionEnvironmentValues {/// The editor over Home's fan; nil where no fan stands (a pushed page,/// the Mac), and then a card is not edited in place.publicvar deckEditor: DeckEditor? { get { self[DeckEditorKey.self] } set { self[DeckEditorKey.self] = newValue } }}/// A write the deck could not make: its sentence, said once (`DeckWritingLayer`).publicstructDeckRefusal: Equatable, Sendable {publiclet id = UUID()publiclet sentence: String}