{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "swap",
  "title": "Swap",
  "description": "A box whose content crossfades, or rolls, when it changes, while its width follows, and an icon that rolls when something turns on. Button, Toast, Toggle, Tabs and Segmented control share it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/swap.tsx",
      "content": "'use client'\n\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { animateSize, transitionsSettled, withoutTransition } from '@/registry/lib/resize'\nimport {\n  Children,\n  cloneElement,\n  createContext,\n  Fragment,\n  isValidElement,\n  type ReactNode,\n  type RefObject,\n  use,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Content that changes in place. The old content stays mounted until its exit\n * has played, the new content enters beside it, and the box follows the new\n * width. It moves on the `enter`, `exit` and `layout` roles.\n */\n\nconst componentIds = new WeakMap<object, number>()\nlet componentCount = 0\n\nconst LAZY = Symbol.for('react.lazy')\n\nfunction typeName(type: unknown): string {\n  if (typeof type === 'string') return type\n  if (typeof type !== 'function' && (typeof type !== 'object' || type === null)) return ''\n  // A Server Component hands a client component over in a new lazy wrapper on\n  // every payload, so a wrapper's identity says nothing about what it holds.\n  if ((type as { $$typeof?: symbol }).$$typeof === LAZY) return ''\n  // By identity, because a production build renames components.\n  let id = componentIds.get(type)\n  if (id === undefined) {\n    id = componentCount\n    componentCount += 1\n    componentIds.set(type, id)\n  }\n  return `#${id}`\n}\n\nconst KEY_DEPTH = 8\n\n/**\n * A string that changes when the content does: its text, which components its\n * elements are, their `key` and their plain props. Class names, styles and\n * handlers are left out, so rendering the same content again is no change.\n */\nfunction contentKey(value: unknown, depth = 0): string {\n  if (typeof value === 'string' || typeof value === 'number') return String(value)\n  if (value === true) return 'true'\n  if (typeof value !== 'object' || value === null || depth > KEY_DEPTH) return ''\n  if (Array.isArray(value)) {\n    return value.map((item) => contentKey(item, depth + 1)).join('')\n  }\n  if (isValidElement(value)) {\n    const props = contentKey(value.props, depth + 1)\n    return `<${typeName(value.type)} ${value.key ?? ''} ${props}>`\n  }\n  if (Object.getPrototypeOf(value) !== Object.prototype) return ''\n  return Object.entries(value)\n    .filter(([name]) => name !== 'className' && name !== 'style')\n    .map(([name, item]) => `${name}=${contentKey(item, depth + 1)}`)\n    .join(' ')\n}\n\n/**\n * Children as a flat list, with fragments opened. An element from inside a\n * fragment takes the fragment's key before its own, so the children of two\n * fragments in a mapped list never share a key.\n */\nfunction flattenChildren(children: ReactNode, prefix = ''): ReactNode[] {\n  return Children.toArray(children).flatMap((child) => {\n    if (!isValidElement(child)) return [child]\n    const key = `${prefix}${child.key ?? ''}`\n    if (child.type === Fragment) {\n      return flattenChildren((child.props as { children?: ReactNode }).children, key)\n    }\n    return prefix ? [cloneElement(child, { key })] : [child]\n  })\n}\n\nconst segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' })\n\n/** The text as the characters a reader sees, so an emoji or an accent is never cut in two. */\nfunction graphemes(text: string): string[] {\n  return Array.from(segmenter.segment(text), (part) => part.segment)\n}\n\n/** What two texts share at each end, and what differs between. */\nfunction seam(from: string, to: string) {\n  const a = graphemes(from)\n  const b = graphemes(to)\n  const shortest = Math.min(a.length, b.length)\n  let start = 0\n  while (start < shortest && a[start] === b[start]) start += 1\n  let end = 0\n  while (end < shortest - start && a[a.length - 1 - end] === b[b.length - 1 - end]) {\n    end += 1\n  }\n  return {\n    prefix: b.slice(0, start).join(''),\n    suffix: b.slice(b.length - end).join(''),\n    was: a.slice(start, a.length - end).join(''),\n    now: b.slice(start, b.length - end).join(''),\n  }\n}\n\n/**\n * A width rounded up to the 1/64px layout works in. A computed width is\n * rounded to three decimals, which can be a hair under the real one, and\n * content held at that width wraps a line that fits (234.859px for 234.859375px).\n */\nfunction fullPixels(width: number): number {\n  return Math.ceil(width * 64 - 1e-6) / 64\n}\n\n/** The element's width as layout has it, which a scale on it or above it doesn't change. */\nfunction layoutWidth(element: HTMLElement): number {\n  return Number.parseFloat(getComputedStyle(element).width) || 0\n}\n\nfunction releaseWidth(element: HTMLElement) {\n  element.style.width = ''\n  element.style.removeProperty('--swap-width')\n  element.style.removeProperty('--swap-shrink')\n  delete element.dataset.resizing\n}\n\n/**\n * Moves `element` from one width to another, then hands the width back to\n * layout. While it moves, `--swap-width` holds the content at its final\n * width, so nothing truncates or reflows on the way.\n */\nfunction animateWidth(element: HTMLElement, from: number, to: number) {\n  void animateSize(element, 'width', from, to, {\n    alongside: (start) => {\n      if (!start) return\n      element.style.setProperty('--swap-width', `${fullPixels(to)}px`)\n      element.style.setProperty('--swap-shrink', '0')\n      element.dataset.resizing = ''\n    },\n  }).then((latest) => {\n    if (latest) releaseWidth(element)\n  })\n}\n\n/** The width the element had in the last frame, mid-transition or not. */\nfunction useLastWidth(ref: RefObject<HTMLElement | null>) {\n  const last = useRef<number | null>(null)\n  useEffect(() => {\n    const element = ref.current\n    if (!element) return\n    const observer = new ResizeObserver(([entry]) => {\n      last.current = entry.borderBoxSize[0].inlineSize\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [ref])\n  return last\n}\n\n/** With `enabled`, the height the element had in the last frame, mid-transition or not. */\nfunction useLastHeight(ref: RefObject<HTMLElement | null>, enabled: boolean) {\n  const last = useRef<number | null>(null)\n  useEffect(() => {\n    const element = ref.current\n    if (!element || !enabled) return\n    const observer = new ResizeObserver(([entry]) => {\n      last.current = entry.borderBoxSize[0].blockSize\n    })\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [ref, enabled])\n  return last\n}\n\n/** Calls `done` once every transition on `ref` and inside it has ended or been turned round. */\nfunction useSettled(\n  ref: RefObject<HTMLElement | null>,\n  /** Waits again whenever this changes; nothing waits while it is empty. */\n  pending: string,\n  done: () => void,\n) {\n  const doneRef = useRef(done)\n  useEffect(() => {\n    doneRef.current = done\n  })\n  useEffect(() => {\n    const element = ref.current\n    if (!pending || !element) return\n    let cancelled = false\n    // Transitions only: a spinner inside turns for as long as it shows.\n    void transitionsSettled(element, { subtree: true }).then(() => {\n      if (!cancelled) doneRef.current()\n    })\n    return () => {\n      cancelled = true\n    }\n  }, [ref, pending])\n}\n\n// What changes only fades, with no scale or blur, so a swap costs one layer's\n// opacity (Greg, 2026-11-30: lighter to draw, in Firefox most). A buyer's\n// `--swap-roll`, on the box or anything above it, wins over the default each\n// kind of box keeps in `--swap-default-roll`. With reduced motion nothing\n// travels, so what leaves goes at once: two contents never fade over each\n// other in one place.\nconst swapItemMotion =\n  'transition-[opacity,translate] duration-(--motion-enter-duration) ease-(--motion-enter-easing) data-[phase=out]:opacity-0 data-[phase=out]:duration-(--motion-exit-duration) data-[phase=out]:ease-(--motion-exit-easing) data-fresh:starting:opacity-0 motion-reduce:data-[phase=out]:transition-none'\n\n// What arrives waits for a fifth of the exit, so two labels never read at once.\n// Under reduced motion what leaves goes at once, so there is nothing to wait for.\nconst swapWait =\n  'motion-safe:data-[phase=in]:not-data-returned:delay-[calc(var(--motion-exit-duration)*0.2)]'\n\n// What arrives waits until what leaves has mostly gone: content too large to\n// read over itself, such as a form's steps, never shows two at once.\nconst swapWaitLonger =\n  'motion-safe:data-[phase=in]:not-data-returned:delay-[calc(var(--motion-exit-duration)*0.6)]'\n\n// Stepping out to a wider view, what leaves falls away and what arrives\n// comes from nearer; stepping in, the reverse. `--swap-zoom` is the scale of\n// the far end, and the near end is its inverse.\nconst swapZoom =\n  'data-[depth=far]:data-[phase=out]:scale-(--swap-zoom,0.92) data-[depth=near]:data-[phase=out]:scale-[calc(1/var(--swap-zoom,0.92))] data-fresh:data-[depth=far]:starting:scale-(--swap-zoom,0.92) data-fresh:data-[depth=near]:starting:scale-[calc(1/var(--swap-zoom,0.92))] motion-reduce:[--swap-zoom:1]'\n\n// What leaves goes up and what arrives comes from below; a change turned round\n// goes back the way it came. Both move at once, like a counter.\nconst swapRoll =\n  'data-[phase=out]:translate-y-[calc(var(--swap-roll,var(--swap-default-roll))*-1)] data-back:data-[phase=out]:translate-y-(--swap-roll,var(--swap-default-roll)) data-fresh:starting:translate-y-(--swap-roll,var(--swap-default-roll)) motion-reduce:[--swap-roll:0px]'\n\n// Forward, what leaves goes towards the reading start and what arrives comes\n// from the end, as the pages of a book; a change back goes the other way.\nconst swapSlide =\n  '[--swap-dir:1] rtl:[--swap-dir:-1] data-[side=start]:[--swap-side:-1] data-[side=end]:[--swap-side:1] data-[phase=out]:translate-x-[calc(var(--swap-slide,var(--swap-default-slide))*var(--swap-side)*var(--swap-dir))] data-fresh:starting:translate-x-[calc(var(--swap-slide,var(--swap-default-slide))*var(--swap-side)*var(--swap-dir))] motion-reduce:[--swap-slide:0px]'\n\nconst swapAlignment = {\n  center: 'justify-center',\n  start: 'justify-start',\n  end: 'justify-end',\n}\n\ninterface SwapItem {\n  key: string\n  node: ReactNode\n  phase: 'in' | 'out'\n  /** Arrived after the first paint, so it may animate in. */\n  fresh: boolean\n  /** Leaves the way it came, because the change was turned round. */\n  back?: boolean\n  /**\n   * With `slide`, which way it is offset at its far end: 1 towards the\n   * reading end, -1 towards the start. What arrives starts there; what leaves\n   * goes there.\n   */\n  side?: 1 | -1\n  /**\n   * With `zoom`, which way it is scaled at its far end: `near` larger, as if\n   * closer, or `far` smaller.\n   */\n  depth?: 'near' | 'far'\n  /** Came back while it was leaving, so it turns round at once with no wait. */\n  returned?: boolean\n}\n\n/**\n * The items after the content changes to `key`. Content that comes back while\n * it leaves turns round, and what leaves then goes back the way it came.\n */\nfunction swapTo(\n  items: readonly SwapItem[],\n  key: string,\n  node: ReactNode,\n  /** With `slide`, the way the change travels: 1 forward, -1 back. */\n  trend?: 1 | -1,\n  /** With `zoom`, whether the change steps `out` to a wider view or `in` to a closer one. */\n  zoom?: 'in' | 'out',\n): SwapItem[] {\n  const returning = items.find((item) => item.key === key)\n  const back = returning ? !returning.back : false\n  const next = items.map((item): SwapItem => {\n    if (item.key === key) return { ...item, phase: 'in', returned: true }\n    const leaving = item.phase === 'in'\n    const out: SwapItem = {\n      ...item,\n      phase: 'out',\n      back: leaving ? back : item.back,\n    }\n    // What was showing leaves the way the change goes; what was already leaving keeps going.\n    // A change with no slide never slides what leaves, however it once arrived.\n    if (leaving && trend) out.side = trend === 1 ? -1 : 1\n    else if (leaving) delete out.side\n    // Stepping out, what leaves falls away and what arrives comes from nearer; stepping in, the reverse.\n    // A change with no zoom never scales what leaves, however it once arrived.\n    if (leaving && zoom) out.depth = zoom === 'out' ? 'far' : 'near'\n    else if (leaving) delete out.depth\n    return out\n  })\n  if (!returning) {\n    const fresh: SwapItem = { key, node, phase: 'in', fresh: true }\n    if (trend) fresh.side = trend\n    if (zoom) fresh.depth = zoom === 'out' ? 'near' : 'far'\n    next.push(fresh)\n  }\n  return next\n}\n\n/** The items once those in `left` have finished leaving; one that came back stays. */\nfunction dropLeft(items: readonly SwapItem[], left: readonly string[]): SwapItem[] {\n  return items.filter((item) => item.phase === 'in' || !left.includes(item.key))\n}\n\n/** False inside content that is leaving. */\nconst SwapShowingContext = createContext(true)\n\n/**\n * Whether the content around it is leaving, so a part that registers itself\n * somewhere, such as one of ui-sdk's, can draw a still copy instead and leave\n * its place to the content that replaced it.\n */\nfunction useSwapLeaving() {\n  return !use(SwapShowingContext)\n}\n\n/**\n * Content as it last showed: what leaves keeps what it said at the end, as\n * content under one `id` (a line with a bar that grows) changes while it shows.\n * Text truncates on its line, or in a block, whose height follows its\n * content, wraps onto as many as it needs.\n */\nfunction SwapHeld({\n  showing,\n  wrap,\n  children,\n}: {\n  showing: boolean\n  wrap: boolean\n  children: ReactNode\n}) {\n  const [held, setHeld] = useState(children)\n  if (showing && held !== children) setHeld(children)\n  return (\n    <SwapShowingContext value={showing}>\n      {heldParts(showing ? children : held, wrap)}\n    </SwapShowingContext>\n  )\n}\n\nfunction heldParts(children: ReactNode, wrap: boolean) {\n  return flattenChildren(children).map((child, index) =>\n    typeof child === 'string' || typeof child === 'number' ? (\n      wrap ? (\n        // oxlint-disable-next-line react/no-array-index-key -- the parts of one piece of content keep their order\n        <span key={index} className='min-w-0'>\n          {child}\n        </span>\n      ) : (\n        // oxlint-disable-next-line react/no-array-index-key -- the parts of one piece of content keep their order\n        // A label a `CutTooltip` around it can measure.\n        <span key={index} data-cut className='min-w-0 truncate'>\n          {child}\n        </span>\n      )\n    ) : (\n      child\n    ),\n  )\n}\n\n// An icon that changes rolls: the old one leaves upwards and the new one rises\n// from below, fading as it goes. The travel is a share of the button's own\n// height, the share Greg picked in the playground (about 20px for a default\n// button at Balanced), so a small button's icon never leaves it empty. Outside\n// a button it is a share of the control height.\nconst swapIconClassName =\n  'shrink-0 overflow-x-clip [--swap-default-roll:calc(var(--button-height,var(--control-height))*0.55)]'\n\n/**\n * A box whose content changes. When the children change (see `contentKey`),\n * the old ones fade out, the new ones fade in, and the box's width follows.\n * Content that comes back while it leaves turns round from where it is.\n * What changes fades, with no scale or blur. `--swap-roll` sets how far it rolls with `roll` and `--swap-slide` how far it\n * slides with `slide` and `--swap-zoom` how far it scales with `zoom`, on the box or anything above it; `--swap-gap` is the space between its parts.\n */\nfunction Swap({\n  children,\n  align = 'center',\n  bleed = false,\n  roll = false,\n  slide,\n  zoom,\n  id: idProp,\n  className,\n  fill = false,\n  block: blockProp = false,\n  dock = false,\n  wait = false,\n}: {\n  children?: ReactNode\n  /** Where content that is leaving sits in the box while the width changes. */\n  align?: keyof typeof swapAlignment\n  /**\n   * Lets the box reach into its parent's padding, where content wider than\n   * the box fades out while the width catches up, in place of a hard cut.\n   */\n  bleed?: boolean\n  /** Rolls the content vertically, `--swap-roll` far, in place of fading it where it is. */\n  roll?: boolean\n  /**\n   * Slides the content sideways, `--swap-slide` far, the way the change\n   * travels: 1 forward, as to a next month, -1 back. Set it with each change.\n   */\n  slide?: 1 | -1\n  /**\n   * Scales the content the way the change goes, `--swap-zoom` far: `out` to\n   * a wider view, as from days to months, or `in` to a closer one. Set it\n   * with each change.\n   */\n  zoom?: 'in' | 'out'\n  /**\n   * What the content is, when it says so better than the content itself: a\n   * line holding a progress bar is the same line while its value climbs, and\n   * a month whose picked day moves is still that month. Content under one\n   * `id` updates in place; a new `id` swaps it.\n   */\n  id?: string\n  className?: string\n  /** Takes its parent's width and stretches its content across it, such as a line with a bar that grows. */\n  fill?: boolean\n  /**\n   * Holds a block of content, such as a month's grid: what leaves stays\n   * where it was, from the top, and the box's height moves to the new\n   * content's on `layout`, so what sits below follows instead of jumping.\n   */\n  block?: boolean\n  /**\n   * Holds a block that sits on the bottom edge of what holds it, such as a\n   * chat's composer: the box takes the new content's height at once, what\n   * leaves stays on the bottom edge, and what arrives rises or settles the\n   * difference with a transform on `layout`. What sits above it, whose room\n   * changes, is laid out once rather than on every frame of a height's move.\n   */\n  dock?: boolean\n  /**\n   * Holds what arrives until what leaves has mostly gone, sliding or not,\n   * for content too large to read over itself, such as a form's steps.\n   */\n  wait?: boolean\n}) {\n  const block = blockProp || dock\n  const ref = useRef<HTMLSpanElement>(null)\n  const refs = useMemo(() => mergeRefs(ref, markMounted), [])\n  const id = idProp ?? contentKey(children)\n  const [stored, setStored] = useState<{ id: string; items: SwapItem[] }>(() => ({\n    id,\n    items: [{ key: id, node: children, phase: 'in', fresh: false }],\n  }))\n  let { items } = stored\n  if (stored.id !== id) {\n    items = swapTo(items, id, children, slide, zoom)\n    setStored({ id, items })\n  }\n\n  const leaving = items.filter((item) => item.phase === 'out').map((item) => item.key)\n  useSettled(ref, leaving.length > 0 ? JSON.stringify(leaving) : '', () => {\n    setStored((latest) => ({\n      ...latest,\n      items: dropLeft(latest.items, leaving),\n    }))\n  })\n\n  const lastWidth = useLastWidth(ref)\n  useLayoutEffect(() => {\n    const element = ref.current\n    const from = lastWidth.current\n    if (!element || from === null || fill) return\n    const padding = Number.parseFloat(getComputedStyle(element).paddingInlineStart) * 2\n    for (const content of element.querySelectorAll<HTMLElement>(\n      ':scope > [data-phase] > [data-slot=swap-content]',\n    )) {\n      const current = content.parentElement?.dataset.phase === 'in'\n      // Content that leaves keeps the width it had, so text stays truncated\n      // where it was and a row that wraps keeps its lines: the box's last\n      // width at rest, or mid-move the width it was held at. Rounded up to\n      // the whole pixel, since the box's width can fall a hair short of its\n      // content's, and a row that wraps would break a line.\n      if (current) content.style.maxWidth = ''\n      else if (!content.style.maxWidth) {\n        const held = Number.parseFloat(element.style.getPropertyValue('--swap-width'))\n        const width = element.style.width && Number.isFinite(held) ? held : from\n        content.style.maxWidth = `${Math.ceil(width - padding)}px`\n      }\n    }\n    let to = 0\n    withoutTransition(element, () => {\n      releaseWidth(element)\n      to = layoutWidth(element)\n    })\n    if (Math.abs(to - from) >= 0.5) animateWidth(element, from, to)\n  }, [id, lastWidth, fill])\n\n  // After the width, whose measuring would otherwise cut the height's move short.\n  const lastHeight = useLastHeight(ref, block)\n  useLayoutEffect(() => {\n    const element = ref.current\n    const from = lastHeight.current\n    if (!element || from === null || !block) return\n    let to = 0\n    // Only the height stops to be measured: the width's move, just started, runs on.\n    withoutTransition(\n      element,\n      () => {\n        element.style.height = ''\n        to = element.offsetHeight\n      },\n      { properties: ['height'] },\n    )\n    if (Math.abs(to - from) < 0.5) return\n    if (dock) {\n      // The box is at its new height: the new content starts where the old top edge was, and moves the rest on the compositor.\n      const content = element.querySelector<HTMLElement>(\n        ':scope > [data-phase=in] > [data-slot=swap-content]',\n      )\n      if (!content) return\n      withoutTransition(content, () => {\n        content.style.transform = `translateY(${to - from}px)`\n        content.getBoundingClientRect()\n      })\n      content.style.transform = ''\n      // Clipped while it moves, so the content below the box's edge never makes what holds it scroll.\n      const move = String(Number(element.dataset.docking ?? 0) + 1)\n      element.dataset.docking = move\n      void transitionsSettled(content, { property: 'transform' }).then(() => {\n        if (element.dataset.docking === move) delete element.dataset.docking\n      })\n      return\n    }\n    // Clipped only while the height moves, so what leaves never shows past\n    // the box as it shrinks, and a focus ring at its edge stays whole at rest.\n    element.dataset.resizingHeight = ''\n    void animateSize(element, 'height', from, to).then((latest) => {\n      if (!latest) return\n      element.style.height = ''\n      delete element.dataset.resizingHeight\n    })\n  }, [id, lastHeight, block, dock])\n\n  return (\n    <span\n      ref={refs}\n      data-slot='swap'\n      className={cn(\n        // Content that changes before the first paint has settled, such as an\n        // icon that follows a saved theme once the page hydrates, takes its\n        // place at once: nothing moves on load.\n        'not-data-mounted:*:transition-none',\n        // A box's width while it moves is its own: one inside another (a\n        // button's icon in a moving label) never takes its parent's.\n        '[--swap-shrink:initial] [--swap-width:initial]',\n        fill ? 'flex w-full' : 'inline-flex',\n        block && !dock\n          ? 'transition-[width,height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) data-resizing-height:overflow-y-clip motion-reduce:transition-none'\n          : 'transition-[width] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n        // A block sits at the top, as what leaves it does, while the height moves; a dock sits on its bottom edge.\n        dock\n          ? 'items-end data-docking:overflow-y-clip'\n          : block\n            ? 'items-start'\n            : 'items-center',\n        'relative min-w-0 [--swap-default-roll:0.75em] [--swap-default-slide:1rem]',\n        bleed\n          ? '-mx-(--swap-bleed) px-(--swap-bleed) [--swap-bleed:--spacing(2)] data-resizing:[mask-image:linear-gradient(to_right,transparent,black_var(--swap-bleed),black_calc(100%-var(--swap-bleed)),transparent)] data-resizing:[mask-repeat:repeat-y] data-resizing:[mask-clip:no-clip]'\n          : '[--swap-bleed:0px]',\n        swapAlignment[align],\n        className,\n      )}\n    >\n      {items.map((item) => {\n        const current = item.key === id\n        return (\n          <span\n            key={item.key}\n            data-phase={item.phase}\n            data-fresh={item.fresh ? '' : undefined}\n            data-back={item.phase === 'out' && item.back ? '' : undefined}\n            data-side={item.side ? (item.side === 1 ? 'end' : 'start') : undefined}\n            data-depth={item.depth}\n            data-returned={item.returned ? '' : undefined}\n            aria-hidden={current ? undefined : true}\n            // A control on its way out, such as a button, can't take focus.\n            inert={!current}\n            className={cn(\n              current\n                ? fill\n                  ? 'flex w-full min-w-0'\n                  : 'inline-flex w-[calc(var(--swap-width)-var(--swap-bleed)*2)] min-w-0 shrink-[var(--swap-shrink,1)]'\n                : dock\n                  ? 'pointer-events-none absolute inset-x-0 bottom-0 flex items-end px-(--swap-bleed)'\n                  : block\n                    ? 'pointer-events-none absolute inset-x-0 top-0 flex items-start px-(--swap-bleed)'\n                    : 'pointer-events-none absolute inset-0 flex items-center px-(--swap-bleed)',\n              !current && swapAlignment[align],\n              swapItemMotion,\n              // An item keeps its slide when a change with none comes mid-way, so it turns from where it is.\n              roll ? swapRoll : item.side ? swapSlide : swapWait,\n              wait && swapWaitLonger,\n              swapZoom,\n            )}\n          >\n            <span\n              data-slot='swap-content'\n              className={cn(\n                'inline-flex items-center gap-(--swap-gap)',\n                fill ? 'w-full min-w-0' : current ? 'min-w-0' : 'w-max shrink-0',\n                dock &&\n                  'transition-transform duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none',\n              )}\n            >\n              <SwapHeld showing={current} wrap={block}>\n                {current ? children : item.node}\n              </SwapHeld>\n            </span>\n          </span>\n        )\n      })}\n    </span>\n  )\n}\n\ninterface SwapTextPart {\n  key: number\n  text: string\n  phase: 'in' | 'out'\n  /** Arrived with a change, so it fades in. */\n  fresh: boolean\n  /** Put in already leaving, so it starts fully shown and fades out. */\n  seeded: boolean\n}\n\ninterface SwapTextView {\n  text: string\n  prefix: string\n  suffix: string\n  parts: SwapTextPart[]\n  next: number\n}\n\nfunction nextView(view: SwapTextView, text: string): SwapTextView {\n  const { prefix, suffix, was, now } = seam(view.text, text)\n  // Back across the same seam: the letters still leaving turn round.\n  if (prefix === view.prefix && suffix === view.suffix && view.parts.length > 0) {\n    const parts = view.parts.map((part): SwapTextPart => ({\n      ...part,\n      phase: part.text === now ? 'in' : 'out',\n    }))\n    if (parts.some((part) => part.phase === 'in')) return { ...view, text, parts }\n    parts.push({\n      key: view.next,\n      text: now,\n      phase: 'in',\n      fresh: true,\n      seeded: false,\n    })\n    return { ...view, text, parts, next: view.next + 1 }\n  }\n  return {\n    text,\n    prefix,\n    suffix,\n    parts: [\n      { key: view.next, text: was, phase: 'out', fresh: false, seeded: true },\n      {\n        key: view.next + 1,\n        text: now,\n        phase: 'in',\n        fresh: true,\n        seeded: false,\n      },\n    ],\n    next: view.next + 2,\n  }\n}\n\n/** Whether a `SwapText` cut short gives its whole text as a `title`: not inside a `CutTooltip`, which shows it. */\nconst SwapTextTitleContext = createContext(true)\n\ntype SwapTextMove = { text: string; from: number; to: number }\n\n/** Who measures in a stack, and its last move. */\nfunction swapTextStack() {\n  let lead: string | null = null\n  let last: SwapTextMove | null = null\n  return {\n    /** Leads the stack if no one does yet. */\n    join: (id: string) => {\n      lead ??= id\n    },\n    leave: (id: string) => {\n      if (lead === id) lead = null\n    },\n    /** The lead's own move, or for the others, the lead's move to the same text. */\n    move: (id: string, own: SwapTextMove): SwapTextMove => {\n      if (lead === id) last = own\n      return last?.text === own.text ? last : own\n    },\n  }\n}\n\nconst SwapTextStackContext = createContext<ReturnType<typeof swapTextStack> | null>(null)\n\n/** Copies of one text laid over each other: the first `SwapText` inside measures each change and the rest move with it. */\nfunction SwapTextStack({ children }: { children: ReactNode }) {\n  const [stack] = useState(swapTextStack)\n  return <SwapTextStackContext value={stack}>{children}</SwapTextStackContext>\n}\n\nfunction currentPart(middle: Element | null): Element | null {\n  return middle?.querySelector(':scope > [data-phase=in]') ?? null\n}\n\nfunction isTruncated(...elements: (Element | null | undefined)[]): boolean {\n  return elements.some((element) => element && element.scrollWidth > element.clientWidth)\n}\n\n/**\n * Text that keeps what two values share. From \"Save changes\" to \"Saved\",\n * \"Save\" stays put, \" changes\" fades out and \"d\" fades in, and the width\n * between them follows. Text too long for its box truncates, with the whole\n * text as its `title`, or inside a `CutTooltip` in its tooltip: it says\n * whether it is cut with `data-cut`.\n */\nfunction SwapText({ text, className }: { text: string; className?: string }) {\n  const rootRef = useRef<HTMLSpanElement>(null)\n  const prefixRef = useRef<HTMLSpanElement>(null)\n  const middleRef = useRef<HTMLSpanElement>(null)\n  const suffixRef = useRef<HTMLSpanElement>(null)\n  const [stored, setStored] = useState<SwapTextView>(() => ({\n    text,\n    prefix: text,\n    suffix: '',\n    parts: [],\n    next: 0,\n  }))\n  let view = stored\n  if (stored.text !== text) {\n    view = nextView(stored, text)\n    setStored(view)\n  }\n  const split = view.parts.length > 0\n\n  // Text that fits stays split once it has changed: joining it would re-kern\n  // the seam and nudge the letters a fraction of a pixel.\n  useSettled(middleRef, split ? text : '', () => {\n    const truncated = isTruncated(prefixRef.current, currentPart(middleRef.current))\n    setStored((latest) => {\n      if (latest.text !== text) return latest\n      return truncated\n        ? { ...latest, prefix: text, suffix: '', parts: [] }\n        : {\n            ...latest,\n            parts: latest.parts.filter((part) => part.phase === 'in'),\n          }\n    })\n  })\n\n  const [truncated, setTruncated] = useState(false)\n  const titled = use(SwapTextTitleContext)\n  useEffect(() => {\n    const root = rootRef.current\n    if (!root) return\n    const observer = new ResizeObserver(() => {\n      setTruncated(isTruncated(prefixRef.current, currentPart(middleRef.current)))\n    })\n    observer.observe(root)\n    return () => observer.disconnect()\n  }, [view])\n\n  // The first in a stack to mount leads it; layout effects run in tree order.\n  const self = useId()\n  const stack = use(SwapTextStackContext)\n  useLayoutEffect(() => {\n    if (!stack) return\n    stack.join(self)\n    return () => stack.leave(self)\n  }, [stack, self])\n\n  const lastWidth = useLastWidth(rootRef)\n  useLayoutEffect(() => {\n    const middle = middleRef.current\n    const total = lastWidth.current\n    if (!middle || !prefixRef.current || !suffixRef.current || total === null) return\n    const [prefix, suffix] = [prefixRef.current, suffixRef.current]\n    let to = 0\n    let from = 0\n    withoutTransition(middle, () => {\n      releaseWidth(middle)\n      to = layoutWidth(middle)\n      from = Math.max(0, total - layoutWidth(prefix) - layoutWidth(suffix))\n    })\n    if (stack) ({ from, to } = stack.move(self, { text, from, to }))\n    if (Math.abs(to - from) >= 0.5) animateWidth(middle, from, to)\n  }, [text, lastWidth, stack, self])\n\n  return (\n    <span\n      ref={rootRef}\n      // Its own direction, so a label keeps its letter order in a page that reads the other way.\n      dir='auto'\n      data-slot='swap-text'\n      title={truncated && titled ? text : undefined}\n      data-cut={truncated ? 'cut' : 'whole'}\n      className={cn('inline-flex min-w-0 items-center whitespace-pre', className)}\n    >\n      {/* Read as one piece of text: the pieces below would be read with a space at each seam. */}\n      {split ? <span className='sr-only'>{text}</span> : null}\n      <span\n        ref={prefixRef}\n        aria-hidden={split || undefined}\n        className={cn('overflow-hidden text-ellipsis', split ? 'shrink-0' : 'min-w-0')}\n      >\n        {view.prefix}\n      </span>\n      <span\n        ref={middleRef}\n        aria-hidden={split || undefined}\n        className='relative inline-flex min-w-0 self-stretch overflow-x-clip transition-[width] duration-(--motion-layout-duration) ease-(--motion-layout-easing) motion-reduce:transition-none'\n      >\n        {view.parts.map((part) => (\n          <span\n            key={part.key}\n            data-phase={part.phase}\n            data-fresh={part.fresh ? '' : undefined}\n            data-seeded={part.seeded ? '' : undefined}\n            className={cn(\n              part.phase === 'in'\n                ? 'w-[var(--swap-width,auto)] min-w-0 shrink-[var(--swap-shrink,1)] overflow-hidden text-ellipsis'\n                : 'pointer-events-none absolute inset-y-0 start-0 flex items-center',\n              swapItemMotion,\n              swapWait,\n              'data-seeded:starting:opacity-100',\n            )}\n          >\n            {part.text}\n          </span>\n        ))}\n      </span>\n      <span ref={suffixRef} aria-hidden={split || undefined} className='shrink-0'>\n        {view.suffix}\n      </span>\n    </span>\n  )\n}\n\n/**\n * An icon that rolls to `onIcon` when something turns on, such as a pressed\n * toggle or a picked tab, and back when it turns off.\n */\nfunction SwapIcon({\n  on,\n  onIcon,\n  slot,\n  clip = false,\n  children,\n}: {\n  on: boolean\n  onIcon: ReactNode\n  /**\n   * The `data-slot` of the icon's box, such as `segmented-control-icon`, when\n   * no part around it, such as ui-sdk's `ToggleIcon`, carries one.\n   */\n  slot?: string\n  /**\n   * Clips the roll at the icon's own box, for an icon with more beside it\n   * than a control's edge, such as a line of text below in a taller row.\n   */\n  clip?: boolean\n  children: ReactNode\n}) {\n  return (\n    <Swap roll className={cn(swapIconClassName, clip && 'overflow-y-clip')}>\n      <span key={on ? 'on' : 'off'} data-slot={slot} className='flex'>\n        {on ? onIcon : children}\n      </span>\n    </Swap>\n  )\n}\n\n/**\n * Focus that follows what a Swap brings in. Call the function it gives\n * before a change, then, once the change has rendered with a new `key`, the\n * first `[data-focus-target]` in `root` outside what is leaving (which is\n * inert) takes focus. With no argument it follows only when focus was inside\n * `root`, so it never pulls focus in from elsewhere. A change nobody called\n * it for, such as new data from the page, follows too when focus was on what\n * leaves, which would otherwise drop it to the page; `false` keeps it where\n * it is.\n */\nfunction useSwapFocus(root: RefObject<HTMLElement | null>, key: unknown) {\n  // Whether the next change follows, when it was asked; null to follow focus that is leaving.\n  const moving = useRef<boolean | null>(null)\n  useLayoutEffect(() => {\n    const asked = moving.current\n    moving.current = null\n    const active = document.activeElement\n    const leaving =\n      active !== null &&\n      (root.current?.contains(active) ?? false) &&\n      active.closest('[inert]') !== null\n    if (!(asked ?? leaving)) return\n    const targets = root.current?.querySelectorAll<HTMLElement>('[data-focus-target]')\n    Array.from(targets ?? [])\n      .find((target) => !target.closest('[inert]'))\n      // It takes the place of what had focus, so nothing scrolls to it: a content still rising would scroll its column.\n      ?.focus({ preventScroll: true })\n  }, [key, root])\n  return useCallback(\n    (follow?: boolean) => {\n      moving.current = follow ?? root.current?.contains(document.activeElement) ?? false\n    },\n    [root],\n  )\n}\n\nexport {\n  SwapTextStack,\n  swapTextStack,\n  SwapTextTitleContext,\n  contentKey,\n  fullPixels,\n  dropLeft,\n  flattenChildren,\n  graphemes,\n  nextView,\n  seam,\n  Swap,\n  SwapIcon,\n  swapIconClassName,\n  swapTo,\n  SwapText,\n  useSwapFocus,\n  useSwapLeaving,\n}\nexport type { SwapItem, SwapTextView }\n",
      "type": "registry:lib",
      "target": "@lib/swap.tsx"
    }
  ],
  "type": "registry:lib"
}