---
title: "deck.ts | Luis Krötz Docs"
type: docs-file
route: "/docs/website/components/home/cardstack/deck.ts"
locale: en
language: "en"
canonical: "https://luiskr.com/docs/website/components/home/cardstack/deck.ts"
markdown: "https://luiskr.com/llm/en/docs/website/components/home/cardstack/deck.ts.md"
json: "https://luiskr.com/llm/en/docs/website/components/home/cardstack/deck.ts.json"
generated: 2026-11-19T15:46:51.755Z
policy: "ai-train=yes, search=yes, ai-input=yes"
---

# deck.ts | Luis Krötz Docs

```ts
/**
 * @file cardstack/deck.ts — the coverflow geometry for <card-stack>:
 * responsive tier pick, signed ring offsets → per-card 3D poses, deck
 * measurement, and the imperative style writes that drive both the drag
 * tracking frames and the CSS-transition settle.
 */

import { CARD_STACK_CLASSES } from '@core/tokens/classes/card-stack.js'
import { CARD_STACK_SELECTORS } from '@core/tokens/selectors/card-stack.js'
import { CARD_STACK_LAYOUT, CARD_STACK_TIERS } from '@core/tokens/motion/card-stack.js'
import type {
  CardStackFanTier,
  CardStackStackTier,
  CardStackTier,
} from '@core/tokens/motion/card-stack.js'
import { ATTR_VALUES } from '@core/tokens/attrs/values.js'
import { COMMON_ATTRS } from '@core/tokens/attrs/common.js'
import { CHAR_STRINGS } from '@core/tokens/strings/chars.js'
import { TYPE_STRINGS } from '@core/tokens/strings/types.js'
import { ARIA_ATTRS } from '@core/tokens/attrs/aria.js'
import { HTML_TAGS } from '@core/tokens/elements/html.js'
import { flushLayout, viewportHeight, viewportWidth } from '@core/utils/dom.js'
import { writeInfo } from './info.js'
import { stopAutoplay } from './autoplay.js'
import type { CardStackItem, CardPose } from './types.js'
import type { CardStack } from '../CardStack.js'

/** Degrees → radians for the projected-edge trigonometry. */
const DEG = Math.PI / 180

/**
 * Last pose-pass visibility per card element — a card that was hidden on
 * the previous pass and is visible now seeds its rise-and-fade entrance.
 * Keyed by element so a re-rendered card starts a fresh baseline (no
 * entrance on first paint).
 */
const _wasVisible = new WeakMap<Element, boolean>()

/**
 * Last pose signature (transform|opacity|z|visibility|active) applied
 * to each card element. applyPoses runs per gesture frame and once per
 * observer re-delivery; a pass whose pose values match the last write
 * skips every DOM write so the converged deck costs compares only —
 * the write→notify churn browsers report as ResizeObserver loops.
 */
const _poseSig = new WeakMap<Element, string>()

/**
 * Last measure signature per host — a ResizeObserver hop whose inputs
 * (tier, card box, stage budget, deck rect) are unchanged skips the
 * field publishes entirely, so an unchanged delivery is a compare and
 * a return instead of a host write burst downstream code can observe.
 */
const _measureSig = new WeakMap<CardStack, string>()

/**
 * Every pushed item fans in the deck — the full portfolio list in order
 * (the featured flag is decorative only; no filtering applies).
 * @param host The CardStack element.
 * @returns The deck's ordered item list.
 */
export function deckItems(host: CardStack): CardStackItem[] {
  return host.processedItems
}

/**
 * Signed ring distance of `d` modulo `len`, normalized into (-len/2, len/2]
 * so the shortest fan direction wins — fractional `d` (mid-drag) passes
 * through unchanged in magnitude.
 * @param d Raw index difference (may be fractional, any sign).
 * @param len Deck length.
 * @returns Signed ring offset.
 */
export function ringSigned(d: number, len: number): number {
  if (len <= 0) return 0

  const n = ((d % len) + len) % len

  return n > len / 2 ? n - len : n
}

/**
 * The coverflow tier for a viewport — the first (widest) tier whose
 * MIN_VW the width meets; the portrait tablet tier also requires a
 * taller-than-wide viewport, mirroring the SCSS `orientation` split.
 * The final (phone) tier has MIN_VW 0 and is the unconditional floor.
 * @param vw Viewport width px.
 * @param vh Viewport height px.
 * @returns The matching tier.
 */
export function pickTier(vw: number, vh: number): CardStackTier {
  const last = CARD_STACK_TIERS.length - 1

  for (let i = 0; i < last; i++) {
    const tier = CARD_STACK_TIERS[i]

    if (vw >= tier.MIN_VW && (!tier.PORTRAIT || vh > vw)) return tier
  }

  return CARD_STACK_TIERS[last]
}

/**
 * The coverflow pose for signed offset `s` (see CardStackTier for the
 * full model). With a = |s|, the near term min(a,1) carries the big
 * front→neighbour jump (FIRST_STEP / DEPTH / the full ROT_Y turn) and
 * the far term max(a−1,0) the tight per-card stacking (STEP /
 * DEPTH_STEP, plus ROT_STEP of extra turn per level so the fan wraps
 * like a carousel wall instead of parallel planes, capped at ROT_MAX)
 * — all linear in `a`, so a fractional drag offset slides every card
 * continuously along the curve. Right-hand
 * cards (s > 0) turn by +ROT_Y, which in CSS's rotateY convention sends
 * their outer edge away from the viewer; the left side mirrors it.
 * `0 - …` keeps the front depth at +0 (never −0). Opacity steps down
 * per level (FAN_DIM_STEP, floored at FAN_DIM_FLOOR) so the outer cards
 * darken into the deck edges exactly like the reference coverflow.
 * @param s Signed ring offset (0 = front).
 * @param len Deck length — drives the z-index ladder.
 * @param w Card width px.
 * @param tier The active coverflow fan tier.
 * @param peek Visible cards per side; |s| beyond it hides the card.
 * @returns The pose record for the DOM write.
 */
export function fanPose(
  s: number,
  len: number,
  w: number,
  tier: CardStackFanTier,
  peek: number = tier.PEEK
): CardPose {
  const a = Math.abs(s)

  const sign = s < 0 ? -1 : 1

  const near = Math.min(a, 1)

  const far = Math.max(a - 1, 0)

  return {
    x: sign * (near * tier.FIRST_STEP + far * tier.STEP) * w,
    y: CARD_STACK_LAYOUT.FAN_LIFT,
    depth: 0 - (near * tier.DEPTH + far * tier.DEPTH_STEP) * w,
    // Progressive wrap — neighbours sit at ROT_Y and each deeper card
    // turns ROT_STEP steeper until ROT_MAX parks it just short of
    // edge-on: the smooth carousel arc of the reference, not parallel
    // planes. The sign is INWARD — a right-side card's rotateY is
    // negative so every face converges on the deck centre (the camera
    // reads the covers nearly frontal); +sign pointed faces outward
    // into grazing slivers.
    rot: 0 - sign * Math.min(tier.ROT_MAX, near * tier.ROT_Y + far * tier.ROT_STEP),
    rotZ: 0,
    opacity: Math.max(CARD_STACK_LAYOUT.FAN_DIM_FLOOR, 1 - a * CARD_STACK_LAYOUT.FAN_DIM_STEP),
    // The active-card boost — the centre card is plainly WIDER/TALLER
    // than its fanned neighbours (the reference's hero card), easing
    // off linearly across the front→neighbour interval so a fractional
    // drag slides the size change continuously with the deal-through.
    scale: 1 + Math.max(0, 1 - a) * (CARD_STACK_LAYOUT.FRONT_SCALE - 1),
    z: Math.round((len - a) * CARD_STACK_LAYOUT.Z_STRIDE),
    visible: a <= peek,
  }
}

/**
 * The stacked-layout pose for signed offset `s` — the "entire card"
 * pile of the phone/portrait tiers, modelled as a dealt deck:
 *  - s = +1 is the DEAL slot — the next card shifted down-right so its
 *    bottom band (description + CTA) peeks below the front card's edge.
 *  - s ≥ +2 is the draw-pile FAN — each level a further step up-left,
 *    tilted counter-clockwise, so only the top-left corners sliver out
 *    into the page margins.
 *  - s < 0 are the returned cards — they slide under the pile's bottom
 *    edge (the deepest up-left slot), |s|-scaled so the swiped card
 *    travels there smoothly mid-drag; only the most recent stays lit.
 * The s > 0 path is piecewise-linear in `a` across three segments —
 * min(a,1) travels 0 → DEAL_*, clamp(a−1,0,1) travels DEAL_* → FAN_*
 * (first fan level, so the terms are the FAN−DEAL delta), and
 * max(a−2,0) adds each deeper FAN_*_STEP — a fractional drag offset
 * glides through deal/fan continuously.
 * @param s Signed ring offset (0 = front).
 * @param len Deck length — drives the z-index ladder.
 * @param w Card width px.
 * @param h Card height px.
 * @param tier The active stacked tier.
 * @param peek Visible pile depth; deeper upcoming cards hide.
 * @returns The pose record for the DOM write.
 */
export function stackPose(
  s: number,
  len: number,
  w: number,
  h: number,
  tier: CardStackStackTier,
  peek: number = tier.PEEK
): CardPose {
  const a = Math.abs(s)

  if (s < 0) {
    // Returned-to-bottom cards — parked under the pile's up-left bottom
    // edge. |s|-scaled: the front card slides there (not teleports) as
    // a drag crosses s = 0; only the freshest parked card stays lit.
    // Opacity scrubs down with the same |s| — the outgoing card fades
    // as the swipe carries it under, and a cancelled gesture slides a
    // back to 0, undoing the dim with the motion (never a snap-back).
    return {
      x: 0 - tier.PARK_X * a * w,
      y: 0 - tier.PARK_Y * a * h,
      depth: 0 - tier.PARK_D * a * w,
      rot: 0,
      rotZ: 0 - tier.PARK_RZ * a,
      opacity: 1 - a * CARD_STACK_LAYOUT.PARK_DIM_STEP,
      scale: 1,
      z: Math.round(a * CARD_STACK_LAYOUT.Z_STRIDE),
      visible: a <= 1,
    }
  }

  const deal = Math.min(a, 1)

  const fan = Math.min(Math.max(a - 1, 0), 1)

  const deep = Math.max(a - 2, 0)

  return {
    x: (tier.DEAL_X * deal + (tier.FAN_X - tier.DEAL_X) * fan + tier.FAN_X_STEP * deep) * w,
    y: (tier.DEAL_Y * deal + (tier.FAN_Y - tier.DEAL_Y) * fan + tier.FAN_Y_STEP * deep) * h,
    depth: 0 - (tier.DEAL_D * deal + (tier.FAN_D - tier.DEAL_D) * fan + tier.FAN_D_STEP * deep) * w,
    rot: 0,
    rotZ: tier.DEAL_RZ * deal + (tier.FAN_RZ - tier.DEAL_RZ) * fan + tier.FAN_RZ_STEP * deep,
    opacity: 1,
    scale: 1,
    z: Math.round((len - a) * CARD_STACK_LAYOUT.Z_STRIDE),
    visible: a <= peek,
  }
}

/**
 * Pose dispatcher — the STACKED tiers' down-right cascade or the fan
 * tiers' left/right coverflow. Single routing site for applyPoses and
 * the skeleton renderer.
 * @param tier The active tier (narrows the pose model).
 * @param s Signed ring offset.
 * @param len Deck length.
 * @param w Card width px.
 * @param h Card height px.
 * @param peek Visible depth window.
 * @returns The pose record for the DOM write.
 */
export function tierPose(
  tier: CardStackTier,
  s: number,
  len: number,
  w: number,
  h: number,
  peek: number
): CardPose {
  return tier.STACKED ? stackPose(s, len, w, h, tier, peek) : fanPose(s, len, w, tier, peek)
}

/**
 * Screen-space x (px from the deck centre) of the outer edge of the card
 * at offset `a` on the right side, after the perspective divide.
 *
 * The card's outer edge sits at its centre x plus the half-width turned
 * by rot: X = x + (w/2)·cos(rot), Z = depth − (w/2)·sin(rot) (the turn
 * sends the outer edge back). The deck's perspective P = PERSPECTIVE·w
 * with its origin at the deck centre — the cards' own anchor — projects
 * it to X·P / (P − Z); Z ≤ 0 so the edge only ever pulls inward.
 * @param a Unsigned ring offset.
 * @param w Card width px.
 * @param tier The active coverflow fan tier.
 * @returns The projected outer-edge x in px.
 */
export function projectedEdge(a: number, w: number, tier: CardStackFanTier): number {
  const pose = fanPose(a, 1, w, tier)

  const t = pose.rot * DEG

  const p = tier.PERSPECTIVE * w

  const ex = pose.x + (w / 2) * Math.cos(t)

  const ez = pose.depth - (w / 2) * Math.sin(t)

  return (ex * p) / (p - ez)
}

/**
 * Visible cards per side — the deepest offset (≤ tier.PEEK) whose
 * projected outer edge stays inside the deck half-width × EDGE_ROOM,
 * never below PEEK_MIN. The fan is symmetric, so one count serves both
 * sides: on landscape/desktop the left-most card can't reach into the
 * text column, and on phones EDGE_ROOM > 1 lets the neighbours bleed
 * off-screen as the swipe hint.
 * @param deckW Deck width px.
 * @param w Card width px.
 * @param tier The active coverflow fan tier.
 * @returns Cards visible per side.
 */
export function fitPeek(deckW: number, w: number, tier: CardStackFanTier): number {
  const room = (deckW / 2) * tier.EDGE_ROOM

  let peek = tier.PEEK

  // Bounded count-down (≤ PEEK steps), not a traversal.
  while (peek > CARD_STACK_LAYOUT.PEEK_MIN && projectedEdge(peek, w, tier) > room) peek--

  return peek
}

/**
 * Measures the deck region and publishes the card box + tier: the card
 * width is the tier's CARD_SHARE of the deck width, capped so its height
 * (width × CARD_H_RATIO) stays inside HEIGHT_SHARE of the stage height —
 * the deck's own box, clamped to the stage budget the VIEWPORT actually
 * leaves it: the section is min-height 100dvh, so when the chrome (title
 * header, info column, foot) needs more than the window the section
 * overflows and the deck's measured height lies about the room available.
 * The stage budget subtracts the space above and below the deck inside
 * the section from the viewport, so the card shrinks on short windows
 * instead of holding a constant height while the page scrolls.
 * Pre-paint/hidden contexts report zero rects → the viewport width
 * stands in for the deck width and the height cap is skipped.
 * @param host The CardStack element.
 */
export function measure(host: CardStack): void {
  const deck = host.$(CARD_STACK_SELECTORS.CARD_STACK_DECK)

  const rect = deck ? deck.getBoundingClientRect() : null

  const vw = viewportWidth() || CARD_STACK_LAYOUT.CARD_W_FALLBACK

  const vh = viewportHeight()

  const tier = pickTier(vw, vh)

  const deckW = rect?.width || vw

  let deckH = rect?.height || 0

  // Carried-over outputs for the unmeasurable branch — the signature
  // compares against the values the last pass published, so a hidden
  // deck holds its previous stage budget instead of collapsing to 0.
  let stageH = host._stageH

  let autoStage = host._autoStage

  if (deck && rect?.height) {
    const section = host.$(CARD_STACK_SELECTORS.CARD_STACK)

    const secRect = section ? section.getBoundingClientRect() : null

    if (secRect) {
      const style = getComputedStyle(section as HTMLElement)

      const headerEl = (section as HTMLElement).querySelector(
        CARD_STACK_SELECTORS.CARD_STACK_HEADER
      )

      const footEl = (section as HTMLElement).querySelector(CARD_STACK_SELECTORS.CARD_STACK_FOOT)

      const boxH = (el: Element | null) => (el ? el.getBoundingClientRect().height : 0)

      const marginsOf = (el: Element | null) => {
        if (!el) return 0

        const s = getComputedStyle(el as HTMLElement)

        return (parseFloat(s.marginTop) || 0) + (parseFloat(s.marginBottom) || 0)
      }

      // Fixed chrome only — the section's vertical padding plus the
      // header and foot rows (with margins). Edge deltas can't be used
      // here: the one-column grid aligns its rows `space-evenly`, so
      // the slack around the deck lands inside those deltas and the
      // budget would collapse to the deck's own measured height — a
      // ratchet that only ever shrinks. The slack is the very space
      // the pile may grow into, so it must NOT count as chrome. On the
      // ≥1280 side-by-side grid (rows auto / minmax(0,1fr) / auto) the
      // slack already lives inside the deck's own track, and this same
      // fixed-chrome sum resolves identically.
      const chromeH =
        (parseFloat(style.paddingTop) || 0) +
        (parseFloat(style.paddingBottom) || 0) +
        boxH(headerEl) +
        marginsOf(headerEl) +
        boxH(footEl) +
        marginsOf(footEl)

      // The raw viewport allotment — fitDeckToFront's stage cap. Kept
      // apart from deckH (which clamps to it): the band's cap must read
      // the budget itself, not the deck's own current height, or a
      // band measured mid-overflow locks the cap to the wrong figure.
      stageH = Math.max(0, vh - chromeH)

      // Whether the section is content-sized (the ≥3840 rung drops the
      // 100dvh floor → min-height computes to 0/auto, both parse falsy):
      // the deck row then has no 1fr allotment and fitDeckToFront must
      // publish the fan's band itself instead of riding the row's.
      autoStage = !(parseFloat(style.minHeight) > 0)

      deckH = Math.min(deckH, stageH)
    }
  }

  const byWidth = deckW * tier.CARD_SHARE

  const heightRoom = stageH || deckH

  const byHeight = heightRoom ? (heightRoom * tier.HEIGHT_SHARE) / tier.CARD_H_RATIO : byWidth

  // The card's height-derived width input differs per layout contract:
  // the fan tiers' 1fr deck row IS the allotment, so the measured deck
  // height is the honest bound; the stacked tiers' deck row is
  // auto-height — its measurement is the band the LAST card size
  // produced, which feeds back as a sticky ratchet that can only
  // shrink. There the bound is the stage budget itself (the viewport
  // allotment after fixed chrome): the pile may grow into the
  // space-evenly slack until the band hits the cap.
  // Every tier reads the stage BUDGET (viewport minus fixed chrome), not
  // the deck row's live measurement: under the ≥3840 content-height
  // section the deck row IS the published card band, so measuring it
  // would feed the last card size back as a shrink-only ratchet. With
  // min-height:100dvh the 1fr row resolves to the same number anyway —
  // this only decouples the cap from the layout mode — read off the
  // `heightRoom` local computed above.

  // Copy-carrying stacked tiers size by width alone — the front card
  // auto-grows to its copy (height:auto in applyPoses) and the deck row
  // follows via fitDeckToFront's min-height, so the page scrolls
  // instead of crushing the card into the stage's leftover height. The
  // image-only stacked band (1024–1279 landscape) and the fan tiers
  // keep the height cap — no copy ever grows those cards, so the pile
  // must fit the bounded side-by-side stage and never push its bottom
  // edge past the section's clip boundary.
  const cardW = Math.min(
    Math.max(
      tier.STACKED && tier.IN_CARD_INFO ? byWidth : Math.min(byWidth, byHeight),
      CARD_STACK_LAYOUT.CARD_W_MIN
    ),
    CARD_STACK_LAYOUT.CARD_W_MAX
  )

  // Autoplay is fan-tier only — a resize into a stacked layout kills a
  // running countdown (stopAutoplay no-ops when nothing is armed).
  if (tier.STACKED) stopAutoplay(host)

  // The fan's peek is width-fitted to the deck edges; the stacked pile's
  // depth window is the tier's authored count (the cascade's own offsets
  // — not a horizontal fit — decide what peeks out).
  const peek = tier.STACKED ? tier.PEEK : fitPeek(deckW, cardW, tier)

  // Signature gate — every independent output (tier camera, card width,
  // stage budget, deck rect, content-stage flag) joins into one key;
  // an unchanged key means the delivery that triggered this measure
  // observed no real resize, so the publishes below are skipped: an
  // RO notification whose only cause was our own min-height write or
  // a sub-pixel jitter ends here instead of reposing the whole pile.
  const sig = `${CARD_STACK_TIERS.indexOf(tier)}|${cardW}|${deckW}|${deckH}|${stageH}|${autoStage}`

  if (_measureSig.get(host) === sig) return

  _measureSig.set(host, sig)

  host._cardW = cardW

  host._cardH = cardW * tier.CARD_H_RATIO

  host._step = cardW * tier.FIRST_STEP

  host._tier = tier

  host._peek = peek

  host._deckW = deckW

  host._deckH = deckH

  host._stageH = stageH

  host._autoStage = autoStage
}

/** Zero-padded counter/index number — "01", "08" — shared by the deck
 *  counter and the index rows. */
export function padNum(n: number): string {
  return `${n}`.padStart(CARD_STACK_LAYOUT.PAD, CHAR_STRINGS.ZERO)
}

/**
 * Writes every card's pose for the current virtual front `f` — derived
 * from `activeIdx - _dragX/_step`, so a live drag slides the whole
 * coverflow continuously and `activeIdx` alone reproduces the rest pose.
 * Every DOM write is value-guarded: card box properties and the deck
 * perspective (the tier's camera distance) compare against the current
 * inline value before touching it, and a card whose whole pose
 * signature matched the last pass is skipped outright — re-delivered
 * observer passes cost compares, not relayouts. Runs inside the
 * gesture rAF — reads are cached fields and inline-style values.
 * @param host The CardStack element.
 */
export function applyPoses(host: CardStack): void {
  // The print adapter strips inline styles for the snapshot — a rAF/RO
  // pose write landing mid-job would scatter the flattened mosaic back
  // into fan geometry on paper.
  if (host._printing) return

  const items = host.deckItems

  const len = items.length

  if (!len) return

  const w = host._cardW

  const h = host._cardH

  const tier = host._tier

  const cards = host._cardEls

  // Live drag — the f fraction freezes on the committed front: the
  // pressed card tracks the finger in px below, and only the incoming
  // neighbour walks its slot→front pose (progress of a card-width
  // pull). The old continuous f moved the WHOLE stack through pose
  // space at _step per step — on the 0.4·w stacked tier one hold
  // dealt through 2–3 cards under the finger (the "changes 1, 2, 3
  // slides" report) and a cancel slammed them all back.
  const dragging = host._dragActive

  const f = dragging ? host.activeIdx : host.activeIdx - host._dragX / host._step

  const progress = dragging ? Math.min(Math.abs(host._dragX) / Math.max(w, 1), 1) : 0

  const dragDir = host._dragX < 0 ? 1 : -1

  const incoming = len > 1 ? (host.activeIdx + dragDir + len) % len : -1

  // The uniform stacked box — the tallest card's natural height folded
  // over the ratio box. EVERY stacked card gets it: the pile's sheets
  // are identical, so only the thin stair offsets peek out instead of a
  // near-full second image spilling below the front card's bottom edge
  // — and no card's border-box can ever move mid-gesture or per nav.
  const pileH = h + host._frontExtra

  // Fresh-node batch — elements that have never been posed collect
  // here so a single post-loop flush commits all their baselines at
  // once. Allocated lazily: mount/re-render passes only, never per
  // gesture frame (zero-allocation frame-loop rule).
  let fresh: HTMLElement[] | null = null

  for (let i = 0; i < cards.length; i++) {
    const el = cards[i] as HTMLElement

    // The incoming neighbour is the only stack card that moves during a
    // drag — its slot→front pose rides the travel fraction so the card
    // visibly enters accompanying the swipe instead of teleporting in
    // on release; every other card holds its integer slot.
    let s = ringSigned(i - f, len)

    if (dragging && i === incoming) s = dragDir * (1 - progress)

    const pose = tierPose(tier, s, len, w, pileH, host._peek)

    // The pressed card rides the finger 1:1 in px — not pose space —
    // so the card under the touch can never run ahead of or lag behind
    // the pointer, and the stack's single-card boundary holds no matter
    // how far the drag travels.
    if (dragging && i === host.activeIdx) pose.x += host._dragX

    // A right-swipe on the stacked tiers un-stacks the parked card:
    // give it an extra card-width of travel so it sweeps in from off
    // the parked edge instead of fading in place under the departing
    // card, and let it materialize as it travels — the parked-dim scrub
    // alone starts at 0.45 and reads as a pop when the card enters the
    // visible band. Mirrored tiers sweep from their own parked side.
    if (dragging && i === incoming && tier.STACKED && dragDir < 0) {
      pose.x -= Math.sign(tier.PARK_X) * (1 - progress) * w

      pose.opacity *= progress
    }

    const wasVisible = _wasVisible.get(el)

    _wasVisible.set(el, pose.visible)

    // First pose per element — a never-posed node has no "before" to
    // animate from. Mount and re-render insert cards whose only resolved
    // style is transform:none (measure()'s forced rect read resolves
    // them before this write), so without suppression the stylesheet's
    // 0.52s transform transition flies every card in from the deck
    // centre on load — the mount flicker. The write lands instantly;
    // the post-loop flush commits it as the baseline before the CSS
    // transition returns.
    if (wasVisible === undefined) {
      el.style.transition = ATTR_VALUES.NONE

      ;(fresh ??= []).push(el)
    }

    // Card box — the FINAL layout value for this tier, each property
    // guarded against its current inline value so a pass that
    // re-derives identical geometry never invalidates layout. Every
    // stacked card gets the SAME box: pileH is the tallest card's
    // natural height (fitDeckToFront's max-over-cards measure — never
    // truncate, always fit), so nothing resizes under the finger, on
    // nav, or when a class flips — the border-box is invariant.
    const wantW = `${w}${COMMON_ATTRS.PX}`

    const wantH = `${tier.STACKED ? pileH : h}${COMMON_ATTRS.PX}`

    const wantMin = tier.STACKED ? `${pileH}${COMMON_ATTRS.PX}` : ATTR_VALUES.EMPTY

    if (el.style.width !== wantW) el.style.width = wantW

    if (el.style.height !== wantH) el.style.height = wantH

    if (el.style.minHeight !== wantMin) el.style.minHeight = wantMin

    // Centre-anchored: the card's own centre sits on the deck centre —
    // the perspective origin — so translate3d + the fan's rotateY (and
    // the stack cascade's rotateZ) pivot it in place and the
    // perspective divide scales it toward that point. The stacked pile
    // shares the front card's LIVE height (pileH above), so plain
    // centering keeps every card's top edge on the same line — the
    // pile never bleeds into the header when the front is capped, and
    // only the authored stair offsets peek past its edges. Stacked
    // tiers write a FLAT pose — translateZ under a `perspective` deck
    // pushes every card through WebKit's 3D compositing path, the
    // layer-graph family that jetsam-kills iOS tabs under a pile of
    // textured sheets; the pile still staggers on x/y/rotZ.
    const wantT = tier.STACKED
      ? `translate(-50%, -50%) translate3d(${pose.x}${COMMON_ATTRS.PX}, ${pose.y}${COMMON_ATTRS.PX}, 0) rotate(${pose.rotZ}deg) scale(${pose.scale})`
      : `translate(-50%, -50%) translate3d(${pose.x}${COMMON_ATTRS.PX}, ${pose.y}${COMMON_ATTRS.PX}, ${pose.depth}${COMMON_ATTRS.PX}) rotateY(${pose.rot}deg) rotate(${pose.rotZ}deg) scale(${pose.scale})`

    // Opacity writes the pose value for visible cards and the hidden
    // floor — the entering seed's 0→1 and the leaving card's 1→0
    // dissolve both ride the stylesheet's opacity transition; the
    // stacked parked branch scrubs its dim with the drag fraction.
    const wantO = pose.visible ? `${pose.opacity}` : CHAR_STRINGS.ZERO

    const wantZ = `${pose.z}`

    const wantV = pose.visible ? ATTR_VALUES.VISIBLE : ATTR_VALUES.HIDDEN

    // While a drag is live the held card keeps --active outright — the
    // incoming neighbour's s dips inside FRONT_EPS past half-travel and
    // two active cards would double-render the info column.
    const wantA = dragging
      ? i === host.activeIdx
      : pose.visible && Math.abs(s) < CARD_STACK_LAYOUT.FRONT_EPS

    // Signature gate — an applyPoses re-delivery whose every output
    // matches the last write skips the whole card's DOM surface: the
    // compare is one string read + a WeakMap hit against ~N writes.
    // The `!el.style.transform` probe self-heals stripped nodes (the
    // print snapshot clears inline styles — a cache hit alone would
    // leave them bare since poses re-derive to the same signature).
    const sig = `${wantT}|${wantO}|${wantZ}|${wantV}|${wantA}`

    if (_poseSig.get(el) === sig && el.style.transform) continue

    _poseSig.set(el, sig)

    // A card entering the fan seeds below its slot, transparent, with
    // transitions off for that one write — restoring them lets the base
    // transition carry it up into place while it fades in (the deck's
    // wrap-around "rise + fade" the boundary nav relies on). A card
    // leaving the fan simply writes opacity 0 + --hidden, and its
    // opacity/visibility transition dissolves it in place.
    if (pose.visible && wasVisible === false && !tier.STACKED) {
      el.style.transition = ATTR_VALUES.NONE

      el.style.transform = `translate(-50%, -50%) translate3d(${pose.x}${COMMON_ATTRS.PX}, ${pose.y + h * CARD_STACK_LAYOUT.ENTER_RISE}${COMMON_ATTRS.PX}, ${pose.depth}${COMMON_ATTRS.PX}) rotateY(${pose.rot}deg) rotate(${pose.rotZ}deg) scale(${pose.scale})`

      el.style.opacity = CHAR_STRINGS.ZERO

      el.style.visibility = ATTR_VALUES.VISIBLE

      el.style.zIndex = wantZ

      void flushLayout(el)

      el.style.transition = ATTR_VALUES.EMPTY
    }

    if (el.style.transform !== wantT) el.style.transform = wantT

    if (el.style.opacity !== wantO) el.style.opacity = wantO

    if (el.style.zIndex !== wantZ) el.style.zIndex = wantZ

    if (el.style.visibility !== wantV) el.style.visibility = wantV

    if (el.classList.contains(CARD_STACK_CLASSES.CARD_STACK_CARD_HIDDEN) === pose.visible) {
      el.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_CARD_HIDDEN, !pose.visible)
    }

    if (el.classList.contains(CARD_STACK_CLASSES.CARD_STACK_CARD_ACTIVE) !== wantA) {
      el.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_CARD_ACTIVE, wantA)
    }
  }

  if (host._deckEl) {
    // Stacked tiers get no camera — a `perspective` deck would re-enter
    // the 3D compositing path the flattened poses just left. The write
    // is value-guarded like the cards': a converged camera doesn't
    // re-invalidate the deck's compositing state per pass.
    const wantP = tier.STACKED ? ATTR_VALUES.NONE : `${tier.PERSPECTIVE * w}${COMMON_ATTRS.PX}`

    if ((host._deckEl as HTMLElement).style.perspective !== wantP) {
      ;(host._deckEl as HTMLElement).style.perspective = wantP
    }
  }

  if (fresh) {
    // One style resolution commits every fresh card's pose as its
    // transition baseline — per-card flushes inside the loop resolve
    // globally anyway, so a single read covers the batch (one reflow,
    // not N). Restoring the stylesheet transition after the commit
    // keeps later pose writes animating normally.
    void flushLayout(fresh[0] as HTMLElement)

    for (const el of fresh) el.style.transition = ATTR_VALUES.EMPTY
  }
}

/**
 * Refreshes the non-pose chrome after a nav — the "PROJECT 01 OF 08"
 * counter (projectLabel + ofLabel, both localized), the dot --active
 * flags, each card's aria-hidden/tabindex so off-front cards leave the
 * tab order and AT tree, and the text column's copy for the new front.
 * @param host The CardStack element.
 */
export function updateChrome(host: CardStack): void {
  const len = host.deckItems.length

  if (!len) return

  const navIndex = host.$(CARD_STACK_SELECTORS.CARD_STACK_NAV_INDEX) as HTMLElement | null

  if (navIndex) {
    const n = host.activeIdx + 1

    const num = navIndex.querySelector(CARD_STACK_SELECTORS.CARD_STACK_NAV_INDEX_NUM)

    // The "1 / 13" position rides beside the stack glyph; the button's
    // accessible name must contain that same visible text (WCAG 2.5.3 —
    // label-content-name-mismatch), so the label mirrors the number
    // format rather than the "of N" word form.
    if (num) {
      num.textContent = `${n}${CHAR_STRINGS.SPACE_CHAR}${CHAR_STRINGS.SLASH}${CHAR_STRINGS.SPACE_CHAR}${len}`
    }

    navIndex.setAttribute(
      ARIA_ATTRS.ARIA_LABEL,
      `${host._t.projectLabel} ${n} ${CHAR_STRINGS.SLASH} ${len}`
    )

    dealNavIndex(host, navIndex)
  }

  const dots = host.$$(CARD_STACK_SELECTORS.CARD_STACK_DOT)

  dots.forEach((dot, i) => {
    dot.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_DOT_ACTIVE, i === host.activeIdx)
  })

  host._cardEls.forEach((card, i) => {
    const front = i === host.activeIdx

    card.setAttribute(ARIA_ATTRS.ARIA_HIDDEN, front ? ATTR_VALUES.FALSE : ATTR_VALUES.TRUE)

    const link = card.querySelector(HTML_TAGS.A)

    ;(link as HTMLElement | null)?.setAttribute(
      ARIA_ATTRS.TABINDEX,
      front ? ATTR_VALUES.TABINDEX_ZERO : ATTR_VALUES.NEGATIVE_TABINDEX
    )
  })

  // Settle _frontExtra + the pile's height writes BEFORE writeInfo
  // mounts the in-card burns — a stale delta (the outgoing front's own
  // grown extra) otherwise survives into the arm-time measure and the
  // burn canvas anchors to a box the settled layout never had, which
  // reads as the burning title jumping once the fit rewrites heights.
  fitDeckToFront(host)

  writeInfo(host)
}

/** Last chromed index per host — the nav-index deal animation's
 *  direction cue (a mount's first pass has no previous front). */
const _chromeIdx = new WeakMap<CardStack, number>()

/**
 * Deals the nav-index stack glyph after a front change — the top card
 * of the icon flings in the nav direction (forward on next, backward
 * on prev, ring-normalized so wrap-around navs read correctly) and
 * slides back under the pile, echoing the deck's own card exchange.
 * The class re-arms through a frame-boundary remove → rAF add pair so
 * a mid-animation nav restarts the keyframe without a forced reflow.
 * @param host The CardStack element.
 * @param navIndex The nav-index button carrying the glyph.
 */
function dealNavIndex(host: CardStack, navIndex: HTMLElement): void {
  const len = host.deckItems.length

  const prev = _chromeIdx.get(host)

  _chromeIdx.set(host, host.activeIdx)

  if (prev === undefined || prev === host.activeIdx || len <= 1) return

  const delta = host.activeIdx - prev

  const fwd = delta > 0 ? delta <= len / 2 : delta < -len / 2

  navIndex.classList.remove(
    CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_NEXT,
    CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_PREV
  )

  requestAnimationFrame(() => {
    navIndex.classList.add(
      fwd
        ? CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_NEXT
        : CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_PREV
    )
  })
}

/**
 * Re-fits the stacked deck's height to the TALLEST card's natural box —
 * never truncate, always fit: applyPoses gives every stacked card the
 * same pileH (ratio height + _frontExtra), and the measured max delta
 * parks as _frontExtra so a copy-heavy description sizes the WHOLE
 * pile, not just the card carrying it. Card border-boxes are then
 * invariant under gestures, navs, and class flips — the page absorbs
 * the overflow. The front card's ResizeObserver re-runs the fit when
 * fonts/locale/typewriter change the copy after mount. Fan tiers just
 * clear the artifact. One layout read per nav/mount — same class as
 * measure(), never per-frame.
 * @param host The CardStack element.
 */
export function fitDeckToFront(host: CardStack): void {
  // Print pass — the flattened sheet's copy reflow fires this observer;
  // its min-height write would re-pose the deck mid-snapshot just like
  // an applyPoses call. A live drag owns the pile too — a mid-gesture
  // re-anchor would rewrite every card's border-box under the finger.
  if (host._printing || host._dragActive) return

  const deck = host._deckEl as HTMLElement | null

  if (!host._tier?.STACKED) {
    host._frontExtra = 0

    if (deck) {
      // Fan tiers ride the 1fr row's allotment under min-height:100dvh —
      // the absolute cards contribute no flow height, so a content-sized
      // section (the ≥3840 rung) would collapse the row to ~0. There the
      // band is authored: the scaled front card's extent plus its
      // negative FAN_LIFT clearance (cards park -40px above centre).
      // Value-guarded: an unchanged band never re-invalidates the deck —
      // a same-value write still feeds the observer that called us.
      const band =
        host._autoStage && host._cardH
          ? `${
              host._cardH * CARD_STACK_LAYOUT.FRONT_SCALE - CARD_STACK_LAYOUT.FAN_LIFT * 2
            }${COMMON_ATTRS.PX}`
          : ATTR_VALUES.EMPTY

      if (deck.style.minHeight !== band) deck.style.minHeight = band
    }

    return
  }

  const front = host._cardEls[host.activeIdx] as HTMLElement | undefined

  if (!front) return

  // Image-only stacked tiers (the 1024–1279 landscape pile) have no
  // copy that can grow — every card keeps the ratio box, so the live
  // measure is skipped entirely. getBoundingClientRect includes the
  // running transform/scale, and a mid-transition read feeds back into
  // pileH via _frontExtra: the whole pile would visibly compress and
  // re-expand on every nav. _frontExtra pins at 0 and the deck band is
  // the fixed ratio height + pad — identical geometry on every card.
  if (!host._tier.IN_CARD_INFO) {
    if (host._fitRO) {
      host._fitRO.disconnect()

      host._fitFront = null
    }

    host._frontExtra = 0

    if (deck) {
      const band = `${host._cardH + host._cardH * CARD_STACK_LAYOUT.STACKED_DECK_PAD}${COMMON_ATTRS.PX}`

      if (deck.style.minHeight !== band) deck.style.minHeight = band
    }

    return
  }

  if (host._fitFront !== front) {
    host._fitRO?.disconnect()

    if (typeof ResizeObserver !== TYPE_STRINGS.UNDEFINED) {
      // RO notifications are pre-paint: writing sizes back inside the
      // same notification turn resizes observed boxes and the browser
      // reports "ResizeObserver loop completed with undelivered
      // notifications". Worse, the description typewriter grows the
      // watched info column EVERY FRAME, so a same-frame fit would
      // write deck min-height + re-pose the pile per type tick — the
      // production RO-loop errors and the mid-animation relayout
      // storm. Debouncing to the settle point keeps the notification
      // turn write-free (the loop detector stays quiet) and lands one
      // fit per growth burst instead of one per frame.
      host._fitRO ??= new ResizeObserver(() => {
        if (host._fitTimer) clearTimeout(host._fitTimer)

        host._fitTimer = setTimeout(() => {
          host._fitTimer = 0

          fitDeckToFront(host)
        }, CARD_STACK_LAYOUT.FIT_SETTLE_MS)
      })

      host._fitRO.observe(front)

      // The in-card summary is plain text — nothing inside the pile
      // types or grows — but a late font swap can still re-wrap the
      // copy, so the card, link, info column, and desc stay watched:
      // one settled re-fit absorbs the font-load delta.
      const linkEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_LINK)

      if (linkEl) host._fitRO.observe(linkEl)

      const infoEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_INFO)

      if (infoEl) host._fitRO.observe(infoEl)

      const descEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_INFO_DESC)

      if (descEl) host._fitRO.observe(descEl)
    }

    host._fitFront = front
  }

  // Uniform pile height — never truncate, always fit: the biggest
  // description in the deck sets EVERY card's box, so all stacked
  // cards are identical and a border-box can never change under the
  // finger or between navs. Measure all cards' natural heights in one
  // batch: every height:auto + min-height:0 write lands first (style
  // mutations don't reflow until a read), then the offsetHeight loop
  // forces a single layout — one reflow for the whole pile. The floor
  // MUST clear too: a live pileH min-height feeds the card's own
  // padding+border back into the measure (+2px every pass = the
  // infinite-growth ratchet), and the link's min-height:inherit
  // compounds it. offsetHeight is the layout border box, so the
  // running pose transform can't contaminate the read the way
  // getBoundingClientRect would.
  for (const el of host._cardEls) {
    const st = (el as HTMLElement).style

    st.height = ATTR_VALUES.AUTO
    st.minHeight = ATTR_VALUES.EMPTY
  }

  let realH = host._cardH

  for (const el of host._cardEls) {
    realH = Math.max(realH, (el as HTMLElement).offsetHeight)
  }

  // Content-driven height — the pile NEVER caps at the stage budget:
  // the tallest copy sizes every card's box outright and the deck band
  // grows to match, so a copy-heavy card simply pushes the pile +
  // controls past the fold and the PAGE scrolls. _stageH stays as
  // measure()'s width bound for the image-only band — it no longer
  // clamps any card's height.
  const grow = realH - host._cardH

  const anchor = grow

  if (deck) {
    const band = `${host._cardH + grow + host._cardH * CARD_STACK_LAYOUT.STACKED_DECK_PAD}${COMMON_ATTRS.PX}`

    // Value-guarded — the RO-loop fix: this write resizes the observed
    // deck, so re-landing an identical band re-fires _deckRO for
    // nothing. Only a real delta may touch the DOM.
    if (deck.style.minHeight !== band) deck.style.minHeight = band
  }

  host._frontExtra = anchor

  // pileH (and every stacked card's height write) rides the delta —
  // and the measure's height:auto toggles must be restored on EVERY
  // pass, not just when the anchor moved. applyPoses is value-guarded,
  // so an identical pose re-derivation costs compares, not relayouts.
  applyPoses(host)
}

```

---
Canonical page: https://luiskr.com/docs/website/components/home/cardstack/deck.ts
JSON replica: https://luiskr.com/llm/en/docs/website/components/home/cardstack/deck.ts.json

## Language alternates

- [en](https://luiskr.com/llm/en/docs/website/components/home/cardstack/deck.ts.md)
