Cotton code
57 lines · 2.4 KB · SwiftRaw
// Where a several-choice column is written by tapping its words// (`ChoiceChips`), drawn once for every table: over a list whose definition// names `chips`, every word, wrapped; tap some and Save, and a record holding// them is made through `create` — no typing, no model, no network (the Mood// screen's row of feelings, the only way to name a moment's emotions without// an assistant).import CottonValuesimport SwiftUI/// The chips over a list, and the Save that makes a record of them.struct ChipRowHead: View {    @Environment(\.theme) private var theme    let definition: TableDefinition    /// Writes the record; false when it was not made, and the chips come back.    let onSave: ([String: RecordValue]) async -> Bool    @State private var chosen: Set<String> = []    var body: some View {        if let row = definition.chips, let column = definition.column(row.column) {            VStack(alignment: .trailing, spacing: 4) {                // What a tap does, said over the row ("Log a mood"): chips                // with no words over them read as decoration.                if let label = row.label {                    Text(label).paperHand(15, ink: .pencil)                        .frame(maxWidth: .infinity, alignment: .leading)                        .accessibilityAddTraits(.isHeader)                }                ChoiceChips(                    words: column.choices ?? [], chosen: chosen,                    identifier: "list-\(definition.id)-chips"                ) { word in                    if chosen.contains(word) { chosen.remove(word) } else { chosen.insert(word) }                }                if !chosen.isEmpty {                    PaperTypedButton("Save", size: 15) { save() }                        .accessibilityLabel(ShellLines.line("record", "chips.save", ["kind": "\(definition.name.lowercased())"]))                        .accessibilityIdentifier("list-\(definition.id)-chips-save")                }            }            .padding(.bottom, RecordListSurfaceKnobs.paperGap)        }    }    /// The chips clear BEFORE the write and come back only if it is refused:    /// a row that holds its choice through a round trip reads as a save    /// that did nothing.    private func save() {        guard let data = definition.chipRecord(chosen) else { return }        let kept = chosen        chosen = []        Task {            if await !onSave(data), chosen.isEmpty { chosen = kept }        }    }}