// 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. import CottonFaces import CottonKit import CottonPaper import CottonValues import os import SwiftUI /// What the fan answers while a card is being edited. public enum DeckEditing: 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. struct DeckOffer: Identifiable { let id: String let word: String var 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? = nil var 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. struct DeckOfferPicks { let act: String var record: TableRecord? var place: DeckPickPlace } /// The card being edited: its table, its record and, for a date, the column /// the corner says. public struct DeckEditTarget: Equatable, Hashable, Sendable, Identifiable { public var id: String { "\(table)|\(record)" } public var table: String public var record: String /// The date column the corner (or the When act) sets. public var date: String? public init(table: String, record: String, date: String?) { self.table = table self.record = record self.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. public static func 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. public struct DeckWriting: Equatable, Sendable, Identifiable { public enum Editor: 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 } public let id = UUID() public let editor: Editor /// The words as the record holds them. public let words: String /// The record's title, over the full-screen editor. public let title: String? /// The words in pencil while nothing is typed (a new record's). public let hint: String? /// Written away, its column keeps its words: a card's title. public let 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`). public let 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. public var 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. public var keyboard: String? public init(editor: Editor, words: String, title: String?, hint: String?, keepsWords: Bool, writes: JSONValue) { self.editor = editor self.words = words self.title = title self.hint = hint self.keepsWords = keepsWords self.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. public var kind: String? { writes["kind"]?.string } /// The card a column write is for: its record, or its draft. public var record: String? { guard kind == "column" else { return nil } return writes["id"]?.string ?? writes["draft"]?.string } } /// `shell.input {op: ask}`'s answer: the editor a write stands in. struct InputAsk: Decodable, Equatable, Sendable { let editor: DeckWriting.Editor let words: String let hint: String? let title: String? let keeps_words: Bool let 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. struct InputCommitted: 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? struct Lands: 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. struct DraftSaid: Decodable, Sendable { let id: String let table: String let values: [String: RecordValue] let card: RecordValue? let made: String? } /// `shell.opened {step: pick}`'s step: the pick now due. struct PickStep: Decodable, Equatable, Sendable { let label: String let index: Int /// What a row's value is committed with (`shell.input`). let writes: JSONValue let 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? struct FileAsk: Decodable, Equatable, Sendable { let accept: [String] let hint: String? let writes: JSONValue } struct Row: Decodable, Equatable, Sendable { let value: String let words: String let detail: String? let picture: String? let initials: String? /// `answer`, `count`, `day` or `search`. let does: String let count: Double? let day: String? let search: InputAsk? } } private struct PickAnswer: Decodable, Sendable { let step: PickStep } @MainActor @Observable public final class DeckEditor { /// 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`). public static let session = DeckEditor() /// What the fan answers; nil while it shows tools. public private(set) var editing: DeckEditing? /// Close restores the tier beneath; replacements (days → times) do not add one. @ObservationIgnored private var 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 { if let sharedTiers { return sharedTiers } Self.unconnected() let stack = Self.rootedTiers() sharedTiers = stack return 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. static func standing() -> DeckEditor { let editor = DeckEditor() editor.sharedTiers = rootedTiers() return editor } private static func 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. static var 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. private var shown: FanTiers? { sharedTiers } private func clearEditorTiers() { guard let shown else { return } while shown.open?.editorState != nil { shown.pop() } } @ObservationIgnored private var closeOpened: (() -> Void)? public private(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`). public private(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 private var draftStore: (any Records)? /// The core the draft is kept by (`shell.draft`). @ObservationIgnored private var draftCore: (any CottonCalling)? @ObservationIgnored private var draftMade: ((TableRecord) -> Void)? /// The last write the deck could not make, said by its writer layer. public private(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) guard let worn, let core else { return } Task { @MainActor in let ask: JSONValue = .object(["step": "face", "table": .string(target.table), "face": .string(worn)]) let rows = (try? await core.call(CottonMethod.shellOpened, ask, as: OpenedStep.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() } private func push(_ next: DeckEditing) { guard editing != next || navigation.open?.editorState == nil else { return } editing = next let tier = FanTier(id: "editor-\(String(describing: next))", cards: [], editorState: next) navigation.push(tier, onPop: { [weak self] in guard let self else { return } self.picking = nil self.editing = self.navigation.open?.editorState if self.editing == nil { self.closeOpened?() } }) { _ in } } private func replace(_ next: DeckEditing) { guard navigation.open?.editorState != nil else { 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. private func finish() { if let openedTarget { while let 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. public private(set) var days: [DateChoice] = [] /// How often a record can come round, as the core said it. public private(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. public private(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. public private(set) var tile: FanTileLook? /// The card `actions` were read for, so another card never wears them. public private(set) var actsTarget: DeckEditTarget? /// The Status step's verbs, as the core said them for the held card. public private(set) var statuses: [OpenedChoice] = [] /// The Group step's row (`shell.opened {step: group}`): New list, then the lists. public private(set) var groupRows: [GroupChoice] = [] /// The Send step (`shell.opened {step: send}`): the people, or why there are none. public private(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 private var asked: (any CottonCalling)? /// What the held card was asked with (`view`, `face`): asked again with /// it once a new card is made. @ObservationIgnored private var 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. public private(set) var times: [TimeChoice] = [] /// The day the days row just wrote: the time is written onto it. public private(set) var chosenDay: String? /// The record the last saved edit left its ink mark on, and when. public private(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. public private(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]) async throws -> URL? = { try await PickedFile.choose($0) } /// The column the shell's input or full-screen editor writes; nil while /// neither stands. public private(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`). public private(set) var holdsKeyboard = false /// The keyboard stands on screen (`DeckWritingLayer` hears it). @ObservationIgnored private var keyboardShown = false /// What a new record's commit hands its deck: the record made. @ObservationIgnored private var 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 private var rewritten: ((TableRecord) -> Void)? /// The records the writing card's deck reads: what a commit writes to. @ObservationIgnored private var 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. public private(set) var landed: DeckLanded? public nonisolated init() {} /// The card a fan answers for, whichever way it was opened. public var 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): target case nil: 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. public private(set) var corner: String? public func 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. public func holds(_ place: String?) -> Bool { corner == nil || place == nil || corner == place } /// The fan answers for a card: the floating line and the strip fade. public var isEditing: Bool { editing != nil || writing != nil } /// The part a tap last opened an editor from, and the record it is on /// (`DeckFaceParts`). private var tapped: (part: FacePart, record: String)? /// A tap on `record`'s `part`, which opens that part's editor. public func 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. public func selected(on record: String) -> FacePart? { guard let tapped, tapped.record == record else { return nil } let open: 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 == record case (.state, _), (.group, _), (.picture, _), (.seal, _), (.weather, _): false default: writing?.record == record } return open ? 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. public var holdsActs: Bool { switch editing { case .acts, .exports, .offered, .toolActs: return true default: return false } } // 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. public func openDays(_ target: DeckEditTarget, record: TableRecord?, core: (any CottonCalling)?, at place: String? = nil) { guard target.date != nil else { return } if editing == .days(target) { return close() } corner = place held = record chosenDay = nil if let 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. private func stage(_ stage: JSONValue) { guard let 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 in await before?.value do { let said = try await 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 private var staging: Task? /// The draft as the core answered it: its values and its card, while it /// is still the draft asked about. private func took(_ said: DraftSaid, asked id: String) { guard var now = draft, now.id == id else { return } if now.isNew { now.record.values = said.values } now.said = said.card.flatMap { said in switch DeckCard.read(said) { case .success(let card)?: return card case .failure(let failure)?: DeckCardLog.unreadable(id, failure); return nil case nil: return nil } } draft = now if 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` (`/`); Face where it wears `face` and may wear another. public func openActs(_ target: DeckEditTarget, record: TableRecord?, view: String? = nil, face: String? = nil, core: (any CottonCalling)? = nil) { held = record actions = [] parts = [:] actsTarget = nil if let 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. public func 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 = acts self.tile = tile actsTarget = nil push(.toolActs(target)) } /// `tools.acts`: the acts of the tools owning `table` that stand now on /// the deck of `view` (`/`: 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. static func 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. enum ToolActsHeld: 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. static func toolActsAnswer(of table: String, view: String? = nil, held: ToolActsHeld? = nil, core: (any CottonCalling)?) async -> CardActions { var ask = ["table": table] if let view { ask["view"] = view } if let held { ask["held"] = held.rawValue } guard let core, let answer = try? await core.call(CottonMethod.toolsActs, ask, as: CardActions.self) else { return CardActions(actions: []) } return CardActions(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`). public func askDoor(_ act: DefinitionCreateAct, door: String, table: String, core: (any CottonCalling)?, toasts: ToastCenter?, landed: (@MainActor (String) -> Void)? = nil) { guard let words = act.signedOut else { return ask(table: table, door: door, core: core, landed: landed) } Task { @MainActor in guard let 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. static func 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. static func sends(_ action: CardAction) -> DeckEditTarget? { guard action.step == EditingAct.send.rawValue, let table = action.table, let record = action.record else { return nil } return DeckEditTarget(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`). private func readActs(_ target: DeckEditTarget) async { guard let 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. public private(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. public func part(_ slot: String, on record: String) -> CardPart? { guard actsTarget?.record == record else { return nil } return parts[slot] } /// What the held card is asked by: its id, or a new card's values. private func openedAsk(_ target: DeckEditTarget, step: String? = nil) -> OpenedAsk { let draft = self.draft.flatMap { $0.isNew && $0.record.id == target.record ? $0.record.values : nil } return OpenedAsk(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. private func readStep(_ step: String, of target: DeckEditTarget, core: (any CottonCalling)?, all: Bool = false, column: String? = nil) async -> [Row]? { if let core { asked = core } guard let core = asked ?? draftCore else { return nil } var ask = openedAsk(target, step: step) ask.all = all ? true : nil ask.column = column return try? await core.call(CottonMethod.shellOpened, ask, as: OpenedStep.self).step.rows } /// A step row's write committed as the core said it (`shell.input`): /// why it was refused, nil where it landed. static func commitRow(_ writes: JSONValue, core: any CottonCalling) async -> String? { let ask: JSONValue = .object(["op": "commit", "writes": writes, "words": "", "timezone": .string(TimeZone.current.identifier)]) do { return try await 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`. public func openFaces(for target: DeckEditTarget) { guard faces.count > 1 else { return } push(.faces(target)) } /// The footer's status word tapped: the fan becomes the statuses. public func 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. public func 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. public func open(_ next: DeckEditing, core: (any CottonCalling)?) { push(next) if case .days(let target) = next { chosenDay = nil Task { await readDays(target, core: core) } Task { await readTimes(target, core: core) } } if case .repeats(let target) = next, repeats.isEmpty { Task { await readRepeats(target, core: core) } } if case .statuses(let target) = next { Task { await readStatuses(target, core: core) } } if case .groups(let target) = next { Task { await readGroups(target, core: core) } } if case .sends(let target) = next { sendStep = nil Task { 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. private func readSend(_ target: DeckEditTarget, core: (any CottonCalling)?) async { if let core { asked = core } guard let core = asked ?? draftCore else { return } do { sendStep = try await 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. public func close() { if writing != nil { dismissWriting(); return } picking = nil if let 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 { return await copySealed(on: target, core: place.core ?? asked ?? draftCore) } guard command.needsPick else { mark(target) return await run(command, on: target, store: place.store) } var place = place if 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) return await 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 { guard let command = definition.command(forMark: mark, on: record) else { return .none } let target = DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn) return await 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 { guard let 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) return await 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 { guard var picking, editing == .picks(picking.target), let step = picking.step else { return .none } switch option.does { case .search(let asked): guard let asked else { return .none } holdsKeyboard = true writing = DeckWriting(asked) return .asking case .count(let count): picking.count = count self.picking = picking return await ask() case .day(let day): picking.day = day self.picking = picking return await ask() case .answer(let value): return await 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. private func committed(_ value: String, writes: JSONValue) async -> DeckActOutcome { guard let picking, let core = picking.place.core else { return .none } let answer: InputCommitted do { answer = try await core.call(CottonMethod.shellInput, commitAsk(writes, words: value), as: InputCommitted.self) } catch { close() return .refused((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } if let 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. private func pickFile(_ file: PickStep.FileAsk, step: PickStep) async -> DeckActOutcome { guard var picking else { return .none } picking.step = step self.picking = picking let copy: URL? do { copy = try await chooseFile(file.accept) } catch { if editing == .picks(picking.target) { close() } self.picking = nil return .refused((error as? CottonCallError)?.message ?? ActionRefused.words(for: error)) } guard let copy else { if editing == .picks(picking.target) { close() } self.picking = nil return .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. private func picked(_ answer: InputCommitted, in asked: DeckPicking) -> DeckActOutcome { if let refusal = answer.refusal { close() return .refused(refusal) } if let 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 = nil if let draft = answer.draft { mark(asked.target) took(draft, asked: draft.id) return .none } if let 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 { guard let picking, editing == .picks(picking.target) else { return false } 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 { guard var asked = picking, picksRecords else { return } // The same letters (a backspace on none): the answers stand. guard ink.letters != asked.ink.letters else { picking?.ink = ink return } 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). private func ask(opening: DeckEditTarget? = nil) async -> DeckActOutcome { guard let picking, let core = picking.place.core else { return .none } let asked = picking.asked let step: PickStep do { step = try await 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. guard let now = self.picking, now.asked == asked, opening != nil || editing == .picks(now.target) else { return .none } if let file = step.file { return await 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. private func show(_ step: PickStep, opening: DeckEditTarget?) -> DeckActOutcome { guard var picking else { return .none } picking.step = step if let 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 = nil return .refused(step.nothing ?? ShellLines.line("editing", "command.the_choices_could_not")) } picking.options = options self.picking = picking if let 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. private func copySealed(on target: DeckEditTarget, core: (any CottonCalling)?, clipboard: any Clipboard = SystemClipboard(), keyring: VaultKeyring = VaultKeyring()) async -> DeckActOutcome { guard let core else { return .refused(ShellLines.line("record", "unreadable")) } let id = target.record var answer: JSONValue do { answer = try await core.callJSON(CottonMethod.passwordReveal, ["id": id]) } catch let refusal as CottonCallError where refusal.code == "vault_locked" { let read = await Task.detached(priority: .userInitiated) { () -> Result in do { return .success(try keyring.privateKey()) } catch { return .failure(error) } }.value guard case .success(let key) = read else { if case .failure(let error) = read, case .cancelled? = error as? VaultKeyError { return .none } return .refused(ShellLines.line("passwords", "vault.phone_own_key")) } do { answer = try await core.callJSON(CottonMethod.passwordReveal, ["id": id, "privateKey": key]) } catch { return .refused(SecretCopy.problem(error)) } } catch { return .refused(SecretCopy.problem(error)) } guard let 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. private func run(_ command: RecordCommand, on target: DeckEditTarget, store: (any Records)?) async -> DeckActOutcome { if let draft, draft.isNew, draft.record.id == target.record { stage(.object(["act": .string(command.id)])) return .none } guard let engine = store as? any RecordCommands else { return .none } do { let change = try await 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. public func choose(_ choice: DateChoice, store: (any Records)?, core: (any CottonCalling)?) { guard let 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. public func chooseNoDate(store: (any Records)?, core: (any CottonCalling)?) { guard case .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. public func choose(_ choice: TimeChoice?, store: (any Records)?, core: (any CottonCalling)?) { guard let 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. private var dayTarget: DeckEditTarget? { switch editing { case .days(let target), .pickDays(let target): target default: nil } } /// The card a time is chosen for: the times row or the picked times. private var timeTarget: DeckEditTarget? { switch editing { case .times(let target), .pickTimes(let target): target default: 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}`). public func 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. public private(set) var pickedDays: [DateChoice] = [] /// Pick a time's every half hour, as the core said them. public private(set) var pickedTimes: [TimeChoice] = [] /// A choice column's values, as the core says them (`{step: options}`). public private(set) var optionRows: [OpenedChoice] = [] // MARK: The when's two halves /// One half of a card's when: kept as it is, cleared, or set. public enum WhenHalf: Equatable, Sendable { case keep, clear case 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). public func writeWhen(_ target: DeckEditTarget, day: WhenHalf, time: WhenHalf, store: (any Records)?, core: (any CottonCalling)?) { guard target.date != nil else { 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: break case .clear: when[key] = .null case .set(let value): when[key] = .string(value) } } stage(.object(["when": .object(when)])) return } guard let 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: break case .clear: request[key] = .null case .set(let value): request[key] = .string(value) } } do { _ = try await 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. public func save(_ target: DeckEditTarget, patch: [String: RecordValue], store: (any Records)?) { mark(target) if draft?.isNew == true { stage(.object(["values": Self.json(patch)])); return } guard let store else { return } Task { guard let 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`). private func 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). if let target = openedTarget, target.table == table, change?.after.map({ $0.id == target.record }) ?? true { Task { await readActs(target) } } guard let 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. if let after = change?.after, after.id == draft.record.id, DeckCard(after) != nil { self.draft?.record = after held = after } else if let store = draftStore { Task { guard let 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. public func write(_ target: DeckEditTarget, column: String, store: (any Records)?, core: (any CottonCalling)?) { if openedTarget == nil { finish() } writingStore = store ?? draftStore if draft?.isNew == true { made = draftMade } var ask: [String: JSONValue] = ["op": "ask", "kind": "column", "table": .string(target.table), "column": .string(column)] if let 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 = store self.rewritten = rewritten open(["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. private func open(_ ask: [String: JSONValue], core: (any CottonCalling)?, overReader: Bool = false) { guard let core else { return say(ShellLines.line("record", "acting.that_change_was_not")) } writingCore = core holdsKeyboard = true let token = UUID() asking = token Task { @MainActor in do { let asked = try await 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 = nil var writing = DeckWriting(asked) writing.overReader = overReader self.writing = writing } catch { guard asking == token else { return } asking = nil if self.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`). public func create(_ definition: TableDefinition, preset: [String: RecordValue], store: (any Records)?, core: (any CottonCalling)? = nil, made: @escaping (TableRecord) -> Void) { guard let core else { return } dismissOpened() Task { @MainActor in let said: DraftSaid do { said = try await 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 = core let target = DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn) presentOpened(target, record: record, core: core) { [weak self] in self?.dismissOpened() } writingStore = store follows = DeckFace.tagsNoPart(definition) self.made = made draftMade = made open(["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 = store open(["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)] if case .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. static let addPersonKind = "people_add" /// The core the shell's writer commits through. @ObservationIgnored private var writingCore: (any CottonCalling)? /// The ask the writer waits on (`open`): a writer put away before the /// core answers drops it. @ObservationIgnored private var asking: UUID? /// Where a tool's act run from the input says its receipt (`askToolWords`). @ObservationIgnored private var actingToasts: ToastCenter? /// Who stands on the record an act at the object lands (`CreateAct.lands`). @ObservationIgnored private var actingLands: (@MainActor (String) -> Void)? /// A new card's face tags no part: its body is written next (`next`). @ObservationIgnored private var 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). public func ask(table: String, door: String? = nil, core: (any CottonCalling)?, landed: (@MainActor (String) -> Void)? = nil) { dismissOpened() actingLands = landed var ask: [String: JSONValue] = ["op": "ask", "kind": "act", "table": .string(table)] if let 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. public func 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?) { guard let words = action.words, let tool = action.tool else { return } dismissOpened() actingToasts = toasts var 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)] { if let value { ask[key] = .string(value) } } open(ask, core: core) } private static let acts = Logger(subsystem: "com.cottondb.deck", category: "acts") /// A value as the core takes it. static func json(_ value: some Encodable) -> JSONValue { (try? JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value))) ?? .null } /// `shell.input {op: commit}`'s request for `writes` and the words typed. private func 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. public func commit(_ text: String) { guard let writing else { return } let made = self.made let 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 ?? draftCore let toasts = actingToasts let lands = actingLands let 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 = picking guard let 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 in var answer: InputCommitted let ask = commitAsk(writing.writes, words: text) do { answer = try await 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 { guard let key = await Self.lentKey() else { return } lent["privateKey"] = .string(key) answer = try await 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. private static func lentKey(keyring: VaultKeyring = VaultKeyring()) async -> String? { await Task.detached(priority: .userInitiated) { try? keyring.privateKey() }.value } /// What a commit came to, on the deck. private func 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 ?? "" if let query = answer.query, var asked = picking { asked.query = query picking = asked if case .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 { if case .refused(let words) = picked(answer, in: asked) { say(words) } return } if let id = answer.made { await madeDraft(id, answer: answer, made: made) } else if let change = answer.written { land(change, on: table) if let after = change.after { rewritten?(after) } } if let draft = answer.draft { took(draft, asked: draft.id) } if let id = answer.lands?.id { lands?(id) } if let said = answer.said { if let undo = answer.undo { DeckActs.say(.receipt(said, undo: undo), toasts: toasts, core: core) } else { DeckActs.say(.said(said), toasts: toasts, core: core) } } if let 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) if case .sends(let target)? = editing { await readSend(target, core: core) } } if let next = answer.next { holdsKeyboard = true self.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`). private func madeDraft(_ id: String, answer: InputCommitted, made: ((TableRecord) -> Void)?) async { guard var draft = self.draft else { return } let table = draft.definition.id var 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 = false self.draft = draft let 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) } } if let store = draftStore, let read = try? await store.get(table: table, id: id) { after = read } if self.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. private func say(_ sentence: String) { refusal = DeckRefusal(sentence: sentence) } /// The input dismissed: nothing is written, and an act asking its words /// there runs nothing. public func 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. public func keyboard(shown: Bool) { keyboardShown = shown if !shown, writing == nil { holdsKeyboard = false } } /// The edit is made: its mark is left and the fan returns to its tools. public func mark(_ target: DeckEditTarget) { marked = DeckInkMark(record: target.record, at: .now) finish() } /// The mark fades: it was a reward, not a state. public func 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. private func readDays(_ target: DeckEditTarget, core: (any CottonCalling)?) async { guard let 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. private func readTimes(_ target: DeckEditTarget, core: (any CottonCalling)?) async { times = [] times = await readStep("time", of: target, core: core) ?? [] } private func readRepeats(_ target: DeckEditTarget, core: (any CottonCalling)?) async { guard let rows: [RepeatChoice] = await readStep("repeat", of: target, core: core) else { return } repeats = rows } /// The Status step's verbs (`shell.opened {step: status}`). private func 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. private func 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. public func choose(_ choice: RepeatChoice, core: (any CottonCalling)?) { guard case .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) } } private func writeRepeat(_ choice: RepeatChoice, on target: DeckEditTarget, core: (any CottonCalling)?) async { guard let core else { return } let request = ["id": target.record, "preset": choice.key, "timezone": TimeZone.current.identifier] guard (try? await core.callJSON(CottonMethod.cardsRepeat, request)) != nil else { return } land(nil, on: target.table) } /// The days handed in whole (a specimen's fixture, a test). public func show(days: [DateChoice]) { self.days = days } /// The times handed in whole (a specimen's fixture, a test). public func show(times: [TimeChoice]) { self.times = times } /// Opens straight onto a row, for a specimen. public func stand(_ editing: DeckEditing?) { if let 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. public struct DeckLanded: Equatable, Sendable { public let id = UUID() public let table: String public let change: ChangeRecord? } /// The small ink mark a saved edit leaves on the card. public struct DeckInkMark: Equatable, Sendable { public var record: String public var 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. struct OpenedAsk: Encodable, Sendable { let table: String let 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`). struct CardActions: Decodable, Sendable { public var actions: [CardAction] public var 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`). struct OpenedActs: 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. public struct CardPart: Decodable, Equatable, Hashable, Sendable { /// `days`, `statuses`, `groups`, `options`, `viewer`, `line` or `page`. public var does: String public var column: String? public init(does: String, column: String? = nil) { self.does = does self.column = column } } /// `shell.opened {step}`'s answer: the step's rows, in order. struct OpenedStep: Decodable, Sendable { struct Step: Decodable, Sendable { var kind: String var 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). public struct OpenedChoice: Decodable, Equatable, Hashable, Sendable { public var value: String public var words: String /// It takes the record away (Drop): drawn red. public var red: Bool? /// The picture the core names for it (`act-stamp`), where it names one. public var picture: String? /// Its kit pictogram, by reference, where its tool's fan tile names one. public var pictogram: String? /// The one the record stands on now (the face it wears). public var chosen: Bool? /// What `shell.input` commits to choose it, where the core says. public var 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. public struct GroupChoice: Decodable, Equatable, Hashable, Sendable { public var value: String public var words: String public var new: Bool? public var detail: String? public var holds: Bool? /// The picture the core names for it (`act-plus`, `edit-act-group`). public var picture: String? /// Its kit pictogram, by reference, where its tool's fan tile names one. public var pictogram: String? /// The one the record stands on now (the face it wears). public var chosen: Bool? /// What `shell.input` commits to join or leave this list. public var writes: JSONValue? } /// How often a record comes round (`shell.opened {step: repeat}`): Never, /// then the presets. public struct RepeatChoice: Decodable, Equatable, Hashable, Sendable, Identifiable { /// The preset (`none`, `daily`, `weekly` …). public var key: String public var label: String /// The picture the core names for it (`act-cross`, `act-cycle`). public var picture: String? public var id: String { key } enum CodingKeys: 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. public struct CardAction: Decodable, Equatable, Hashable, Sendable, Identifiable { public var id: String public var label: String /// `command`, `chooser`, `address` or `tool`. public var kind: String /// `main`, `more` or `away`. public var rank: String? /// The one act a business look prints on its brand's fill. public var primary: Bool? /// Drawn red: it takes the record away, and stands last. public var red: Bool? /// The picture the fan draws it with (`act-stamp`, `edit-act-when`), /// where it has one. public var icon: String? /// The column a chooser sets (`due_at`, `recurrence_id`, `status`). public var column: String? /// The step a tap opens instead of running (`when`, `repeat`, `status`…). public var step: String? /// A handoff's address, opened by the OS. public var url: String? /// A tool's act: the tool it is, whether it asks first (Disconnect), and /// the account it is for. public var tool: String? public var asks: Bool? public var 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. public var group: String? public var record: String? /// The table `record` is of, where an act names a record of its own (a list's Send). public var 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. public var words: CardActionWords? /// Its kit pictogram, by reference (`photo:`), where its tool's /// fan tile names one (`FanTileLook`). public var pictogram: String? public init(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 = id self.label = label self.kind = kind self.rank = rank self.primary = primary self.red = red self.icon = icon self.column = column self.step = step self.url = url self.tool = tool self.asks = asks self.account = account self.group = group } } /// What a tool's act asks in the short-text input (`CardAction.words`). public struct CardActionWords: Decodable, Equatable, Hashable, Sendable { public var prefill: String? public var hint: String? public init(prefill: String? = nil, hint: String? = nil) { self.prefill = prefill self.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). struct ToolActAnswer: 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? enum CodingKeys: 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 = try RecordPlatformAction.fromAnswer(decoder) } } /// What a tool's act came to (`DeckActs.ran`). enum ToolActOutcome: 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. struct ToolActAsk: Encodable, Sendable { let tool: String let act: String let account: String? var group: String? = nil var record: String? = nil var words: String? = nil } /// One time on offer (`shell.opened {step: time}`): its words as the core /// said them, and the time it sets. public struct TimeChoice: Decodable, Equatable, Hashable, Sendable, Identifiable { /// `none` (No time), `HH:MM`, or `pick` (Pick a time). public var key: String public var label: String /// `HH:MM`; none for No time and Pick a time. public var time: String? /// The record's own time. public var chosen: Bool? /// The picture the core names for it (`act-clock`, `act-cross`). public var picture: String? public var id: String { key } enum CodingKeys: String, CodingKey { case key = "value", label = "words", time, chosen, picture } public init(key: String, label: String, time: String? = nil, chosen: Bool? = nil, picture: String? = nil) { self.key = key self.label = label self.time = time self.chosen = chosen self.picture = picture } } /// One day on offer (`shell.opened {step: when}`): its words as the core /// said them, and the day it sets. public struct DateChoice: Decodable, Equatable, Hashable, Sendable, Identifiable { /// Stable from day to day ("today", "weekday-2", "month-1", "pick"). public var key: String /// `none` (No date), `today`, `day`, `week`, `month` or `pick`: what it does. public var kind: String public var label: String public var detail: String? /// `YYYY-MM-DD`; none for Pick a date. public var day: String? /// The picture the core names for it (`edit-value-today`, `act-cross`). public var picture: String? public var id: String { key } enum CodingKeys: String, CodingKey { case key = "value", kind, label = "words", detail, day, picture } public init(key: String, kind: String, label: String, detail: String? = nil, day: String? = nil, picture: String? = nil) { self.key = key self.kind = kind self.label = label self.detail = detail self.day = day self.picture = picture } } private struct DeckEditorKey: EnvironmentKey { static let defaultValue: DeckEditor? = nil } private struct DeckViewNameKey: EnvironmentKey { static let defaultValue: String? = nil } extension EnvironmentValues { /// The view the deck shows, as `/` (`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 } } } extension EnvironmentValues { /// 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. public var deckEditor: DeckEditor? { get { self[DeckEditorKey.self] } set { self[DeckEditorKey.self] = newValue } } } /// A write the deck could not make: its sentence, said once (`DeckWritingLayer`). public struct DeckRefusal: Equatable, Sendable { public let id = UUID() public let sentence: String }