{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "resize",
  "title": "Resize",
  "description": "Moves an element from one size to another on its own transition, then hands the size back to layout; a change mid-way goes on from where it is. Also the panel that opens and closes on its height, and follows its content while open, a table’s columns gliding to new widths, and a change made at once with transitions off. Accordion, Collapsible, Dialog, Drawer, Slider, Swap, Table and the choice cards share it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/resize.ts",
      "content": "/**\n * Moving an element from one size to another on its own CSS transition, then\n * handing the size back to layout: the Accordion's panel, the Dialog's and\n * Drawer's box, and the Swap's width. Kept outside components: the React\n * Compiler drops a forced reflow written inside one, and then the size jumps.\n */\n\nimport { commitStyles } from '@/registry/lib/refs'\n\nconst runs = new WeakMap<object, number>()\n\n/**\n * Starts a new run on `key`, and returns whether it is still the latest: a\n * change that comes mid-way starts another, and the older one must then leave\n * the size alone.\n */\nexport function startRun(key: object): () => boolean {\n  const run = (runs.get(key) ?? 0) + 1\n  runs.set(key, run)\n  return () => runs.get(key) === run\n}\n\nconst sizeRuns = new WeakMap<object, Partial<Record<Size, object>>>()\n\n/**\n * Starts a new run of `element`'s `size`, and returns whether it is still the\n * latest. A newer run of the same size ends it, and so does `startRun(element)`,\n * which ends every size's run at once; a run of the other size doesn't, so a\n * box's width and height move together, as in a Swap that holds a block.\n */\nexport function startSizeRun(element: object, size: Size): () => boolean {\n  const keys = sizeRuns.get(element) ?? {}\n  sizeRuns.set(element, keys)\n  keys[size] ??= {}\n  const ownLatest = startRun(keys[size])\n  const elementRun = runs.get(element) ?? 0\n  return () => ownLatest() && (runs.get(element) ?? 0) === elementRun\n}\n\n/**\n * The id of a Web Animation a component plays in step with one of its CSS\n * transitions. Its duration comes from a role's variable or the transition's\n * own, so a tool that retimes the roles, such as the playground's Speed,\n * retimes it too.\n */\nexport const FOLLOWS_TRANSITION = 'follows-transition'\n\n/**\n * The id of a Web Animation that waits on a time in ms rather than a role's,\n * such as the page's clock. A tool that slows the page, such as the\n * playground's Speed, slows it by its `playbackRate`.\n */\nexport const PAGE_TIME = 'page-time'\n\n/** A CSS time, such as a `--motion-press-duration` of `0.3s` or `300ms`, in ms; `fallback` when it is empty or not a time. */\nexport function cssTime(value: string, fallback: number) {\n  const number = Number.parseFloat(value)\n  if (!Number.isFinite(number)) return fallback\n  return value.trim().endsWith('ms') ? number : number * 1000\n}\n\n/** A motion role's duration where `element` is, in ms, as the feel sets it; `fallback` outside a Kino theme. */\nexport function roleDuration(\n  element: Element,\n  role: 'press' | 'enter' | 'exit' | 'layout' | 'morph' | 'draw',\n  fallback = 0,\n) {\n  return cssTime(\n    getComputedStyle(element).getPropertyValue(`--motion-${role}-duration`),\n    fallback,\n  )\n}\n\n/** A computed CSS list split at its top-level commas: `linear(0, 1), ease` is two items. */\nfunction cssList(value: string): string[] {\n  const items: string[] = []\n  let depth = 0\n  let start = 0\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index]\n    if (character === '(') depth++\n    else if (character === ')') depth--\n    else if (character === ',' && depth === 0) {\n      items.push(value.slice(start, index).trim())\n      start = index + 1\n    }\n  }\n  items.push(value.slice(start).trim())\n  return items\n}\n\n/**\n * How `property` moves in an element's computed transition: its duration in\n * ms and its easing, or null when it doesn't move, because it isn't listed or\n * has no duration (reduced motion, an instant open). A Web Animation played\n * on it with this timing follows the feel, as the transition would.\n */\nexport function transitionTiming(\n  style: Pick<\n    CSSStyleDeclaration,\n    'transitionProperty' | 'transitionDuration' | 'transitionTimingFunction'\n  >,\n  property: string,\n): { duration: number; easing: string } | null {\n  const index = cssList(style.transitionProperty).findLastIndex(\n    (name) => name === property || name === 'all',\n  )\n  if (index < 0) return null\n  const at = (list: string[]) => list[index % list.length] ?? ''\n  const duration = cssTime(at(cssList(style.transitionDuration)), 0)\n  if (!(duration > 0)) return null\n  return { duration, easing: at(cssList(style.transitionTimingFunction)) }\n}\n\n/** The CSS transitions running on `element`, or inside it too with `subtree`, of one property, of several, or of any. */\nexport function runningTransitions(\n  element: Element,\n  {\n    property,\n    subtree = false,\n  }: { property?: string | readonly string[]; subtree?: boolean } = {},\n): CSSTransition[] {\n  const properties = typeof property === 'string' ? [property] : property\n  return element\n    .getAnimations({ subtree })\n    .filter(\n      (animation): animation is CSSTransition =>\n        animation instanceof CSSTransition &&\n        (properties === undefined || properties.includes(animation.transitionProperty)),\n    )\n}\n\n/**\n * Resolves once the transitions running a frame from now (so the ones just\n * started exist) have ended or been turned round. Animations that aren't\n * transitions, such as a spinner's turn, don't count.\n */\nexport function transitionsSettled(\n  element: Element,\n  options?: { property?: string | readonly string[]; subtree?: boolean },\n): Promise<void> {\n  return new Promise((resolve) => {\n    requestAnimationFrame(() => {\n      void Promise.allSettled(\n        runningTransitions(element, options).map((animation) => animation.finished),\n      ).then(() => resolve())\n    })\n  })\n}\n\n/**\n * Resolves once no transition is left running, where `transitionsSettled`\n * resolves when the ones running now end or are turned round. A change that\n * comes mid-way turns them round into new ones, and this waits for those\n * too, so what leaves is let go only once it has finished leaving.\n */\nexport async function transitionsQuiet(\n  element: Element,\n  options?: { property?: string | readonly string[]; subtree?: boolean },\n): Promise<void> {\n  await transitionsSettled(element, options)\n  while (runningTransitions(element, options).length > 0) {\n    // oxlint-disable-next-line no-await-in-loop -- each wait is for the transitions that replaced the last\n    await transitionsSettled(element, options)\n  }\n}\n\ntype Size = 'height' | 'width'\n\n/** The size `element` is at now if it is moving, or `rest` if it isn't: a change mid-way goes on from where it is. */\nexport function sizeNow(element: HTMLElement, size: Size, rest: number): number {\n  return runningTransitions(element, { property: size }).length > 0\n    ? Number.parseFloat(getComputedStyle(element)[size])\n    : rest\n}\n\n/**\n * Moves `element`'s height or width from `from` to `to` pixels on its own\n * transition. `write` sets the size (its style property unless given), and\n * `alongside` moves something with it: it is called with `true` while the\n * start is set with no transition, then `false` once things may move. It\n * resolves when the move has settled, with whether this run is still the\n * latest, so the caller can hand the size back to layout.\n */\nexport function animateSize(\n  element: HTMLElement,\n  size: Size,\n  from: number,\n  to: number,\n  {\n    write = (value) => {\n      element.style[size] = value\n    },\n    alongside,\n  }: {\n    write?: (value: string) => void\n    alongside?: (start: boolean) => void\n  } = {},\n): Promise<boolean> {\n  const latest = startSizeRun(element, size)\n  withoutTransition(\n    element,\n    () => {\n      write(`${from}px`)\n      alongside?.(true)\n    },\n    { properties: [size] },\n  )\n  write(`${to}px`)\n  alongside?.(false)\n  return transitionsSettled(element, { property: size }).then(latest)\n}\n\n/**\n * Makes `change` land at once: `element`'s transitions (or each one's, for\n * several) are off while it\n * runs, its style is read so the change is styled with none, and then its\n * inline `transition-property` is put back; its durations, delays and easings\n * are never touched. With `properties`, only those stop and the rest keep\n * running, such as a fade the change happens during, unless it transitions\n * `all`, which can't be split and stops whole. With\n * `subtree`, every element inside it stops too. Kept outside components: the\n * React Compiler drops the forced read written inside one, and then the\n * change animates.\n */\nexport function withoutTransition(\n  element: HTMLElement | SVGElement | readonly (HTMLElement | SVGElement)[],\n  change: () => void,\n  {\n    properties,\n    subtree = false,\n  }: { properties?: readonly string[]; subtree?: boolean } = {},\n) {\n  const elements = isList(element) ? element : [element]\n  const parts = elements.flatMap((one) =>\n    subtree ? [one, ...one.querySelectorAll<HTMLElement | SVGElement>('*')] : [one],\n  )\n  const held = parts.map((part) => {\n    const before = part.style.transitionProperty\n    if (!properties) {\n      part.style.transitionProperty = 'none'\n    } else {\n      const list = getComputedStyle(part)\n        .transitionProperty.split(',')\n        .map((name) => name.trim())\n      part.style.transitionProperty = list.includes('all')\n        ? 'none'\n        : transitionsWithout(list, properties).join(', ')\n    }\n    return () => {\n      part.style.transitionProperty = before\n    }\n  })\n  change()\n  // Reading one style styles the whole document, so every part, inside\n  // too, takes the change, and drops a starting style, with none.\n  for (const one of elements) commitStyles(one)\n  for (const release of held) release()\n}\n\nfunction isList<T>(value: T | readonly T[]): value is readonly T[] {\n  return Array.isArray(value)\n}\n\n/**\n * A transition list with each of `properties` replaced by a name nothing\n * animates. Each one keeps its place, so every other property keeps its own\n * duration.\n */\nexport function transitionsWithout(\n  list: readonly string[],\n  properties: readonly string[],\n): string[] {\n  return list.map((name) => (properties.includes(name) ? '--held' : name))\n}\n\n/**\n * Moves `surface` to `inner`'s height, or width, whenever that changes, on\n * the surface's own transition, then hands the size back to layout: a dialog\n * whose content grows, a list that filters, a number that gains a digit. A\n * change mid-way goes on from where it is. `moving` is called as each move\n * starts, with the sizes it moves between, and may return an `alongside` for\n * it (see `animateSize`); `settled` runs once a move has ended and no newer\n * one has started. Returns a function that stops following.\n */\nexport function followSize(\n  surface: HTMLElement,\n  inner: HTMLElement,\n  size: Size,\n  {\n    moving,\n    settled,\n    instant,\n  }: {\n    moving?: (from: number, to: number) => ((start: boolean) => void) | undefined\n    settled?: () => void\n    /** Whether this change takes the new size at once, with no move. */\n    instant?: () => boolean\n  } = {},\n): () => void {\n  // A width to the fraction of a pixel, as text has, so nothing jumps when layout takes it back.\n  const measure = () =>\n    size === 'height' ? inner.offsetHeight : inner.getBoundingClientRect().width\n  const sides =\n    size === 'height'\n      ? (['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom'] as const)\n      : (['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight'] as const)\n  // The surface's size for an inner one: with its own border and padding,\n  // and no larger than its maximum, past which it doesn't move.\n  const outer = (inside: number) => {\n    const style = getComputedStyle(surface)\n    const chrome =\n      style.boxSizing === 'border-box'\n        ? sides\n            .map((side) => Number.parseFloat(style[side]) || 0)\n            .reduce((sum, value) => sum + value, 0)\n        : 0\n    const limit = size === 'height' ? style.maxHeight : style.maxWidth\n    const max = limit.endsWith('px') ? Number.parseFloat(limit) : Infinity\n    return Math.min(inside + chrome, max)\n  }\n  let last = measure()\n  const observer = new ResizeObserver(() => {\n    const inside = measure()\n    if (inside === last) return\n    if (instant?.()) {\n      last = inside\n      // A move under way is dropped, and layout has the size.\n      startRun(surface)\n      surface.style[size] = ''\n      settled?.()\n      return\n    }\n    const running = runningTransitions(surface, { property: size }).length > 0\n    const from = sizeNow(surface, size, outer(last))\n    const to = outer(inside)\n    last = inside\n    if (!running && Math.abs(to - from) < 0.5) return\n    void animateSize(surface, size, from, to, {\n      alongside: moving?.(from, to),\n    }).then((latest) => {\n      if (!latest) return\n      surface.style[size] = ''\n      settled?.()\n    })\n  })\n  observer.observe(inner)\n  return () => observer.disconnect()\n}\n\n/** `followSize` on the height. */\nexport function followHeight(\n  surface: HTMLElement,\n  inner: HTMLElement,\n  options?: Parameters<typeof followSize>[3],\n): () => void {\n  return followSize(surface, inner, 'height', options)\n}\n\n/**\n * A copy of `element` no one can reach or read: no ids, hidden from screen\n * readers, inert, out of the flow and taking no pointer, with `style` on\n * top. For a copy that leaves in an item's place (`leaveAsCopies` in the\n * flow lib), or one that shows where a layout will land before it does.\n */\nexport function inertCopy(\n  element: HTMLElement,\n  style?: Partial<CSSStyleDeclaration>,\n): HTMLElement {\n  const copy = element.cloneNode(true) as HTMLElement\n  for (const node of [copy, ...copy.querySelectorAll('[id]')]) node.removeAttribute('id')\n  copy.setAttribute('aria-hidden', 'true')\n  copy.inert = true\n  Object.assign(\n    copy.style,\n    { position: 'absolute', margin: '0', pointerEvents: 'none' },\n    style,\n  )\n  return copy\n}\n\n/** One hold per element, shared by everything that holds it. */\nconst holds = new WeakMap<HTMLElement, { frame: number; holders: number }>()\n\n/**\n * Marks `element` `data-resizing` from each `hold()` until two frames after\n * the latest, so what changes meanwhile lands at once instead of gliding.\n * Holders of one element share the mark; the last to `stop()` clears it.\n */\nexport function holdResizing(element: HTMLElement) {\n  const shared = holds.get(element) ?? { frame: 0, holders: 0 }\n  holds.set(element, shared)\n  shared.holders += 1\n  let stopped = false\n  return {\n    hold() {\n      element.dataset.resizing = ''\n      cancelAnimationFrame(shared.frame)\n      // Two frames: what places from a size measured by its own observer (ui-sdk's tab indicator) catches up a frame late.\n      shared.frame = requestAnimationFrame(() => {\n        shared.frame = requestAnimationFrame(() => delete element.dataset.resizing)\n      })\n    },\n    stop() {\n      if (stopped) return\n      stopped = true\n      shared.holders -= 1\n      if (shared.holders > 0) return\n      cancelAnimationFrame(shared.frame)\n      delete element.dataset.resizing\n      holds.delete(element)\n    },\n  }\n}\n\n/**\n * A ref that marks `element` `data-resizing` for two frames each time it changes\n * size, so what it places in `cqw` or `cqh`, which turn into pixels, moves at\n * once instead of gliding to the new size: a Slider's thumbs, a colour area's.\n */\nexport function markResizing(element: HTMLElement | null) {\n  if (!element) return\n  const resizing = holdResizing(element)\n  const observer = new ResizeObserver(() => resizing.hold())\n  observer.observe(element)\n  return () => {\n    observer.disconnect()\n    resizing.stop()\n  }\n}\n\n/**\n * A panel that opens and closes on its height, on `layout`, its content\n * fading out on `exit` and in as it opens: the Accordion's and a\n * collapsible's. Set `--collapse-height` to the height ui-sdk gives it\n * (`--accordion-panel-height`, `--collapsible-panel-height`), and clip it.\n * With `data-instant` it opens, closes and grows at once, for a panel the app\n * moves on its own, such as a run's rows as the run starts and ends.\n */\nexport const collapseClassName =\n  'h-(--collapse-height) transition-[height] duration-(--motion-layout-duration) ease-(--motion-layout-easing) *:transition-opacity *:duration-(--motion-enter-duration) *:ease-(--motion-enter-easing) data-ending-style:h-0 data-ending-style:*:opacity-0 data-ending-style:*:duration-(--motion-exit-duration) data-ending-style:*:ease-(--motion-exit-easing) data-starting-style:h-0 data-starting-style:*:opacity-0 data-instant:transition-none data-instant:*:transition-none motion-reduce:transition-none'\n\n/** Whether two lists of widths differ anywhere by half a pixel or more, or in length. */\nexport function widthsChanged(from: readonly number[], to: readonly number[]): boolean {\n  return (\n    from.length !== to.length ||\n    from.some((width, index) => Math.abs(width - to[index]) >= 0.5)\n  )\n}\n\n/** A table's columns, as the cells of its first row, in the header if it has one. */\nexport function columnCells(table: HTMLTableElement) {\n  return [...((table.tHead?.rows[0] ?? table.rows[0])?.cells ?? [])]\n}\n\n/** The width of each of a table's columns now, in px. */\nexport function columnWidths(table: HTMLTableElement) {\n  return columnCells(table).map((cell) => cell.getBoundingClientRect().width)\n}\n\n/**\n * The width of each cell in a row whose cells span `spans` columns, from\n * the columns' `widths`: each cell is as wide as the columns it spans.\n */\nexport function spanWidths(widths: readonly number[], spans: readonly number[]) {\n  let column = 0\n  return spans.map((span) => {\n    const width = widths.slice(column, column + span).reduce((sum, next) => sum + next, 0)\n    column += span\n    return width\n  })\n}\n\n/**\n * Moves a table's columns to their new widths on the header cells' own width\n * transition whenever rows come or go, then hands the widths back to layout:\n * the column whose widest value just left narrows, and the ones beside it\n * widen, in place of jumping. While they move the table is laid out fixed,\n * so a column can be narrower than what just came into it, and marked\n * `data-columns-moving`, for its cells to clip what they hold until it fits. The\n * columns are its first row's cells, in the header if it has one. Returns a\n * function that stops following.\n */\nexport function followColumns(table: HTMLTableElement): () => void {\n  const widths = (row: HTMLTableCellElement[]) =>\n    row.map((cell) => cell.getBoundingClientRect().width)\n  const sum = (list: number[]) => list.reduce((total, next) => total + next, 0)\n  const hold = (width: number | null) => {\n    table.style.tableLayout = width === null ? '' : 'fixed'\n    table.style.width = width === null ? '' : `${width}px`\n    table.toggleAttribute('data-columns-moving', width !== null)\n  }\n  // The widths last laid out: once rows have changed, layout already has the new ones.\n  let last = widths(columnCells(table))\n  const sizes = new ResizeObserver(() => {\n    if (!table.hasAttribute('data-columns-moving')) last = widths(columnCells(table))\n  })\n  const watch = () => {\n    sizes.disconnect()\n    for (const cell of columnCells(table)) sizes.observe(cell)\n  }\n  const changes = new MutationObserver((records) => {\n    // Rows in the table's own sections, not copies of them in a layer.\n    const rows = records.some(\n      (record) =>\n        record.target === table || record.target instanceof HTMLTableSectionElement,\n    )\n    if (!rows) return\n    const row = columnCells(table)\n    if (row.length !== last.length) {\n      last = widths(row)\n      watch()\n      return\n    }\n    const from = row.map((cell, index) => sizeNow(cell, 'width', last[index]))\n    hold(null)\n    for (const cell of row) cell.style.width = ''\n    const to = widths(row)\n    last = to\n    if (!widthsChanged(from, to)) return\n    const latest = startRun(table)\n    // Its narrower width: a table wider than its box grows to its columns.\n    hold(Math.min(sum(from), sum(to)))\n    const moves = row.map((cell, index) =>\n      animateSize(cell, 'width', from[index], to[index]),\n    )\n    void Promise.all(moves).then(() => {\n      if (!latest()) return\n      for (const cell of row) cell.style.width = ''\n      hold(null)\n    })\n  })\n  watch()\n  changes.observe(table, { childList: true, subtree: true })\n  return () => {\n    changes.disconnect()\n    sizes.disconnect()\n  }\n}\n\n/**\n * Keeps an open collapsing panel on its content's height. ui-sdk sizes the\n * panel while it opens and closes, then leaves it at `auto`, so content that\n * grows or shrinks after that would jump: this moves the panel to the new\n * height on its own transition, then hands it back to `auto`. Content that is\n * itself moving, such as a nested panel opening, is followed frame by frame\n * instead. `variable` is the height ui-sdk writes\n * (`--accordion-panel-height`). A column that changes width re-flows the\n * text, and the panel follows that at once. Returns a function that stops\n * following.\n */\nexport function followPanelContent(\n  panel: HTMLElement,\n  content: HTMLElement,\n  variable: string,\n): () => void {\n  const write = (value: string) => panel.style.setProperty(variable, value)\n  // The size the panel last followed, so steps too small to act on add up.\n  let last: { width: number; height: number } | null = null\n  const observer = new ResizeObserver(([entry]) => {\n    const [{ inlineSize: width, blockSize: height }] = entry.borderBoxSize\n    const previous = last\n    if (!previous || Math.abs(previous.width - width) >= 0.5) {\n      last = { width, height }\n      return\n    }\n    if (Math.abs(previous.height - height) < 0.5) return\n    last = { width, height }\n    const open =\n      panel.hasAttribute('data-open') && !panel.hasAttribute('data-starting-style')\n    if (!open) return\n    if (runningTransitions(content, { property: 'height', subtree: true }).length > 0) {\n      // A move of the panel's own that is still running stops where it is.\n      startRun(panel)\n      write('auto')\n      return\n    }\n    // The panel's own padding (the Accordion's room for a focus ring) sits around the content.\n    const style = getComputedStyle(panel)\n    const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)\n    const target = height + padding\n    void animateSize(\n      panel,\n      'height',\n      sizeNow(panel, 'height', previous.height + padding),\n      target,\n      {\n        write,\n      },\n    ).then((latest) => {\n      // Closed meanwhile: the height is ui-sdk's again.\n      if (!latest || !panel.hasAttribute('data-open')) return\n      if (panel.style.getPropertyValue(variable) === `${target}px`) write('auto')\n    })\n  })\n  observer.observe(content)\n  return () => observer.disconnect()\n}\n",
      "type": "registry:lib",
      "target": "@lib/resize.ts"
    }
  ],
  "type": "registry:lib"
}