Cotton code
789 lines · 35.6 KB · SwiftRaw
// A tool's groups, above its list (Spec 6, note 8c089dd6): a row of small// piles in the slot other lists already stand in (`otherLists(above:)`), one// pile per group — the table's own polaroids for People, its own paper slips// for Todos, its own covers for Documents and Reader (`TableGroups.stack`) —// each under its name and its count, and "New" last. The row is not drawn// until a group exists; the list's menu offers "New group" from the first day.//// A tap on a pile opens the group's page: the group's records on the table's// OWN list surface, narrowed to the group (`GroupRecords.members`), so a// person in Family is drawn, searched and opened exactly as in People. Its// "+" and its empty words add records to the group (the table's list as a// pick); its menu removes some, renames the group and deletes it, asked// first. A record the bar makes there joins the group.//// A table whose groups are kept in another table (`TableGroups.keptIn`;// Spec 10 G item 3) draws that table's records as its stacks: the photo// list's piles are its albums, a suggested one marked "suggested" in red as// the album list marks it. A tap opens the album's own page through the// list's opener, never a group page; an album starts from its pictures, so// the row offers no "New" — Select → Add to group makes one of them.//// Nothing here draws a new face: a pile is `PolaroidFace` or a cut `Paper`// laid three deep, turned a few degrees.import CottonKitimport CottonValuesimport SwiftUI/// The row of stacks above a list, as the core answered its groups/// (`shell.list`); nothing until the table has a group.struct GroupStacksRow: View {    let definition: TableDefinition    let groups: TableGroups    /// The groups the core answered, each with the top of its pile.    let answered: [ListAnswer.Group]    /// Whether the row ends in "New": the core's `offers_new_group`.    let offersNew: Bool    /// "New group" was asked for (the row's last pile, or the list's menu).    @Binding var naming: Bool    /// A change a group's page made as it closed (the group deleted): it    /// wears the list's own receipt, with its Undo.    let received: @MainActor (ChangeRecord) -> Void    /// A group was made or changed here: the list asks the core again.    let asked: @MainActor () async -> Void    @Environment(\.records) private var store    @Environment(\.recordOpener) private var opener    @State private var opened: RecordGroup?    /// The piles as answered.    private var stacks: [GroupStack] {        answered.map { group in            GroupStack(                group: RecordGroup(id: group.id, name: group.name, of: definition.id, count: group.count,                                   keptIn: group.opens.id == nil ? nil : group.opens.table, byline: group.byline),                top: group.top.compactMap { $0.record?.record })        }    }    var body: some View {        // A stack, never a `Group`: with no group yet the row draws nothing,        // and a `Group` of nothing would hand the read, the name sheet and        // the group's page to no view at all — the first group could never        // be made from the menu, and no row would ever be read.        VStack(spacing: 0) {            if !stacks.isEmpty {                ScrollView(.horizontal, showsIndicators: false) {                    HStack(alignment: .top, spacing: 14) {                        ForEach(stacks) { stack in                            Button {                                if !Self.openKept(stack.group, with: opener) { opened = stack.group }                            } label: {                                GroupStackFace(                                    definition: definition, face: groups.stack, seed: stack.group.id,                                    name: stack.group.name, count: stack.group.count, top: stack.top,                                    byline: stack.group.byline)                            }                            .buttonStyle(MotionButtonStyle())                            .accessibilityLabel(GroupStackFace.spoken(                                name: stack.group.name, count: stack.group.count, in: definition, byline: stack.group.byline))                            .accessibilityIdentifier("list-\(definition.id)-group-\(stack.group.id)")                        }                        if offersNew {                            Button { naming = true } label: {                                GroupStackFace(definition: definition, face: groups.stack, seed: "new-\(definition.id)", name: "New", count: nil, top: [], isNew: true)                            }                            .buttonStyle(MotionButtonStyle())                            .accessibilityLabel(ShellLines.line("lists", "group.new"))                            .accessibilityIdentifier("list-\(definition.id)-group-new")                        }                    }                    .padding(.horizontal, 4)                    .padding(.vertical, 8)                    // Room to bring the last pile out from under a list's                    // letter index, which stands over the row's right edge.                    .padding(.trailing, 28)                }                .padding(.bottom, 14)                .accessibilityIdentifier("list-\(definition.id)-groups")            }        }        .cottonCard(isPresented: $naming) {            GroupNameSheet(title: ShellLines.line("lists", "group.new"), name: "", identifier: "list-\(definition.id)-group-name") { name in                await make(name)            }        }        .pageDestination(item: $opened) { group in            GroupPage(definition: definition, group: group) { change in                received(change)                Task { await asked() }            }                .environment(\.recordOpener, opener)        }    }    /// A group that is another table's record (an album) opens that    /// record's own page through the list's opener — `/photos/album/[id]`,    /// unchanged — and answers whether it did; any other group, or one no    /// opener here has a page for, opens the group's page on this stack.    static func openKept(_ group: RecordGroup, with opener: RecordOpener?) -> Bool {        guard let table = group.keptIn, let opener, opener.opens(table) else { return false }        opener(table, TableRecord(id: group.id, values: [:]))        return true    }    /// Makes the group and opens its page; the sentence why not when refused.    private func make(_ name: String) async -> String? {        guard let grouping = GroupRecords.grouping(store) else { return ShellLines.line("lists", "group.none_kept") }        do {            let made = try await grouping.createGroup(named: name, of: definition.id, records: [])            await asked()            if let group = made.group ?? stacks.last(where: { $0.group.name == name })?.group { opened = group }            return nil        } catch {            return ActionRefused.words(for: error)        }    }}/// One pile: up to three of the group's records laid one on another, the/// first on top, over the group's name and its count on one line.struct GroupStackFace: View {    @Environment(\.theme) private var theme    let definition: TableDefinition    let face: TableGroups.Stack    let seed: String    let name: String    let count: Int?    let top: [TableRecord]    var isNew = false    /// The word the group's record wears, in red under its name ("suggested").    var byline: String? = nil    static let side: CGFloat = 74    /// How far each sheet under the top one is turned and moved, top first.    static let lay: [(turn: Double, x: CGFloat, y: CGFloat)] = [(0, 0, 0), (-5, -5, 3), (6, 6, 5)]    var body: some View {        VStack(spacing: 8) {            ZStack {                if top.isEmpty {                    sheet(nil).opacity(isNew ? 0.75 : 1)                    if isNew {                        Image(systemName: "plus")                            .font(.system(size: 18, weight: .medium))                            .foregroundStyle(CottonColors.inkSecondary)                    }                } else {                    // Drawn bottom first, so the group's first record is on top.                    ForEach(Array(top.prefix(Self.lay.count).enumerated()).reversed(), id: \.element.id) { index, record in                        sheet(record, top: index == 0)                            .rotationEffect(.degrees(Self.lay[index].turn))                            .offset(x: Self.lay[index].x, y: Self.lay[index].y)                    }                }            }            .frame(width: Self.side + 14, height: height + 12)            // The name and its count on ONE line, "Prelaunch · 3" (owner, 5            // Oct): the count a line below with a gap read as a second            // thing. A long name wraps to a second line at its full size            // (walker 604bcce6: names cut off with room to spare); the            // count stays on the name's last line and never gives way.            (Text(name).font(CottonFonts.type(13)).foregroundStyle(CottonColors.ink)                + Text(count.map { " \u{00B7} \($0)" } ?? "").font(theme.type.hand(14)).foregroundStyle(theme.print(.pencil)))                .lineLimit(2)                .multilineTextAlignment(.center)                .fixedSize(horizontal: false, vertical: true)            if let byline {                Text(byline).paperHand(13, ink: .red).lineLimit(1)            }        }        .frame(width: Self.side + 18)        .contentShape(Rectangle())    }    private var height: CGFloat {        switch face {        case .polaroids: return Self.side * 1.2        case .slips: return Self.side * 0.72        case .covers: return coverWidth / coverAspect        }    }    /// A paperback stands as tall as a polaroid; a postcard lies as wide as a slip.    private var postcard: Bool { CoverFace.isPostcard(definition) }    private var coverAspect: CGFloat { postcard ? CoverFaceKnobs.faceCoverPostcardAspect : CoverFaceKnobs.faceCoverPaperbackAspect }    private var coverWidth: CGFloat { postcard ? Self.side : Self.side * 1.2 * CoverFaceKnobs.faceCoverPaperbackAspect }    /// One sheet of the pile: the record's own face, small; with no record,    /// the face empty (a group nobody is in yet, or "New"). Only the top    /// sheet wears its words: a print under it is a bare print, or the    /// captions of three turned prints wrote over one another (290 walk,    /// People's piles).    @ViewBuilder private func sheet(_ record: TableRecord?, top: Bool = true) -> some View {        switch face {        case .polaroids:            if let record, top {                PolaroidFace(definition: definition, record: record, width: Self.side)                    .frame(width: Self.side)            } else {                EmptyPrint(seed: record?.id ?? seed).frame(width: Self.side)            }        case .slips:            Paper(                dye: record.map { FaceTint.dye(for: $0.id) } ?? .cream, edge: .cut, seed: record?.id ?? seed,                tilt: false, inset: 7, fills: true            ) {                Text(top ? record.flatMap { $0.said?.slip.title } ?? "" : "")                    .font(CottonFonts.type(9))                    .foregroundStyle(CottonColors.ink)                    .lineLimit(3)                    .multilineTextAlignment(.leading)                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)            }            .frame(width: Self.side, height: Self.side * 0.72)        case .covers:            if let record, top {                CoverFace(definition: definition, record: record, width: coverWidth)            } else {                Paper(dye: .cream, edge: .cut, seed: seed, tilt: false, inset: 0, fills: true) { Color.clear }                    .frame(width: coverWidth, height: coverWidth / coverAspect)            }        }    }    /// What a pile is read out as: "Family, 4 people"; "Goa, 12 photos,    /// suggested" for an album Cotton suggested.    static func spoken(name: String, count: Int?, in definition: TableDefinition, byline: String? = nil) -> String {        var said = name        if let count { said += ", \(count) \((count == 1 ? definition.name : definition.plural).lowercased())" }        if let byline { said += ", \(byline)" }        return said    }}/// A group's page: its records on the table's own list, and the group's acts.struct GroupPage: View {    let definition: TableDefinition    /// The group was deleted and the page has closed: the change is handed    /// to the list underneath, whose receipt can take it back.    let onDeleted: @MainActor (ChangeRecord) -> Void    @Environment(\.records) private var store    @Environment(\.recordOpener) private var opener    @Environment(\.recordsRevision) private var revision    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    @Environment(ToastCenter.self) private var toasts    @Environment(\.cottonCore) private var core    @Environment(\.openURL) private var openURL    @Environment(\.toolDefinitions) private var tools    @State private var group: RecordGroup    /// Whether THIS phone keeps the group always — nil off a phone, where    /// the menu offers neither act (`KeepOnThisPhone`).    @State private var keptHere: Bool?    @State private var adding = false    @State private var removing = false    /// Rename, as the core offered it: its words on the name sheet.    @State private var renaming: CardAction?    /// Remove list, asked first in the core's words.    @State private var removal: ListAnswer.MenuItem?    /// Bumped when the group's records changed under the list.    @State private var changes = 0    /// The newest putting-in or taking-out: the page's own receipt.    @State private var landed: ChangeRecord?    /// The record opened from the group. Opened on the page's own stack:    /// the list's route would push beside the group's page and close it, so    /// Back from the record would land on the whole list.    @State private var member: TableRecord?    /// The history of the record opened from the group, on the same stack.    /// The ids the group holds, so the Add picker marks them as in it.    @State private var members: Set<String> = []    /// The tool whose list this is, when the page that opens it knows it    /// (the ring's); else the tool that lists the table (`ListTool.key`).    let tool: String?    init(definition: TableDefinition, group: RecordGroup, tool: String? = nil, onDeleted: @escaping @MainActor (ChangeRecord) -> Void) {        self.definition = definition        self.tool = tool        self.onDeleted = onDeleted        _group = State(initialValue: group)    }    /// The view a list's deck stands for, `<tool>/group:<id>`, named by the    /// tool that lists its table (`ListTool.key`): the core reads the list    /// through that tool's views (`shell.deck`), so a name made of the    /// table's id — Films' `film`, Books' `book`, Music's `song`, none of    /// which names a tool block — is no tool's, and the deck could not be    /// read (Cotton Cinemas 1.0 (2), 6 Nov 2026). Nil where no tool lists    /// the table: the deck is read by its members alone.    static func deckName(of group: RecordGroup, in definition: TableDefinition, tool: String?, tools: [ToolDefinition]) -> String? {        ListTool.key(handed: tool, table: definition, tools: tools).map { "\($0)/\(ToolView.groupPrefix)\(group.id)" }    }    private var plural: String { definition.plural.lowercased() }    var body: some View {        if DeckSwitch.draws(definition, view: nil, plain: true) {            // No scrolling lists: a group of a tool with a card is its deck of            // the group's members; membership is the card's Group act.            // Its cards and placeholder offer the list's own acts beside the tool's.            DeckSurface(definition: definition, filter: GroupRecords.members(of: group), view: nil,                        standsFor: Self.deckName(of: group, in: definition, tool: tool, tools: tools.all))        } else {            list        }    }    /// The page's scope: its empty words, its add, and its menu — the    /// list's own acts as the core answered them (`shell.list`'s menu on a    /// group's page), run here, beside this phone's Keep.    private var scope: ListScope {        var scope = ListScope(            empty: EmptyWords(                title: ShellLines.line("empty", "group.title", ["group": group.name]),                message: ShellLines.line("empty", "group.message", ["plural": plural])),            addLabel: ShellLines.line("lists", "add_plural", ["plural": plural]),            add: { adding = true },            menu: keepItem,            barWords: ShellLines.line("lists", "group.add_to_more", ["group": group.name]),            received: landed,            made: { id in await joined(id) })        scope.runs = { act($0) }        return scope    }    @ViewBuilder private var list: some View {        RecordListSurface(            definition: definition, where: GroupRecords.members(of: group), title: group.name, scope: scope,            onOpen: { member = $0 }        )        .environment(\.recordsRevision, revision &+ changes)        .cottonScreenFrame()        .pageDestination(item: $member) { record in            RecordOpening(definition: definition, opens: .record(record.id, record))                .cottonScreenFrame()                .environment(\.recordOpener, opener)        }        .pageDestination(isPresented: $adding) {            RecordListSurface(                definition: definition,                pick: ListPick(                    table: definition.id, column: "id", preset: [:],                    label: ShellLines.line("lists", "group.add_to", ["group": group.name]),                    act: { ids in await change(ListAct.add, ids) },                    held: members, heldWords: ShellLines.line("lists", "group.already_in", ["group": group.name]),                    done: { adding = false; changes += 1 }),                onOpen: { _ in }            )            .cottonScreenFrame()        }        .pageDestination(isPresented: $removing) {            RecordListSurface(                definition: definition, where: GroupRecords.members(of: group),                pick: ListPick(                    table: definition.id, column: "id", preset: [:],                    label: ShellLines.line("lists", "group.remove_from", ["group": group.name]), action: .remove,                    act: { ids in await change(ListAct.takeOut, ids) },                    done: { removing = false; changes += 1 }),                onOpen: { _ in }            )            .cottonScreenFrame()        }        .cottonCard(isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {            if let renaming {                GroupNameSheet(title: renaming.label, name: renaming.words?.prefill ?? group.name, identifier: "group-\(definition.id)-rename") { name in                    await rename(renaming, name)                }            }        }        .task(id: revision &+ changes) {            await readMembers()            keptHere = await KeepOnThisPhone.kept(kind: "group", target: group.id, core: core)        }        .confirmDecision(            item: $removal,            title: { $0.question?.title ?? $0.label },            message: { $0.question?.message ?? "" },            confirmLabel: { $0.question?.confirm ?? $0.label },            identifier: "group-\(definition.id)-delete",            onConfirm: { item in if let act = item.act { delete(act) } }        )    }    /// One of the list's own acts, from its menu: Add and Remove open their    /// pick, Rename its name sheet, Remove list its question; any other (a    /// picture, a move, Play) runs as the fan runs it.    private func act(_ item: ListAnswer.MenuItem) {        guard let act = item.act else { return }        switch item.picks {        case "add": adding = true        case "remove": removing = true        default:            if act.words != nil {                renaming = act            } else if item.question != nil {                removal = item            } else {                Task { await run(act) }            }        }    }    /// A list act with no pick or words, as the deck's fan runs it: a picker    /// it answers opens, its receipt is said with its Undo.    private func run(_ act: CardAction) async {        guard let core else { return }        do {            switch try await DeckActs.ran(act, core: core) {            case .opens(let page): openURL(page)            case .platform(let effect): _ = await RecordPlatformEffects.perform(effect)            case let outcome: DeckActs.say(outcome, toasts: toasts, core: core)            }            changes += 1        } catch {            toasts.show(ActionRefused.words(for: error), tone: .error)        }    }    /// "Keep on this phone", or "Stop keeping" once it is — on a phone only.    private var keepItem: [PopoverMenuItem] {        guard let kept = keptHere, let core else { return [] }        return [            PopoverMenuItem(                id: "group-keep", object: CardEnamel.device.rawValue, does: kept ? .putsAway : nil,                label: kept ? KeepOnThisPhone.stopLabel : KeepOnThisPhone.keepLabel            ) {                Task {                    do {                        landed = try await KeepOnThisPhone.act(                            kept: kept, kind: "group", target: group.id, table: definition.id, record: group.id, core: core)                        changes += 1                    } catch {                        toasts.show(ActionRefused.words(for: error), tone: .error)                    }                }            },        ]    }    /// Every id the group holds, page after page (a group is hand-picked,    /// so a few pages at most), and the group's name. A read that fails    /// keeps what was read.    private func readMembers() async {        guard let store else { return }        var ids: Set<String> = []        var page: Int? = 0        while let at = page {            guard let read = try? await store.list(                table: definition.id, project: nil, query: nil, page: at, where: GroupRecords.members(of: group))            else { return }            ids.formUnion(read.records.map(\.id))            page = read.next        }        // Its name as kept now: a rename undone from the receipt puts the        // old one back under a title still showing the new.        let kept = try? await GroupRecords.grouping(store)?.groups(of: definition.id, holding: nil)        guard !Task.isCancelled else { return }        members = ids        if let name = kept?.first(where: { $0.id == group.id })?.group.name, name != group.name { group.name = name }    }    /// A record the bar made on this page joins the group; the making keeps    /// the receipt, so the joining wears none.    private func joined(_ id: String) async {        if await change(ListAct.add, [id], wearing: false).isEmpty { changes += 1 }    }    /// The list's act that puts the picked records in or takes them out    /// (`tools.act`) — the page's receipt, with its Undo — answering the ids    /// it could not do (all of them, when the act is refused, said why).    private func change(_ act: String, _ ids: [String], wearing: Bool = true) async -> [String] {        do {            let done = try await ListAct.run(act, group: group.id, table: definition.id, records: ids, core: core)            if wearing { landed = done }            return []        } catch {            toasts.show(ActionRefused.words(for: error), tone: .error)            return ids        }    }    /// Rename, as the core runs it: refused in the list's own words (an    /// empty name, one another list has), said on the sheet.    private func rename(_ act: CardAction, _ name: String) async -> String? {        do {            // The rename wears the page's receipt, with its Undo — and takes            // the place of an older one that still named the old name.            landed = try await ListAct.run(act.id, group: group.id, table: act.tool ?? definition.id, words: name, core: core)            group.name = name            return nil        } catch {            return ActionRefused.words(for: error)        }    }    /// Remove list, as the core runs it: the list goes to the bin, its    /// records stay, and the list underneath wears the receipt.    private func delete(_ act: CardAction) {        Task {            do {                let change = try await ListAct.run(act.id, group: group.id, table: act.tool ?? definition.id, core: core)                CardClosing.close(closeCard, else: dismiss)                onDeleted(change)            } catch {                toasts.show(ActionRefused.words(for: error), tone: .error)            }        }    }}/// The sheet a group's name is typed on: held up until the name is taken,/// a refusal printed under the line in the store's own sentence. Return in/// the line saves, as Save does; a name already there (Rename) opens/// selected, so typing replaces it.struct GroupNameSheet: View {    @Environment(\.theme) private var theme    let title: String    let identifier: String    /// Writes the name: nil once it was taken, else the sentence why not.    let onSave: @MainActor (String) async -> String?    @State private var name: String    @State private var running = false    @State private var problem: String?    @FocusState private var focused: Bool    #if os(iOS)    @State private var selection: TextSelection?    #endif    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    init(title: String, name: String, identifier: String, onSave: @escaping @MainActor (String) async -> String?) {        self.title = title        self.identifier = identifier        self.onSave = onSave        _name = State(initialValue: name)    }    var body: some View {        VStack(alignment: .leading, spacing: 14) {            Text(title)                .paperTitle(theme.scale.titleSize + 2)                .accessibilityAddTraits(.isHeader)            field                .onSubmit { save() }                .submitLabel(.done)                .accessibilityLabel(ShellLines.line("lists", "group.name"))                .accessibilityIdentifier("\(identifier)-field")            if let problem {                Text(problem)                    .paperBody(13, ink: .red)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("\(identifier)-problem")            }            HStack {                Spacer(minLength: 0)                PaperInkCircle(label: ShellLines.line("lists", "save"), isEnabled: !running && GroupRecords.name(typed: name) != nil, isBusy: running) {                    save()                }                .accessibilityIdentifier("\(identifier)-save")            }        }        .frame(maxWidth: .infinity, alignment: .leading)        .onAppear { focused = true }        #if os(iOS)        .task {            // Once the line has the keyboard: a selection set before it is            // focused is put back to the end as the caret arrives.            guard !name.isEmpty else { return }            try? await Task.sleep(for: .milliseconds(400))            selection = TextSelection(range: name.startIndex..<name.endIndex)        }        #endif        // A container that holds its own elements: an identifier put on a        // stack that is not one is stamped over every child in it, and the        // title, the line and Save all answered to the sheet's one name.        .accessibilityElement(children: .contain)        .accessibilityIdentifier(identifier)    }    @ViewBuilder private var field: some View {        #if os(iOS)        PaperTextField("Name", text: $name, selection: $selection, focus: $focused)        #else        PaperTextField("Name", text: $name, focus: $focused)        #endif    }    private func save() {        guard !running, let typed = GroupRecords.name(typed: name) else { return }        running = true        problem = nil        Task {            let refused = await onSave(typed)            running = false            if let refused { problem = refused } else { CardClosing.close(closeCard, else: dismiss) }        }    }}/// "Add to group\u{2026}": the table's groups, each a line that takes the/// records, and a name typed under them that makes a new group of them. The/// main way a group is filled — a list's Select and a record's page both/// offer it. The sheet stays up with a refusal's own sentence.struct GroupChoiceSheet: View {    @Environment(\.theme) private var theme    let definition: TableDefinition    /// The records being added.    let ids: [String]    /// The one change the adding was, once the sheet has closed: it wears    /// the surface's own receipt ("Added 3 people to Family"), whose Undo    /// takes every one of them out again.    let onAdded: @MainActor (ChangeRecord) -> Void    @Environment(\.records) private var store    @Environment(\.dismiss) private var dismiss    @Environment(\.closeCard) private var closeCard    @Environment(\.tableDefinitions) private var definitions    @Environment(\.cottonCore) private var core    @State private var groups: [GroupStack] = []    @State private var name = ""    @State private var running = false    @State private var problem: String?    private var identifier: String { "group-\(definition.id)-choice" }    /// What a group is called here: "album" where the groups are albums.    private var noun: String {        definition.groups?.keptIn.flatMap { definitions[$0.table]?.name.lowercased() } ?? "group"    }    var body: some View {        VStack(alignment: .leading, spacing: 14) {            Text(ShellLines.line("lists", "group.add_to_noun", ["noun": noun]))                .paperTitle(theme.scale.titleSize + 2)                .accessibilityAddTraits(.isHeader)            ForEach(groups) { stack in                // A group that already holds the one record says so, and is                // not offered again.                PaperTypedButton(stack.holds == true ? ShellLines.line("lists", "group.already_in_it", ["group": stack.group.name]) : stack.group.name) {                    Task { await add(to: stack.group) }                }                .disabled(running || stack.holds == true)                .accessibilityIdentifier("\(identifier)-\(stack.group.id)")            }            PaperFormSection("New \(noun)") {                HStack(alignment: .center, spacing: 12) {                    PaperTextField("Name", text: $name)                        .onSubmit { Task { await makeAndAdd() } }                        .submitLabel(.done)                        .accessibilityLabel(ShellLines.line("lists", "group.new_name", ["noun": noun]))                        .accessibilityIdentifier("\(identifier)-new-name")                    PaperInkCircle(label: ShellLines.line("lists", "group.make", ["noun": noun]), isEnabled: !running && GroupRecords.name(typed: name) != nil, isBusy: running) {                        Task { await makeAndAdd() }                    }                    .accessibilityIdentifier("\(identifier)-new-save")                }            }            if let problem {                Text(problem)                    .paperBody(13, ink: .red)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("\(identifier)-problem")            }        }        .frame(maxWidth: .infinity, alignment: .leading)        .task {            guard let grouping = GroupRecords.grouping(store) else { return }            groups = (try? await grouping.groups(of: definition.id, holding: ids.count == 1 ? ids.first : nil)) ?? []        }        // Its own elements inside, each under its own identifier (as the        // name sheet's).        .accessibilityElement(children: .contain)        .accessibilityIdentifier(identifier)    }    /// A new group made holding the records: one write, one receipt.    private func makeAndAdd() async {        guard let grouping = GroupRecords.grouping(store), !running, let typed = GroupRecords.name(typed: name) else { return }        await run { try await grouping.createGroup(named: typed, of: definition.id, records: ids).change }    }    /// The records put in the group, by the list's own Add: one write, one receipt, one Undo.    private func add(to group: RecordGroup) async {        guard !running else { return }        await run { try await ListAct.run(ListAct.add, group: group.id, table: definition.id, records: ids, core: core) }    }    /// Runs the write; done, the sheet closes and hands its change on —    /// refused, it stays up with the store's own sentence.    private func run(_ write: () async throws -> ChangeRecord) async {        running = true        problem = nil        do {            let change = try await write()            running = false            CardClosing.close(closeCard, else: dismiss)            onAdded(change)        } catch {            running = false            problem = ActionRefused.words(for: error)        }    }}/// The groups a record's page links to ("Groups 2" in its row of links):/// the ones holding it, read through the groups' own `holding` answer.extension GroupRecords {    /// The groups of `definition`'s table holding `id`; nil where the table    /// keeps no groups or the read failed (the link keeps what it drew).    static func holding(_ id: String, of definition: TableDefinition, in store: (any Records)?) async -> [RecordGroup]? {        guard definition.groups != nil, let grouping = grouping(store),            let read = try? await grouping.groups(of: definition.id, holding: id)        else { return nil }        return read.filter { $0.holds == true }.map(\.group)    }}extension View {    /// The "Add to group\u{2026}" sheet for `ids`: what it did is handed to    /// `received`, so it wears the surface's receipt with its Undo.    func addingToGroup(        isPresented: Binding<Bool>, definition: TableDefinition, ids: [String],        received: @escaping @MainActor (ChangeRecord) -> Void, onAdded: @escaping @MainActor () -> Void = {}    ) -> some View {        cottonCard(isPresented: isPresented) {            GroupChoiceSheet(definition: definition, ids: ids) { change in                received(change)                onAdded()            }        }    }}/// A list's own act run by the core (`tools.act`, `tool_acts::list_act`):/// the records picked put in or taken out, a rename, its removal — each one/// write, answered with the change whole for the surface's receipt; a/// refusal is the core's sentence, thrown.enum ListAct {    static let add = "list_add"    static let takeOut = "list_take_out"    private struct Ask: Encodable {        let tool: String        let act: String        let group: String        var records: [String]?        var words: String?    }    private struct Answer: Decodable {        let change: CoreRecords.WireChange    }    @MainActor    static func run(_ act: String, group: String, table: String, records: [String]? = nil, words: String? = nil,                    core: (any CottonCalling)?) async throws -> ChangeRecord {        guard let core else { throw ActionRefused(ShellLines.line("lists", "group.none_kept")) }        let answer = try await core.call(CottonMethod.toolsAct, Ask(tool: table, act: act, group: group, records: records, words: words), as: Answer.self)        return CoreRecords.change(CoreRecords.WireWrite(change: answer.change, record: nil))    }}