// 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.importCottonFacesimportCottonKitimportCottonPaperimportCottonValuesimportSwiftUI/// The deck's own space, the ink's strokes and the front card's frame/// measured in it.enumDeckInk {staticlet 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).staticfunc lands(_ points: [CGPoint], on papers: [CGRect]) -> Bool {let xs = points.map(\.x), ys = points.map(\.y)guardlet minX = xs.min(), let maxX = xs.max(), let minY = ys.min(), let maxY = ys.max() else { returnfalse }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.enumRecordLanding { @MainActorstaticfunc arrived(_ link: RecordLink, in store: (any Records)?) async -> Bool {for _ in0..<DeckKnobs.landingTries {iflet store, (try? await store.get(table: link.table, id: link.id)) != nil { returntrue }try? awaitTask.sleep(for: .milliseconds(DeckKnobs.landingEveryMs)) }returnfalse }}enumDeckKnobs {staticlet 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.staticlet landingTries = 120staticlet landingEveryMs = 500staticlet lineHeight: CGFloat = 60staticlet lineSide: CGFloat = 28/// The hand's place on the top row: its target and the row's spacing.staticlet handRoom: CGFloat = ScreenBarKnobs.chromeNavCircleTarget + 12/// The crumb line under the top line, while a whole's parts are dealt.staticlet 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.staticlet headHeight: CGFloat = 44staticlet crumbSize: CGFloat = 14staticlet crumbChevron: CGFloat = 9staticlet positionSize: CGFloat = 16/// How far the card stands above the fan's cover.staticlet footRoom: CGFloat = 18/// How far a swipe travels before it moves a card.staticlet swipe: CGFloat = 70/// How near the end of the rows read the next page is asked for.staticlet readAhead = 4staticlet foundMost = 8/// How long the crossing into another view is said.staticlet crossingMs = 900}/// The beat a rollover shows: the view crossed into, stamped on a slip of the/// deck's paper for a moment.structDeckCrossing: View {let label: String @Environment(\.theme) privatevar themevar body: someView {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") }}structDeckSurface: View {let definition: TableDefinitionlet 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) privatevar store @Environment(\.deckEditor) privatevar deckEditor @Environment(\.currentProject) privatevar currentProject @Environment(\.recordsRevision) privatevar revision @Environment(DatabaseScene.self) privatevar databaseScene: DatabaseScene? @Environment(\.fanCover) privatevar cover @Environment(DatabasesModel.self) privatevar databasesModel: DatabasesModel? @Environment(\.tableDefinitions) privatevar definitions @Environment(ToastCenter.self) privatevar toasts: ToastCenter? @Environment(\.toolDefinitions) privatevar tools @Environment(ToolViews.self) privatevar toolViews: ToolViews? @Environment(\.theme) privatevar theme/// The personal object's session: before backup, a tool only the server/// fills says so on its empty deck (`ToolServerLine`). @Environment(PersonalObject.self) privatevar personal: PersonalObject? @State privatevar heldModel: DeckReading? @State privatevar composedOnLanding = false @State privatevar 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.privatevar model: DeckReading? { modelRead == reading ? heldModel : nil }/// The view the deck stands on: its own, else the one the core landed it on.privatevar standing: ToolView.Read? { view ?? model?.landedView }/// What the deck holds to: its own values, then its landed view's.privatevar narrowing: [String: RecordValue] { filter.merging(model?.landedView?.filter ?? [:]) { own, _ in own } }privatevar 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 privatevar front: String? @State privatevar turn = FaceTurnMotion() @State privatevar turnWindow: [Int: DeckCard] = [:] @State privatevar 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 privatevar 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 privatevar openedInPlace: String?/// A check ticked here, drawn at once until the re-read says it. @State privatevar ticked: [String: Bool] = [:] @State privatevar searching = false @State privatevar query = "" @State privatevar found: [TableRecord] = []/// A record in front that the view's rows do not hold (`bring`). @State privatevar visitor: TableRecord?/// Rolled back into the previous view: it opens on its last card. @State privatevar entersAtEnd = false/// The view just rolled into, said for a beat over the deck. @State privatevar crossing: String?/// What the showing table's rows are doing (`DeckMoving`): the counter/// says it while they move. @State privatevar 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 privatevar onPhoneHead: String? @Environment(\.cottonCore) privatevar core @Environment(\.cottonSync) privatevar 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 privatevar 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 privatevar 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 privatevar inkSurface = "deck:\(UUID().uuidString)"/// The card in front when the first letter was written: clearing the/// letters stands the deck there again. @State privatevar frontBeforeInk: String?/// The groups the ink read, acted on one after another. @State privatevar inkQueue: Task<Void, Never>?/// The top row's width: the ink's readout grows to half of it. @State privatevar lineWidth: CGFloat = 0/// The front card's faces' page turns, innermost last: the swipe the/// ink reads turns them (`DeckPageTurners`). @State privatevar pageTurners: [DeckPageTurner] = []/// The front card's frame in the deck's space (`DeckInk.space`). @State privatevar 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 privatevar papers: [UUID: CGRect] = [:]/// Where the ink's space lies on the screen, to place the papers in it. @State privatevar inkOrigin: CGPoint = .zero @Environment(\.accessibilityVoiceOverEnabled) privatevar voiceOver @Environment(\.cottonHaptics) privatevar haptics @Environment(Navigator.self) privatevar navigator: Navigator? @Environment(\.viewerPresenter) privatevar viewerPresenter @Environment(\.readerPresenter) privatevar readerPresenter/// A door's files being chosen in the system's picker (`DeckDoors`). @State privatevar choosing: DefinitionCreateFiles?/// A door's pictures being chosen in the photo picker or taken with the camera (`DoorPictures`). @State privatevar 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 privatevar 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 privatevar listening = ListeningState()structListeningState {var face: PlayerFace = .hifivar visiting: TableRecord? }/// The song the one music player holds, on Listening alone.privatevar playingSong: QueuedSong? { standing?.name == ListeningCard.view ? MusicNowPlaying.shared.song : nil }privatevar 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.privatevar cards: [(record: TableRecord, card: DeckCard)] {guardlet model else { return [] }var rows = model.recordsiflet visitor, !rows.contains(where: { $0.id == visitor.id }) { rows.insert(visitor, at: 0) }let made: [(record: TableRecord, card: DeckCard)] = rows.compactMap { record inguardvar card = model.card(record.id) else { returnnil }iflet ticked = ticked[record.id], card.checked != nil { card.fields["check"] = .bool(ticked) }return (record, card) }guardlet song = playingSong else { return made }returnListeningCard.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.privatevar playerVolume: Double? { #if os(iOS) listening.face == .amp ? SystemVolume.shared.level : nil #elsenil #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.privatefunc listen(to song: QueuedSong?) async {guardlet song, let core else { return }let face = awaitPlayerSettings.read(core).facevar visiting: TableRecord?iflet album = song.album, !(model?.records.contains { $0.id == album } ?? false) { visiting = try? awaitCoreRecords(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.privatefunc wear(_ face: PlayerFace) { listening.face = faceguardlet core else { return }let toasts = toastsTask {do { tryawaitPlayerSettings.wear(face, core: core) } catch { toasts?.show(error.localizedDescription, tone: .error) } } }privatefunc index(in cards: [(record: TableRecord, card: DeckCard)]) -> Int {guard !cards.isEmpty else { return0 }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.privatevar drawn: someView {let cards = cardslet 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)))returnGeometryReader { geo inlet 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.heightlet 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)iflet 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 { awaitInkKnobs.shared.load(core) }// The ground beside and above the card moves by the zones too. .deckZonedGround(searching || cards.isEmpty ? nil : zones) { step inlet 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) {iflet 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: awaitDeckMovingRead.read(core))guard !Task.isCancelled else { return }if now != moving { moving = now }guardDeckMoving.readsAgain(now, passing: sync?.passing == true) else { return }try? awaitTask.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 = awaitFilmKeeper.shared.head() #endif } .task(id: crossing) {guard crossing != nilelse { return }try? awaitTask.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 inlet 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 { awaitMusicPlayback.shared.restore() } #endif } }var body: someView {// 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.privatevar watched: someView {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 inguardlet landed, landed.table == definition.id || model?.cards.contains(where: { $0.table == landed.table }) == trueelse { return }iflet 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 iniflet 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 = readinglet words = query.trimmingCharacters(in: .whitespaces)guard !words.isEmpty else { found = []; return }try? awaitTask.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.privatevar read: someView {AnyView(drawn) .task(id: reading) {let reading = readingguardlet 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 = readingawait 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() }iflet opensAt, openedAtOn == nil { openedAtOn = readingawait bring(opensAt) }await takeBrought()if entersAtEnd { entersAtEnd = falseawait 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 inguardlet words = note.userInfo?["query"] as? String, !words.isEmpty else { return } query = words searching = true } .onChange(of: ink.letters) { before, letters inif 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) { _, _ inTask { 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) } }privatestructRead: Equatable {let definition: TableDefinitionlet 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).privatestructListeningRestore: Equatable {let view: String?let revision: Intlet pulled: String? }/// What reads the showing table's movement again.privatestructMovingReads: Equatable {let table: Stringlet revision: Intlet pulled: String?let pending: Intlet 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.privatestructDeckOnPhone: Equatable {/// The view whose top line it is (`cinemas`' `on_phone`).staticlet view = "cinemas/on_phone"let view: String?let pulled: String?let keeping: [String]/// The films coming down now, by key. @MainActor staticvar keeping: [String] { #if os(iOS)return (Array(FilmKeeper.shared.keeping.keys) + Array(FilmKeeper.shared.fetching)).sorted() #elsereturn [] #endif } }/// The front card's papers in the ink's space.privatevar 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.privatefunc 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 { returnnil }// Listening deals the player in front of the core's order: counted as dealt.if playingSong != nil, query.isEmpty {returnShellLines.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.privatevar 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.privatevar keepingLine: String? {// Songs and films coming in say how far, "41 of 212", before// anything else.iflet coming = MusicIntakeProgress.shared.line(table: definition.id) { return coming }iflet coming = FilmIntakeProgress.shared.line(table: definition.id) { return coming } #if os(iOS)iflet 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).privatevar onPhoneLine: String? {guard !searching, let line = keepingLine, line == onPhoneHead else { returnnil }return line }privatefunc headLine(_ said: String, on ground: FaceGround?) -> someView {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 privatefunc floatingLine(at: Int, in cards: [(record: TableRecord, card: DeckCard)], on ground: FaceGround?) -> someView { 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.iflet 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) } } elseif 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 inTask { 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].recordNavCircle(symbol: "paperplane", label: model?.page?.acts[EditingAct.send.rawValue]?.label ?? "") { send(record) } .accessibilityIdentifier("deck-send") }iflet 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`).privatefunc add(_ plus: DeckAnswer.Plus) {switch plus.does {case"doors": deckEditor?.offer(doors(plus), for: .emptyDeck(of: definition.id))case"act":guard plus.act != nilelse { return } deckEditor?.ask(table: definition.id, core: core, landed: landed)case"route":guardlet 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":guardlet method = plus.method, let core else { return }Task { @MainActor indo {let answer = tryawait core.call(method, JSONValue.object([:]), as: DeckCalled.self)iflet action = answer.action { _ = awaitRecordPlatformEffects.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.privatefunc 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).privatefunc landed(_ id: String) {Task { @MainActor infor _ in0..<DeckKnobs.landingTries {iflet store, let record = try? await store.get(table: definition.id, id: id) {await bring(id, seen: record)return }try? awaitTask.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.privatefunc 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).privatevar inkWrittenOn: InkSurface {let editor = deckEditor ?? DeckEditor.sessionlet viewName = standing?.name ?? standing?.sectionif editor.picksRecords, let picking = editor.picking {returnInkSurface(name: picking.inkSurface, table: picking.step?.table, pick: true, tool: definition.id, view: viewName, tier: "pick") }returnInkSurface(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.privatevar 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.privatefunc takeInk(_ answer: InkAnswer) {let before = inkQueue inkQueue = Task { @MainActor inawait before?.valuefor group in answer.groups {for stroke in group.strokes { await act(on: stroke) }iflet keep = InkKnobs.shared.values?.keepGroups { awaitInkCapture.shared.keep(group.line, last: keep) } }let editor = deckEditor ?? DeckEditor.sessionif answer.surface.pick {if editor.picksRecords, editor.picking?.inkSurface == answer.surface.name { await editor.narrowPick(to: answer.letters) } } elseif 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.privatefunc act(on stroke: InkStroke) async {let cards = cardslet at = index(in: cards)guardlet first = stroke.points.first, let last = stroke.points.last else { return }switch stroke.run.read {case"mark":guardlet 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.xguard abs(dx) > abs(last.y - first.y), abs(dx) > DeckKnobs.swipe, cards.indices.contains(at) else { return }iflet 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.privatefunc act(mark name: String, over points: [CGPoint], on record: TableRecord?) async {let editor = deckEditor ?? DeckEditor.sessionguardlet record, !editor.picksRecords, DeckInk.lands(points, on: [cardFrame] + inkPapers) else { return }let place = DeckPickPlace(store: store, core: core, definitions: definitions)ifcase .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.privatefunc turnByKnob(_ points: [CGPoint]) {let cards = cardslet at = index(in: cards)guardlet 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) } elseif step != 0 { move(step, in: cards, from: at) } }/// Whether `point` (in the deck's space) is on the front Rolodex's knob.privatefunc onKnob(_ point: CGPoint) -> Bool {let cards = cardslet at = index(in: cards)guard cards.indices.contains(at), turns(cards[at].card), cardFrame.contains(point) else { returnfalse }returnRolodexHit.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.privatefunc editInk(_ edit: InkEdit) async {guardlet core else { return }let surface = inkSurfacedo {let letters = tryawaitInkReader.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.privatefunc crumbLine(on ground: FaceGround?) -> someView { HStack(spacing: 6) {ForEach(Array(crumbs.enumerated()), id: \.offset) { at, crumb inif 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 { iflet 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 privatefunc deck(_ cards: [(record: TableRecord, card: DeckCard)], at: Int, zones: DeckZones) -> someView {if cards.isEmpty {iflet 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() } }) } } elseif 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?.emptylet 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") } elseif !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.privatefunc 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.privatefunc provenance(at: Int, in cards: [(record: TableRecord, card: DeckCard)]) -> String? {guard cards.indices.contains(at), openedInPlace == cards[at].record.id else { returnnil }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.privatefunc 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 privatefunc frontSheet(record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)]) -> someView {let opened = openedInPlace == record.idiflet (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.privatefunc 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`).privatefunc 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.privatefunc 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.privatefunc opening(_ record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)]) -> DeckOpening {guard model?.answered(record.id)?.list == nil, viewCard(record) == nilelse { return .whole }returnDeckOpening.of(record, card: card, in: cards.map(\.record), definition: own(record), presenter: viewerPresenter, readAll: {await model?.readToEnd()return model?.records ?? cards.map(\.record) }) }privatefunc frontCard(record: TableRecord, card: DeckCard, cards: [(record: TableRecord, card: DeckCard)], at: Int, zones: DeckZones) -> someView { 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 == nilelse { 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.iflet (tool, view) = viewCard(record) { return openView(view, of: tool) }// A list's own card (its cassette) plays the list.iflet 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:guardlet navigator, navigator.tile != nilelse { 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:guardlet 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:guardlet 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) == nilelse { 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 inguard !inkOwns, !turns(card), openedInPlace == nil, abs(value.translation.width) > abs(value.translation.height) else { return } drag = value.translation.width } .onEnded { value inguard !inkOwns, !turns(card), openedInPlace == nilelse { return }let width = value.translation.widthif width < -DeckKnobs.swipe { move(1, in: cards, from: at) }elseif 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.privatefunc playList(_ id: String) { #if os(iOS)guardlet core else { return } haptics.select()let toasts = toastsMusicPlayback.play(list: id, core: core) { toasts?.show($0, tone: .error) } #endif }privatefunc turns(_ card: DeckCard) -> Bool { DeckFace.registered(card)?.steps == .turns }privatefunc turnAvailable(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], at: Int) -> Bool {guard cards.indices.contains(at + step) else { returnfalse }returnDeckFace.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.privatefunc 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) }privatefunc 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 }privatefunc faceTurn(in cards: [(record: TableRecord, card: DeckCard)], at: Int) -> FaceTurn {guard turns(cards[at].card) else { returnFaceTurn() }returnFaceTurn(progress: turn.progress, window: turnWindow, band: turn.band) }privatefunc turnOrMove(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], from at: Int) {guard openedInPlace == nilelse { 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.privatefunc move(_ step: Int, in cards: [(record: TableRecord, card: DeckCard)], from at: Int) {// An opened card holds its deck: nothing moves it.guard openedInPlace == nilelse { return }switchDeckStep.of(step, from: at, count: cards.count) {case .past(let forward): withAnimation(.snappy) { drag = 0 } roll(forward: forward, held: cards.count)returncase .card(let next): front = cards[next].record.id drag = 0 }// A visitor stands only while it is in front.iflet 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).privatefunc roll(forward: Bool, held: Int) {if forward, model?.hasMore == true {Task { await model?.loadMore() }return }guardlet rollover else { return }let back = !forwardguardlet 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.privatefunc follow(_ showing: String?) {guardlet showing, DeckViewer.shows(definition),let card = cards.first(where: { DeckViewer.itemID(definition, $0.record.id) == showing }), card.record.id != frontelse { return } front = card.record.id }privatefunc toggle(_ record: TableRecord, _ card: DeckCard) {guardlet model, let checked = card.checked else { return } ticked[record.id] = !checkedlet toasts = toastsTask {do { tryawait model.toggle(record) } catch { toasts?.show(error.localizedDescription, tone: .error) } } }// MARK: Searchprivatevar results: someView {ScrollView { VStack(alignment: .leading, spacing: 0) {ForEach(found, id: \.id) { record inButton { 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.privatefuncopen(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.privatefunc takeBrought() async {guard model?.phase == .loaded, let asked = navigator?.bringing else { return }let tool = standing?.name?.split(separator: "/").first.map(String.init)switchDeckBrought.step(asked, deckTable: definition.id, deckView: standing?.name, tool: tool, views: tool.flatMap { toolViews?.views(of: $0) } ?? []) {case .leave: returncase .turn(let whole):iflet tool { toolViews?.choose(whole, of: tool) }case .take: navigator?.bringing = nilawait bring(asked.id) } }privatefunc 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).enumDeckLanding { @MainActorstaticfunc 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).staticfunc visitor(holding held: TableRecord?, front: String?, answered: (String) -> TableRecord?, brought: TableRecord?) -> TableRecord? {iflet brought, brought.id == front { return brought }iflet 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`.enumDeckTurnWindow {staticlet reach = 4staticfunc span(count: Int, at: Int, travel: Int) -> ClosedRange<Int>? {guard (0..<count).contains(at) else { returnnil }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`).enumDeckBrought: 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).staticfunc step(_ asked: Navigator.Bringing, deckTable: String, deckView: String?, tool: String?, views: [ToolView]) -> DeckBrought {let whole = tool.flatMap { tool inToolView.whole(of: asked.table, in: views).map { (tool, $0.id) } }guard asked.table == deckTable else {guardlet (_, 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`).privatestructDeckCalled: Decodable {let action: RecordPlatformAction?init(from decoder: Decoder) throws { action = tryRecordPlatformAction.fromAnswer(decoder) }}