{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "deck",
  "title": "Deck",
  "description": "A stack of cards as a ui-sdk primitive, the Carousel's deck: the top card follows a drag and is thrown off by its speed, Previous brings the last one back, and an agent pages it with the Carousel's actions.",
  "dependencies": [
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/resize.json"
  ],
  "files": [
    {
      "path": "registry/lib/deck.ts",
      "content": "import { withoutTransition } from '@/registry/lib/resize'\nimport {\n  bindDrag,\n  type ChangeDetails,\n  createChange,\n  createRovingFocus,\n  definePrimitive,\n  elements,\n  isRTL,\n} from '@ui-sdk/core'\nimport type { CarouselPageChangeReason } from '@ui-sdk/core/carousel'\nimport { createVelocityTracker } from '@ui-sdk/core/gesture'\n\n/*\n * A stack of cards that shows one at a time, the Carousel's deck: the top\n * card follows a drag and tilts with it, and let go far or fast enough it is\n * thrown off and goes under the stack while the rest step up. Previous\n * brings the last card back from the side it left. It always loops. Its\n * page, from 1, is the top card, with the Carousel's names and reasons, so a\n * Carousel passes the same props to its track or its deck, and an agent\n * pages either the same way.\n */\n\n/** Why the top card changed: the Carousel's reasons that a deck has. */\ntype DeckPageChangeReason = Extract<\n  CarouselPageChangeReason,\n  | 'previous-press'\n  | 'next-press'\n  | 'item-press'\n  | 'list-navigation'\n  | 'swipe'\n  | 'content-resize'\n  | 'imperative'\n>\n\ntype DeckPageOptions = { reason?: DeckPageChangeReason; event?: Event }\n\ntype DeckOptions = {\n  /** The card on top, from 1. Pass it to control the deck. */\n  page?: number\n  defaultPage?: number\n  onPageChange?: (page: number, details: ChangeDetails<DeckPageChangeReason>) => void\n}\n\n/** How far a card is dragged, as a share of its width, before letting go throws it. */\nconst THROW_SHARE = 0.35\n\n/** How far a thrown card goes on from where it was let go, as a share of its width: `--carousel-slide`'s default. */\nconst SLIDE_SHARE = 0.6\n\n/** How far a press moves before it is a drag, in pixels, so a page still scrolls under a finger that moves up or down. */\nconst DRAG_SLOP = 6\n\n/** A flick at least this fast, in px/ms, the way it was dragged, throws the card however far it went. */\nconst FLICK_VELOCITY = 0.5\n\n/** How long a thrown card takes to go, in milliseconds, at its fastest and slowest, and the shortest share of its role that leaves. */\nconst MIN_THROW_MS = 80\nconst MAX_THROW_MS = 360\nconst MIN_STRENGTH = 0.1\n\n/** Arrow keys belong to these, inside a card: a field's caret, a list's own keys. */\nconst KEEPS_ARROWS =\n  'input, textarea, select, [contenteditable]:not([contenteditable=\"false\"]), [role=\"slider\"], [role=\"spinbutton\"], [role=\"listbox\"], [role=\"grid\"], [role=\"tablist\"], [role=\"menu\"], [role=\"menubar\"], [role=\"radiogroup\"], [role=\"tree\"], [role=\"toolbar\"]'\n\nconst FOCUSABLE =\n  'a[href], button:not([disabled]), input, select, textarea, [tabindex]:not([tabindex=\"-1\"])'\n\n/** How far a card is under the top one: 0 on top, wrapping round. `index` counts from 0, `page` from 1. */\nfunction deckDepth(index: number, page: number, count: number) {\n  return count > 0 ? (((index - (page - 1)) % count) + count) % count : index\n}\n\n/** The page `page` asks for, round the deck's `count` cards. */\nfunction wrapPage(page: number, count: number) {\n  const n = Math.max(1, count)\n  return ((((page - 1) % n) + n) % n) + 1\n}\n\n/** Whether a card let go `dx` pixels along, at `velocity` px/ms, is thrown off: dragged far enough, or flicked the way it went. */\nfunction throws(dx: number, velocity: number, width: number) {\n  const flicked =\n    Math.abs(velocity) >= FLICK_VELOCITY && Math.sign(velocity) === Math.sign(dx)\n  return flicked || Math.abs(dx) >= width * THROW_SHARE\n}\n\n/**\n * How much of its role's duration a throw takes, from 0.1 to 1, as\n * `--carousel-swipe-strength`: `remaining` pixels to go at `velocity` px/ms.\n * A slow release takes the whole role, so a press and a drag let go feel\n * the same, and only a flick is quicker.\n */\nfunction throwStrength(remaining: number, velocity: number) {\n  const speed = Math.abs(velocity)\n  if (speed <= 0.2 || remaining <= 0) return 1\n  const ms = Math.max(\n    MIN_THROW_MS,\n    Math.min(MAX_THROW_MS, remaining / Math.min(speed, 4)),\n  )\n  return (\n    MIN_STRENGTH +\n    ((ms - MIN_THROW_MS) / (MAX_THROW_MS - MIN_THROW_MS)) * (1 - MIN_STRENGTH)\n  )\n}\n\n/** Which page an arrow, Home or End takes the deck to from `page`, or null for a key it doesn't take. Left and right swap in right to left. */\nfunction keyPage(key: string, page: number, count: number, rtl: boolean) {\n  const forward = rtl ? 'ArrowLeft' : 'ArrowRight'\n  const back = rtl ? 'ArrowRight' : 'ArrowLeft'\n  if (key === forward) return wrapPage(page + 1, count)\n  if (key === back) return wrapPage(page - 1, count)\n  if (key === 'Home') return 1\n  if (key === 'End') return count\n  return null\n}\n\nfunction cardsIn(stack: HTMLElement | null) {\n  return [...(stack?.children ?? [])].filter(\n    (child): child is HTMLElement => child instanceof HTMLElement,\n  )\n}\n\nfunction release(card: HTMLElement, root: HTMLElement | null) {\n  card.style.removeProperty('--carousel-drag-x')\n  card.style.removeProperty('--carousel-drag-share')\n  root?.style.removeProperty('--carousel-swipe-progress')\n}\n\n/**\n * The top card went from `from` to `to`: the one that was on top is thrown\n * off `way` (1 towards the end, -1 towards the start) and lands under the\n * stack, or, one back, the card brought back comes in from the side it left\n * by. Kept outside the primitive: the React Compiler drops the forced style\n * read a component would make, and then the change animates.\n */\nfunction shuffle(\n  stack: HTMLElement,\n  root: HTMLElement,\n  from: number,\n  to: number,\n  way: number | null,\n  carry: boolean,\n) {\n  const all = cardsIn(stack)\n  const count = all.length\n  const towardsStart = isRTL(stack) ? 1 : -1\n  const fromCard = all[from - 1]\n  const toCard = all[to - 1]\n  // A card still on its way off that comes straight back on top, as in a\n  // deck of two, turns back from where it is.\n  const turnedBack = Boolean(toCard?.hasAttribute('data-thrown'))\n  if (turnedBack && toCard) {\n    toCard.removeAttribute('data-thrown')\n    release(toCard, null)\n  }\n  // Focus in the card leaving the top would be lost as it goes inert: it\n  // moves into the new top card, or to the viewport, which then takes the\n  // arrow keys, or to Next.\n  // The new top card is let out of `inert` now, ahead of its attributes.\n  if (carry) {\n    if (toCard) toCard.inert = false\n    const next =\n      toCard?.querySelector<HTMLElement>(FOCUSABLE) ??\n      stack.closest<HTMLElement>('[tabindex=\"0\"]') ??\n      root.querySelector<HTMLElement>('[data-carousel-next]')\n    next?.focus({ preventScroll: true })\n  }\n  if (to === wrapPage(from - 1, count) && count > 2) {\n    // One still on its way off is already turning back from where it is.\n    if (!toCard || turnedBack) return\n    withoutTransition(toCard, () => {\n      toCard.style.setProperty('--carousel-throw', `${towardsStart}`)\n      toCard.setAttribute('data-thrown', '')\n    })\n    toCard.removeAttribute('data-thrown')\n    return\n  }\n  if (!fromCard) return\n  // A press throws it in the role's own time; only a flick shortens it.\n  if (way === null) root.style.setProperty('--carousel-swipe-strength', '1')\n  fromCard.style.setProperty('--carousel-throw', `${way ?? towardsStart}`)\n  // It leaves from where the drag let it go.\n  fromCard.setAttribute('data-thrown', '')\n  const land = (event?: TransitionEvent) => {\n    if (event && (event.target !== fromCard || event.propertyName !== 'opacity')) return\n    fromCard.removeEventListener('transitionend', land)\n    clearTimeout(timer)\n    // Brought back on top before it landed: it is already on its way back.\n    if (!fromCard.hasAttribute('data-thrown')) return\n    // It goes under the deck where it can't be seen, then fades in there.\n    withoutTransition(fromCard, () => {\n      fromCard.removeAttribute('data-thrown')\n      release(fromCard, null)\n      fromCard.style.opacity = '0'\n    })\n    fromCard.style.opacity = ''\n  }\n  fromCard.addEventListener('transitionend', land)\n  // In case it can't transition, such as while the tab is hidden.\n  const timer = setTimeout(land, 4000)\n}\n\nconst deck = definePrimitive({\n  name: 'carousel',\n  options: { page: 'number', defaultPage: 'number', onPageChange: 'callback' },\n  controlled: ['page'],\n  state: (options: DeckOptions) => ({\n    page: Math.max(1, Math.floor(options.page ?? options.defaultPage ?? 1)),\n    /** How many cards there are, or null before they are counted, as on the server. */\n    pageCount: null as number | null,\n    /** The indicator with the tab stop. */\n    stop: null as string | null,\n    dragging: false,\n  }),\n  sync: (options) => (options.page === undefined ? {} : { page: options.page }),\n  api: (context) => {\n    const { store } = context\n    const change = createChange(context)\n    const count = () => elements(context, 'item').length\n    // Which way the next throw goes: the way the card was dragged, or towards the start.\n    let way: number | null = null\n    let stop: (() => void) | undefined\n    let fitting = false\n    // Whether focus was in the top card as the page was asked to change.\n    let carry = false\n    const cardsAt = () => elements(context, 'item').map((item) => item.el)\n    context.onDestroy(() => stop?.())\n\n    const setPage = (page: number, options: DeckPageOptions = {}) => {\n      const n = count()\n      if (n === 0) return false\n      const to = Math.max(1, Math.min(n, Math.round(page)))\n      if (to === store.get().page) return false\n      // Read before the card goes inert, which drops the focus in it.\n      carry = Boolean(cardsAt()[store.get().page - 1]?.contains(document.activeElement))\n      const changed = change('page', to, {\n        reason: options.reason ?? 'imperative',\n        event: options.event,\n      })\n      if (!changed) carry = false\n      return changed\n    }\n    const step = (by: number, options: DeckPageOptions) => {\n      const n = count()\n      if (n < 2) return false\n      return setPage(wrapPage(store.get().page + by, n), options)\n    }\n    const indicatorPage = (key: string) =>\n      context.props<{ page?: number }>('indicator', key)?.page ?? 0\n\n    const roving = createRovingFocus(context, {\n      slot: 'indicator',\n      key: 'stop',\n      remember: false,\n      orientation: () => 'horizontal',\n      loop: () => true,\n      preferred: (item) => indicatorPage(item.key) === store.get().page,\n      claims: (state, item) => (item.props as { page?: number }).page === state.page,\n    })\n\n    return {\n      roving,\n      /** Shows the card at `page`, from 1, held between the first and the last. */\n      setPage,\n      /** Throws the top card off, and the next comes up; after the last, the first. */\n      next: (options: DeckPageOptions = {}) =>\n        step(1, { reason: 'imperative', ...options }),\n      /** Brings the last card thrown back on top; before the first, the last. */\n      previous: (options: DeckPageOptions = {}) =>\n        step(-1, { reason: 'imperative', ...options }),\n      internal: {\n        count,\n        indicatorPage,\n        /** Counts the cards, and moves a page past the last card onto it, as the track does. */\n        fit() {\n          store.set({ pageCount: count() })\n          // Once every card that binds with this one has: the first alone counts one.\n          if (fitting) return\n          fitting = true\n          queueMicrotask(() => {\n            fitting = false\n            const n = count()\n            store.set({ pageCount: n })\n            if (n > 0 && store.get().page > n)\n              change('page', n, { reason: 'content-resize' })\n          })\n        },\n        /** Whether the top card holds nothing to focus, so the viewport takes the arrow keys itself. */\n        bare: (page: number) => {\n          const card = elements(context, 'item')[page - 1]?.el\n          return Boolean(card && !card.querySelector(FOCUSABLE))\n        },\n        /** The id of the card at `page`, which its indicator controls. */\n        cardId: (page: number) => elements(context, 'item')[page - 1]?.el.id || undefined,\n        /** Arrow keys inside the top card page the deck, unless what has focus keeps them. */\n        keydown(event: KeyboardEvent, el: HTMLElement) {\n          if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey)\n            return\n          if (event.shiftKey) return\n          if ((event.target as Element | null)?.closest(KEEPS_ARROWS)) return\n          const n = count()\n          const to = keyPage(event.key, store.get().page, n, isRTL(el))\n          if (to === null || n < 2) return\n          event.preventDefault()\n          setPage(to, { reason: 'list-navigation', event })\n        },\n        indicatorKeydown(event: KeyboardEvent) {\n          const moved = roving.keydown(event, event.target as HTMLElement)\n          if (!moved || moved.key === moved.from) return\n          setPage(indicatorPage(moved.key), { reason: 'list-navigation', event })\n        },\n        /** A press on the top card may become a drag that throws it. */\n        press(event: PointerEvent, stack: HTMLElement) {\n          if (event.button !== 0 || !(event.target instanceof Element)) return\n          if (event.target.closest('input, textarea, select, [contenteditable]')) return\n          const card = cardsIn(stack)[store.get().page - 1]\n          if (!card?.contains(event.target) || count() < 2) return\n          const root = context.element('root') ?? null\n          const tracker = createVelocityTracker()\n          const startX = event.clientX\n          const startY = event.clientY\n          let dx = 0\n          stop?.()\n          stop = bindDrag(stack, event, {\n            threshold: DRAG_SLOP,\n            cancelOnEscape: true,\n            // A press that goes up or down more than sideways is the page's scroll.\n            onStart: (move) => {\n              if (Math.abs(move.clientY - startY) >= Math.abs(move.clientX - startX))\n                return false\n              window.getSelection()?.removeAllRanges()\n              tracker.add(event.timeStamp, startX)\n              store.set({ dragging: true })\n            },\n            onMove: ({ x, event: move }) => {\n              dx = x - startX\n              tracker.add(move.timeStamp, x)\n              const width = card.offsetWidth || 1\n              card.style.setProperty('--carousel-drag-x', `${dx}px`)\n              card.style.setProperty('--carousel-drag-share', `${dx / width}`)\n              root?.style.setProperty(\n                '--carousel-swipe-progress',\n                `${Math.min(1, Math.abs(dx) / (width * THROW_SHARE))}`,\n              )\n            },\n            onEnd: (end, canceled) => {\n              store.set({ dragging: false })\n              const width = card.offsetWidth || 1\n              const velocity = canceled ? 0 : tracker.velocity(end.timeStamp)\n              if (canceled || !throws(dx, velocity, width)) {\n                root?.style.setProperty('--carousel-swipe-strength', '1')\n                release(card, root)\n                return\n              }\n              root?.style.setProperty(\n                '--carousel-swipe-strength',\n                `${throwStrength(width * SLIDE_SHARE, velocity)}`,\n              )\n              root?.style.removeProperty('--carousel-swipe-progress')\n              way = Math.sign(dx) || (isRTL(stack) ? 1 : -1)\n              const from = store.get().page\n              step(1, { reason: 'swipe', event: end })\n              // An owner that holds the page back keeps the card: it returns.\n              requestAnimationFrame(() => {\n                if (store.get().page !== from) return\n                way = null\n                root?.style.setProperty('--carousel-swipe-strength', '1')\n                release(card, root)\n              })\n            },\n          })\n        },\n        /** Moves the cards each time the top one changes, however it changed. */\n        follow(stack: HTMLElement) {\n          let shown = store.get().page\n          return store.subscribe(() => {\n            const page = store.get().page\n            if (page === shown) return\n            const from = shown\n            shown = page\n            const root = context.element('root')\n            if (root) shuffle(stack, root, from, page, way, carry)\n            carry = false\n            way = null\n          })\n        },\n      },\n    }\n  },\n  slots: (slot) => ({\n    root: slot({\n      role: 'region',\n      state: (state) => ({ page: state.page, pageCount: state.pageCount }),\n      attrs: () => ({ 'aria-roledescription': 'carousel' }),\n    }),\n    viewport: slot({\n      attrs: (state, { api }) => ({\n        'data-dragging': state.dragging ? '' : undefined,\n        tabindex:\n          state.pageCount !== null && api.internal.bare(state.page) ? '0' : undefined,\n      }),\n      on: {\n        keydown: (event, { api, el }) => {\n          if (el) api.internal.keydown(event as KeyboardEvent, el)\n        },\n      },\n    }),\n    content: slot({\n      on: {\n        pointerdown: (event, { api, el }) => {\n          if (el) api.internal.press(event as PointerEvent, el)\n        },\n      },\n      bind: (el, { api }) => api.internal.follow(el),\n    }),\n    item: slot<{ index: number; count: number; id?: string }>({\n      role: 'group',\n      props: { index: 'number', count: 'number', id: 'id' },\n      attrs: (state, { props }) => {\n        const depth = deckDepth(props.index, state.page, props.count)\n        return {\n          id: props.id,\n          'aria-roledescription': 'slide',\n          'aria-label': `${props.index + 1} of ${props.count}`,\n          'data-top': depth === 0 ? '' : undefined,\n          // Only the top card can be read and used; the ones under it are a picture of the deck.\n          inert: depth === 0 ? undefined : '',\n          'aria-hidden': depth === 0 ? undefined : 'true',\n          style: `--carousel-depth:${Math.min(depth, 3)};--carousel-z:${props.count - depth}`,\n        }\n      },\n      bind: (_el, { api }) => {\n        api.internal.fit()\n        return () => api.internal.fit()\n      },\n    }),\n    previous: slot({\n      attrs: (state) => {\n        const off = state.pageCount !== null && state.pageCount < 2\n        return {\n          type: 'button',\n          'aria-disabled': off ? 'true' : undefined,\n          'data-disabled': off ? '' : undefined,\n        }\n      },\n      press: ({ api }, event) => {\n        api.previous({ reason: 'previous-press', event })\n      },\n    }),\n    next: slot({\n      attrs: (state) => {\n        const off = state.pageCount !== null && state.pageCount < 2\n        return {\n          type: 'button',\n          'aria-disabled': off ? 'true' : undefined,\n          'data-disabled': off ? '' : undefined,\n        }\n      },\n      press: ({ api }, event) => {\n        api.next({ reason: 'next-press', event })\n      },\n    }),\n    'indicator-group': slot({\n      role: 'tablist',\n      keys: ['ArrowLeft', 'ArrowRight', 'Home', 'End'],\n      on: {\n        keydown: (event, { api }) =>\n          api.internal.indicatorKeydown(event as KeyboardEvent),\n      },\n    }),\n    indicator: slot<{ page: number; id?: string }>({\n      role: 'tab',\n      focus: 'roving',\n      props: { page: 'number', id: 'id' },\n      state: (state, { props }) => ({\n        page: props.page,\n        selected: props.page === state.page,\n      }),\n      attrs: (state, part) => ({\n        type: 'button',\n        tabindex: part.api.roving.tabIndex(state, part),\n        'aria-selected': String(part.props.page === state.page),\n        'aria-controls': part.api.internal.cardId(part.props.page),\n        'data-selected': part.props.page === state.page ? '' : undefined,\n      }),\n      press: ({ api, el, props }, event) => {\n        if (el && document.activeElement !== el) el.focus({ preventScroll: true })\n        api.setPage(props.page, { reason: 'item-press', event })\n      },\n      bind: (el, part) => part.api.roving.bind(el, part),\n    }),\n  }),\n  agent: { actions: ['setPage', 'next', 'previous'] },\n})\n\nexport { deck, deckDepth, keyPage, throwStrength, throws, wrapPage }\nexport type { DeckOptions, DeckPageChangeReason, DeckPageOptions }\n",
      "type": "registry:lib",
      "target": "@lib/deck.ts"
    }
  ],
  "type": "registry:lib"
}