Cotton code
1424 lines · 71.8 KB · SwiftRaw
// THE DECK (cardtrial, image 1): one record at a time, as a card, above the// strip of views and the fan, which stay as they are; nothing is drawn// behind it. A tap on the screen's right third brings the next at once, on// its left third the one before, the middle third is the card's own tap// (`DeckZones`); a swipe moves too. A tap on a part of the face never// changes card.// No title bar: a floating line holds the position ("3 / 14"), search and +.// A card whose face lies on a ground of its own (a list's cassette on the// music's tolex) has that ground laid behind the page, and the line's words// take the light ink on it (`DeckGround`).// Search answers a short list that opens the deck at the chosen record. No// grid, no A–Z.//// Tap opens the record; a hold opens its card at rest, IN PLACE: the card// stays where it is and the acts tier fans at the hub (`OpenedInPlace`).// Only that opened card installs the editing tap map, and the deck holds// every move while it stands. A record outside the// current view stands in front as a visitor; moving on drops it.//// The cards are the core's (`shell.deck`, `DeckReading`): its order, each// card worn and filled, its position said, its tap map; the deck draws them// and pages on as it nears the end of what it holds.import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport SwiftUI/// The deck's own space, the ink's strokes and the front card's frame/// measured in it.enum DeckInk {    static let space = "deck-ink"    /// Whether a mark's strokes land on the card: the middle of their box    /// within its frame or on one of its papers (the deck's ink space).    static func lands(_ points: [CGPoint], on papers: [CGRect]) -> Bool {        let xs = points.map(\.x), ys = points.map(\.y)        guard let minX = xs.min(), let maxX = xs.max(), let minY = ys.min(), let maxY = ys.max() else { return false }        let middle = CGPoint(x: (minX + maxX) / 2, y: (minY + maxY) / 2)        return papers.contains { $0.contains(middle) }    }}/// A record an act made at the object, which comes to this phone by sync:/// waited for as a "+" act's record is (`DeckKnobs.landingTries`), `true`/// once it is here, `false` when it never came.enum RecordLanding {    @MainActor    static func arrived(_ link: RecordLink, in store: (any Records)?) async -> Bool {        for _ in 0..<DeckKnobs.landingTries {            if let store, (try? await store.get(table: link.table, id: link.id)) != nil { return true }            try? await Task.sleep(for: .milliseconds(DeckKnobs.landingEveryMs))        }        return false    }}enum DeckKnobs {    static let sideInset: CGFloat = 22    /// How long a "+" act's record is waited for before the deck stands on    /// it (`CreateAct.lands`): it comes by sync, asked for as the act answers.    static let landingTries = 120    static let landingEveryMs = 500    static let lineHeight: CGFloat = 60    static let lineSide: CGFloat = 28    /// The hand's place on the top row: its target and the row's spacing.    static let handRoom: CGFloat = ScreenBarKnobs.chromeNavCircleTarget + 12    /// The crumb line under the top line, while a whole's parts are dealt.    static let crumbHeight: CGFloat = 26    /// On this phone's top line, on its own row under the deck's line:    /// two lines of it at most, the type shrinking to stand whole.    static let headHeight: CGFloat = 44    static let crumbSize: CGFloat = 14    static let crumbChevron: CGFloat = 9    static let positionSize: CGFloat = 16    /// How far the card stands above the fan's cover.    static let footRoom: CGFloat = 18    /// How far a swipe travels before it moves a card.    static let swipe: CGFloat = 70    /// How near the end of the rows read the next page is asked for.    static let readAhead = 4    static let foundMost = 8    /// How long the crossing into another view is said.    static let crossingMs = 900}/// The beat a rollover shows: the view crossed into, stamped on a slip of the/// deck's paper for a moment.struct DeckCrossing: View {    let label: String    @Environment(\.theme) private var theme    var body: some View {        Text(label)            .scaledFace(relativeTo: .callout) { CottonFonts.type((DeckKnobs.positionSize + 1) * $0) }            .foregroundStyle(theme.sheet(.cream))            .padding(.horizontal, 18)            .padding(.vertical, 8)            .background(Capsule().fill(theme.print(.ink)))            .softShadow()            .transition(.opacity.combined(with: .scale(scale: 0.92)))            .accessibilityAddTraits(.updatesFrequently)            .accessibilityIdentifier("deck-crossing")    }}struct DeckSurface: View {    let definition: TableDefinition    let filter: [String: RecordValue]    let view: ToolView.Read?    /// The record the deck opens at, when something named one.    var opensAt: String?    /// ROLLOVER (door row 5): a swipe past the last card goes on to the next    /// view chip's first card, back past the first to the previous chip's    /// last. Asked with the direction; answers the label of the view it    /// moved to, nil where there is none that way (the deck stops as before).    var rollover: ((_ forward: Bool) -> String?)?    /// Opened to make one (a tool's "new" route): the blank card stands at once.    var composesOnArrival = false    /// A blank's own values (a new event on the day its route names): the    /// record it composes starts with them over the create's own (that day,    /// not today). Never a read filter: a bare day matches no stored instant.    var blank: [String: RecordValue] = [:]    /// The day the rows are read from (a date's own calendar), nil for the    /// view's own start.    var opensOn: String?    /// A whole's parts dealt (`WholePath`): the crumb line under the top    /// line, and where a crumb's tap goes (the depth of wholes it leaves).    var crumbs: [WholeCrumb] = []    var crumbTap: ((Int) -> Void)?    /// The card in front, said as it changes: a whole's parts fan rests on it.    var fronts: ((String?) -> Void)?    /// The view a deck read by no view of its own stands for, as    /// `<tool>/group:<id>`: a list's deck of its members, whose cards and    /// placeholder offer the list's acts (Set picture from Photos).    var standsFor: String?    /// A record's or a blank's deck names no view: the core names the one it    /// lands on (`shell.deck`'s `lands`), and the deck stands on that.    var lands = false    @Environment(\.records) private var store    @Environment(\.deckEditor) private var deckEditor    @Environment(\.currentProject) private var currentProject    @Environment(\.recordsRevision) private var revision    @Environment(DatabaseScene.self) private var databaseScene: DatabaseScene?    @Environment(\.fanCover) private var cover    @Environment(DatabasesModel.self) private var databasesModel: DatabasesModel?    @Environment(\.tableDefinitions) private var definitions    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.toolDefinitions) private var tools    @Environment(ToolViews.self) private var toolViews: ToolViews?    @Environment(\.theme) private var theme    /// The personal object's session: before backup, a tool only the server    /// fills says so on its empty deck (`ToolServerLine`).    @Environment(PersonalObject.self) private var personal: PersonalObject?    @State private var heldModel: DeckReading?    @State private var composedOnLanding = false    @State private var modelRead: Read?    /// A changed view must never draw the preceding view's rows or empty state,    /// even in the frame before its new read task starts.    private var model: DeckReading? { modelRead == reading ? heldModel : nil }    /// The view the deck stands on: its own, else the one the core landed it on.    private var standing: ToolView.Read? { view ?? model?.landedView }    /// What the deck holds to: its own values, then its landed view's.    private var narrowing: [String: RecordValue] { filter.merging(model?.landedView?.filter ?? [:]) { own, _ in own } }    private var reading: Read { Read(definition: definition, project: project, view: view, filter: filter, opensOn: opensOn) }    /// The record in front, kept by id so a re-read keeps it in front.    @State private var front: String?    @State private var turn = FaceTurnMotion()    @State private var turnWindow: [Int: DeckCard] = [:]    @State private var drag: CGFloat = 0    /// The front card's opening stands over the deck: what the pinch out and    /// a reading card's own tap open (`DeckOpening.open`).    @State private var opened = false    /// The record opened in place (`OpenedInPlace`): while it stands the    /// deck holds every move — the zones, the swipe, the ink's line, the    /// wheel — so a stroke edits or acts instead of turning.    @State private var openedInPlace: String?    /// A check ticked here, drawn at once until the re-read says it.    @State private var ticked: [String: Bool] = [:]    @State private var searching = false    @State private var query = ""    @State private var found: [TableRecord] = []    /// A record in front that the view's rows do not hold (`bring`).    @State private var visitor: TableRecord?    /// Rolled back into the previous view: it opens on its last card.    @State private var entersAtEnd = false    /// The view just rolled into, said for a beat over the deck.    @State private var crossing: String?    /// What the showing table's rows are doing (`DeckMoving`): the counter    /// says it while they move.    @State private var moving: DeckMoving = .settled    /// Cotton Cinemas' On this phone, its top line: what this phone keeps of    /// films (`FilmKeeper.head`), read while that view shows.    @State private var onPhoneHead: String?    @Environment(\.cottonCore) private var core    @Environment(\.cottonSync) private var sync    /// The letters written above the fan, narrowing the deck to the records    /// a word of whose title starts with them (`InkGround`); cleared when    /// the view read changes.    @State private var ink = InkLetters()    /// The letter in progress, as the core reads it at the last lift: shown    /// in the readout provisionally until its group is read and acted on.    @State private var inkPending: [String] = []    /// The core's name for this deck's ink: a fresh one for every view read,    /// so another deck starts with no letters.    @State private var inkSurface = "deck:\(UUID().uuidString)"    /// The card in front when the first letter was written: clearing the    /// letters stands the deck there again.    @State private var frontBeforeInk: String?    /// The groups the ink read, acted on one after another.    @State private var inkQueue: Task<Void, Never>?    /// The top row's width: the ink's readout grows to half of it.    @State private var lineWidth: CGFloat = 0    /// The front card's faces' page turns, innermost last: the swipe the    /// ink reads turns them (`DeckPageTurners`).    @State private var pageTurners: [DeckPageTurner] = []    /// The front card's frame in the deck's space (`DeckInk.space`).    @State private var cardFrame: CGRect = .zero    /// The front card's papers on the screen, as each reports itself    /// (`CardPaperReport`, told to the front card alone): the face's frame    /// is its whole slot, not its paper.    @State private var papers: [UUID: CGRect] = [:]    /// Where the ink's space lies on the screen, to place the papers in it.    @State private var inkOrigin: CGPoint = .zero    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver    @Environment(\.cottonHaptics) private var haptics    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.viewerPresenter) private var viewerPresenter    @Environment(\.readerPresenter) private var readerPresenter    /// A door's files being chosen in the system's picker (`DeckDoors`).    @State private var choosing: DefinitionCreateFiles?    /// A door's pictures being chosen in the photo picker or taken with the camera (`DoorPictures`).    @State private var picking: DefinitionCreatePick?    /// The read `opensAt` was brought on: the record a landing (an intake,    /// a card opened from elsewhere) opened the deck at is brought once, on    /// the view the deck opened on; a view the tier chooses after is that    /// view's own deck, never the landed card again as a visitor on each    /// (the Cinemas walk, 5 Nov 2026: The Salt Road stood 3 / 3 on every view).    @State private var openedAtOn: Read?    /// Listening's player: the face it wears and the playing album, read on    /// its own while Listening does not hold it yet (`ListeningCard`).    @State private var listening = ListeningState()    struct ListeningState {        var face: PlayerFace = .hifi        var visiting: TableRecord?    }    /// The song the one music player holds, on Listening alone.    private var playingSong: QueuedSong? {        standing?.name == ListeningCard.view ? MusicNowPlaying.shared.song : nil    }    private var project: String? { definition.projectScope(currentProject) }    /// The cards the deck holds, as the core answered them (`shell.deck`),    /// narrowed there by the letters written on its ground; a visitor first.    private var cards: [(record: TableRecord, card: DeckCard)] {        guard let model else { return [] }        var rows = model.records        if let visitor, !rows.contains(where: { $0.id == visitor.id }) { rows.insert(visitor, at: 0) }        let made: [(record: TableRecord, card: DeckCard)] = rows.compactMap { record in            guard var card = model.card(record.id) else { return nil }            if let ticked = ticked[record.id], card.checked != nil { card.fields["check"] = .bool(ticked) }            return (record, card)        }        guard let song = playingSong else { return made }        return ListeningCard.dealt(made, song: song, visiting: listening.visiting, face: listening.face, volume: playerVolume,                                   said: MusicNowPlaying.shared.said)    }    /// The amp's small knob reads the system's volume.    private var playerVolume: Double? {        #if os(iOS)        listening.face == .amp ? SystemVolume.shared.level : nil        #else        nil        #endif    }    /// A song starts in Listening: the face the player wears is read, its    /// album read on its own where Listening does not hold it yet, and its    /// card brought to the front.    private func listen(to song: QueuedSong?) async {        guard let song, let core else { return }        let face = await PlayerSettings.read(core).face        var visiting: TableRecord?        if let album = song.album, !(model?.records.contains { $0.id == album } ?? false) {            visiting = try? await CoreRecords(core: core).get(table: definition.id, id: album)        }        guard !Task.isCancelled else { return }        listening = ListeningState(face: face, visiting: visiting)        front = song.album ?? song.id    }    /// The hand's tap while a song plays: the next of the player's faces,    /// worn at once and written on the `player` row.    private func wear(_ face: PlayerFace) {        listening.face = face        guard let core else { return }        let toasts = toasts        Task {            do { try await PlayerSettings.wear(face, core: core) } catch { toasts?.show(error.localizedDescription, tone: .error) }        }    }    private func index(in cards: [(record: TableRecord, card: DeckCard)]) -> Int {        guard !cards.isEmpty else { return 0 }        return front.flatMap { id in cards.firstIndex { $0.record.id == id } } ?? 0    }    /// The deck as drawn, with what stands on it while it is shown.    private var drawn: some View {        let cards = cards        let at = index(in: cards)        let searching = searching && modelRead == reading        // The front card's own ground, while the deck shows it.        let pending = cards.isEmpty && (model == nil || model?.phase == .loading)        // With no card up, a one-tool app's deck keeps its tool's ground (`DeckGround.laid`).        let ground = pending ? cover?.ground : (searching ? FaceGround.app : DeckGround.laid(            front: cards.indices.contains(at) && viewCard(cards[at].record) == nil ? cards[at].card : nil, table: standing?.card ?? definition.card,            installed: tools.all.map(\.id)))        return GeometryReader { geo in            let frame = geo.frame(in: .global)            // The card stands above where the standing fan's top lies, open            // or closed (`FanCover.standingEdge`): the fan hovers, and its            // opening or closing never moves or resizes the card.            let live = cover?.standingEdge.map { max(0, $0 - frame.minY) } ?? geo.size.height            let crumbRoom = (crumbs.isEmpty ? 0 : DeckKnobs.crumbHeight) + (onPhoneLine == nil ? 0 : DeckKnobs.headHeight)            let zones = DeckZones(frame)            VStack(spacing: 0) {                Group {                    floatingLine(at: at, in: cards, on: ground)                        .frame(height: DeckKnobs.lineHeight)                    if let onPhoneLine {                        headLine(onPhoneLine, on: ground).frame(height: DeckKnobs.headHeight)                    }                    if !crumbs.isEmpty {                        crumbLine(on: ground).frame(height: DeckKnobs.crumbHeight)                    }                }                .animation(.easeInOut(duration: DeckGroundKnobs.fade), value: ground)                if searching {                    results                } else {                    deck(cards, at: at, zones: zones)                        .padding(.horizontal, DeckKnobs.sideInset)                        .padding(.bottom, DeckKnobs.footRoom)                        .frame(height: max(0, live - DeckKnobs.lineHeight - crumbRoom))                }                Spacer(minLength: 0)            }            .frame(maxWidth: .infinity, maxHeight: .infinity)            .coordinateSpace(.named(DeckInk.space))            .onGeometryChange(for: CGPoint.self) { $0.frame(in: .global).origin } action: { inkOrigin = $0 }            // Every stroke above the fan, the card's included, is read on            // lift: a letter narrows the deck, a scratch-out clears it, a            // level line is the page swipe. The discs' strip and a Rolodex's            // knob keep their own.            .inkWriting(InkReads.here(voiceOver: voiceOver) && !searching,                        ink: DeckGround.ink(.ink, on: ground, theme: theme),                        card: cards.indices.contains(at) ? InkCard(papers: inkPapers, ink: DeckGround.ink(.ink, on: nil, theme: theme)) : nil,                        surface: inkWrittenOn,                        reads: { $0.y >= DeckKnobs.lineHeight + crumbRoom && !onKnob($0) },                        answered: takeInk, unread: turnByKnob)            // The ink's knobs, read once from the core: until then no ink.            .task { await InkKnobs.shared.load(core) }            // The ground beside and above the card moves by the zones too.            .deckZonedGround(searching || cards.isEmpty ? nil : zones) { step in                let cards = self.cards                turnOrMove(step, in: cards, from: index(in: cards))            }            .onChange(of: cards.indices.contains(at) ? cards[at].record.id : nil, initial: true) { _, id in fronts?(id) }        }        // The keyboard (a search's) comes up over the fan; the deck neither        // shrinks to the room above it nor shuffles to avoid it.        .ignoresSafeArea(.keyboard, edges: .bottom)        // The shell alone paints this ground, through the page and fan.        .preference(key: DeckGroundPreference.self, value: pending ? .pending : .known(ground))        .overlay(alignment: .top) {            if let crossing { DeckCrossing(label: crossing).padding(.top, DeckKnobs.lineHeight + 14) }        }        // While the table's rows move, read again until they settle; a sync        // pass, a write or another table showing reads anew.        .task(id: MovingReads(table: definition.id, revision: sync?.revision ?? 0, pulled: sync?.lastPullAt,                              pending: sync?.pendingOps ?? 0, local: sync?.localWrites ?? 0, passing: sync?.passing == true)) {            while !Task.isCancelled {                let now = DeckMoving.of(definition.id, in: await DeckMovingRead.read(core))                guard !Task.isCancelled else { return }                if now != moving { moving = now }                guard DeckMoving.readsAgain(now, passing: sync?.passing == true) else { return }                try? await Task.sleep(for: .seconds(DeckMovingKnobs.every))            }        }        // Cotton Cinemas' On this phone reads its top line again as what is        // kept changes and as this phone backs up.        .task(id: DeckOnPhone(view: standing?.name, pulled: sync?.lastPullAt, keeping: DeckOnPhone.keeping)) {            guard standing?.name == DeckOnPhone.view else { return }            #if os(iOS)            onPhoneHead = await FilmKeeper.shared.head()            #endif        }        .task(id: crossing) {            guard crossing != nil else { return }            try? await Task.sleep(for: .milliseconds(DeckKnobs.crossingMs))            withAnimation(.easeOut(duration: 0.3)) { crossing = nil }        }        // A note's last page swiped on moves the card, as the card's own        // swipe does (`NoteFace.passOn`).        .environment(\.deckPassOn) { forward in            let cards = cards            move(forward ? 1 : -1, in: cards, from: index(in: cards))        }        .onAppear {            if composesOnArrival, !lands, definition.create != nil { compose() }        }        .task(id: playingSong?.id) { await listen(to: playingSong) }        .task(id: ListeningRestore(view: standing?.name, revision: sync?.revision ?? 0, pulled: sync?.lastPullAt)) {            // Music always has a player: the song the core keeps or offers,            // resting, asked again as the songs arrive (music-player-first).            #if os(iOS)            if standing?.name == ListeningCard.view { await MusicPlayback.shared.restore() }            #endif        }    }    var body: some View {        // Cut in four, each its own frame handed on as AnyView: as one chain        // the deck's value ran past the 2 KB a body may copy at every        // modifier on the phone's 1 MB main stack (`SurfaceStackTests`).        AnyView(watched)        // The tool acts its cards and its placeholder offer are this view's.        .environment(\.deckViewName, standing?.name ?? standsFor)        // A door's files, chosen in the system's picker and handed to the        // share sheet's intake (`DeckDoors.bring`).        .doorFiles($choosing, for: definition.id)        .doorPictures($picking, for: definition.id)        // A container: the deck is named, and its card, search and add keep        // their own names inside it (the walk and VoiceOver reach each one).        .accessibilityElement(children: .contain)        .accessibilityIdentifier("deck")    }    /// The deck read, and what it watches: the shell editor's writes, its    /// count, its page landing, a face chosen and the search's words.    private var watched: some View {        AnyView(read)        // A write the shell's editor made on this deck's table: the deck        // reads itself again, never waiting on a sync event for its own.        .onChange(of: deckEditor?.landed) { _, landed in            guard let landed, landed.table == definition.id || model?.cards.contains(where: { $0.table == landed.table }) == true else { return }            if let change = landed.change, change.before?.id == visitor?.id, change.after == nil {                visitor = nil                openedInPlace = nil            }            Task { await model?.landed(landed.change) }        }        .onChange(of: model?.count, initial: true) { _, count in            if let count, project == nil, model?.ink.isEmpty == true { toolViews?.counted(count, for: standing) }        }        // A read landed: what it says of a ticked check and of the visitor stands.        .onChange(of: model?.page) { _, _ in            ticked = [:]            // The record being brought, answered by a read that landed after            // the bring's own (a data event's): it stands as the visitor.            visitor = DeckLanding.visitor(holding: visitor, front: front, answered: { model?.answered($0)?.record.record },                                          brought: model?.visitor?.record.record)        }        .task(id: query) {            guard searching, let store else { return }            let reading = reading            let words = query.trimmingCharacters(in: .whitespaces)            guard !words.isEmpty else { found = []; return }            try? await Task.sleep(for: .milliseconds(200))            guard !Task.isCancelled,                let page = try? await store.list(table: definition.id, project: project, query: words, page: 0, where: narrowing)            else { return }            guard !Task.isCancelled, reading == self.reading else { return }            found = Array(page.records.prefix(DeckKnobs.foundMost))        }    }    /// The deck drawn, and its rows read: when it opens, when a card is    /// brought, when the data moves under it.    private var read: some View {        AnyView(drawn)        .task(id: reading) {            let reading = reading            guard let store else { return }            let asked = DeckReading.Asked(table: definition.id, view: view?.name ?? standsFor, filter: filter,                                          opensOn: opensOn, database: databaseScene?.shownId, lands: lands)            let model = DeckReading.retaining(heldModel, asked: asked, core: core, store: store)            model.chosen = toolViews?.chosen ?? [:]            if heldModel !== model {                front = nil; ticked = [:]; visitor = nil                searching = false; query = ""; found = []; opened = false; openedInPlace = nil            }            heldModel = model            modelRead = reading            await model.reload()            guard !Task.isCancelled, modelRead == reading, heldModel === model else { return }            // A blank that lands composes once it stands on its view: the            // record it makes holds that view's own values.            if composesOnArrival, lands, !composedOnLanding, definition.create != nil {                composedOnLanding = true                compose()            }            if let opensAt, openedAtOn == nil {                openedAtOn = reading                await bring(opensAt)            }            await takeBrought()            if entersAtEnd {                entersAtEnd = false                await model.readToEnd()                front = cards.last?.record.id            }        }        // Another view read is another deck: the letters go.        .onChange(of: reading) { _, _ in            ink = InkLetters()            inkPending = []            inkSurface = "deck:\(UUID().uuidString)"        }        // The letters narrow the deck where its cards are read.        // A spoken command that named no record: Find, with its words.        .onReceive(NotificationCenter.default.publisher(for: VoiceCommands.search)) { note in            guard let words = note.userInfo?["query"] as? String, !words.isEmpty else { return }            query = words            searching = true        }        .onChange(of: ink.letters) { before, letters in            if before.isEmpty, !letters.isEmpty { frontBeforeInk = front }            if letters.isEmpty, !before.isEmpty { front = frontBeforeInk; frontBeforeInk = nil }            Task { await model?.narrow(letters) }        }        // A card brought from Home: the fan turned here, the deck opens at it.        .onChange(of: navigator?.bringing) { _, _ in Task { await takeBrought() } }        .onChange(of: revision) { _, _ in model?.dataMoved() }        // The viewer opened over the deck walks it: the card in front        // follows the one on screen, so a swipe down goes back into it.        .onChange(of: viewerPresenter?.showing) { _, showing in follow(showing) }    }    private struct Read: Equatable {        let definition: TableDefinition        let project: String?        let view: ToolView.Read?        let filter: [String: RecordValue]        let opensOn: String?    }    /// What asks the music player again on Listening: the view showing, and    /// records arriving (a sign-in's songs come down after the view shows).    private struct ListeningRestore: Equatable {        let view: String?        let revision: Int        let pulled: String?    }    /// What reads the showing table's movement again.    private struct MovingReads: Equatable {        let table: String        let revision: Int        let pulled: String?        let pending: Int        let local: Int        /// A pass is in flight: its pages land inside one cycle.        let passing: Bool    }    /// What reads Cotton Cinemas' On this phone top line again: the view    /// showing, a pass that reached the object, and what is coming down.    private struct DeckOnPhone: Equatable {        /// The view whose top line it is (`cinemas`' `on_phone`).        static let view = "cinemas/on_phone"        let view: String?        let pulled: String?        let keeping: [String]        /// The films coming down now, by key.        @MainActor static var keeping: [String] {            #if os(iOS)            return (Array(FilmKeeper.shared.keeping.keys) + Array(FilmKeeper.shared.fetching)).sorted()            #else            return []            #endif        }    }    /// The front card's papers in the ink's space.    private var inkPapers: [CGRect] {        papers.values.map { $0.offsetBy(dx: -inkOrigin.x, dy: -inkOrigin.y) }    }    // MARK: The floating line    /// "1 / 135": the front card's place; nil on an empty or uncounted deck.    private func position(at: Int, in cards: [(record: TableRecord, card: DeckCard)]) -> String? {        let shown = turn.position(from: at, count: cards.count)        guard cards.indices.contains(shown) else { return nil }        // Listening deals the player in front of the core's order: counted as dealt.        if playingSong != nil, query.isEmpty {            return ShellLines.line("cards", "deck.position", ["at": String(shown + 1), "of": String(cards.count)])        }        return model?.answered(cards[shown].record.id)?.position    }    /// The view's head as the core said it (`shell.deck`), while no letters    /// narrow the deck: what they keep is the position's to say.    private var head: String? { model?.page?.head }    /// A film of this deck coming down to keep (`FilmKeeper`): the counter    /// says how far, in its own place and type.    private var keepingLine: String? {        // Songs and films coming in say how far, "41 of 212", before        // anything else.        if let coming = MusicIntakeProgress.shared.line(table: definition.id) { return coming }        if let coming = FilmIntakeProgress.shared.line(table: definition.id) { return coming }        #if os(iOS)        if let coming = FilmKeeper.shared.line(table: definition.id) { return coming }        #endif        // On this phone: "14 films · 2 episodes · 38 GB · backed up 1 h ago".        return standing?.name == DeckOnPhone.view ? onPhoneHead : nil    }    /// On this phone's top line, when it is the line the deck says: it    /// stands on its own row, the width of the deck, under Search and Plus    /// (the Cinemas gaps walk, 5 Nov 2026: beside them it broke mid-word at    /// the largest text size and was cut at the top at the default one).    private var onPhoneLine: String? {        guard !searching, let line = keepingLine, line == onPhoneHead else { return nil }        return line    }    private func headLine(_ said: String, on ground: FaceGround?) -> some View {        Text(said)            .scaledFace(relativeTo: .callout) { CottonFonts.type(DeckKnobs.positionSize * $0) }            .foregroundStyle(DeckGround.ink(.pencil, on: ground, theme: theme))            .lineLimit(2)            .minimumScaleFactor(0.3)            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.horizontal, DeckKnobs.lineSide)            .accessibilityIdentifier("deck-head")            .deckEditingFades()    }    @ViewBuilder private func floatingLine(at: Int, in cards: [(record: TableRecord, card: DeckCard)], on ground: FaceGround?) -> 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 = ""                    found = []                }            } else {                // While the table's rows move the counter says so, on an                // empty deck too (a fresh phone's first sync); else the                // view's head where it has one (Finished: "12 of 24 this                // year"); else the position, narrowed by letters to what                // they keep.                if let said = provenance(at: at, in: cards) ?? (onPhoneLine == nil ? keepingLine : nil) ?? moving.line(name: definition.name, plural: definition.plural) ?? head ?? position(at: at, in: cards) {                    Text(said)                        .scaledFace(relativeTo: .callout) { CottonFonts.type(DeckKnobs.positionSize * $0) }                        .foregroundStyle(DeckGround.ink(.pencil, on: ground, theme: theme))                        // 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()                // The hand before Search, where the table offers faces; on                // Listening with a song playing, the player's four.                let faces = playingSong != nil ? PlayerFace.allCases.map(\.rawValue) : model?.page?.hand ?? []                if playingSong != nil {                    PlayerFaceControl(worn: listening.face) { wear($0) }                } else if faces.count > 1, let next = model?.page?.hand_next {                    FaceChoiceControl(next: next)                }                // The search disc, holding the letters the ink has read. Its                // pill grows into the room the readout was given: beside the                // hand, that room less the hand's, so the row never overflows.                InkReadout(letters: ink, provisional: inkPending, widest: lineWidth / 2 - (faces.count > 1 ? DeckKnobs.handRoom : 0),                           search: { searching = true }, edit: { edit in Task { await editInk(edit) } })                    .accessibilityIdentifier("deck-search")                // Send, where the card in view can be sent: the core's rule                // offers it among the card's acts (`card_actions`, `send`).                if cards.indices.contains(at), model?.answered(cards[at].record.id)?.acts.contains(EditingAct.send.rawValue) == true {                    let record = cards[at].record                    NavCircle(symbol: "paperplane", label: model?.page?.acts[EditingAct.send.rawValue]?.label ?? "") { send(record) }                        .accessibilityIdentifier("deck-send")                }                if let plus = model?.page?.plus, plus.does != "none" {                    NavCircle(symbol: "plus", label: plus.label ?? "") { add(plus) }                        .accessibilityIdentifier("deck-add")                }            }        }        .padding(.horizontal, DeckKnobs.lineSide)        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { lineWidth = $0 }        .deckEditingFades()    }    /// The deck's "+", as the core says (`shell.plus`): its doors' choice    /// tier (Books' Find a book, Add a file, Bring Goodreads in); its act at    /// the object; its own route (People's contacts import) — a route that is    /// an instruction is OPENED, typing, as the list's is; else the shell's    /// short-text input for the new record's title (`compose`).    private func add(_ plus: DeckAnswer.Plus) {        switch plus.does {        case "doors": deckEditor?.offer(doors(plus), for: .emptyDeck(of: definition.id))        case "act":            guard plus.act != nil else { return }            deckEditor?.ask(table: definition.id, core: core, landed: landed)        case "route":            guard let route = plus.route.flatMap(Route.parse) else {                toasts?.show(ShellLines.line("reading", "list.this_version", ["plural": definition.plural]), tone: .error)                return            }            if route.tier == .action { navigator?.open(route, start: .typing) } else { navigator?.push(route) }        case "call":            guard let method = plus.method, let core else { return }            Task { @MainActor in                do {                    let answer = try await core.call(method, JSONValue.object([:]), as: DeckCalled.self)                    if let action = answer.action { _ = await RecordPlatformEffects.perform(action) }                } catch {                    toasts?.show(ActionRefused.words(for: error), tone: .error)                }            }        default: compose()        }    }    /// The table's doors as the fan's choice tier (`shell.plus`'s doors): Plus    /// opens it, and so does the empty deck held.    private func doors(_ plus: DeckAnswer.Plus?) -> [DeckOffer] {        plus?.offers(deckEditor, table: definition.id, core: core, toasts: toasts, landed: landed, pick: { picking = $0 }) { choosing = $0 } ?? []    }    /// The record an act at the object made or found (`CreateAct.lands`):    /// once sync brings it, it stands in front, a visitor where the view    /// does not hold it (Find a book's card on Reading).    private func landed(_ id: String) {        Task { @MainActor in            for _ in 0..<DeckKnobs.landingTries {                if let store, let record = try? await store.get(table: definition.id, id: id) {                    await bring(id, seen: record)                    return                }                try? await Task.sleep(for: .milliseconds(DeckKnobs.landingEveryMs))            }        }    }    /// A new record by its title, in the shell's input: made on commit with    /// the view's own preset, and the deck stands on it.    private func compose() {        let base = definition.createPreset().merging(blank) { _, given in given }        let preset = RecordListModel.narrowed(base, filter: narrowing, project: project, in: definition)        deckEditor?.create(definition, preset: preset, store: store, core: core) { made in            front = made.id        }    }    // MARK: The ink    /// What the ink is written on (`InkSurface`): the record pick standing    /// on the fan when there is one (the people to add to a todo), read by its    /// table's names; else this deck, read by its columns — letters on a deck    /// of names, digits on one of amounts, both where they mix — and an opened    /// card holds its letters (it narrows only a pick).    private var inkWrittenOn: InkSurface {        let editor = deckEditor ?? DeckEditor.session        let viewName = standing?.name ?? standing?.section        if editor.picksRecords, let picking = editor.picking {            return InkSurface(name: picking.inkSurface, table: picking.step?.table, pick: true, tool: definition.id, view: viewName, tier: "pick")        }        return InkSurface(name: inkSurface, table: definition.id, narrows: openedInPlace == nil, tool: definition.id, view: viewName, tier: "deck")    }    /// Whether the ink reads every stroke above the fan (`inkWriting`): the    /// card's own drags stand down for it.    private var inkOwns: Bool { InkReads.here(voiceOver: voiceOver) && !(searching && modelRead == reading) }    /// What the ink came to above the fan: each mark and page swipe acted on    /// in turn, after any answer before it, each group kept on the phone (the    /// core's line, `InkCapture`), then the letters the core holds after them    /// narrow the pick or the deck — a letter is always taken: one that leaves    /// nothing leaves the deck empty, the core saying so (`shell.deck`), never    /// dropped (owner, 4 Nov 2026) — and the letter in progress shows.    private func takeInk(_ answer: InkAnswer) {        let before = inkQueue        inkQueue = Task { @MainActor in            await before?.value            for group in answer.groups {                for stroke in group.strokes { await act(on: stroke) }                if let keep = InkKnobs.shared.values?.keepGroups { await InkCapture.shared.keep(group.line, last: keep) }            }            let editor = deckEditor ?? DeckEditor.session            if answer.surface.pick {                if editor.picksRecords, editor.picking?.inkSurface == answer.surface.name { await editor.narrowPick(to: answer.letters) }            } else if answer.surface.name == inkSurface {                ink = answer.letters                inkPending = answer.provisional            }        }    }    /// A mark or a line read above the fan, acted on; a letter's work is the    /// core's, in the letters it hands back.    private func act(on stroke: InkStroke) async {        let cards = cards        let at = index(in: cards)        guard let first = stroke.points.first, let last = stroke.points.last else { return }        switch stroke.run.read {        case "mark":            guard let name = stroke.run.mark else { return }            await act(mark: name, over: stroke.points, on: cards.indices.contains(at) ? cards[at].record : nil)        case "line" where stroke.run.edit == nil:            // A line that edited no letters is the page swipe, decided on            // lift: the innermost face's own pages turn first, then the deck.            let dx = last.x - first.x            guard abs(dx) > abs(last.y - first.y), abs(dx) > DeckKnobs.swipe, cards.indices.contains(at) else { return }            if let turner = pageTurners.last { turner.turn(dx < 0) } else { turnOrMove(dx < 0 ? 1 : -1, in: cards, from: at) }        default:            return        }    }    /// A mark drawn over the front card — the middle of its strokes within    /// its frame or on its paper — runs what the card's table binds to the mark on its record    /// (`DeckEditor.act(mark:)`), as its acts would; over a pick standing on    /// the fan, or off the card, it is nothing, and its ink fades as any.    private func act(mark name: String, over points: [CGPoint], on record: TableRecord?) async {        let editor = deckEditor ?? DeckEditor.session        guard let record, !editor.picksRecords, DeckInk.lands(points, on: [cardFrame] + inkPapers) else { return }        let place = DeckPickPlace(store: store, core: core, definitions: definitions)        if case .refused(let words) = await editor.act(mark: name, on: record, definition: own(record), place: place) {            _ = toasts?.show(words, tone: .error)        }    }    /// A stroke begun where the ink is not read: a Rolodex's knob drawn up    /// or down, its cards going by a card to the knob's gearing.    private func turnByKnob(_ points: [CGPoint]) {        let cards = cards        let at = index(in: cards)        guard let first = points.first, let last = points.last, onKnob(first), cards.indices.contains(at) else { return }        let steps = Int(((last.y - first.y) / RolodexHit.knobGearing).rounded())        let step = min(cards.count - 1 - at, max(-at, steps))        if abs(step) == 1 { turnOrMove(step, in: cards, from: at) } else if step != 0 { move(step, in: cards, from: at) }    }    /// Whether `point` (in the deck's space) is on the front Rolodex's knob.    private func onKnob(_ point: CGPoint) -> Bool {        let cards = cards        let at = index(in: cards)        guard cards.indices.contains(at), turns(cards[at].card), cardFrame.contains(point) else { return false }        return RolodexHit.knob(CGPoint(x: point.x - cardFrame.minX, y: point.y - cardFrame.minY), in: cardFrame.size)    }    /// A tap or a hold on the readout: the deck's last letter taken back, or    /// all cleared.    private func editInk(_ edit: InkEdit) async {        guard let core else { return }        let surface = inkSurface        do {            let letters = try await InkReader.edit(core, surface: surface, edit)            if surface == inkSurface { ink = letters }        } catch {            print("ink: \(error)")        }    }    // MARK: The crumb line    /// Where the fan stands inside wholes: the tool, the table, each whole    /// by its title, a chevron between; a tap on a word goes back to it.    private func crumbLine(on ground: FaceGround?) -> some View {        HStack(spacing: 6) {            ForEach(Array(crumbs.enumerated()), id: \.offset) { at, crumb in                if at > 0 {                    Image(systemName: "chevron.right")                        .scaledFace(relativeTo: .subheadline) { .system(size: DeckKnobs.crumbChevron * $0, weight: .semibold) }                        .foregroundStyle(DeckGround.ink(.pencil, on: ground, theme: theme))                        .accessibilityHidden(true)                }                Button { if let depth = crumb.depth { crumbTap?(depth) } } label: {                    Text(crumb.word)                        .scaledFace(relativeTo: .subheadline) { CottonFonts.type(DeckKnobs.crumbSize * $0) }                        .foregroundStyle(DeckGround.ink(crumb.depth == nil ? .ink : .pencil, on: ground, theme: theme))                        .lineLimit(1)                        .truncationMode(.middle)                }                .buttonStyle(.plain)                .disabled(crumb.depth == nil)                // The word where the fan stands keeps its room first.                .layoutPriority(crumb.depth == nil ? 1 : 0)                .accessibilityIdentifier("deck-crumb-\(at)")            }            Spacer(minLength: 0)        }        .padding(.horizontal, DeckKnobs.lineSide)        .deckEditingFades()        .accessibilityElement(children: .contain)        .accessibilityIdentifier("deck-crumbs")    }    // MARK: The deck    @ViewBuilder private func deck(_ cards: [(record: TableRecord, card: DeckCard)], at: Int, zones: DeckZones) -> some View {        if cards.isEmpty {            if let model, model.phase == .failed {                // A deck that could not be read says why, as the list does:                // a table mid-move in its one line (it draws itself on the                // move's done signal), any other with Try again.                let why = CouldNotRead.said(model.readStall, otherwise: model.readProblem, scene: databaseScene,                                            databases: databasesModel, definitions: definitions)                if model.readStall?.waitsForMove == true {                    DeckEmptyLine(title: why ?? "")                        .accessibilityIdentifier("deck-moving")                } else {                    DeckEmptyLine(                        title: ShellLines.line("reading", "list.could_not_read", ["plural": definition.plural]),                        message: why ?? ShellLines.line("empty", "unchanged"),                        actionLabel: CottonStrings.tryAgainAction, actionIdentifier: "deck-read-again",                        action: { Task { await model.reload() } })                }            } else if model?.phase == .loaded {                // Every empty deck the same: its line alone where the card                // would stand (`DeckEmptyLine`), in the core's words — the                // view's, the table's, or what letters that leave no card say.                let words = model?.page?.empty                let doors = doors(model?.page?.plus)                if ink.isEmpty, personal?.isLocal == true, let line = ToolServerLine.of(definition, tools: tools.all) {                    // Before backup, a tool whose rows only the server brings                    // says so in its own words, with Back up (owner, 1 Nov                    // 2026): Settings › Backup.                    DeckEmptyLine(title: words?.title ?? "", message: line,                                  actionLabel: ShellLines.line("board", "object.backup.act"), actionIdentifier: "deck-back-up",                                  action: { navigator?.push(.backup) })                        .deckEmptyActs(table: definition.id, doors: doors)                        .accessibilityIdentifier("deck-empty")                } else if !ink.isEmpty {                    // A backspace or a scratch-out brings the cards back.                    DeckEmptyLine(title: words?.title ?? "")                        .accessibilityIdentifier("deck-narrowed-nothing")                } else {                    // With no card to hold, the placeholder holds the tool's own                    // acts (the Calendar's Connect Google Calendar).                    DeckEmptyLine(title: words?.title ?? "", message: words?.message ?? "")                        .deckEmptyActs(table: definition.id, doors: doors)                        .accessibilityIdentifier("deck-empty")                }            }        } else {            let (record, card) = cards[at]            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.                frontCard(record: record, card: card, cards: cards, at: at, zones: zones)                    .frame(width: width, height: width / CardPaperKnobs.aspect)                    .id(record.id)                    .frame(width: box.size.width, height: box.size.height, alignment: .top)            }            .task(id: at) {                if cards.count - at <= DeckKnobs.readAhead { await model?.loadMore() }            }        }    }    /// The card in view sent: the fan becomes Send's people    /// (`shell.opened {step: send}`), as its held Send act opens them.    private func send(_ record: TableRecord) {        deckEditor?.open(.sends(DeckEditTarget(table: own(record).id, record: record.id, date: nil)), core: core)    }    /// Where the card opened in place came from, when a send brought it    /// ("From Asha, Thu 13 Nov", `shell.deck`'s `from`): the line says it while it stands open.    private func provenance(at: Int, in cards: [(record: TableRecord, card: DeckCard)]) -> String? {        guard cards.indices.contains(at), openedInPlace == cards[at].record.id else { return nil }        return model?.answered(cards[at].record.id)?.from    }    /// The card opened at rest, in place (`OpenedInPlace`). Keep it in    /// front even when its edit takes it out of the current view; moving on    /// drops this visitor as it does any other.    private func openAtRest(_ record: TableRecord) {        visitor = record        front = record.id        openedInPlace = record.id    }    /// The card in front: its face as it is, on the paper it lays. A photo's    /// print and a film's still open it in the one viewer over the deck    /// (`DeckOpening.viewer`). Opened in place, its check ticks.    @ViewBuilder private func frontSheet(record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)]) -> some View {        let opened = openedInPlace == record.id        if let (tool, view) = viewCard(record) {            DeckViewTile(tool: tool, view: view, tile: model?.answered(record.id)?.tile)        } else {            DeckFace.view(for: card, record: record) { if opened { toggle(record, card) } }        }    }    /// The table a card's record is of: its own where letters searched the    /// app's whole kit (a highlight among books), else the deck's.    private func own(_ record: TableRecord) -> TableDefinition {        model?.answered(record.id)?.table.flatMap { definitions[$0] } ?? definition    }    /// The fan's view a result card stands for, by its tool (`shell.deck`'s `view`).    private func viewCard(_ record: TableRecord) -> (tool: String, view: ToolView)? {        model?.answered(record.id)?.opensView    }    /// A view's tile in the results tapped: the fan stands on that view, as    /// its own tile's tap stands it, its deck with no letters — the view in    /// view's too, where choosing it moves nothing.    private func openView(_ view: ToolView, of tool: String) {        haptics.select()        if toolViews?.current(of: tool)?.id == view.id {            ink = InkLetters()            inkPending = []            inkSurface = "deck:\(UUID().uuidString)"        }        toolViews?.choose(view.id, of: tool)    }    /// What the front card's tap and its pinch out both open: the thing it    /// holds, the viewer walking the deck's records in deck order    /// (`FullScreenRoute`). A list's own card (its cassette) is no record of    /// the deck's and opens nothing: its tap plays the list.    private func opening(_ record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)]) -> DeckOpening {        guard model?.answered(record.id)?.list == nil, viewCard(record) == nil else { return .whole }        return DeckOpening.of(record, card: card, in: cards.map(\.record), definition: own(record), presenter: viewerPresenter,                              readAll: {                                  await model?.readToEnd()                                  return model?.records ?? cards.map(\.record)                              })    }    private func frontCard(record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)], at: Int,                           zones: DeckZones) -> some View {        frontSheet(record: record, card: card, cards: cards)        // Its papers say where they lie, for the ink (`InkCard`).        .environment(\.cardPaperReport, CardPaperReport { id, frame in papers[id] = frame })        // The ink reads this face's drags; its pages turn on the swipe the        // ink reads (`DeckPageTurners`). Only this face: what the card opens        // over the page reads its own.        .environment(\.deckReadsStrokes, inkOwns)        .environment(\.faceTurn, faceTurn(in: cards, at: at))        .onChange(of: turn.index, initial: true) { refillTurnWindow(in: cards, at: at) }        .onChange(of: at) { refillTurnWindow(in: cards, at: at) }        .onChange(of: turnWindowRecords(in: cards, at: at)) { refillTurnWindow(in: cards, at: at) }        .onDisappear { turn.cancel() }        // Opened, it stays where it is (`OpenedInPlace`); at rest no editing        // target rides down, so its tagged fields open the record.        .opensInPlace(openedInPlace == record.id, definition: own(record), record: record, worn: card.face) {            if openedInPlace == record.id { openedInPlace = nil }        }        .environment(\.faceChoiceTable, own(record).id)        // The zones (`DeckZones`): a side third moves the deck where no part        // stands; the middle third is the card's own tap — every part the        // shell does not route to an editor falls through to it        // (`DeckFaceParts.writes`) — and it opens what the card holds        // (`DeckCardTap`).        .deckZoned(zones, move: { turnOrMove($0, in: cards, from: at) }) {            // Opened, the card's taps are its parts' (`deckEditable`).            guard openedInPlace == nil else { return }            // A song on no album playing stands for itself: no album to open.            guard !ListeningCard.isSingle(card) else { return }            // A view's tile in the results opens its view.            if let (tool, view) = viewCard(record) { return openView(view, of: tool) }            // A list's own card (its cassette) plays the list.            if let list = model?.answered(record.id)?.list { return playList(list) }            // What the tap opens is the core's (`shell.deck`'s `tap.card`);            // the shell only draws the opening — and opens the card at rest            // where it hosts none (a whole off the fan, a deck with no viewer).            let opening = opening(record, card: card, cards: cards)            switch model?.answered(record.id)?.opens ?? .opened {            case .whole:                guard let navigator, navigator.tile != nil else { return openAtRest(record) }                haptics.select()                navigator.enter(WholeLevel(table: own(record).id, id: record.id,                                           title: WholePath.title(of: record, in: own(record))))            case .group:                guard let navigator, let group = model?.answered(record.id)?.group else { return openAtRest(record) }                haptics.select()                navigator.push(.tableList(table: group.table, filter: FilteredListOpening.encoded([group.column: .text(group.value)]),                                          title: group.title, query: nil, view: group.view))            case .conversation:                navigator?.push(BoardRecord.route(table: own(record).id, id: record.id, definition: own(record)))            case .writer:                openAtRest(record)            case .reader:                haptics.select()                readerPresenter?.open(ReaderOpening(id: record.id, table: own(record).id))            case .viewer:                guard let viewer = opening.viewer else { return openAtRest(record) }                haptics.select()                viewer()            case .reading:                guard opening.reads else { return openAtRest(record) }                haptics.select()                opening.open($opened)            case .opened:                openAtRest(record)            case .play:                break            }        }        .onLongPressGesture(minimumDuration: DeckEditableKnobs.hold) {            // A list's own card is no record of the deck's: nothing to open at rest.            guard openedInPlace != record.id, model?.answered(record.id)?.list == nil, viewCard(record) == nil else { return }            haptics.press()            openAtRest(record)        }        // A pinch out opens what the card holds (row 12, `DeckOpening`), as        // a reading card's own tap does.        .pinchOpens(opening(record, card: card, cards: cards), opened: $opened)        .contentShape(Rectangle())        // The viewer grows out of the card and goes back into it.        .viewerSource(DeckViewer.itemID(own(record), record.id))        .offset(x: drag)        .rotationEffect(.degrees(Double(drag) / 40))        .gesture(            DragGesture(minimumDistance: 14)                .onChanged { value in                    guard !inkOwns, !turns(card), openedInPlace == nil,                          abs(value.translation.width) > abs(value.translation.height) else { return }                    drag = value.translation.width                }                .onEnded { value in                    guard !inkOwns, !turns(card), openedInPlace == nil else { return }                    let width = value.translation.width                    if width < -DeckKnobs.swipe { move(1, in: cards, from: at) }                    else if width > DeckKnobs.swipe { move(-1, in: cards, from: at) }                    withAnimation(.snappy) { drag = 0 }                })        .modifier(RolodexSpinGesture(enabled: turns(card) && !inkOwns && openedInPlace == nil, motion: turn, bounds: (-at)...(cards.count - 1 - at)) { step in            move(min(cards.count - 1 - at, max(-at, step)), in: cards, from: at)        })        .onPreferenceChange(DeckPageTurners.self) { pageTurners = $0 }        .onGeometryChange(for: CGRect.self) { $0.frame(in: .named(DeckInk.space)) } action: { cardFrame = $0 }        .accessibilityElement(children: .contain)        .accessibilityIdentifier(openedInPlace == record.id ? "opened-card" : "deck-card")        .accessibilityAdjustableAction { direction in            move(direction == .increment ? 1 : -1, in: cards, from: at)        }        .deckMoveActions { move($0, in: cards, from: at) }    }    /// The list `id` played from its first song, as its cassette's tap plays it.    private func playList(_ id: String) {        #if os(iOS)        guard let core else { return }        haptics.select()        let toasts = toasts        MusicPlayback.play(list: id, core: core) { toasts?.show($0, tone: .error) }        #endif    }    private func turns(_ card: DeckCard) -> Bool { DeckFace.registered(card)?.steps == .turns }    private func turnAvailable(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], at: Int) -> Bool {        guard cards.indices.contains(at + step) else { return false }        return DeckFace.faceID(cards[at].card) == DeckFace.faceID(cards[at + step].card)    }    /// The records the turn's window is filled from: what a refill reads, so    /// a neighbour a sync changed is filled again before the wheel shows it.    private func turnWindowRecords(in cards: [(record: TableRecord, card: DeckCard)], at: Int) -> [TableRecord] {        guard cards.indices.contains(at), turns(cards[at].card),              let span = DeckTurnWindow.span(count: cards.count, at: at, travel: turn.index) else { return [] }        return cards[span].map(\.record)    }    private func refillTurnWindow(in cards: [(record: TableRecord, card: DeckCard)], at: Int) {        guard cards.indices.contains(at), turns(cards[at].card),              let span = DeckTurnWindow.span(count: cards.count, at: at, travel: turn.index) else { turnWindow = [:]; return }        var window: [Int: DeckCard] = [:]        for index in span {            let row = cards[index]            window[index - at] = row.card        }        turnWindow = window    }    private func faceTurn(in cards: [(record: TableRecord, card: DeckCard)], at: Int) -> FaceTurn {        guard turns(cards[at].card) else { return FaceTurn() }        return FaceTurn(progress: turn.progress, window: turnWindow, band: turn.band)    }    private func turnOrMove(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], from at: Int) {        guard openedInPlace == nil else { return }        guard cards.indices.contains(at), turns(cards[at].card) else { move(step, in: cards, from: at); return }        turn.tap(step, available: turnAvailable(step, in: cards, at: at), bounds: (-at)...(cards.count - 1 - at)) {            move($0, in: cards, from: at)        }    }    /// One card on, or back: a plain cut, no slide (owner, 29 Oct 2026:    /// keep tapping and the records fly by); past an end, the roll.    private func move(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], from at: Int) {        // An opened card holds its deck: nothing moves it.        guard openedInPlace == nil else { return }        switch DeckStep.of(step, from: at, count: cards.count) {        case .past(let forward):            withAnimation(.snappy) { drag = 0 }            roll(forward: forward, held: cards.count)            return        case .card(let next):            front = cards[next].record.id            drag = 0        }        // A visitor stands only while it is in front.        if let visitor, visitor.id != front, !(model?.records.contains { $0.id == visitor.id } ?? false) {            self.visitor = nil            model?.dropVisitor()        }    }    /// Past the deck's end: on to the neighbouring view, unless rows of this    /// one are still unread (they are read first).    private func roll(forward: Bool, held: Int) {        if forward, model?.hasMore == true {            Task { await model?.loadMore() }            return        }        guard let rollover else { return }        let back = !forward        guard let label = rollover(forward) else { return }        haptics.select()        entersAtEnd = back        front = nil        visitor = nil        withAnimation(.easeOut(duration: 0.2)) { crossing = label }    }    /// The viewer stands on `showing`: when it is one of this deck's cards,    /// that card comes to the front.    private func follow(_ showing: String?) {        guard let showing, DeckViewer.shows(definition),              let card = cards.first(where: { DeckViewer.itemID(definition, $0.record.id) == showing }),              card.record.id != front        else { return }        front = card.record.id    }    private func toggle(_ record: TableRecord, _ card: DeckCard) {        guard let model, let checked = card.checked else { return }        ticked[record.id] = !checked        let toasts = toasts        Task {            do { try await model.toggle(record) } catch { toasts?.show(error.localizedDescription, tone: .error) }        }    }    // MARK: Search    private var results: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                ForEach(found, id: \.id) { record in                    Button { open(found: record) } label: {                        Text(DeckCard(record)?.text("title") ?? record[definition.title].text ?? "")                            .scaledFace(relativeTo: .body) { CottonFonts.type(17 * $0) }                            .foregroundStyle(theme.print(.ink))                            .frame(maxWidth: .infinity, alignment: .leading)                            .padding(.vertical, 12)                    }                    .buttonStyle(.plain)                    Rectangle().fill(theme.print(.pencil).opacity(0.25)).frame(height: 1)                }                if found.isEmpty, !query.trimmingCharacters(in: .whitespaces).isEmpty {                    Text(ShellLines.line("cards", "deck.nothing_found"))                        .scaledFace(relativeTo: .subheadline) { CottonFonts.type(15 * $0) }                        .foregroundStyle(theme.print(.pencil))                        .padding(.vertical, 12)                }            }            .padding(.horizontal, DeckKnobs.lineSide)        }        .accessibilityIdentifier("deck-search-results")    }    /// The deck opened at a record search found.    private func open(found record: TableRecord) {        Task {            await bring(record.id, seen: record)            searching = false            query = ""            found = []        }    }    /// Puts `id` in front: read on until it is among the deck's rows, and one    /// the view does not hold stands in front as a visitor on its own card —    /// never a page.    /// The card `Navigator.bringing` asks of this deck's table, taken once    /// the deck has read: the fan turned here from Home to show it.    /// The first of many brought at once stands on the tool's whole view    /// (Books' All, where every one of them is): a deck of another view turns    /// the ring there and leaves the card to that view's deck.    private func takeBrought() async {        guard model?.phase == .loaded, let asked = navigator?.bringing else { return }        let tool = standing?.name?.split(separator: "/").first.map(String.init)        switch DeckBrought.step(asked, deckTable: definition.id, deckView: standing?.name, tool: tool,                                views: tool.flatMap { toolViews?.views(of: $0) } ?? []) {        case .leave: return        case .turn(let whole):            if let tool { toolViews?.choose(whole, of: tool) }        case .take:            navigator?.bringing = nil            await bring(asked.id)        }    }    private func bring(_ id: String, seen: TableRecord? = nil) async {        let model = DeckLanding.reading(heldModel, table: definition.id)        await model?.bring(id)        if model?.records.contains(where: { $0.id == id }) != true {            // Only the record brought: a read that raced the bring's own may            // still answer the visitor before it.            visitor = model?.visitor.flatMap { $0.id == id ? $0.record.record : nil } ?? seen        }        front = id    }}/// The deck's reading a record is brought into: the one held now, whenever/// it reads this table. A landing runs from the surface as it stood when Plus/// was tapped, and the record's own arrival changes the view it read (an/// empty Reading's whole-table count), so that copy's `model` answers nil/// and the core is never asked for the visitor (books-4-walk, 6 Nov 2026:/// Find a book's card never stood on an empty Reading).enum DeckLanding {    @MainActor    static func reading(_ held: DeckReading?, table: String) -> DeckReading? {        held?.asked.table == table ? held : nil    }    /// The visitor the deck draws once a read lands: the record it stands    /// on (`front`) as the read answers it, else the one it holds as answered    /// anew, else the one it holds. A read the bring raced can leave the    /// deck holding the visitor it stood on before — Find a book's card,    /// then a file added — and a card the reading no longer answers is never    /// drawn, so the deck stood blank (books-4-walk, 6 Nov 2026).    static func visitor(holding held: TableRecord?, front: String?, answered: (String) -> TableRecord?, brought: TableRecord?) -> TableRecord? {        if let brought, brought.id == front { return brought }        if let held, let fresh = answered(held.id) { return fresh }        return held    }}/// The cards a face that turns (the Rolodex) has filled around it: four/// either side of the card the wheel stands on, `travel` cards from the/// shown one at `at`.enum DeckTurnWindow {    static let reach = 4    static func span(count: Int, at: Int, travel: Int) -> ClosedRange<Int>? {        guard (0..<count).contains(at) else { return nil }        let centre = min(count - 1, max(0, at + travel))        return max(0, centre - reach)...min(count - 1, centre + reach)    }}/// What a deck does with the card `Navigator.bringing` asks for — pure, so it/// is tested without a deck (`NavigatorBringsTests`).enum DeckBrought: Equatable {    /// Not this deck's: another tool's deck, or a tool with no view of it.    case leave    /// This tool's, on a view that is not where it stands: the ring turns to    /// the view of that id, whose deck takes it.    case turn(String)    /// Put it in front here.    case take    /// A card of this deck's table is taken here, but the first of many    /// stands on the view that reads the table whole (Books' All). A card of    /// another table on this deck's tool turns the ring to the tool's view    /// that reads that table whole: a link shared into Web pages while it    /// stood on Made for you (which reads documents) opens on All at the    /// link's card, never on "No pages made for you yet" (Rigby 11 walk,    /// 8 Nov 2026).    static func step(_ asked: Navigator.Bringing, deckTable: String, deckView: String?, tool: String?, views: [ToolView]) -> DeckBrought {        let whole = tool.flatMap { tool in ToolView.whole(of: asked.table, in: views).map { (tool, $0.id) } }        guard asked.table == deckTable else {            guard let (_, id) = whole else { return .leave }            return .turn(id)        }        if asked.many, let (tool, id) = whole, deckView != "\(tool)/\(id)" { return .turn(id) }        return .take    }}/// What a "+" that calls a phone method answered: the platform action in it,/// if any (`DeckAnswer.Plus.method`).private struct DeckCalled: Decodable {    let action: RecordPlatformAction?    init(from decoder: Decoder) throws {        action = try RecordPlatformAction.fromAnswer(decoder)    }}