{
  "$schema": "https://shadcn-svelte.com/schema/registry-item.json",
  "name": "dual-wave",
  "title": "DualWave",
  "type": "registry:ui",
  "description": "Waves two text columns past a photo that changes as a tile mosaic or a clean cut.",
  "dependencies": [],
  "meta": {
    "kida": {
      "package": {
        "name": "@kida-ui/svelte",
        "exportName": "DualWave",
        "styleImports": [
          "@kida-ui/styles/components/dual-wave.css"
        ]
      },
      "framework": "svelte"
    }
  },
  "categories": [
    "image"
  ],
  "files": [
    {
      "content": "<script lang=\"ts\">\nimport './dual-wave.css'\nimport { type DualWaveControls, dualWave, getDualWaveMosaicRows } from './dual-wave.motion.js'\nimport { untrack } from 'svelte'\nimport type { DualWaveProps } from './dual-wave.types.js'\n\nlet {\n  items,\n  headings = ['Projects', 'Clients'],\n  layout = 'mosaic',\n  columns = 3,\n  defaultIndex = 0,\n  index = $bindable(),\n  strength,\n  response,\n  captureScroll,\n  onIndexChange,\n  element = $bindable(null),\n  'aria-label': ariaLabel,\n  'aria-describedby': describedBy,\n  tabindex = 0,\n  ...rest\n}: DualWaveProps = $props()\n\nconst toIndex = (value: number | undefined, total: number) =>\n  total && value !== undefined && Number.isFinite(value)\n    ? ((Math.round(value) % total) + total) % total\n    : 0\n\nconst helpId = $props.id()\nlet controls: DualWaveControls | null = null\nconst root = $derived(element)\nconst count = $derived(items.length)\nlet selected = $state(untrack(() => toIndex(index ?? defaultIndex, items.length)))\nconst active = $derived(count ? Math.min(selected, count - 1) : 0)\nconst current = $derived(items[active])\nconst gridColumns = $derived(\n  Number.isFinite(columns) ? Math.max(2, Math.min(5, Math.round(columns))) : 3,\n)\nconst gridRows = $derived(getDualWaveMosaicRows(gridColumns))\nconst tiles = $derived(\n  Array.from({ length: gridColumns * gridRows }, (_, tile) => ({\n    column: tile % gridColumns,\n    row: Math.floor(tile / gridColumns),\n  })),\n)\nconst restartKey = $derived(\n  JSON.stringify([\n    items.map((item) => [item.id, item.src, item.title, item.subtitle]),\n    layout,\n    gridColumns,\n  ]),\n)\nconst optionsKey = $derived(JSON.stringify([strength, response, captureScroll]))\nconst requested = $derived(index === undefined || !count ? undefined : toIndex(index, count))\n\n$effect(() => {\n  const node = root\n  void restartKey\n  if (!node) return\n  const created = untrack(() =>\n    dualWave(node, {\n      index: active,\n      strength,\n      response,\n      captureScroll,\n      onIndexChange(next) {\n        selected = next\n        index = next\n        onIndexChange?.(next)\n      },\n    }),\n  )\n  controls = created\n  return () => {\n    created.destroy()\n    if (controls === created) controls = null\n  }\n})\n\n$effect(() => {\n  void optionsKey\n  untrack(() => controls?.update({ strength, response, captureScroll }))\n})\n\n$effect(() => {\n  const next = requested\n  if (next === undefined) return\n  untrack(() => {\n    if (next !== active) controls?.select(next)\n  })\n})\n</script>\n\n<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n<section\n  {...rest}\n  bind:this={element}\n  data-kida-dual-wave=\"\"\n  data-layout={layout}\n  aria-roledescription=\"carousel\"\n  aria-label={ariaLabel ?? headings[0]}\n  aria-describedby={describedBy ?? helpId}\n  {tabindex}\n>\n  <div data-kida-dual-wave-headings=\"\" aria-hidden=\"true\">\n    <span>{headings[0]}</span>\n    <span>{headings[1]}</span>\n  </div>\n  <div data-kida-dual-wave-field=\"\">\n    <fieldset data-kida-dual-wave-column=\"title\" aria-label={headings[0]}>\n      {#each items as item, itemIndex (item.id)}\n        <button\n          type=\"button\"\n          data-kida-dual-wave-item=\"\"\n          aria-label={`Show ${item.title}, ${item.subtitle}`}\n          aria-current={itemIndex === active ? 'true' : undefined}\n          tabindex={itemIndex === active ? 0 : -1}\n        >{item.title}</button>\n      {/each}\n    </fieldset>\n    <fieldset data-kida-dual-wave-column=\"subtitle\" aria-label={headings[1]}>\n      {#each items as item, itemIndex (item.id)}\n        <button\n          type=\"button\"\n          data-kida-dual-wave-item=\"\"\n          aria-label={`Show ${item.subtitle}, ${item.title}`}\n          aria-current={itemIndex === active ? 'true' : undefined}\n          tabindex={-1}\n        >{item.subtitle}</button>\n      {/each}\n    </fieldset>\n  </div>\n  <div data-kida-dual-wave-media=\"\">\n    {#if layout === 'mosaic'}\n      <div\n        data-kida-dual-wave-mosaic=\"\"\n        data-kida-dual-wave-columns={gridColumns}\n        aria-hidden=\"true\"\n        style:--kida-dual-wave-columns={gridColumns}\n        style:--kida-dual-wave-rows={gridRows}\n        style:--kida-dual-wave-initial={current ? `url(${JSON.stringify(current.src)})` : undefined}\n      >\n        {#each tiles as tile, tileIndex (tileIndex)}\n          <div\n            data-kida-dual-wave-tile=\"\"\n            style:--kida-dual-wave-column={tile.column}\n            style:--kida-dual-wave-row={tile.row}\n          >\n            <span data-kida-dual-wave-layer=\"\"></span>\n            <span data-kida-dual-wave-layer=\"\"></span>\n          </div>\n        {/each}\n      </div>\n    {/if}\n    <div data-kida-dual-wave-images=\"\" aria-hidden=\"true\">\n      {#each items as item, itemIndex (item.id)}\n        <img\n          {...item.imageProps}\n          src={item.src}\n          alt=\"\"\n          data-kida-dual-wave-image=\"\"\n          data-current={itemIndex === active ? '' : undefined}\n          decoding={item.imageProps?.decoding ?? 'async'}\n          draggable=\"false\"\n        />\n      {/each}\n    </div>\n    {#if current}\n      <span data-kida-dual-wave-sr=\"\" role=\"img\" aria-label={current.alt}></span>\n    {/if}\n  </div>\n  <span id={helpId} data-kida-dual-wave-sr=\"\">Scroll, swipe, or use arrow keys</span>\n  <span data-kida-dual-wave-sr=\"\" aria-live=\"polite\" aria-atomic=\"true\">{current ? `Item ${active + 1} of ${count}: ${current.title}, ${current.subtitle}.` : ''}</span>\n</section>\n",
      "type": "registry:ui",
      "target": "kida/dual-wave.svelte"
    },
    {
      "content": "import type { DualWaveLayout, DualWaveOptions } from './dual-wave.motion.js';\n\nimport type { HTMLAttributes, HTMLImgAttributes } from 'svelte/elements';\n\nexport type { DualWaveLayout } from './dual-wave.motion.js';\n\ntype TextAttributes<T extends EventTarget> = Omit<HTMLAttributes<T>, 'children'>;\n\nexport interface DualWaveItem {\n    id: string;\n    title: string;\n    subtitle: string;\n    src: string;\n    alt: string;\n    imageProps?: Omit<HTMLImgAttributes, 'src' | 'alt' | 'draggable'>;\n}\n\nexport interface DualWaveProps extends DualWaveOptions, TextAttributes<HTMLElement> {\n    items: readonly DualWaveItem[];\n    headings?: readonly [\n        string,\n        string\n    ];\n    layout?: DualWaveLayout;\n    columns?: number;\n    defaultIndex?: number;\n    index?: number;\n    onIndexChange?: (index: number) => void;\n    element?: HTMLElement | null;\n}\n",
      "type": "registry:ui",
      "target": "kida/dual-wave.types.ts"
    },
    {
      "content": "[data-kida-dual-wave] {\n  --kida-dual-wave-surface: #fffafb;\n  --kida-dual-wave-ink: #211c24;\n  --kida-dual-wave-muted: #71666b;\n  --kida-dual-wave-accent: #e94f86;\n  --kida-dual-wave-line: #e9dfda;\n  --kida-dual-wave-placeholder: #f8dbe5;\n  --kida-dual-wave-focus: var(--kida-dual-wave-accent);\n\n  container-type: inline-size;\n  position: relative;\n  display: block;\n  height: var(--kida-dual-wave-height, clamp(26rem, 78svh, 44rem));\n  overflow: hidden;\n  isolation: isolate;\n  border: 1px solid var(--kida-dual-wave-line);\n  border-radius: var(--kida-dual-wave-radius, 1.5rem);\n  background: var(--kida-dual-wave-surface);\n  color: var(--kida-dual-wave-ink);\n  overscroll-behavior: contain;\n}\n\n[data-kida-dual-wave]:focus-visible,\n[data-kida-dual-wave] [data-kida-dual-wave-item]:focus-visible {\n  outline: 2px solid var(--kida-dual-wave-focus);\n  outline-offset: 4px;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-headings] {\n  position: absolute;\n  z-index: 2;\n  inset: 1.5rem 1.75rem auto;\n  display: flex;\n  justify-content: space-between;\n  gap: 1.25rem;\n  color: var(--kida-dual-wave-muted);\n  font-size: 0.625rem;\n  font-weight: 650;\n  letter-spacing: 0.08em;\n  text-transform: uppercase;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-field] {\n  position: absolute;\n  inset: 4.375rem 1.75rem;\n  overflow: hidden;\n  mask-image: linear-gradient(transparent, black 13%, black 87%, transparent);\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-column] {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  width: 37%;\n  min-width: 0;\n  margin: 0;\n  padding: 0;\n  border: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-column=\"title\"] {\n  left: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-column=\"subtitle\"] {\n  right: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-item] {\n  position: absolute;\n  top: 50%;\n  width: max-content;\n  max-width: 100%;\n  /* The row height is also the spacing between rows, so a smaller value fits more of them. */\n  height: var(--kida-dual-wave-row-height, clamp(1.875rem, 3.9cqw, 3.75rem));\n  margin: 0;\n  margin-top: calc(var(--kida-dual-wave-row-height, clamp(1.875rem, 3.9cqw, 3.75rem)) / -2);\n  padding: 0;\n  overflow: hidden;\n  border: 0;\n  border-radius: 0.25rem;\n  background: transparent;\n  color: var(--kida-dual-wave-ink);\n  font: inherit;\n  font-size: var(--kida-dual-wave-font-size, clamp(0.8125rem, 2.8cqw, 2.75rem));\n  font-weight: 450;\n  line-height: 1;\n  letter-spacing: -0.055em;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  cursor: pointer;\n  /* Until the controller positions the rows, only the current item is shown, at the center. */\n  opacity: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-column=\"title\"] > [data-kida-dual-wave-item] {\n  left: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-column=\"subtitle\"] > [data-kida-dual-wave-item] {\n  right: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-item][aria-current=\"true\"] {\n  color: color-mix(in srgb, var(--kida-dual-wave-accent) 75%, var(--kida-dual-wave-ink));\n  opacity: 1;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-item]:hover {\n  text-decoration: underline;\n  text-decoration-color: var(--kida-dual-wave-accent);\n  text-decoration-thickness: 2px;\n  text-underline-offset: 0.375rem;\n}\n\n/* The photo sits outside the faded text field and fits the stage's height as well as its width. */\n[data-kida-dual-wave] [data-kida-dual-wave-media] {\n  position: absolute;\n  top: 50%;\n  left: 50%;\n  height: min(\n    calc(100% - 9.75rem),\n    calc(var(--kida-dual-wave-image-width, clamp(7rem, 22cqw, 18.75rem)) * 4 / 3)\n  );\n  aspect-ratio: 3 / 4;\n  transform: translate(-50%, -50%);\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-images] {\n  position: relative;\n  width: 100%;\n  aspect-ratio: 3 / 4;\n  overflow: hidden;\n  border-radius: var(--kida-dual-wave-image-radius, 0.625rem);\n  background: var(--kida-dual-wave-placeholder);\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-image] {\n  position: absolute;\n  inset: 0;\n  display: block;\n  width: 100%;\n  height: 100%;\n  object-fit: cover;\n  pointer-events: none;\n  opacity: 0;\n  visibility: hidden;\n}\n\n/* The current photo shows before the controller starts and while later photos decode. */\n[data-kida-dual-wave] [data-kida-dual-wave-image][data-current] {\n  opacity: 1;\n  visibility: visible;\n}\n\n/* Mosaic: tiles paint the photo. The images stay mounted for loading and the decode check.\n   Opacity, unlike visibility, cannot be overridden by the images' own inline styles. */\n[data-kida-dual-wave][data-layout=\"mosaic\"] [data-kida-dual-wave-images] {\n  position: absolute;\n  inset: 0;\n  opacity: 0;\n  pointer-events: none;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-mosaic] {\n  display: grid;\n  grid-template-columns: repeat(var(--kida-dual-wave-columns), 1fr);\n  aspect-ratio: 3 / 4;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-tile] {\n  position: relative;\n  overflow: hidden;\n  clip-path: inset(var(--kida-dual-wave-gutter, 2px) round 3px);\n  background: var(--kida-dual-wave-placeholder);\n}\n\n[data-kida-dual-wave][data-state=\"moving\"] [data-kida-dual-wave-tile] {\n  will-change: transform;\n}\n\n/* Each layer is the whole photo, offset so the tile shows only its own slice. */\n[data-kida-dual-wave] [data-kida-dual-wave-layer] {\n  position: absolute;\n  top: calc(var(--kida-dual-wave-row) * -100%);\n  left: calc(var(--kida-dual-wave-column) * -100%);\n  width: calc(var(--kida-dual-wave-columns) * 100%);\n  height: calc(var(--kida-dual-wave-rows) * 100%);\n  background-position: center;\n  background-size: cover;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-layer]:first-child {\n  background-image: var(--kida-dual-wave-initial, none);\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-layer]:last-child {\n  opacity: 0;\n}\n\n[data-kida-dual-wave] [data-kida-dual-wave-sr] {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  margin: -1px;\n  overflow: hidden;\n  clip-path: inset(50%);\n  white-space: nowrap;\n}\n\n@container (max-width: 30rem) {\n  [data-kida-dual-wave] [data-kida-dual-wave-headings] {\n    inset-inline: 0.875rem;\n    font-size: 0.5625rem;\n  }\n\n  [data-kida-dual-wave] [data-kida-dual-wave-field] {\n    inset: 4rem 0.625rem;\n  }\n\n  [data-kida-dual-wave] [data-kida-dual-wave-column] {\n    width: 35%;\n  }\n\n  [data-kida-dual-wave] [data-kida-dual-wave-item] {\n    font-size: var(--kida-dual-wave-font-size, clamp(0.625rem, 3cqw, 0.875rem));\n  }\n\n  [data-kida-dual-wave] [data-kida-dual-wave-media] {\n    height: min(calc(100% - 9rem), calc(var(--kida-dual-wave-image-width, 27cqw) * 4 / 3));\n  }\n\n  [data-kida-dual-wave] [data-kida-dual-wave-mosaic] {\n    --kida-dual-wave-gutter: 1px;\n  }\n}\n",
      "type": "registry:ui",
      "target": "kida/dual-wave.css"
    },
    {
      "content": "import {\n  dampPosition,\n  getDualWaveMosaicRows,\n  itemDistance,\n  nearestItemPosition,\n  tileDelay,\n  tileProgress,\n  waveOffset,\n  wrapIndex,\n} from './dual-wave-math.motion.js'\nimport { prefersReducedMotion, watchReducedMotion } from './reduced-motion.motion.js'\n\nexport { getDualWaveMosaicRows } from './dual-wave-math.motion.js'\n\n/** `mosaic` splits the photo into tiles that cascade and part with speed; `frame` cuts to it. */\nexport type DualWaveLayout = 'mosaic' | 'frame'\n\nexport interface DualWaveOptions {\n  /** Horizontal wave travel and how far mosaic tiles part, from 0 to 100. @default 80 */\n  strength?: number\n  /** Settling speed multiplier, from 0.25 to 3. @default 1 */\n  response?: number\n  /** Whether wheel and swipe gestures over the stage move between items. @default true */\n  captureScroll?: boolean\n}\n\nexport interface DualWaveSetup extends DualWaveOptions {\n  /** Item shown when the controller starts. @default 0 */\n  index?: number\n  /** Called when the item nearest the center changes. */\n  onIndexChange?: (index: number) => void\n}\n\nexport interface DualWaveControls {\n  /** Travels the shortest way around the loop to an item. */\n  select(index: number): void\n  /** Moves by whole items; negative values move backward. */\n  step(delta: number): void\n  /** Applies new options without restarting or moving. */\n  update(options: DualWaveOptions): void\n  destroy(): void\n}\n\nconst DEFAULTS = { strength: 80, response: 1, captureScroll: true } as const\nconst NAVIGATION_KEYS = new Map([\n  ['ArrowDown', 1],\n  ['ArrowRight', 1],\n  ['PageDown', 1],\n  ['ArrowUp', -1],\n  ['ArrowLeft', -1],\n  ['PageUp', -1],\n])\n\n// Shared by every instance and restart: once a photo is decoded it can be shown immediately.\n// Showing a loaded-but-undecoded image paints an empty frame first, which reads as a blink.\nconst decodedImages = new WeakSet<HTMLImageElement>()\n\nconst clamp = (value: number, min: number, max: number) =>\n  Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : min\n\n/**\n * Drives a DualWave stage: two text columns that wave past each other and a photo between them.\n * Only transforms, opacity, and background images are written per frame; layout is read on resize.\n */\nexport function dualWave(root: HTMLElement, setup: DualWaveSetup = {}): DualWaveControls {\n  const columns = [\n    root.querySelector<HTMLElement>('[data-kida-dual-wave-column=\"title\"]'),\n    root.querySelector<HTMLElement>('[data-kida-dual-wave-column=\"subtitle\"]'),\n  ]\n  const [titles, subtitles] = columns.map((column) =>\n    column ? [...column.querySelectorAll<HTMLElement>('[data-kida-dual-wave-item]')] : [],\n  ) as [HTMLElement[], HTMLElement[]]\n  const images = [...root.querySelectorAll<HTMLImageElement>('img[data-kida-dual-wave-image]')]\n  const mosaicRoot = root.querySelector<HTMLElement>('[data-kida-dual-wave-mosaic]')\n  const count = titles.length\n\n  let strength: number = DEFAULTS.strength\n  let response: number = DEFAULTS.response\n  let captureScroll: boolean = DEFAULTS.captureScroll\n  const applyOptions = (options: DualWaveOptions) => {\n    if (options.strength !== undefined) strength = clamp(options.strength, 0, 100)\n    if (options.response !== undefined) response = clamp(options.response, 0.25, 3)\n    if (options.captureScroll !== undefined) captureScroll = options.captureScroll\n  }\n  applyOptions(setup)\n\n  const mosaicColumns = Math.max(1, Number(mosaicRoot?.dataset.kidaDualWaveColumns) || 1)\n  const mosaicRows = getDualWaveMosaicRows(mosaicColumns)\n  const mosaic = [\n    ...(mosaicRoot?.querySelectorAll<HTMLElement>('[data-kida-dual-wave-tile]') ?? []),\n  ]\n    .map((tile, index) => {\n      const [from, to] = tile.querySelectorAll<HTMLElement>('[data-kida-dual-wave-layer]')\n      const column = index % mosaicColumns\n      const row = Math.floor(index / mosaicColumns)\n      return {\n        tile,\n        from,\n        to,\n        delay: tileDelay(column, row, mosaicColumns, mosaicRows),\n        x: column - (mosaicColumns - 1) / 2,\n        y: row - (mosaicRows - 1) / 2,\n      }\n    })\n    .filter((part): part is typeof part & { from: HTMLElement; to: HTMLElement } =>\n      Boolean(part.from && part.to),\n    )\n\n  let reduced = prefersReducedMotion()\n  const start = count ? wrapIndex(Math.round(setup.index ?? 0), count) : 0\n  const state = { position: start, target: start }\n  let announced = start\n  let frame = 0\n  let previousTime = 0\n  let snapTimer = 0\n  let visible = false\n  let disposed = false\n  let rowHeight = 48\n  let stageHeight = 600\n  let titleRange = 0\n  let subtitleRange = 0\n  let tileWidth = 0\n  let wheelRemainder = 0\n  let touchStart: { x: number; y: number } | null = null\n  let lastImage = start\n  let frontImage = -1\n  let backImage = -1\n  let shownFrom = -1\n  let shownTo = -1\n\n  // A restart (for example a layout change) must not inherit what the previous pass wrote.\n  for (const image of images) image.style.removeProperty('opacity')\n  for (const image of images) image.style.removeProperty('visibility')\n  for (const image of images) image.style.removeProperty('z-index')\n\n  const ready = (index: number) => {\n    const image = images[index]\n    return image ? decodedImages.has(image) : false\n  }\n\n  const paintImages = (position: number, nearest: number) => {\n    const lower = wrapIndex(Math.floor(position), count)\n    const upper = wrapIndex(Math.ceil(position), count)\n    const canBlend = ready(lower) && ready(upper)\n    if (canBlend || ready(nearest)) lastImage = nearest\n    else if (!ready(lastImage)) {\n      const fallback = images.findIndex((image) => decodedImages.has(image))\n      if (fallback >= 0) lastImage = fallback\n    }\n\n    if (mosaic.length) {\n      const from = canBlend ? lower : lastImage\n      const to = canBlend ? upper : lastImage\n      if (!ready(from) || !ready(to)) return\n      const t = canBlend && !reduced ? position - Math.floor(position) : 0\n      const source = (index: number) => {\n        const image = images[index]\n        return `url(\"${image?.currentSrc || image?.src || ''}\")`\n      }\n      // Background swaps only happen when the pair changes; each frame writes opacity/transform.\n      for (const part of mosaic) {\n        if (from !== shownFrom) part.from.style.backgroundImage = source(from)\n        if (to !== shownTo) part.to.style.backgroundImage = source(to)\n      }\n      shownFrom = from\n      shownTo = to\n      // Tiles part with velocity and settle back into one image at rest.\n      const parting = reduced ? 0 : Math.min(1, Math.abs(state.target - position) / 1.5)\n      const gap = tileWidth * 0.16 * (strength / 100) * parting\n      for (const { tile, to: layer, delay, x, y } of mosaic) {\n        const progress = tileProgress(t, delay)\n        const lift = reduced ? 0 : Math.sin(progress * Math.PI)\n        layer.style.opacity = String(progress)\n        tile.style.transform =\n          gap || lift\n            ? `translate3d(${x * gap}px, ${y * gap - lift * tileWidth * 0.08}px, 0) scale(${1 - lift * 0.06})`\n            : ''\n      }\n      return\n    }\n\n    // Frame cuts straight to the photo. The previous one stays underneath, so a late first paint\n    // of the new photo reveals it rather than the empty backdrop.\n    if (lastImage !== frontImage && ready(lastImage)) {\n      backImage = frontImage\n      frontImage = lastImage\n    }\n    if (frontImage < 0) return\n    images.forEach((image, index) => {\n      const shown = index === frontImage || index === backImage\n      image.style.opacity = shown ? '1' : '0'\n      image.style.visibility = shown ? 'visible' : 'hidden'\n      image.style.zIndex = index === frontImage ? '1' : ''\n    })\n  }\n\n  const paint = () => {\n    if (!count) return\n    const position = state.position\n    const nearest = wrapIndex(Math.round(position), count)\n    if (announced !== nearest) {\n      announced = nearest\n      setup.onIndexChange?.(nearest)\n    }\n\n    for (let index = 0; index < count; index++) {\n      const distance = itemDistance(index, position, count)\n      const y = distance * rowHeight\n      const inView = Math.abs(y) < stageHeight / 2 + rowHeight\n      const opacity = 0.38 + 0.62 * Math.max(0, 1 - Math.abs(distance)) ** 2\n      const x = reduced ? 0 : waveOffset(distance, position, 1)\n      for (const [row, range, direction] of [\n        [titles[index], titleRange, 1],\n        [subtitles[index], subtitleRange, -1],\n      ] as const) {\n        if (!row) continue\n        row.style.visibility = inView ? 'visible' : 'hidden'\n        row.style.transform = `translate3d(${x * range * direction}px, ${y}px, 0)`\n        row.style.opacity = String(opacity)\n      }\n    }\n    paintImages(position, nearest)\n  }\n\n  const canRun = () => visible && !document.hidden\n  const settle = () => {\n    root.dataset.state = 'settled'\n    previousTime = 0\n  }\n  const tick = (time: number) => {\n    frame = 0\n    if (!canRun()) return\n    const elapsed = previousTime ? Math.max(0, time - previousTime) : 16.67\n    previousTime = time\n    state.position = dampPosition(state.position, state.target, elapsed, response)\n    const settled = Math.abs(state.target - state.position) < 0.001\n    if (settled) state.position = state.target\n    paint()\n    if (settled) settle()\n    else frame = requestAnimationFrame(tick)\n  }\n  const wake = () => {\n    if (disposed || frame || !canRun()) return\n    if (reduced) {\n      state.position = state.target\n      paint()\n      settle()\n      return\n    }\n    root.dataset.state = 'moving'\n    previousTime = 0\n    frame = requestAnimationFrame(tick)\n  }\n  const step = (delta: number) => {\n    if (!count) return\n    window.clearTimeout(snapTimer)\n    state.target = Math.round(state.target) + Math.round(delta)\n    wake()\n  }\n  const select = (index: number) => {\n    if (!count || !Number.isFinite(index)) return\n    window.clearTimeout(snapTimer)\n    state.target = nearestItemPosition(wrapIndex(Math.round(index), count), state.target, count)\n    wake()\n  }\n  const snap = () => {\n    snapTimer = 0\n    state.target = Math.round(state.target)\n    wake()\n  }\n\n  const prime = (image: HTMLImageElement) => {\n    if (!image.complete || !image.naturalWidth || decodedImages.has(image)) return\n    image\n      .decode()\n      .then(() => {\n        decodedImages.add(image)\n        if (disposed) return\n        if (frame) return\n        // Not animating: paint the newly available photo directly.\n        paint()\n      })\n      .catch(() => {})\n  }\n  const primeLoaded = (event: Event) => prime(event.currentTarget as HTMLImageElement)\n\n  const measure = () => {\n    const titleColumn = columns[0]\n    const subtitleColumn = columns[1]\n    if (!titleColumn || !subtitleColumn) return\n    stageHeight = titleColumn.clientHeight\n    rowHeight = Math.max(titles[0]?.offsetHeight || 48, stageHeight / Math.max(2, count - 1))\n    const widest = (rows: HTMLElement[]) => Math.max(0, ...rows.map((row) => row.offsetWidth))\n    titleRange = Math.max(0, titleColumn.clientWidth - widest(titles)) * (strength / 100)\n    subtitleRange = Math.max(0, subtitleColumn.clientWidth - widest(subtitles)) * (strength / 100)\n    tileWidth = (mosaicRoot?.clientWidth ?? 0) / mosaicColumns\n    paint()\n  }\n\n  const onWheel = (event: WheelEvent) => {\n    // Leave zoom and Shift-scroll to the browser so the page can still scroll past the stage.\n    if (!captureScroll || count < 2 || event.ctrlKey || event.metaKey || event.shiftKey) return\n    if (Math.abs(event.deltaX) > Math.abs(event.deltaY) || !event.deltaY) return\n    event.preventDefault()\n    const delta =\n      event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? stageHeight : 1)\n    if (reduced) {\n      wheelRemainder += delta\n      if (Math.abs(wheelRemainder) >= 60) {\n        step(Math.sign(wheelRemainder))\n        wheelRemainder = 0\n      }\n      return\n    }\n    state.target += Math.max(-1.5, Math.min(1.5, delta / 160))\n    state.target = Math.max(state.position - 4, Math.min(state.position + 4, state.target))\n    wake()\n    window.clearTimeout(snapTimer)\n    snapTimer = window.setTimeout(snap, 140)\n  }\n  const onTouchStart = (event: TouchEvent) => {\n    const touch = event.touches[0]\n    touchStart =\n      captureScroll && event.touches.length === 1 && touch\n        ? { x: touch.clientX, y: touch.clientY }\n        : null\n  }\n  const onTouchMove = (event: TouchEvent) => {\n    if (touchStart && event.touches.length === 1) event.preventDefault()\n  }\n  const onTouchEnd = (event: TouchEvent) => {\n    const touch = event.changedTouches[0]\n    if (!touchStart || !touch) return\n    const x = touchStart.x - touch.clientX\n    const y = touchStart.y - touch.clientY\n    const delta = Math.abs(x) > Math.abs(y) ? x : y\n    if (Math.abs(delta) > 28) step(Math.sign(delta))\n    touchStart = null\n  }\n  const onTouchCancel = () => {\n    touchStart = null\n  }\n  const onClick = (event: MouseEvent) => {\n    const item = (event.target as Element | null)?.closest<HTMLElement>(\n      '[data-kida-dual-wave-item]',\n    )\n    if (!item || !root.contains(item)) return\n    const index = titles.indexOf(item)\n    select(index >= 0 ? index : subtitles.indexOf(item))\n  }\n  const onKeyDown = (event: KeyboardEvent) => {\n    if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return\n    const target = event.target as Element | null\n    if (target?.closest('input, select, textarea, [contenteditable=\"true\"]')) return\n    const delta = NAVIGATION_KEYS.get(event.key)\n    if (delta !== undefined) {\n      event.preventDefault()\n      step(delta)\n    } else if (event.key === 'Home' || event.key === 'End') {\n      event.preventDefault()\n      select(event.key === 'Home' ? 0 : count - 1)\n    }\n  }\n  const syncVisibility = () => {\n    if (canRun()) wake()\n    else {\n      cancelAnimationFrame(frame)\n      frame = 0\n      settle()\n    }\n  }\n\n  const intersection = new IntersectionObserver(([entry]) => {\n    visible = entry?.isIntersecting ?? false\n    syncVisibility()\n  })\n  const resize = new ResizeObserver(measure)\n  const unwatchReducedMotion = watchReducedMotion((next) => {\n    reduced = next\n    state.position = state.target = Math.round(state.target)\n    measure()\n  })\n  resize.observe(root)\n  intersection.observe(root)\n  document.fonts?.addEventListener('loadingdone', measure)\n  document.addEventListener('visibilitychange', syncVisibility)\n  root.addEventListener('wheel', onWheel, { passive: false })\n  root.addEventListener('touchstart', onTouchStart, { passive: true })\n  root.addEventListener('touchmove', onTouchMove, { passive: false })\n  root.addEventListener('touchend', onTouchEnd, { passive: true })\n  root.addEventListener('touchcancel', onTouchCancel, { passive: true })\n  root.addEventListener('click', onClick)\n  root.addEventListener('keydown', onKeyDown)\n  for (const image of images) {\n    image.addEventListener('load', primeLoaded)\n    prime(image)\n  }\n  root.dataset.state = 'settled'\n  measure()\n\n  return {\n    select,\n    step,\n    update(options) {\n      applyOptions(options)\n      measure()\n    },\n    destroy() {\n      disposed = true\n      cancelAnimationFrame(frame)\n      window.clearTimeout(snapTimer)\n      intersection.disconnect()\n      resize.disconnect()\n      unwatchReducedMotion()\n      document.fonts?.removeEventListener('loadingdone', measure)\n      document.removeEventListener('visibilitychange', syncVisibility)\n      root.removeEventListener('wheel', onWheel)\n      root.removeEventListener('touchstart', onTouchStart)\n      root.removeEventListener('touchmove', onTouchMove)\n      root.removeEventListener('touchend', onTouchEnd)\n      root.removeEventListener('touchcancel', onTouchCancel)\n      root.removeEventListener('click', onClick)\n      root.removeEventListener('keydown', onKeyDown)\n      for (const image of images) image.removeEventListener('load', primeLoaded)\n      delete root.dataset.state\n    },\n  }\n}\n",
      "type": "registry:ui",
      "target": "kida/dual-wave.motion.ts"
    },
    {
      "content": "/** Wraps any position onto the item loop. */\nexport const wrapIndex = (position: number, count: number) => ((position % count) + count) % count\n\n/** Signed distance around the loop. Recycled rows always cross outside the visible stage. */\nexport const itemDistance = (index: number, position: number, count: number) =>\n  wrapIndex(index - position + count / 2, count) - count / 2\n\n/** The loop position nearest to `target` that shows `index`. */\nexport const nearestItemPosition = (index: number, target: number, count: number) =>\n  target + itemDistance(index, target, count)\n\n/** Horizontal travel for a row, from 0 to `range`. The phase drifts with position. */\nexport function waveOffset(distance: number, position: number, range: number) {\n  return ((Math.sin(distance * 0.72 + position * 0.18 - Math.PI / 2) + 1) / 2) * range\n}\n\n/** Time-based damping keeps the response consistent on 60 Hz and 120 Hz displays. */\nexport function dampPosition(position: number, target: number, elapsed: number, speed: number) {\n  return position + (target - position) * (1 - Math.exp((-elapsed * speed) / 115))\n}\n\n/** Mosaic rows that keep the grid close to the frame's 3:4 aspect. */\nexport const getDualWaveMosaicRows = (columns: number) => Math.round((columns * 4) / 3)\n\n/**\n * Where a mosaic tile starts its hand-off: bottom rows lead, matching the text rising from below,\n * and the middle columns trail slightly so the front curves like the wave. Returns 0..1.\n */\nexport function tileDelay(column: number, row: number, columns: number, rows: number) {\n  const fromBottom = rows > 1 ? (rows - 1 - row) / (rows - 1) : 0\n  const bow = columns > 1 ? Math.sin((column / (columns - 1)) * Math.PI) : 0\n  return fromBottom * 0.75 + bow * 0.25\n}\n\n/** Per-tile progress for a transition. Pure in `t`, so reversing mid-way retraces the cascade. */\nexport function tileProgress(t: number, delay: number, spread = 1.4) {\n  const x = Math.min(1, Math.max(0, t * (1 + spread) - delay * spread))\n  return x * x * (3 - 2 * x)\n}\n",
      "type": "registry:ui",
      "target": "kida/dual-wave-math.motion.ts"
    },
    {
      "content": "const QUERY = '(prefers-reduced-motion: reduce)'\n\n/**\n * Whether the user has asked for reduced motion.\n *\n * SSR-safe: returns `false` when there is no `window`, matching the CSS default\n * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;\n * this is for the JS-driven paths that CSS cannot express).\n */\nexport function prefersReducedMotion(): boolean {\n  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false\n  return window.matchMedia(QUERY).matches\n}\n\n/**\n * Subscribe to changes of the reduced-motion preference.\n * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.\n */\nexport function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {\n  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}\n\n  const list = window.matchMedia(QUERY)\n  const handler = (event: MediaQueryListEvent) => onChange(event.matches)\n  list.addEventListener('change', handler)\n  return () => list.removeEventListener('change', handler)\n}\n",
      "type": "registry:ui",
      "target": "kida/reduced-motion.motion.ts"
    }
  ]
}
