{"@context":"https://schema.org","@type":"WebPage","specVersion":"llm-replica/1.0","type":"docs-file","title":"deck.ts | Luis Krötz Docs","description":"deck.ts — code (40984 bytes)","route":"/docs/website/components/home/cardstack/deck.ts","locale":"en","language":"en","canonical":"https://luiskr.com/docs/website/components/home/cardstack/deck.ts","alternates":{"en":"https://luiskr.com/llm/en/docs/website/components/home/cardstack/deck.ts.md"},"replicas":{"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"},"content":{"kind":"file","name":"deck.ts","path":"website/components/home/cardstack/deck.ts","format":"code","size":40984,"mtime":"2026-11-18T22:43:22.435Z","docsContent":"https://luiskr.com/docs-content/website/components/home/cardstack/deck.ts.json","text":"/**\n * @file cardstack/deck.ts — the coverflow geometry for <card-stack>:\n * responsive tier pick, signed ring offsets → per-card 3D poses, deck\n * measurement, and the imperative style writes that drive both the drag\n * tracking frames and the CSS-transition settle.\n */\n\nimport { CARD_STACK_CLASSES } from '@core/tokens/classes/card-stack.js'\nimport { CARD_STACK_SELECTORS } from '@core/tokens/selectors/card-stack.js'\nimport { CARD_STACK_LAYOUT, CARD_STACK_TIERS } from '@core/tokens/motion/card-stack.js'\nimport type {\n  CardStackFanTier,\n  CardStackStackTier,\n  CardStackTier,\n} from '@core/tokens/motion/card-stack.js'\nimport { ATTR_VALUES } from '@core/tokens/attrs/values.js'\nimport { COMMON_ATTRS } from '@core/tokens/attrs/common.js'\nimport { CHAR_STRINGS } from '@core/tokens/strings/chars.js'\nimport { TYPE_STRINGS } from '@core/tokens/strings/types.js'\nimport { ARIA_ATTRS } from '@core/tokens/attrs/aria.js'\nimport { HTML_TAGS } from '@core/tokens/elements/html.js'\nimport { flushLayout, viewportHeight, viewportWidth } from '@core/utils/dom.js'\nimport { writeInfo } from './info.js'\nimport { stopAutoplay } from './autoplay.js'\nimport type { CardStackItem, CardPose } from './types.js'\nimport type { CardStack } from '../CardStack.js'\n\n/** Degrees → radians for the projected-edge trigonometry. */\nconst DEG = Math.PI / 180\n\n/**\n * Last pose-pass visibility per card element — a card that was hidden on\n * the previous pass and is visible now seeds its rise-and-fade entrance.\n * Keyed by element so a re-rendered card starts a fresh baseline (no\n * entrance on first paint).\n */\nconst _wasVisible = new WeakMap<Element, boolean>()\n\n/**\n * Last pose signature (transform|opacity|z|visibility|active) applied\n * to each card element. applyPoses runs per gesture frame and once per\n * observer re-delivery; a pass whose pose values match the last write\n * skips every DOM write so the converged deck costs compares only —\n * the write→notify churn browsers report as ResizeObserver loops.\n */\nconst _poseSig = new WeakMap<Element, string>()\n\n/**\n * Last measure signature per host — a ResizeObserver hop whose inputs\n * (tier, card box, stage budget, deck rect) are unchanged skips the\n * field publishes entirely, so an unchanged delivery is a compare and\n * a return instead of a host write burst downstream code can observe.\n */\nconst _measureSig = new WeakMap<CardStack, string>()\n\n/**\n * Every pushed item fans in the deck — the full portfolio list in order\n * (the featured flag is decorative only; no filtering applies).\n * @param host The CardStack element.\n * @returns The deck's ordered item list.\n */\nexport function deckItems(host: CardStack): CardStackItem[] {\n  return host.processedItems\n}\n\n/**\n * Signed ring distance of `d` modulo `len`, normalized into (-len/2, len/2]\n * so the shortest fan direction wins — fractional `d` (mid-drag) passes\n * through unchanged in magnitude.\n * @param d Raw index difference (may be fractional, any sign).\n * @param len Deck length.\n * @returns Signed ring offset.\n */\nexport function ringSigned(d: number, len: number): number {\n  if (len <= 0) return 0\n\n  const n = ((d % len) + len) % len\n\n  return n > len / 2 ? n - len : n\n}\n\n/**\n * The coverflow tier for a viewport — the first (widest) tier whose\n * MIN_VW the width meets; the portrait tablet tier also requires a\n * taller-than-wide viewport, mirroring the SCSS `orientation` split.\n * The final (phone) tier has MIN_VW 0 and is the unconditional floor.\n * @param vw Viewport width px.\n * @param vh Viewport height px.\n * @returns The matching tier.\n */\nexport function pickTier(vw: number, vh: number): CardStackTier {\n  const last = CARD_STACK_TIERS.length - 1\n\n  for (let i = 0; i < last; i++) {\n    const tier = CARD_STACK_TIERS[i]\n\n    if (vw >= tier.MIN_VW && (!tier.PORTRAIT || vh > vw)) return tier\n  }\n\n  return CARD_STACK_TIERS[last]\n}\n\n/**\n * The coverflow pose for signed offset `s` (see CardStackTier for the\n * full model). With a = |s|, the near term min(a,1) carries the big\n * front→neighbour jump (FIRST_STEP / DEPTH / the full ROT_Y turn) and\n * the far term max(a−1,0) the tight per-card stacking (STEP /\n * DEPTH_STEP, plus ROT_STEP of extra turn per level so the fan wraps\n * like a carousel wall instead of parallel planes, capped at ROT_MAX)\n * — all linear in `a`, so a fractional drag offset slides every card\n * continuously along the curve. Right-hand\n * cards (s > 0) turn by +ROT_Y, which in CSS's rotateY convention sends\n * their outer edge away from the viewer; the left side mirrors it.\n * `0 - …` keeps the front depth at +0 (never −0). Opacity steps down\n * per level (FAN_DIM_STEP, floored at FAN_DIM_FLOOR) so the outer cards\n * darken into the deck edges exactly like the reference coverflow.\n * @param s Signed ring offset (0 = front).\n * @param len Deck length — drives the z-index ladder.\n * @param w Card width px.\n * @param tier The active coverflow fan tier.\n * @param peek Visible cards per side; |s| beyond it hides the card.\n * @returns The pose record for the DOM write.\n */\nexport function fanPose(\n  s: number,\n  len: number,\n  w: number,\n  tier: CardStackFanTier,\n  peek: number = tier.PEEK\n): CardPose {\n  const a = Math.abs(s)\n\n  const sign = s < 0 ? -1 : 1\n\n  const near = Math.min(a, 1)\n\n  const far = Math.max(a - 1, 0)\n\n  return {\n    x: sign * (near * tier.FIRST_STEP + far * tier.STEP) * w,\n    y: CARD_STACK_LAYOUT.FAN_LIFT,\n    depth: 0 - (near * tier.DEPTH + far * tier.DEPTH_STEP) * w,\n    // Progressive wrap — neighbours sit at ROT_Y and each deeper card\n    // turns ROT_STEP steeper until ROT_MAX parks it just short of\n    // edge-on: the smooth carousel arc of the reference, not parallel\n    // planes. The sign is INWARD — a right-side card's rotateY is\n    // negative so every face converges on the deck centre (the camera\n    // reads the covers nearly frontal); +sign pointed faces outward\n    // into grazing slivers.\n    rot: 0 - sign * Math.min(tier.ROT_MAX, near * tier.ROT_Y + far * tier.ROT_STEP),\n    rotZ: 0,\n    opacity: Math.max(CARD_STACK_LAYOUT.FAN_DIM_FLOOR, 1 - a * CARD_STACK_LAYOUT.FAN_DIM_STEP),\n    // The active-card boost — the centre card is plainly WIDER/TALLER\n    // than its fanned neighbours (the reference's hero card), easing\n    // off linearly across the front→neighbour interval so a fractional\n    // drag slides the size change continuously with the deal-through.\n    scale: 1 + Math.max(0, 1 - a) * (CARD_STACK_LAYOUT.FRONT_SCALE - 1),\n    z: Math.round((len - a) * CARD_STACK_LAYOUT.Z_STRIDE),\n    visible: a <= peek,\n  }\n}\n\n/**\n * The stacked-layout pose for signed offset `s` — the \"entire card\"\n * pile of the phone/portrait tiers, modelled as a dealt deck:\n *  - s = +1 is the DEAL slot — the next card shifted down-right so its\n *    bottom band (description + CTA) peeks below the front card's edge.\n *  - s ≥ +2 is the draw-pile FAN — each level a further step up-left,\n *    tilted counter-clockwise, so only the top-left corners sliver out\n *    into the page margins.\n *  - s < 0 are the returned cards — they slide under the pile's bottom\n *    edge (the deepest up-left slot), |s|-scaled so the swiped card\n *    travels there smoothly mid-drag; only the most recent stays lit.\n * The s > 0 path is piecewise-linear in `a` across three segments —\n * min(a,1) travels 0 → DEAL_*, clamp(a−1,0,1) travels DEAL_* → FAN_*\n * (first fan level, so the terms are the FAN−DEAL delta), and\n * max(a−2,0) adds each deeper FAN_*_STEP — a fractional drag offset\n * glides through deal/fan continuously.\n * @param s Signed ring offset (0 = front).\n * @param len Deck length — drives the z-index ladder.\n * @param w Card width px.\n * @param h Card height px.\n * @param tier The active stacked tier.\n * @param peek Visible pile depth; deeper upcoming cards hide.\n * @returns The pose record for the DOM write.\n */\nexport function stackPose(\n  s: number,\n  len: number,\n  w: number,\n  h: number,\n  tier: CardStackStackTier,\n  peek: number = tier.PEEK\n): CardPose {\n  const a = Math.abs(s)\n\n  if (s < 0) {\n    // Returned-to-bottom cards — parked under the pile's up-left bottom\n    // edge. |s|-scaled: the front card slides there (not teleports) as\n    // a drag crosses s = 0; only the freshest parked card stays lit.\n    // Opacity scrubs down with the same |s| — the outgoing card fades\n    // as the swipe carries it under, and a cancelled gesture slides a\n    // back to 0, undoing the dim with the motion (never a snap-back).\n    return {\n      x: 0 - tier.PARK_X * a * w,\n      y: 0 - tier.PARK_Y * a * h,\n      depth: 0 - tier.PARK_D * a * w,\n      rot: 0,\n      rotZ: 0 - tier.PARK_RZ * a,\n      opacity: 1 - a * CARD_STACK_LAYOUT.PARK_DIM_STEP,\n      scale: 1,\n      z: Math.round(a * CARD_STACK_LAYOUT.Z_STRIDE),\n      visible: a <= 1,\n    }\n  }\n\n  const deal = Math.min(a, 1)\n\n  const fan = Math.min(Math.max(a - 1, 0), 1)\n\n  const deep = Math.max(a - 2, 0)\n\n  return {\n    x: (tier.DEAL_X * deal + (tier.FAN_X - tier.DEAL_X) * fan + tier.FAN_X_STEP * deep) * w,\n    y: (tier.DEAL_Y * deal + (tier.FAN_Y - tier.DEAL_Y) * fan + tier.FAN_Y_STEP * deep) * h,\n    depth: 0 - (tier.DEAL_D * deal + (tier.FAN_D - tier.DEAL_D) * fan + tier.FAN_D_STEP * deep) * w,\n    rot: 0,\n    rotZ: tier.DEAL_RZ * deal + (tier.FAN_RZ - tier.DEAL_RZ) * fan + tier.FAN_RZ_STEP * deep,\n    opacity: 1,\n    scale: 1,\n    z: Math.round((len - a) * CARD_STACK_LAYOUT.Z_STRIDE),\n    visible: a <= peek,\n  }\n}\n\n/**\n * Pose dispatcher — the STACKED tiers' down-right cascade or the fan\n * tiers' left/right coverflow. Single routing site for applyPoses and\n * the skeleton renderer.\n * @param tier The active tier (narrows the pose model).\n * @param s Signed ring offset.\n * @param len Deck length.\n * @param w Card width px.\n * @param h Card height px.\n * @param peek Visible depth window.\n * @returns The pose record for the DOM write.\n */\nexport function tierPose(\n  tier: CardStackTier,\n  s: number,\n  len: number,\n  w: number,\n  h: number,\n  peek: number\n): CardPose {\n  return tier.STACKED ? stackPose(s, len, w, h, tier, peek) : fanPose(s, len, w, tier, peek)\n}\n\n/**\n * Screen-space x (px from the deck centre) of the outer edge of the card\n * at offset `a` on the right side, after the perspective divide.\n *\n * The card's outer edge sits at its centre x plus the half-width turned\n * by rot: X = x + (w/2)·cos(rot), Z = depth − (w/2)·sin(rot) (the turn\n * sends the outer edge back). The deck's perspective P = PERSPECTIVE·w\n * with its origin at the deck centre — the cards' own anchor — projects\n * it to X·P / (P − Z); Z ≤ 0 so the edge only ever pulls inward.\n * @param a Unsigned ring offset.\n * @param w Card width px.\n * @param tier The active coverflow fan tier.\n * @returns The projected outer-edge x in px.\n */\nexport function projectedEdge(a: number, w: number, tier: CardStackFanTier): number {\n  const pose = fanPose(a, 1, w, tier)\n\n  const t = pose.rot * DEG\n\n  const p = tier.PERSPECTIVE * w\n\n  const ex = pose.x + (w / 2) * Math.cos(t)\n\n  const ez = pose.depth - (w / 2) * Math.sin(t)\n\n  return (ex * p) / (p - ez)\n}\n\n/**\n * Visible cards per side — the deepest offset (≤ tier.PEEK) whose\n * projected outer edge stays inside the deck half-width × EDGE_ROOM,\n * never below PEEK_MIN. The fan is symmetric, so one count serves both\n * sides: on landscape/desktop the left-most card can't reach into the\n * text column, and on phones EDGE_ROOM > 1 lets the neighbours bleed\n * off-screen as the swipe hint.\n * @param deckW Deck width px.\n * @param w Card width px.\n * @param tier The active coverflow fan tier.\n * @returns Cards visible per side.\n */\nexport function fitPeek(deckW: number, w: number, tier: CardStackFanTier): number {\n  const room = (deckW / 2) * tier.EDGE_ROOM\n\n  let peek = tier.PEEK\n\n  // Bounded count-down (≤ PEEK steps), not a traversal.\n  while (peek > CARD_STACK_LAYOUT.PEEK_MIN && projectedEdge(peek, w, tier) > room) peek--\n\n  return peek\n}\n\n/**\n * Measures the deck region and publishes the card box + tier: the card\n * width is the tier's CARD_SHARE of the deck width, capped so its height\n * (width × CARD_H_RATIO) stays inside HEIGHT_SHARE of the stage height —\n * the deck's own box, clamped to the stage budget the VIEWPORT actually\n * leaves it: the section is min-height 100dvh, so when the chrome (title\n * header, info column, foot) needs more than the window the section\n * overflows and the deck's measured height lies about the room available.\n * The stage budget subtracts the space above and below the deck inside\n * the section from the viewport, so the card shrinks on short windows\n * instead of holding a constant height while the page scrolls.\n * Pre-paint/hidden contexts report zero rects → the viewport width\n * stands in for the deck width and the height cap is skipped.\n * @param host The CardStack element.\n */\nexport function measure(host: CardStack): void {\n  const deck = host.$(CARD_STACK_SELECTORS.CARD_STACK_DECK)\n\n  const rect = deck ? deck.getBoundingClientRect() : null\n\n  const vw = viewportWidth() || CARD_STACK_LAYOUT.CARD_W_FALLBACK\n\n  const vh = viewportHeight()\n\n  const tier = pickTier(vw, vh)\n\n  const deckW = rect?.width || vw\n\n  let deckH = rect?.height || 0\n\n  // Carried-over outputs for the unmeasurable branch — the signature\n  // compares against the values the last pass published, so a hidden\n  // deck holds its previous stage budget instead of collapsing to 0.\n  let stageH = host._stageH\n\n  let autoStage = host._autoStage\n\n  if (deck && rect?.height) {\n    const section = host.$(CARD_STACK_SELECTORS.CARD_STACK)\n\n    const secRect = section ? section.getBoundingClientRect() : null\n\n    if (secRect) {\n      const style = getComputedStyle(section as HTMLElement)\n\n      const headerEl = (section as HTMLElement).querySelector(\n        CARD_STACK_SELECTORS.CARD_STACK_HEADER\n      )\n\n      const footEl = (section as HTMLElement).querySelector(CARD_STACK_SELECTORS.CARD_STACK_FOOT)\n\n      const boxH = (el: Element | null) => (el ? el.getBoundingClientRect().height : 0)\n\n      const marginsOf = (el: Element | null) => {\n        if (!el) return 0\n\n        const s = getComputedStyle(el as HTMLElement)\n\n        return (parseFloat(s.marginTop) || 0) + (parseFloat(s.marginBottom) || 0)\n      }\n\n      // Fixed chrome only — the section's vertical padding plus the\n      // header and foot rows (with margins). Edge deltas can't be used\n      // here: the one-column grid aligns its rows `space-evenly`, so\n      // the slack around the deck lands inside those deltas and the\n      // budget would collapse to the deck's own measured height — a\n      // ratchet that only ever shrinks. The slack is the very space\n      // the pile may grow into, so it must NOT count as chrome. On the\n      // ≥1280 side-by-side grid (rows auto / minmax(0,1fr) / auto) the\n      // slack already lives inside the deck's own track, and this same\n      // fixed-chrome sum resolves identically.\n      const chromeH =\n        (parseFloat(style.paddingTop) || 0) +\n        (parseFloat(style.paddingBottom) || 0) +\n        boxH(headerEl) +\n        marginsOf(headerEl) +\n        boxH(footEl) +\n        marginsOf(footEl)\n\n      // The raw viewport allotment — fitDeckToFront's stage cap. Kept\n      // apart from deckH (which clamps to it): the band's cap must read\n      // the budget itself, not the deck's own current height, or a\n      // band measured mid-overflow locks the cap to the wrong figure.\n      stageH = Math.max(0, vh - chromeH)\n\n      // Whether the section is content-sized (the ≥3840 rung drops the\n      // 100dvh floor → min-height computes to 0/auto, both parse falsy):\n      // the deck row then has no 1fr allotment and fitDeckToFront must\n      // publish the fan's band itself instead of riding the row's.\n      autoStage = !(parseFloat(style.minHeight) > 0)\n\n      deckH = Math.min(deckH, stageH)\n    }\n  }\n\n  const byWidth = deckW * tier.CARD_SHARE\n\n  const heightRoom = stageH || deckH\n\n  const byHeight = heightRoom ? (heightRoom * tier.HEIGHT_SHARE) / tier.CARD_H_RATIO : byWidth\n\n  // The card's height-derived width input differs per layout contract:\n  // the fan tiers' 1fr deck row IS the allotment, so the measured deck\n  // height is the honest bound; the stacked tiers' deck row is\n  // auto-height — its measurement is the band the LAST card size\n  // produced, which feeds back as a sticky ratchet that can only\n  // shrink. There the bound is the stage budget itself (the viewport\n  // allotment after fixed chrome): the pile may grow into the\n  // space-evenly slack until the band hits the cap.\n  // Every tier reads the stage BUDGET (viewport minus fixed chrome), not\n  // the deck row's live measurement: under the ≥3840 content-height\n  // section the deck row IS the published card band, so measuring it\n  // would feed the last card size back as a shrink-only ratchet. With\n  // min-height:100dvh the 1fr row resolves to the same number anyway —\n  // this only decouples the cap from the layout mode — read off the\n  // `heightRoom` local computed above.\n\n  // Copy-carrying stacked tiers size by width alone — the front card\n  // auto-grows to its copy (height:auto in applyPoses) and the deck row\n  // follows via fitDeckToFront's min-height, so the page scrolls\n  // instead of crushing the card into the stage's leftover height. The\n  // image-only stacked band (1024–1279 landscape) and the fan tiers\n  // keep the height cap — no copy ever grows those cards, so the pile\n  // must fit the bounded side-by-side stage and never push its bottom\n  // edge past the section's clip boundary.\n  const cardW = Math.min(\n    Math.max(\n      tier.STACKED && tier.IN_CARD_INFO ? byWidth : Math.min(byWidth, byHeight),\n      CARD_STACK_LAYOUT.CARD_W_MIN\n    ),\n    CARD_STACK_LAYOUT.CARD_W_MAX\n  )\n\n  // Autoplay is fan-tier only — a resize into a stacked layout kills a\n  // running countdown (stopAutoplay no-ops when nothing is armed).\n  if (tier.STACKED) stopAutoplay(host)\n\n  // The fan's peek is width-fitted to the deck edges; the stacked pile's\n  // depth window is the tier's authored count (the cascade's own offsets\n  // — not a horizontal fit — decide what peeks out).\n  const peek = tier.STACKED ? tier.PEEK : fitPeek(deckW, cardW, tier)\n\n  // Signature gate — every independent output (tier camera, card width,\n  // stage budget, deck rect, content-stage flag) joins into one key;\n  // an unchanged key means the delivery that triggered this measure\n  // observed no real resize, so the publishes below are skipped: an\n  // RO notification whose only cause was our own min-height write or\n  // a sub-pixel jitter ends here instead of reposing the whole pile.\n  const sig = `${CARD_STACK_TIERS.indexOf(tier)}|${cardW}|${deckW}|${deckH}|${stageH}|${autoStage}`\n\n  if (_measureSig.get(host) === sig) return\n\n  _measureSig.set(host, sig)\n\n  host._cardW = cardW\n\n  host._cardH = cardW * tier.CARD_H_RATIO\n\n  host._step = cardW * tier.FIRST_STEP\n\n  host._tier = tier\n\n  host._peek = peek\n\n  host._deckW = deckW\n\n  host._deckH = deckH\n\n  host._stageH = stageH\n\n  host._autoStage = autoStage\n}\n\n/** Zero-padded counter/index number — \"01\", \"08\" — shared by the deck\n *  counter and the index rows. */\nexport function padNum(n: number): string {\n  return `${n}`.padStart(CARD_STACK_LAYOUT.PAD, CHAR_STRINGS.ZERO)\n}\n\n/**\n * Writes every card's pose for the current virtual front `f` — derived\n * from `activeIdx - _dragX/_step`, so a live drag slides the whole\n * coverflow continuously and `activeIdx` alone reproduces the rest pose.\n * Every DOM write is value-guarded: card box properties and the deck\n * perspective (the tier's camera distance) compare against the current\n * inline value before touching it, and a card whose whole pose\n * signature matched the last pass is skipped outright — re-delivered\n * observer passes cost compares, not relayouts. Runs inside the\n * gesture rAF — reads are cached fields and inline-style values.\n * @param host The CardStack element.\n */\nexport function applyPoses(host: CardStack): void {\n  // The print adapter strips inline styles for the snapshot — a rAF/RO\n  // pose write landing mid-job would scatter the flattened mosaic back\n  // into fan geometry on paper.\n  if (host._printing) return\n\n  const items = host.deckItems\n\n  const len = items.length\n\n  if (!len) return\n\n  const w = host._cardW\n\n  const h = host._cardH\n\n  const tier = host._tier\n\n  const cards = host._cardEls\n\n  // Live drag — the f fraction freezes on the committed front: the\n  // pressed card tracks the finger in px below, and only the incoming\n  // neighbour walks its slot→front pose (progress of a card-width\n  // pull). The old continuous f moved the WHOLE stack through pose\n  // space at _step per step — on the 0.4·w stacked tier one hold\n  // dealt through 2–3 cards under the finger (the \"changes 1, 2, 3\n  // slides\" report) and a cancel slammed them all back.\n  const dragging = host._dragActive\n\n  const f = dragging ? host.activeIdx : host.activeIdx - host._dragX / host._step\n\n  const progress = dragging ? Math.min(Math.abs(host._dragX) / Math.max(w, 1), 1) : 0\n\n  const dragDir = host._dragX < 0 ? 1 : -1\n\n  const incoming = len > 1 ? (host.activeIdx + dragDir + len) % len : -1\n\n  // The uniform stacked box — the tallest card's natural height folded\n  // over the ratio box. EVERY stacked card gets it: the pile's sheets\n  // are identical, so only the thin stair offsets peek out instead of a\n  // near-full second image spilling below the front card's bottom edge\n  // — and no card's border-box can ever move mid-gesture or per nav.\n  const pileH = h + host._frontExtra\n\n  // Fresh-node batch — elements that have never been posed collect\n  // here so a single post-loop flush commits all their baselines at\n  // once. Allocated lazily: mount/re-render passes only, never per\n  // gesture frame (zero-allocation frame-loop rule).\n  let fresh: HTMLElement[] | null = null\n\n  for (let i = 0; i < cards.length; i++) {\n    const el = cards[i] as HTMLElement\n\n    // The incoming neighbour is the only stack card that moves during a\n    // drag — its slot→front pose rides the travel fraction so the card\n    // visibly enters accompanying the swipe instead of teleporting in\n    // on release; every other card holds its integer slot.\n    let s = ringSigned(i - f, len)\n\n    if (dragging && i === incoming) s = dragDir * (1 - progress)\n\n    const pose = tierPose(tier, s, len, w, pileH, host._peek)\n\n    // The pressed card rides the finger 1:1 in px — not pose space —\n    // so the card under the touch can never run ahead of or lag behind\n    // the pointer, and the stack's single-card boundary holds no matter\n    // how far the drag travels.\n    if (dragging && i === host.activeIdx) pose.x += host._dragX\n\n    // A right-swipe on the stacked tiers un-stacks the parked card:\n    // give it an extra card-width of travel so it sweeps in from off\n    // the parked edge instead of fading in place under the departing\n    // card, and let it materialize as it travels — the parked-dim scrub\n    // alone starts at 0.45 and reads as a pop when the card enters the\n    // visible band. Mirrored tiers sweep from their own parked side.\n    if (dragging && i === incoming && tier.STACKED && dragDir < 0) {\n      pose.x -= Math.sign(tier.PARK_X) * (1 - progress) * w\n\n      pose.opacity *= progress\n    }\n\n    const wasVisible = _wasVisible.get(el)\n\n    _wasVisible.set(el, pose.visible)\n\n    // First pose per element — a never-posed node has no \"before\" to\n    // animate from. Mount and re-render insert cards whose only resolved\n    // style is transform:none (measure()'s forced rect read resolves\n    // them before this write), so without suppression the stylesheet's\n    // 0.52s transform transition flies every card in from the deck\n    // centre on load — the mount flicker. The write lands instantly;\n    // the post-loop flush commits it as the baseline before the CSS\n    // transition returns.\n    if (wasVisible === undefined) {\n      el.style.transition = ATTR_VALUES.NONE\n\n      ;(fresh ??= []).push(el)\n    }\n\n    // Card box — the FINAL layout value for this tier, each property\n    // guarded against its current inline value so a pass that\n    // re-derives identical geometry never invalidates layout. Every\n    // stacked card gets the SAME box: pileH is the tallest card's\n    // natural height (fitDeckToFront's max-over-cards measure — never\n    // truncate, always fit), so nothing resizes under the finger, on\n    // nav, or when a class flips — the border-box is invariant.\n    const wantW = `${w}${COMMON_ATTRS.PX}`\n\n    const wantH = `${tier.STACKED ? pileH : h}${COMMON_ATTRS.PX}`\n\n    const wantMin = tier.STACKED ? `${pileH}${COMMON_ATTRS.PX}` : ATTR_VALUES.EMPTY\n\n    if (el.style.width !== wantW) el.style.width = wantW\n\n    if (el.style.height !== wantH) el.style.height = wantH\n\n    if (el.style.minHeight !== wantMin) el.style.minHeight = wantMin\n\n    // Centre-anchored: the card's own centre sits on the deck centre —\n    // the perspective origin — so translate3d + the fan's rotateY (and\n    // the stack cascade's rotateZ) pivot it in place and the\n    // perspective divide scales it toward that point. The stacked pile\n    // shares the front card's LIVE height (pileH above), so plain\n    // centering keeps every card's top edge on the same line — the\n    // pile never bleeds into the header when the front is capped, and\n    // only the authored stair offsets peek past its edges. Stacked\n    // tiers write a FLAT pose — translateZ under a `perspective` deck\n    // pushes every card through WebKit's 3D compositing path, the\n    // layer-graph family that jetsam-kills iOS tabs under a pile of\n    // textured sheets; the pile still staggers on x/y/rotZ.\n    const wantT = tier.STACKED\n      ? `translate(-50%, -50%) translate3d(${pose.x}${COMMON_ATTRS.PX}, ${pose.y}${COMMON_ATTRS.PX}, 0) rotate(${pose.rotZ}deg) scale(${pose.scale})`\n      : `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})`\n\n    // Opacity writes the pose value for visible cards and the hidden\n    // floor — the entering seed's 0→1 and the leaving card's 1→0\n    // dissolve both ride the stylesheet's opacity transition; the\n    // stacked parked branch scrubs its dim with the drag fraction.\n    const wantO = pose.visible ? `${pose.opacity}` : CHAR_STRINGS.ZERO\n\n    const wantZ = `${pose.z}`\n\n    const wantV = pose.visible ? ATTR_VALUES.VISIBLE : ATTR_VALUES.HIDDEN\n\n    // While a drag is live the held card keeps --active outright — the\n    // incoming neighbour's s dips inside FRONT_EPS past half-travel and\n    // two active cards would double-render the info column.\n    const wantA = dragging\n      ? i === host.activeIdx\n      : pose.visible && Math.abs(s) < CARD_STACK_LAYOUT.FRONT_EPS\n\n    // Signature gate — an applyPoses re-delivery whose every output\n    // matches the last write skips the whole card's DOM surface: the\n    // compare is one string read + a WeakMap hit against ~N writes.\n    // The `!el.style.transform` probe self-heals stripped nodes (the\n    // print snapshot clears inline styles — a cache hit alone would\n    // leave them bare since poses re-derive to the same signature).\n    const sig = `${wantT}|${wantO}|${wantZ}|${wantV}|${wantA}`\n\n    if (_poseSig.get(el) === sig && el.style.transform) continue\n\n    _poseSig.set(el, sig)\n\n    // A card entering the fan seeds below its slot, transparent, with\n    // transitions off for that one write — restoring them lets the base\n    // transition carry it up into place while it fades in (the deck's\n    // wrap-around \"rise + fade\" the boundary nav relies on). A card\n    // leaving the fan simply writes opacity 0 + --hidden, and its\n    // opacity/visibility transition dissolves it in place.\n    if (pose.visible && wasVisible === false && !tier.STACKED) {\n      el.style.transition = ATTR_VALUES.NONE\n\n      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})`\n\n      el.style.opacity = CHAR_STRINGS.ZERO\n\n      el.style.visibility = ATTR_VALUES.VISIBLE\n\n      el.style.zIndex = wantZ\n\n      void flushLayout(el)\n\n      el.style.transition = ATTR_VALUES.EMPTY\n    }\n\n    if (el.style.transform !== wantT) el.style.transform = wantT\n\n    if (el.style.opacity !== wantO) el.style.opacity = wantO\n\n    if (el.style.zIndex !== wantZ) el.style.zIndex = wantZ\n\n    if (el.style.visibility !== wantV) el.style.visibility = wantV\n\n    if (el.classList.contains(CARD_STACK_CLASSES.CARD_STACK_CARD_HIDDEN) === pose.visible) {\n      el.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_CARD_HIDDEN, !pose.visible)\n    }\n\n    if (el.classList.contains(CARD_STACK_CLASSES.CARD_STACK_CARD_ACTIVE) !== wantA) {\n      el.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_CARD_ACTIVE, wantA)\n    }\n  }\n\n  if (host._deckEl) {\n    // Stacked tiers get no camera — a `perspective` deck would re-enter\n    // the 3D compositing path the flattened poses just left. The write\n    // is value-guarded like the cards': a converged camera doesn't\n    // re-invalidate the deck's compositing state per pass.\n    const wantP = tier.STACKED ? ATTR_VALUES.NONE : `${tier.PERSPECTIVE * w}${COMMON_ATTRS.PX}`\n\n    if ((host._deckEl as HTMLElement).style.perspective !== wantP) {\n      ;(host._deckEl as HTMLElement).style.perspective = wantP\n    }\n  }\n\n  if (fresh) {\n    // One style resolution commits every fresh card's pose as its\n    // transition baseline — per-card flushes inside the loop resolve\n    // globally anyway, so a single read covers the batch (one reflow,\n    // not N). Restoring the stylesheet transition after the commit\n    // keeps later pose writes animating normally.\n    void flushLayout(fresh[0] as HTMLElement)\n\n    for (const el of fresh) el.style.transition = ATTR_VALUES.EMPTY\n  }\n}\n\n/**\n * Refreshes the non-pose chrome after a nav — the \"PROJECT 01 OF 08\"\n * counter (projectLabel + ofLabel, both localized), the dot --active\n * flags, each card's aria-hidden/tabindex so off-front cards leave the\n * tab order and AT tree, and the text column's copy for the new front.\n * @param host The CardStack element.\n */\nexport function updateChrome(host: CardStack): void {\n  const len = host.deckItems.length\n\n  if (!len) return\n\n  const navIndex = host.$(CARD_STACK_SELECTORS.CARD_STACK_NAV_INDEX) as HTMLElement | null\n\n  if (navIndex) {\n    const n = host.activeIdx + 1\n\n    const num = navIndex.querySelector(CARD_STACK_SELECTORS.CARD_STACK_NAV_INDEX_NUM)\n\n    // The \"1 / 13\" position rides beside the stack glyph; the button's\n    // accessible name must contain that same visible text (WCAG 2.5.3 —\n    // label-content-name-mismatch), so the label mirrors the number\n    // format rather than the \"of N\" word form.\n    if (num) {\n      num.textContent = `${n}${CHAR_STRINGS.SPACE_CHAR}${CHAR_STRINGS.SLASH}${CHAR_STRINGS.SPACE_CHAR}${len}`\n    }\n\n    navIndex.setAttribute(\n      ARIA_ATTRS.ARIA_LABEL,\n      `${host._t.projectLabel} ${n} ${CHAR_STRINGS.SLASH} ${len}`\n    )\n\n    dealNavIndex(host, navIndex)\n  }\n\n  const dots = host.$$(CARD_STACK_SELECTORS.CARD_STACK_DOT)\n\n  dots.forEach((dot, i) => {\n    dot.classList.toggle(CARD_STACK_CLASSES.CARD_STACK_DOT_ACTIVE, i === host.activeIdx)\n  })\n\n  host._cardEls.forEach((card, i) => {\n    const front = i === host.activeIdx\n\n    card.setAttribute(ARIA_ATTRS.ARIA_HIDDEN, front ? ATTR_VALUES.FALSE : ATTR_VALUES.TRUE)\n\n    const link = card.querySelector(HTML_TAGS.A)\n\n    ;(link as HTMLElement | null)?.setAttribute(\n      ARIA_ATTRS.TABINDEX,\n      front ? ATTR_VALUES.TABINDEX_ZERO : ATTR_VALUES.NEGATIVE_TABINDEX\n    )\n  })\n\n  // Settle _frontExtra + the pile's height writes BEFORE writeInfo\n  // mounts the in-card burns — a stale delta (the outgoing front's own\n  // grown extra) otherwise survives into the arm-time measure and the\n  // burn canvas anchors to a box the settled layout never had, which\n  // reads as the burning title jumping once the fit rewrites heights.\n  fitDeckToFront(host)\n\n  writeInfo(host)\n}\n\n/** Last chromed index per host — the nav-index deal animation's\n *  direction cue (a mount's first pass has no previous front). */\nconst _chromeIdx = new WeakMap<CardStack, number>()\n\n/**\n * Deals the nav-index stack glyph after a front change — the top card\n * of the icon flings in the nav direction (forward on next, backward\n * on prev, ring-normalized so wrap-around navs read correctly) and\n * slides back under the pile, echoing the deck's own card exchange.\n * The class re-arms through a frame-boundary remove → rAF add pair so\n * a mid-animation nav restarts the keyframe without a forced reflow.\n * @param host The CardStack element.\n * @param navIndex The nav-index button carrying the glyph.\n */\nfunction dealNavIndex(host: CardStack, navIndex: HTMLElement): void {\n  const len = host.deckItems.length\n\n  const prev = _chromeIdx.get(host)\n\n  _chromeIdx.set(host, host.activeIdx)\n\n  if (prev === undefined || prev === host.activeIdx || len <= 1) return\n\n  const delta = host.activeIdx - prev\n\n  const fwd = delta > 0 ? delta <= len / 2 : delta < -len / 2\n\n  navIndex.classList.remove(\n    CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_NEXT,\n    CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_PREV\n  )\n\n  requestAnimationFrame(() => {\n    navIndex.classList.add(\n      fwd\n        ? CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_NEXT\n        : CARD_STACK_CLASSES.CARD_STACK_NAV_INDEX_DEAL_PREV\n    )\n  })\n}\n\n/**\n * Re-fits the stacked deck's height to the TALLEST card's natural box —\n * never truncate, always fit: applyPoses gives every stacked card the\n * same pileH (ratio height + _frontExtra), and the measured max delta\n * parks as _frontExtra so a copy-heavy description sizes the WHOLE\n * pile, not just the card carrying it. Card border-boxes are then\n * invariant under gestures, navs, and class flips — the page absorbs\n * the overflow. The front card's ResizeObserver re-runs the fit when\n * fonts/locale/typewriter change the copy after mount. Fan tiers just\n * clear the artifact. One layout read per nav/mount — same class as\n * measure(), never per-frame.\n * @param host The CardStack element.\n */\nexport function fitDeckToFront(host: CardStack): void {\n  // Print pass — the flattened sheet's copy reflow fires this observer;\n  // its min-height write would re-pose the deck mid-snapshot just like\n  // an applyPoses call. A live drag owns the pile too — a mid-gesture\n  // re-anchor would rewrite every card's border-box under the finger.\n  if (host._printing || host._dragActive) return\n\n  const deck = host._deckEl as HTMLElement | null\n\n  if (!host._tier?.STACKED) {\n    host._frontExtra = 0\n\n    if (deck) {\n      // Fan tiers ride the 1fr row's allotment under min-height:100dvh —\n      // the absolute cards contribute no flow height, so a content-sized\n      // section (the ≥3840 rung) would collapse the row to ~0. There the\n      // band is authored: the scaled front card's extent plus its\n      // negative FAN_LIFT clearance (cards park -40px above centre).\n      // Value-guarded: an unchanged band never re-invalidates the deck —\n      // a same-value write still feeds the observer that called us.\n      const band =\n        host._autoStage && host._cardH\n          ? `${\n              host._cardH * CARD_STACK_LAYOUT.FRONT_SCALE - CARD_STACK_LAYOUT.FAN_LIFT * 2\n            }${COMMON_ATTRS.PX}`\n          : ATTR_VALUES.EMPTY\n\n      if (deck.style.minHeight !== band) deck.style.minHeight = band\n    }\n\n    return\n  }\n\n  const front = host._cardEls[host.activeIdx] as HTMLElement | undefined\n\n  if (!front) return\n\n  // Image-only stacked tiers (the 1024–1279 landscape pile) have no\n  // copy that can grow — every card keeps the ratio box, so the live\n  // measure is skipped entirely. getBoundingClientRect includes the\n  // running transform/scale, and a mid-transition read feeds back into\n  // pileH via _frontExtra: the whole pile would visibly compress and\n  // re-expand on every nav. _frontExtra pins at 0 and the deck band is\n  // the fixed ratio height + pad — identical geometry on every card.\n  if (!host._tier.IN_CARD_INFO) {\n    if (host._fitRO) {\n      host._fitRO.disconnect()\n\n      host._fitFront = null\n    }\n\n    host._frontExtra = 0\n\n    if (deck) {\n      const band = `${host._cardH + host._cardH * CARD_STACK_LAYOUT.STACKED_DECK_PAD}${COMMON_ATTRS.PX}`\n\n      if (deck.style.minHeight !== band) deck.style.minHeight = band\n    }\n\n    return\n  }\n\n  if (host._fitFront !== front) {\n    host._fitRO?.disconnect()\n\n    if (typeof ResizeObserver !== TYPE_STRINGS.UNDEFINED) {\n      // RO notifications are pre-paint: writing sizes back inside the\n      // same notification turn resizes observed boxes and the browser\n      // reports \"ResizeObserver loop completed with undelivered\n      // notifications\". Worse, the description typewriter grows the\n      // watched info column EVERY FRAME, so a same-frame fit would\n      // write deck min-height + re-pose the pile per type tick — the\n      // production RO-loop errors and the mid-animation relayout\n      // storm. Debouncing to the settle point keeps the notification\n      // turn write-free (the loop detector stays quiet) and lands one\n      // fit per growth burst instead of one per frame.\n      host._fitRO ??= new ResizeObserver(() => {\n        if (host._fitTimer) clearTimeout(host._fitTimer)\n\n        host._fitTimer = setTimeout(() => {\n          host._fitTimer = 0\n\n          fitDeckToFront(host)\n        }, CARD_STACK_LAYOUT.FIT_SETTLE_MS)\n      })\n\n      host._fitRO.observe(front)\n\n      // The in-card summary is plain text — nothing inside the pile\n      // types or grows — but a late font swap can still re-wrap the\n      // copy, so the card, link, info column, and desc stay watched:\n      // one settled re-fit absorbs the font-load delta.\n      const linkEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_LINK)\n\n      if (linkEl) host._fitRO.observe(linkEl)\n\n      const infoEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_INFO)\n\n      if (infoEl) host._fitRO.observe(infoEl)\n\n      const descEl = front.querySelector(CARD_STACK_SELECTORS.CARD_STACK_CARD_INFO_DESC)\n\n      if (descEl) host._fitRO.observe(descEl)\n    }\n\n    host._fitFront = front\n  }\n\n  // Uniform pile height — never truncate, always fit: the biggest\n  // description in the deck sets EVERY card's box, so all stacked\n  // cards are identical and a border-box can never change under the\n  // finger or between navs. Measure all cards' natural heights in one\n  // batch: every height:auto + min-height:0 write lands first (style\n  // mutations don't reflow until a read), then the offsetHeight loop\n  // forces a single layout — one reflow for the whole pile. The floor\n  // MUST clear too: a live pileH min-height feeds the card's own\n  // padding+border back into the measure (+2px every pass = the\n  // infinite-growth ratchet), and the link's min-height:inherit\n  // compounds it. offsetHeight is the layout border box, so the\n  // running pose transform can't contaminate the read the way\n  // getBoundingClientRect would.\n  for (const el of host._cardEls) {\n    const st = (el as HTMLElement).style\n\n    st.height = ATTR_VALUES.AUTO\n    st.minHeight = ATTR_VALUES.EMPTY\n  }\n\n  let realH = host._cardH\n\n  for (const el of host._cardEls) {\n    realH = Math.max(realH, (el as HTMLElement).offsetHeight)\n  }\n\n  // Content-driven height — the pile NEVER caps at the stage budget:\n  // the tallest copy sizes every card's box outright and the deck band\n  // grows to match, so a copy-heavy card simply pushes the pile +\n  // controls past the fold and the PAGE scrolls. _stageH stays as\n  // measure()'s width bound for the image-only band — it no longer\n  // clamps any card's height.\n  const grow = realH - host._cardH\n\n  const anchor = grow\n\n  if (deck) {\n    const band = `${host._cardH + grow + host._cardH * CARD_STACK_LAYOUT.STACKED_DECK_PAD}${COMMON_ATTRS.PX}`\n\n    // Value-guarded — the RO-loop fix: this write resizes the observed\n    // deck, so re-landing an identical band re-fires _deckRO for\n    // nothing. Only a real delta may touch the DOM.\n    if (deck.style.minHeight !== band) deck.style.minHeight = band\n  }\n\n  host._frontExtra = anchor\n\n  // pileH (and every stacked card's height write) rides the delta —\n  // and the measure's height:auto toggles must be restored on EVERY\n  // pass, not just when the anchor moved. applyPoses is value-guarded,\n  // so an identical pose re-derivation costs compares, not relayouts.\n  applyPoses(host)\n}\n","breadcrumbs":[{"name":"Website Module","path":"/docs/website"},{"name":"components","path":"/docs/website/components"},{"name":"home","path":"/docs/website/components/home"},{"name":"cardstack","path":"/docs/website/components/home/cardstack"}]},"policy":{"ai-train":"yes","search":"yes","ai-input":"yes"},"generator":"generate-llm-pages.mjs","generated":"2026-11-19T15:46:51.755Z"}
