Cotton code
210 lines · 10.2 KB · SwiftRaw
// A deck of cards that are not one table's records — the tools (row B of the// deck faces), today's cards on Home (row C). The record deck// (`DeckSurface`) reads one table's `@card` rows; this one is handed its// cards and draws them the same way, as a whole page on the paper ground:// the floating line over the deck — its place in the deck ("3 / 12"), the// search circle that narrows the deck to the cards whose words hold what is// typed, and the + when the page makes something — then the 4:5 card as// large as the room above the bloomed fan allows, its face on the paper it// lays (`onCardPaper`), nothing behind it; a tap on the screen's right third// cuts to the next, on its left third to the last, a swipe moves too, a tap// on the middle third opens it (`DeckZones`), and a hold lifts it with its// acts (`ActLift`) — one act is simply done. The fan, its chips and the// record button are the frame's, under the page.import CottonPaperimport CottonValuesimport SwiftUIstruct CardDeck<Item: Identifiable, Face: View>: View where Item.ID == String {    let items: [Item]    /// The card the deck opens on; the first when nil or not among them.    var opensAt: String? = nil    var emptyLine: String = ShellLines.line("cards", "deck.empty")    let open: (Item) -> Void    var acts: (Item) -> [LiftedAct] = { _ in [] }    /// The words a card is found by; nil, the deck has no search.    var words: ((Item) -> String)? = nil    /// The + over the deck: its label and what it makes; nil, none.    var plus: (label: String, make: () -> Void)? = nil    /// A hold hands the card to the page instead of lifting it: a customer's    /// card turns the fan into its acts (`CustomerDeck`, `DeckEditor.offer`).    /// Nil, the hold lifts the card with `acts`.    var holds: ((Item) -> Void)? = nil    /// The card opened in place (`OpenedInPlace`, the page's own): while it    /// stands the deck holds every move and its taps are the card's parts'.    var opened: String? = nil    @ViewBuilder let face: (Item) -> Face    @Environment(\.theme) private var theme    @Environment(\.actLift) private var lift    @Environment(\.cottonHaptics) private var haptics    @State private var front: String?    @State private var drag: CGFloat = 0    @State private var frame: CGRect = .zero    @State private var searching = false    @State private var query = ""    @Environment(\.fanCover) private var cover    /// The cards the deck holds now: every one, or those found.    private var shown: [Item] {        let wanted = query.trimmingCharacters(in: .whitespaces)        guard searching, !wanted.isEmpty, let words else { return items }        return items.filter { words($0).localizedCaseInsensitiveContains(wanted) }    }    private func at(in shown: [Item]) -> Int {        let wanted = front ?? opensAt        return wanted.flatMap { id in shown.firstIndex { $0.id == id } } ?? 0    }    var body: some View {        let shown = shown        let at = at(in: shown)        GeometryReader { geo in            let top = geo.frame(in: .global).minY            // The card stands above where the standing fan's top lies, open            // or closed, as the record deck's does (`FanCover.standingEdge`).            let live = cover?.standingEdge.map { max(0, $0 - top) } ?? geo.size.height            let zones = DeckZones(geo.frame(in: .global))            VStack(spacing: 0) {                floatingLine(at: at, of: shown.count)                    .frame(height: DeckKnobs.lineHeight)                Group {                    // An empty deck says its line alone where the card would                    // stand (`DeckEmptyLine`), as a record deck's does.                    if shown.isEmpty, searching {                        DeckEmptyLine(title: ShellLines.line("cards", "deck.nothing_found"))                    } else if shown.isEmpty {                        DeckEmptyLine(title: emptyLine)                            .accessibilityIdentifier("deck-empty")                    } else {                        deck(shown, at: at, zones: zones)                    }                }                .padding(.horizontal, DeckKnobs.sideInset)                .padding(.bottom, DeckKnobs.footRoom)                .frame(height: max(0, live - DeckKnobs.lineHeight))                Spacer(minLength: 0)            }            .frame(maxWidth: .infinity, maxHeight: .infinity)            // The ground beside and above the card moves by the zones too.            .deckZonedGround(shown.isEmpty ? nil : zones) { step in move(step, in: shown, from: at) }        }    }    /// The line over the deck: where the card stands in it, search, and +.    @ViewBuilder private func floatingLine(at: Int, of count: Int) -> some View {        HStack(spacing: 12) {            if searching {                TextField(ShellLines.line("cards", "deck.search"), text: $query)                    .scaledFace(relativeTo: .callout) { CottonFonts.type((DeckKnobs.positionSize + 1) * $0) }                    .foregroundStyle(theme.print(.ink))                    .textFieldStyle(.plain)                    .autocorrectionDisabled()                    .submitLabel(.search)                    .accessibilityIdentifier("deck-search-field")                NavCircle(symbol: "xmark", label: ShellLines.line("cards", "deck.close_search")) {                    searching = false                    query = ""                }            } else {                if count > 0 {                    Text(ShellLines.line("cards", "deck.position", ["at": String(at + 1), "of": String(count)]))                        .scaledFace(relativeTo: .callout) { CottonFonts.type(DeckKnobs.positionSize * $0) }                        .foregroundStyle(theme.print(.pencil))                        // At the largest text sizes the line shrinks to stand whole beside                        // Search and Plus, never cut to "1 /…" (the gaps walk, 5 Nov 2026).                        .lineLimit(1)                        .minimumScaleFactor(0.4)                        .layoutPriority(1)                        .accessibilityIdentifier("deck-position")                }                Spacer()                if words != nil {                    NavCircle(symbol: "magnifyingglass", label: ShellLines.line("cards", "deck.search")) { searching = true }                }                if let plus {                    NavCircle(symbol: "plus", label: plus.label) { plus.make() }                }            }        }        .padding(.horizontal, DeckKnobs.lineSide)    }    private func deck(_ items: [Item], at: Int, zones: DeckZones) -> some View {        let item = items[at]        return GeometryReader { box in            // The 4:5 card, as large as the room allows.            let width = max(0, min(box.size.width, box.size.height * CardPaperKnobs.aspect))            // A plain cut: the next card is simply there.            card(item, in: items, at: at, zones: zones)                .frame(width: width, height: width / CardPaperKnobs.aspect)                .id(item.id)                .frame(width: box.size.width, height: box.size.height, alignment: .top)        }    }    private func card(_ item: Item, in items: [Item], at: Int, zones: DeckZones) -> some View {        let held = acts(item)        return face(item)            .opacity(lift?.lifted?.id == lifted(item) ? 0 : 1)            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame = $0 }            // A pinch out reads the card on the whole screen, as a record            // deck's does (`pinchOpens`).            // The zones (`DeckZones`): a side third moves the deck where no            // part stands, the middle third opens the card.            .deckZoned(zones, move: { move($0, in: items, from: at) }) { if opened == nil { open(item) } }            .onLongPressGesture { if opened != item.id { hold(item, acts: held) } }            .offset(x: drag)            .rotationEffect(.degrees(Double(drag) / 40))            .gesture(                DragGesture(minimumDistance: 14)                    .onChanged { value in                        guard opened == nil, abs(value.translation.width) > abs(value.translation.height) else { return }                        drag = value.translation.width                    }                    .onEnded { value in                        guard opened == nil else { return }                        let width = value.translation.width                        if width < -DeckKnobs.swipe { move(1, in: items, from: at) } else if width > DeckKnobs.swipe { move(-1, in: items, from: at) }                        withAnimation(.snappy) { drag = 0 }                    })            .accessibilityElement(children: .contain)            .accessibilityIdentifier(opened == item.id ? "opened-card" : "deck-card")            .accessibilityAddTraits(.isButton)            .accessibilityAction { open(item) }            .accessibilityActions {                ForEach(held) { act in Button(act.word) { act.perform() } }            }            .accessibilityAdjustableAction { direction in move(direction == .increment ? 1 : -1, in: items, from: at) }            .deckMoveActions { move($0, in: items, from: at) }    }    private func lifted(_ item: Item) -> String { "deck/" + item.id }    /// A hold: one act is done; several lift the card with them.    private func hold(_ item: Item, acts: [LiftedAct]) {        if let holds {            haptics.press()            return holds(item)        }        if acts.count == 1 { return acts[0].perform() }        guard !acts.isEmpty, let lift else { return }        haptics.press()        let face = self.face(item).environment(\.theme, theme)        lift.lift(Lifted(id: lifted(item), frame: frame, face: AnyView(face), acts: acts))    }    /// One card on, or back: a plain cut, no slide; nothing past an end.    private func move(_ step: Int, in items: [Item], from at: Int) {        // An opened card holds its deck: nothing moves it.        guard opened == nil else { return }        guard case .card(let next) = DeckStep.of(step, from: at, count: items.count) else {            withAnimation(.snappy) { drag = 0 }            return        }        front = items[next].id        drag = 0    }}