Cotton code
617 lines · 29.6 KB · SwiftRaw
// THE FAN'S VALUE MODE (images 4, 4b): while a card is edited the fan's arc// holds that card's values instead of the tools — one row of days, the// card's acts, its table's groups or its statuses — on the same arc and the// same pivot, turned by the same finger. A tap acts at once and the fan goes// back to its tools; nothing asks first.import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport SwiftUI/// The steps a held card's chooser opens (`shell.opened`'s `step`), and/// Bin, the chooser that runs at once. Outside the iOS guard: the/// deck's top row (DeckSurface) asks for `send` on every platform.enum EditingAct: String, CaseIterable {    case when, group, `repeat`, status, face, bin    /// Send's people (`shell.opened {step: send}`).    case send    /// Everything one send brought, taken away (`send.undo {id}`).    case unsend}#if os(iOS)extension FanTier.Card {    init(item: EditingItem, object: String?, style: Style, red: Bool, primary: Bool) {        self.init(id: item.id, label: item.word, object: object, style: style, pictogram: item.pictogram, red: red, primary: primary)        self.item = item    }    /// What the card does: its item's act; nil for a card made without one.    var handler: EditingItem.Does? { item?.does }}/// One card of the row and what its tap does.struct EditingItem: Identifiable, Equatable {    enum Does: Equatable {        case day(DateChoice)        case noDate        case pick        case time(TimeChoice?)        case act(EditingAct)        case group(String)        /// A new group of the card's table, named in the shell's one        /// short-text input, with the card's record in it.        case newGroup        case command(RecordCommand)        /// A handoff's address the OS opens (Call, Message, Email).        case address(URL)        case repeats(RepeatChoice)        /// Write a package of these tables (`ExportFan`).        case export([String])        /// One of the acts the card's caller handed the fan (`DeckEditor.offer`).        case offered(String)        /// One answer of an act's pick (`DeckPicks`).        case answer(DeckPickOption)        /// One status verb of the Status step (`shell.opened {step: status}`),        /// run as the command it is.        case status(RecordCommand)        /// An act of the card's tool (`tools.act`): Connect Google Calendar.        case tool(CardAction)        /// One value of a choice column (`DeckEditing.options`), written as it is.        case choice(column: String, value: String)        /// One face the card's table offers (`DeckEditing.faces`), worn by        /// every card of the table once chosen.        case face(String)        /// A column the card shows, written in the shell's editor for it        /// (`DeckEditor.write`): offered on a face that tags no part.        case write(column: String)        /// One of the person's people: a tap sends them a copy (`send.make`).        case send(SendPerson)        /// A held tile's Send (a list's): Send's people for its own record.        case sendRecord(DeckEditTarget)        /// Cotton chat's request, opened where the app keeps chat and the        /// person has nobody to send to yet.        case sendDoor(String)        /// Add a person by their number, in the shell's short-text input:        /// the same add as Account's Your people (`DeckEditor.addPerson`).        case sendAdd(SendAdd)        /// One added who has not added this person back: the tap says so        /// (the core's words) and nothing goes.        case sendWaiting(String)    }    let id: String    let word: String    var detail: String? = nil    var picture: String? = nil    /// Its kit pictogram, by reference, where its tool's fan tile names one    /// (`FanTileLook`): drawn on the tier's letterboard.    var pictogram: String? = nil    var initials: String? = nil    let does: Does    /// Drawn red and last: it takes the record away, as the core ranked it.    var red = false    /// The one act a business look prints on its brand's fill, as the core    /// (or the caller handing the acts) said it.    var primary = false}struct EditingFan: View {    let editor: DeckEditor    /// The tools' arc: the row stands on its pivot.    let fan: FanGeometry    @Environment(\.tableDefinitions) private var definitions    @Environment(\.records) private var store    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.theme) private var theme    @Environment(\.cottonHaptics) private var haptics    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @Environment(\.displayScale) private var displayScale    @Environment(\.self) private var environment    @Environment(Navigator.self) private var navigator: Navigator?    @State private var exports: [ExportTable] = []    private var definition: TableDefinition? {        editor.draft?.definition ?? editor.target.flatMap { target in definitions.all.first { $0.id == target.table } }    }    var body: some View {        Color.clear.frame(width: 0, height: 0)        .onChange(of: TierDeal(cards: tierCards, tile: editor.tile), initial: true) { _, deal in            guard var tier = editor.navigation.open, tier.editorState != nil else { return }            tier.replaceCards(deal.cards, restingAt: rest(items))            tier.tile = deal.tile            editor.navigation.replaceOpen(tier) { card in                guard let item = card.item else { return }                tap(item)            }        }        .task(id: exportsAsked) { await readExports() }        // The Send step with nobody to send to, or a record that cannot go: its words are said.        .onChange(of: editor.sendStep) { _, step in            guard let step, step.rows.isEmpty, let words = step.refused ?? step.empty?.words else { return }            toasts?.show(words, tone: step.refused == nil ? .notice : .error)            if step.empty?.door == nil, step.add == nil { editor.close() }        }    }    /// The row's cards and the tile they are drawn on, which change together.    private struct TierDeal: Equatable {        let cards: [FanTier.Card]        let tile: FanTileLook?    }    /// The row as the fan's cards: the held card's acts as objects, in the    /// core's order, red and primary as it said; every other row as leaves.    private var tierCards: [FanTier.Card] {        let acts = if case .acts = editor.editing { true } else { false }        return items.map { item in            FanTier.Card(item: item, object: item.picture, style: acts ? .object : item.initials == nil ? .leaf : .person,                         red: item.red, primary: item.primary)        }    }    // MARK: The row    private var items: [EditingItem] {        guard let editing = editor.editing else { return [] }        switch editing {        case .days:            // The core's row: No date first, then the days.            return editor.days.map { choice in                EditingItem(id: choice.key, word: choice.label, detail: choice.detail,                            picture: choice.picture, does: Self.does(choice))            }        case .times:            // The core's row (todos-time): No time, the hours, Pick a time.            return editor.times.map { choice in                let does: EditingItem.Does =                    switch choice.key {                    case "pick": .pick                    case "none": .time(nil)                    default: .time(choice)                    }                return EditingItem(id: "time-\(choice.key)", word: choice.label, picture: choice.picture, does: does)            }        case .pickDays:            // The core's every day from today (`{step: when, all: true}`).            return editor.pickedDays.map { choice in                EditingItem(id: choice.key, word: choice.label, picture: choice.picture, does: .day(choice))            }        case .pickTimes:            // The core's every half hour (`{step: time, all: true}`).            return editor.pickedTimes.map { choice in                EditingItem(id: choice.key, word: choice.label, picture: choice.picture, does: .time(choice))            }        case .acts(let target):            guard let definition else { return [] }            let own = editor.actsTarget == target ? Self.items(of: editor.actions, in: definition) : []            let writing = editor.actsTarget == target ? Self.items(writing: definition, parts: editor.parts) : []            return writing + own        case .groups:            // The core's row (`shell.opened {step: group}`): New list first,            // a deck's only way to make the first, then the table's lists.            return Self.items(groups: editor.groupRows)        case .statuses:            guard let definition else { return [] }            return Self.items(statuses: editor.statuses, in: definition)        case .options(_, let column):            return Self.items(choosing: editor.optionRows, column: column)        case .repeats:            return editor.repeats.map { choice in                EditingItem(id: "repeat-\(choice.key)", word: choice.label, picture: choice.picture, does: .repeats(choice))            }        case .faces:            return editor.faces.map { EditingItem(id: "face-\($0.value)", word: $0.words, picture: $0.picture, does: .face($0.value)) }        case .exports:            // Everything's word is the core's own name for its table of tables.            return ExportFan.items(exports, everything: definitions[ExportFan.everythingTable]?.plural)        case .offered:            return Self.items(offered: editor.offered)        case .toolActs:            return Self.items(tools: editor.actions)        case .picks:            return Self.items(picking: editor.pickOptions)        case .sends:            return Self.items(sending: editor.sendStep)        }    }    /// The Send step as the fan's cards (`shell.opened {step: send}`): each    /// person by name and initials, the size that goes under them, in the    /// core's order, one still waiting to add this person back saying so at a    /// tap; with nobody, the door to Cotton chat's request where the app    /// keeps chat (the words are said as the tier opens, `sayEmpty`); last,    /// Add a person, whose number is typed in the short-text input.    static func items(sending step: SendStep?) -> [EditingItem] {        guard let step else { return [] }        var items = step.rows.map { person in            EditingItem(id: "send-\(person.value)", word: person.words, detail: person.detail, initials: person.initials ?? "",                        does: person.waiting == true ? .sendWaiting(person.detail ?? "") : .send(person))        }        if items.isEmpty, let door = step.empty?.door {            items.append(EditingItem(id: "send-door", word: door.words, picture: "act-person", does: .sendDoor(door.path)))        }        if let add = step.add {            items.append(EditingItem(id: "send-add", word: add.words, picture: "act-person", does: .sendAdd(add)))        }        return items    }    /// The held card's acts as the core answered them (`shell.opened`), in    /// its order, red and primary as it said: one with a step opens it, a    /// command runs as the definition says it, a handoff opens its address,    /// a tool's runs by `tools.act`, Bin bins. One this build cannot run (a    /// command its definition does not hold, a kind it does not know) is    /// left out rather than drawn as a dead card.    static func items(of actions: [CardAction], in definition: TableDefinition) -> [EditingItem] {        actions.compactMap { action in            let does: EditingItem.Does            let id: String            if let step = action.step.flatMap(EditingAct.init(rawValue:)) {                does = .act(step)                id = action.kind == "command" ? "command-\(action.id)" : "act-\(action.id)"            } else {                switch action.kind {                case "command":                    guard let command = definition.commands?.first(where: { $0.id == action.id }) else { return nil }                    does = .command(command)                    id = "command-\(action.id)"                case "chooser":                    guard let act = EditingAct(rawValue: action.id), act == .bin || act == .unsend else { return nil }                    does = .act(act)                    id = "act-\(action.id)"                case "address":                    guard let url = action.url.flatMap(URL.init(string:)) else { return nil }                    does = .address(url)                    id = "address-\(action.id)"                case "tool":                    guard DeckEditor.runsAsTool(action) else { return nil }                    does = .tool(action)                    id = "tool-\(action.id)-\(action.account ?? "")"                default:                    return nil                }            }            return EditingItem(id: id, word: action.label, picture: action.icon, pictogram: action.pictogram, does: does,                               red: action.red == true, primary: action.primary == true)        }    }    /// The card's words a face that tags no part leaves to the fan (a note's    /// torn page: nothing on it is a part, so no tap on it writes): its    /// title and its body, first on the fan, each by its column's own name,    /// where the core says the held card's place writes words (`parts`). A    /// face that tags its parts writes them from the card, and offers none here.    static func items(writing definition: TableDefinition, parts: [String: CardPart]) -> [EditingItem] {        guard DeckFace.tagsNoPart(definition) else { return [] }        return ["title", "body"].compactMap { place in            guard let part = parts[place], part.does == "line" || part.does == "page", let key = part.column else { return nil }            return EditingItem(id: "write-\(key)", word: definition.column(key)?.name ?? TableEditorModel.words(key),                               does: .write(column: key))        }    }    /// A deck's empty placeholder held (`DeckEditing.toolActs`): its tool's    /// acts alone, as a card's fan draws them, each with the picture its tool    /// paints it with (`icon`); anything else is left out — there is no    /// record for it to act on.    static func items(tools actions: [CardAction]) -> [EditingItem] {        actions.compactMap { action in            if let target = DeckEditor.sends(action) {                return EditingItem(id: "act-send-\(target.record)", word: action.label, picture: action.icon, pictogram: action.pictogram, does: .sendRecord(target))            }            guard DeckEditor.runsAsTool(action) else { return nil }            return EditingItem(id: "tool-\(action.id)-\(action.account ?? "")", word: action.label, picture: action.icon,                               pictogram: action.pictogram, does: .tool(action))        }    }    /// A row's write, committed as the core said it; a refusal is said.    private func committing(_ writes: JSONValue?) {        guard let writes, let core else { return }        Task { if let refusal = await DeckEditor.commitRow(writes, core: core) { toasts?.show(refusal, tone: .error) } }    }    /// The Group step's row as the core said it (`shell.opened {step: group}`),    /// in its order: New list makes one, a list takes the card in or out.    static func items(groups rows: [GroupChoice]) -> [EditingItem] {        rows.map { row in            row.new == true                ? EditingItem(id: "group-new", word: row.words, picture: row.picture, pictogram: row.pictogram, does: .newGroup)                : EditingItem(id: "group-\(row.value)", word: row.words, detail: row.detail, picture: row.picture, pictogram: row.pictogram,                              does: .group(row.value))        }    }    /// The Status step's verbs (`shell.opened {step: status}`), each run as    /// its definition's command; one the definition does not hold is left out.    static func items(statuses: [OpenedChoice], in definition: TableDefinition) -> [EditingItem] {        statuses.compactMap { row in            guard let command = definition.commands?.first(where: { $0.id == row.value }) else { return nil }            return EditingItem(id: "status-\(row.value)", word: row.words, picture: row.picture,                               pictogram: row.pictogram, does: .status(command), red: row.red == true)        }    }    /// A choice column's values as the fan's cards, in its definition's    /// order and in its words, as the core says them (`{step: options}`).    static func items(choosing rows: [OpenedChoice], column: String) -> [EditingItem] {        rows.map { row in            EditingItem(id: "choice-\(row.value)", word: row.words, does: .choice(column: column, value: row.value))        }    }    /// A pick's answers as the fan's cards, in the order they are offered.    static func items(picking options: [DeckPickOption]) -> [EditingItem] {        options.map { EditingItem(id: "pick-\($0.id)", word: $0.word, detail: $0.detail, picture: $0.picture, initials: $0.initials, does: .answer($0)) }    }    /// The acts a card's caller handed the fan, as its cards, in its order,    /// the one it marks primary on the brand's fill.    static func items(offered: [DeckOffer]) -> [EditingItem] {        offered.map {            EditingItem(id: "offer-\($0.id)", word: $0.word, picture: $0.picture, pictogram: $0.pictogram, does: .offered($0.id), primary: $0.primary)        }    }    /// What a day of the When step does: No date clears it, Pick a date    /// opens the picked days, a day sets it.    static func does(_ choice: DateChoice) -> EditingItem.Does {        switch choice.kind {        case "none": .noDate        case "pick": .pick        default: .day(choice)        }    }    // MARK: Taps    private func tap(_ item: EditingItem) {        guard let target = editor.target else { return }        switch item.does {        case .address(let url):            environment.openURL(url)        case .day(let choice):            editor.choose(choice, store: store, core: core)        case .noDate:            editor.chooseNoDate(store: store, core: core)        case .time(let choice):            editor.choose(choice, store: store, core: core)        case .pick:            editor.openPick()        case .act(.when):            editor.open(.days(target), core: core)        case .act(.group):            editor.open(.groups(target), core: core)        case .act(.status):            editor.open(.statuses(target), core: core)        case .act(.`repeat`):            editor.open(.repeats(target), core: core)        case .act(.face):            editor.openFaces(for: target)        case .face(let face):            // The fan goes back to the card's acts; the card, and every card            // of its table, wears the face once the core has written it.            let writes = editor.faces.first { $0.value == face }?.writes            editor.mark(target)            committing(writes)        case .repeats(let choice):            editor.choose(choice, core: core)        case .act(.bin):            bin(target)        case .act(.send):            editor.open(.sends(target), core: core)        case .act(.unsend):            editor.close()            Task { await unsend(target) }        case .send(let person):            editor.close()            Task { await SendCenter.session.send(table: target.table, id: target.record, to: person, core: core, toasts: toasts) }        case .sendRecord(let record):            editor.open(.sends(record), core: core)        case .sendDoor(let path):            editor.close()            if let route = Route.parse(path) { navigator?.open(route) }        case .sendAdd(let add):            editor.addPerson(add, core: core)        case .sendWaiting(let words):            if !words.isEmpty { toasts?.show(words) }        case .offered(let id):            // The caller's act is done and the fan goes back to its tools;            // one that asks asks its picks on this fan first (`DeckPicks`).            guard let act = editor.offered.first(where: { $0.id == id }) else { return editor.close() }            Task { ran(await editor.act(act, on: target)) }        case .export(let tables):            // The fan goes back to its tools; the core writes the file and            // the share sheet opens on it.            editor.close()            Task { await ExportFan.write(tables, core: core, toasts: toasts) }        case .newGroup:            editor.nameGroup(target, store: store)        case .group(let id):            let writes = editor.groupRows.first { $0.value == id }?.writes            editor.mark(target)            committing(writes)        case .command(let command), .status(let command):            // One that picks nothing runs at once; one that picks asks its            // picks on this fan first (`DeckPicks`).            guard let definition else { return }            let place = DeckPickPlace(store: store, core: core, definitions: definitions)            Task { ran(await editor.act(command, on: target, definition: definition, place: place)) }        case .answer(let option):            Task { ran(await editor.answer(option)) }        case .choice(let column, let value):            // Written through the record's own write, as any value the fan sets.            editor.save(target, patch: [column: .text(value)], store: store)        case .write(let key):            // The shell's editor for the column, as a tapped part's would            // open it (`DeckWords`): a title in the short-text input, a body            // on the whole screen.            editor.write(target, column: key, store: store, core: core)        case .tool(let action):            // One that asks its words (a list's Rename) asks them in the            // shell's short-text input.            if action.words != nil {                editor.close()                editor.askToolWords(action, core: core, toasts: toasts)                return            }            // One that asks first (Disconnect) turns the fan into itself            // alone: a second tap runs it, the record button puts it away.            guard action.asks == true else {                editor.close()                Task { await runTool(action) }                return            }            editor.offer([DeckOffer(id: action.id, word: action.label) { _ in await runTool(action) }], for: target)        }    }    /// A tool's act run by the core (`tools.act`): a page it answers opens    /// in the system browser (Google's or Spotify's consent page), a flow it    /// answers runs as this device's own row runs it (Sign in, Sign out),    /// words it answers are said (Back up now), a document it wrote is    /// shared once it has come (Export OPML); a refusal is said.    private func runTool(_ action: CardAction) async {        guard let core else { return }        do {            let outcome = try await DeckActs.ran(action, core: core)            switch outcome {            case .opens(let page): environment.openURL(page)            case .platform(let effect):                await RecordPlatformEffects.perform(effect, nativeFlow: environment.nativeKeptFlow, rekey: environment.rekeyThisDevice)            case .said, .receipt: DeckActs.say(outcome, toasts: toasts, core: core)            case .document(let id, let said):                if let said { _ = toasts?.show(said) }                if let file = try await DocumentShare.file(id, store: store, core: core) { ShareSheet.present(file) }            case .nothing: break            }        } catch {            _ = toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    /// What an act came to: an open command (Open repeat rule, Open people)    /// opens what it names — a deck tool's record opens its deck at the card;    /// a refusal, or a pick with nothing to offer, is said.    private func ran(_ outcome: DeckActOutcome) {        switch outcome {        case .ran(let change):            // The change's receipt, with its Undo where the core says it can be            // taken back (Rigby 11 walk, 8 Nov 2026: Mark done said nothing and            // Reopen was the only way back). An open changed nothing, a draft's            // field is only memory and an unconfirmed intent has not happened:            // none of them wears one.            if change.opened == nil, !change.quiet, !change.pending, let store { DeckActs.said(change, store: store, toasts: toasts) }            switch change.opened {            case .record(let link):                navigator?.push(BoardRecord.route(table: link.table, id: link.id, definition: definitions[link.table]))            case .landed(let link):                Task { @MainActor in                    guard await RecordLanding.arrived(link, in: store) else { return }                    navigator?.push(BoardRecord.route(table: link.table, id: link.id, definition: definitions[link.table]))                }            case .address(let address):                // An address in the app (This device's All devices, "/devices")                // opens here; the system is handed only what is not the app's                // (Rigby 11 walk, 8 Nov 2026: "/devices" went to openURL, which                // logged it was no HTTP URL and opened nothing).                if address.hasPrefix("/"), let route = Route.parse(address) { navigator?.push(route) }                else if let url = URL(string: address) { environment.openURL(url) }            case .platform(let effect):                Task { await RecordPlatformEffects.perform(effect, nativeFlow: environment.nativeKeptFlow, rekey: environment.rekeyThisDevice, reader: environment.readerPresenter) }            default: break            }        case .refused(let words):            // Said until the next tap, as every deck refusal is (Find            // details before sign-in: "Sign in first").            _ = toasts?.show(words, tone: .error, window: ToastWindow.untilTap)        case .asking, .none:            break        }    }    /// Everything the send that brought this record brought, taken away    /// (`send.undo {id}`, the record's `send_id`); what Undo did is said.    private func unsend(_ target: DeckEditTarget) async {        guard let core else { return }        let held: TableRecord?        if let record = editor.held, record.id == target.record { held = record } else { held = try? await store?.get(table: target.table, id: target.record) }        guard let send = held?["send_id"].text else { return }        do {            _ = try await core.callJSON(CottonMethod.sendUndo, JSONValue.object(["id": .string(send)]))            let name = held?["sent_by"].text ?? ""            toasts?.show(ShellLines.line("send", "unsent", ["name": name]))        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    /// Bin acts at once (`DeckActs.binned`).    private func bin(_ target: DeckEditTarget) {        editor.close()        guard let store else { return }        Task { await DeckActs.binned(table: target.table, id: target.record, store: store, toasts: toasts) }    }    // MARK: Exports    /// The tables are read when the Export card's fan opens.    private var exportsAsked: String? {        if case .exports(let target) = editor.editing { return target.id }        return nil    }    private func readExports() async {        guard exportsAsked != nil, let store, let rows = try? await ExportFan.read(store) else { return }        exports = ExportFan.tables(rows, definitions: definitions)    }    // MARK: The arc    private func rest(_ items: [EditingItem]) -> Int {        // The row opens with Today at its left edge, the arc resting on the        // card's own day when the row holds it, else on Tomorrow (image 4).        let rest: Int        if case .days(let target) = editor.editing {            let day = target.date.flatMap { editor.held?.values[$0] }.flatMap { value -> String? in                if case .text(let text) = value { return String(text.prefix(10)) } else { return nil }            }            let own = items.firstIndex { item in                if case .day(let choice) = item.does { return choice.day != nil && choice.day == day } else { return false }            }            // No date stands first: the row rests past it, on Tomorrow.            rest = min(max(own ?? 2, 1), max(0, items.count - 1))        } else if case .times = editor.editing {            // On the record's own time, else the first hour after No time.            let own = editor.times.firstIndex { $0.chosen == true }            rest = min(own ?? 1, max(0, items.count - 1))        } else if case .pickTimes = editor.editing {            // The picked times open on nine in the morning.            rest = min(18, max(0, items.count - 1))        } else if case .faces = editor.editing {            // On the face the card wears, the core's first row.            rest = editor.faces.firstIndex { $0.chosen == true } ?? 0        } else if case .pickDays = editor.editing {            rest = 0        } else if case .exports = editor.editing {            // On Everything, the tables after it.            rest = 0        } else if case .groups = editor.editing {            // On New list, the lists after it however many they are.            rest = 0        } else if case .picks = editor.editing {            // On a number's count, else the first answer.            rest = min(editor.pickRest, max(0, items.count - 1))        } else {            rest = (items.count - 1) / 2        }        return editor.holdsActs ? 0 : rest    }}#endif