{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "flow",
  "title": "Flow",
  "description": "Items in a wrapping row, or a table's rows, that glide to their new places when the row changes, across lines too, and leave as a copy that fades where they were. The Combobox's chips and the Table's rows share it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/flow.ts",
      "content": "/*\n * Items in a wrapping row, such as a field's chips, that glide to their new\n * places when the row changes, and leave as a copy that fades where they\n * were: ui-sdk unmounts a chip the moment it is removed, so the chip itself\n * can't stay to leave. JavaScript only says where each item starts from;\n * the item's own `translate` transition, on `layout`, does the moving, and\n * its leaving styles, on `exit`, the fading. Kept outside components: the\n * React Compiler drops a forced reflow written inside one.\n *\n * An item marked `data-flow=start` is being put where it was seen, so its\n * `translate` must not transition then; a leaving copy is marked\n * `data-leaving`, and its `translate` goes to none on `layout` there. The\n * copy goes back into the row where the item was, so it keeps its place in\n * the order things are painted (an avatar stack's faces overlap); a row that\n * styles its children leaves `[data-leaving]` out. An item marked\n * `data-flow-held` is placed by whoever holds it, such as a row dragged in a\n * sortable list: it is measured, so it glides once let go, but never glided\n * while held. One marked `data-flow-away` as it is taken out has moved to\n * another row, which shows it arrive, so it leaves no copy here.\n */\n\nimport { translateOf } from '@/registry/lib/highlight'\nimport { commitStyles, markMounted } from '@/registry/lib/refs'\nimport {\n  columnWidths,\n  followHeight,\n  inertCopy,\n  runningTransitions,\n  spanWidths,\n  startRun,\n  transitionsSettled,\n  withoutTransition,\n} from '@/registry/lib/resize'\nimport { useEffect, useRef } from 'react'\n\n/**\n * Where an item sits, in px from the start edge and top of the row's offset\n * parent, without any `translate`: a row that moves, such as an avatar\n * stack whose neighbours make room for a face that joins, carries its items\n * with it, and they glide from where they were seen.\n */\nexport interface Spot {\n  x: number\n  y: number\n}\n\n/** A spot, with what a copy of the item needs once it is gone: its size, and its place in the row and the row's in its parent. */\ninterface Placed extends Spot {\n  left: number\n  top: number\n  width: number\n  height: number\n  rowLeft: number\n  rowTop: number\n}\n\n/** An element, HTML or SVG, whose inline style can be set. */\ntype Styled = HTMLElement | SVGElement\n\n/** A property put on an element's inline style, to take off once it may move again. */\nexport type Taken = readonly [Styled, string]\n\n/**\n * A transition an item, or something inside it, was running, to pick up on\n * its copy from where it had got to.\n */\ninterface Running {\n  /** Where it ran: the child indexes from the item down, empty for the item itself. */\n  path: number[]\n  transition: CSSTransition\n  keyframes: Keyframe[]\n  timing: EffectTiming\n  /** Its time, in ms, when it was read. */\n  at: number\n  /** When it was read, on `performance.now()`. */\n  read: number\n}\n\n/**\n * The `translate` that shows an item where it was seen a moment ago, now\n * that it sits at `now`: its old spot plus the `translate` it was moving\n * off, so a glide cut short goes on from where it is. Null when it hasn't\n * moved by half a pixel.\n */\nexport function flowStart(\n  was: Spot,\n  moving: readonly [number, number],\n  now: Spot,\n): readonly [number, number] | null {\n  const x = was.x + moving[0] - now.x\n  const y = was.y + moving[1] - now.y\n  return Math.abs(x) < 0.5 && Math.abs(y) < 0.5 ? null : [x, y]\n}\n\n/**\n * Whether an item that was resized moves the others to new places they\n * glide to. Items that wrap move whenever one changes size, items stacked\n * one under another (a table's rows) only when one changes height. An item\n * that grows or shrinks on a height transition of its own (`sizing`), such\n * as an accordion's panel opening, carries what is below it as it goes, a\n * frame at a time: a glide would hold them back where they were.\n */\nexport function sizeMoves({\n  stacked,\n  heightChanged,\n  sizing,\n}: {\n  stacked: boolean\n  heightChanged: boolean\n  sizing: boolean\n}): boolean {\n  return !sizing && (!stacked || heightChanged)\n}\n\n/**\n * Whether items that changed size glide to their new places, or are only\n * measured where they now are. They glide when they moved because of\n * something inside the row: an item that came, went or changed (`inside`).\n * When the row, or what holds it, changed width with nothing changed inside\n * (the window or a canvas resized), they wrap again where they are, with no\n * glide from where they were.\n */\nexport function resizeGlides({\n  moved,\n  narrowed,\n  inside,\n}: {\n  /** An item changed size in a way that moves the others. */\n  moved: boolean\n  /** The row or what holds it changed width. */\n  narrowed: boolean\n  /** Something inside the row changed since the last look. */\n  inside: boolean\n}): boolean {\n  return moved && (inside || !narrowed)\n}\n\n/**\n * Whether what holds the row takes its new height at once rather than\n * animating to it: the row changed width from outside (the window or a canvas\n * resized), so its items rewrap in place and there is no change to show.\n */\nexport function resizeJumps(change: Parameters<typeof resizeGlides>[0]): boolean {\n  return change.narrowed && !resizeGlides(change)\n}\n\n/**\n * Its layout size with the border, before any transform: unrounded where the\n * styles give it, since a copy a fraction of a pixel narrower than its item\n * cuts its label short (`offsetWidth` rounds).\n */\nfunction borderBoxOf(item: HTMLElement, style: CSSStyleDeclaration): [number, number] {\n  const width = parseFloat(style.width)\n  const height = parseFloat(style.height)\n  return style.boxSizing === 'border-box' && width >= 0 && height >= 0\n    ? [width, height]\n    : [item.offsetWidth, item.offsetHeight]\n}\n\n/**\n * The item's spot, from its centre and its layout size, so a scale on its\n * way in or out doesn't move it. `x` runs from the start edge, so an item\n * whose end moves (an input that fills the rest of a line) keeps its place\n * in right to left as it does in left to right.\n */\nfunction spotOf(item: HTMLElement, row: HTMLElement, box: DOMRect, rtl: boolean): Placed {\n  const itemBox = item.getBoundingClientRect()\n  const style = getComputedStyle(item)\n  const [width, height] = borderBoxOf(item, style)\n  const [x, y] = translateOf(style.translate)\n  const left = (itemBox.left + itemBox.right) / 2 - x - box.left - width / 2\n  const top = (itemBox.top + itemBox.bottom) / 2 - y - box.top - height / 2\n  const parentWidth = row.offsetParent?.clientWidth ?? box.width\n  const start = rtl ? parentWidth - row.offsetLeft - row.offsetWidth : row.offsetLeft\n  return {\n    x: start + (rtl ? row.offsetWidth - left - width : left),\n    y: row.offsetTop + top,\n    left,\n    top,\n    width,\n    height,\n    rowLeft: row.offsetLeft,\n    rowTop: row.offsetTop,\n  }\n}\n\n/** The child indexes from `root` down to `node`, which sits inside it. */\nfunction pathTo(root: Element, node: Element): number[] {\n  const path: number[] = []\n  for (let at = node; at !== root && at.parentElement; at = at.parentElement)\n    path.unshift([...at.parentElement.children].indexOf(at))\n  return path\n}\n\n/** The element at `path` inside `root`, if it has one. */\nfunction atPath(root: Element, path: readonly number[]): Element | undefined {\n  let at: Element | undefined = root\n  for (const index of path) at = at?.children[index]\n  return at\n}\n\n/** The CSS transitions `item` and everything in it are running, as they stand now. */\nfunction runningOn(item: HTMLElement): Running[] {\n  const read = performance.now()\n  return runningTransitions(item, { subtree: true }).flatMap((transition) => {\n    const effect = transition.effect as KeyframeEffect | null\n    // One on a pseudo-element can't be put on an inline style.\n    if (!effect?.target || effect.pseudoElement) return []\n    return [\n      {\n        path: pathTo(item, effect.target),\n        transition,\n        keyframes: effect.getKeyframes(),\n        timing: effect.getTiming(),\n        at: Number(transition.currentTime ?? 0),\n        read,\n      },\n    ]\n  })\n}\n\n/**\n * Puts on `ghost`, and on each part of it, the values the item's transitions\n * had reached: a chip removed while it glides or scales in leaves from where\n * it was seen, and a timeline's event removed while its line draws leaves\n * with the line as far as it got.\n */\nfunction takeOver(ghost: HTMLElement, running: readonly Running[]): Taken[] {\n  const now = performance.now()\n  const values: [Styled, string, string][] = []\n  for (const { path, transition, keyframes, timing, at, read } of running) {\n    const target = atPath(ghost, path)\n    if (!(target instanceof HTMLElement || target instanceof SVGElement)) continue\n    const replay = target.animate(keyframes, { ...timing, fill: 'both' })\n    replay.pause()\n    // Its own time while it still has one; else worked out at its rate,\n    // which the page may have slowed since it was read.\n    replay.currentTime =\n      transition.currentTime === null\n        ? at + (now - read) * transition.playbackRate\n        : Number(transition.currentTime)\n    // The transition's own name for it: keyframes name it in camelCase,\n    // which `getPropertyValue` doesn't read.\n    const property = transition.transitionProperty\n    values.push([target, property, getComputedStyle(target).getPropertyValue(property)])\n    replay.cancel()\n  }\n  for (const [target, property, value] of values)\n    target.style.setProperty(property, value)\n  return values.map(([target, property]) => [target, property] as const)\n}\n\n/**\n * Reads where `item`'s transitions have got to, before it goes, and gives\n * the `from` for its `leaveAsCopy`: the copy leaves from there, not from\n * where `item` rests (a chip removed while it still scales in).\n */\nexport function fromWhereItIs(item: HTMLElement) {\n  const running = runningOn(item)\n  return (copy: HTMLElement) => takeOver(copy, running)\n}\n\n/**\n * Takes `item` back from the copy of it that is leaving, such as a chip\n * brought back by an undo while it still fades: the copy goes, and `item`\n * turns back to where it rests from where the copy had got to, with no jump.\n */\nexport function returnFromCopy(item: HTMLElement, copy: HTMLElement) {\n  const running = runningOn(copy)\n  copy.remove()\n  let taken: readonly Taken[] = []\n  withoutTransition(\n    item,\n    () => {\n      taken = takeOver(item, running)\n    },\n    { subtree: true },\n  )\n  for (const [part, property] of taken) part.style.removeProperty(property)\n}\n\n/** One item to leave as a copy: see `leaveAsCopy`. */\ninterface Leaving {\n  item: HTMLElement\n  parent: HTMLElement\n  next?: Node | null\n  style: Partial<CSSStyleDeclaration>\n  from: (copy: HTMLElement) => readonly Taken[]\n}\n\n/**\n * Leaves a copy of `item` in `parent`, before `next`: ui-sdk unmounts what\n * goes the moment it goes, so the copy plays its leaving styles in its\n * place. The copy can't be reached or read, and takes `style` (where it\n * was seen). `from` puts on the copy, once it is in, the values it and\n * its parts start from and returns what it set; the copy holds them for one\n * style with no transition, then is marked `data-leaving` and transitions\n * from there, and goes once those transitions have played.\n */\nexport function leaveAsCopy(item: HTMLElement, options: Omit<Leaving, 'item'>) {\n  return leaveAsCopies([{ item, ...options }])[0]!\n}\n\n/**\n * Leaves a copy of each item at once, as `leaveAsCopy` does one: every copy\n * goes in and is styled in one pass, so many rows leaving together, such as\n * a long list cut back to a few, cost one style rather than one each.\n */\nexport function leaveAsCopies(leaving: readonly Leaving[]): HTMLElement[] {\n  const copies = leaving.map(({ item, style }) => inertCopy(item, style))\n  // An entrance's starting style, on the copy or on anything in it (a\n  // timeline's marker scaling in, its line drawing), would play it again\n  // first: nothing in the copy transitions until it has been styled once.\n  const taken: Taken[] = []\n  withoutTransition(\n    copies,\n    () => {\n      // A neighbour taken out in the same batch of changes, such as the text\n      // between two words, is no place to go back before: the copy goes last.\n      leaving.forEach(({ parent, next = null }, at) =>\n        parent.insertBefore(copies[at]!, next?.parentNode === parent ? next : null),\n      )\n      leaving.forEach(({ from }, at) => taken.push(...from(copies[at]!)))\n    },\n    { subtree: true },\n  )\n  for (const [part, property] of taken) part.style.removeProperty(property)\n  for (const copy of copies) {\n    // Marked only now, with its transition back, so its leaving styles\n    // transition from where it was seen rather than apply at once.\n    copy.dataset.leaving = ''\n    void transitionsSettled(copy).then(() => copy.remove())\n  }\n  return copies\n}\n\n/**\n * What a copy of an item needs to fade where it was, back in `row` before\n * `next`, then go. Everything it reads from the row is read now, before any\n * copy goes in, so copies made together lay the row out once.\n */\nfunction leaving(\n  item: HTMLElement,\n  spot: Placed,\n  running: readonly Running[],\n  row: HTMLElement,\n  next: Node | null,\n): Leaving {\n  const table = row.closest('table')\n  // A row taken out of the table's layout has no columns: its cells take\n  // the widths the columns have now.\n  const columns =\n    table && item instanceof HTMLTableRowElement ? columnWidths(table) : null\n  return {\n    item,\n    parent: row,\n    next,\n    style: {\n      // Where it was seen, though the row may have moved since.\n      left: `${spot.left + spot.rowLeft - row.offsetLeft}px`,\n      top: `${spot.top + spot.rowTop - row.offsetTop}px`,\n      // Measured while it was there: a removed node has no size.\n      boxSizing: 'border-box',\n      width: `${spot.width}px`,\n      height: `${spot.height}px`,\n    },\n    from: (copy) => {\n      if (columns && copy instanceof HTMLTableRowElement) {\n        const cells = [...copy.cells]\n        const widths = spanWidths(\n          columns,\n          cells.map((cell) => cell.colSpan),\n        )\n        // Laid out as a table of its own, so its cells keep their vertical\n        // alignment; the spacing between the table's rows is not inside it.\n        Object.assign(copy.style, {\n          display: 'table',\n          tableLayout: 'fixed',\n          borderSpacing: '0',\n        })\n        cells.forEach((cell, index) => {\n          Object.assign(cell.style, {\n            boxSizing: 'border-box',\n            width: `${widths[index]}px`,\n          })\n        })\n      }\n      return takeOver(copy, running)\n    },\n  }\n}\n\n/**\n * Follows `row`'s direct children that match `items`: each one that moves,\n * because another came or went or because it changed size, glides there\n * from where it was seen, and each one removed leaves as a copy where it\n * was. `row` must be positioned and isolated (`relative isolate`). An item is marked `data-flowing` while it glides. Returns a\n * function that stops following.\n */\nexport function followFlow(\n  row: HTMLElement,\n  items: string,\n  {\n    resized,\n    holding,\n    key,\n  }: {\n    /**\n     * The attribute that says which thing an item is, such as\n     * `data-notification-id`. An item put back while the copy of the same\n     * thing still leaves (an undo right after an archive) turns back from\n     * where the copy had got to, rather than playing its entrance over it.\n     */\n    key?: string\n    /** Called after each change of size, with whether the row's new height should be taken at once (see `resizeJumps`). */\n    resized?: (jumps: boolean) => void\n    /**\n     * Called before the items that moved are measured where they now are,\n     * and may return what to run once they have been: a frame that follows\n     * the row's height holds its old one meanwhile (`useFlow`), so a box\n     * that centres it doesn't move the row while it is measured.\n     */\n    holding?: () => (() => void) | undefined\n  } = {},\n): () => void {\n  const matching = () =>\n    row.querySelectorAll<HTMLElement>(`:scope > :is(${items}):not([data-leaving])`)\n  const rtl = () => getComputedStyle(row).direction === 'rtl'\n  let seen = new Map<Element, { spot: Placed; running: Running[] }>()\n  const measure = () => {\n    const box = row.getBoundingClientRect()\n    const right = rtl()\n    seen = new Map()\n    for (const item of matching()) {\n      seen.set(item, {\n        spot: spotOf(item, row, box, right),\n        running: runningOn(item),\n      })\n    }\n  }\n\n  /** Every item that moved glides there from where it was seen. Reads first, then writes, so the row is laid out once. */\n  const glide = () => {\n    const held = holding?.()\n    const box = row.getBoundingClientRect()\n    const right = rtl()\n    const starts: [HTMLElement, readonly [number, number]][] = []\n    for (const item of matching()) {\n      const was = seen.get(item)\n      if (!was || item.hasAttribute('data-flow-held')) continue\n      const [x, y] = translateOf(getComputedStyle(item).translate)\n      const start = flowStart(\n        was.spot,\n        [right ? -x : x, y],\n        spotOf(item, row, box, right),\n      )\n      if (start) starts.push([item, right ? [-start[0], start[1]] : start])\n    }\n    for (const [item, [x, y]] of starts) {\n      item.dataset.flow = 'start'\n      item.style.translate = `${x}px ${y}px`\n    }\n    if (starts.length > 0) commitStyles(row)\n    for (const [item] of starts) {\n      delete item.dataset.flow\n      item.style.translate = ''\n      item.dataset.flowing = ''\n      const latest = startRun(item)\n      void transitionsSettled(item, { property: 'translate' }).then(() => {\n        if (latest()) delete item.dataset.flowing\n      })\n    }\n    measure()\n    held?.()\n  }\n\n  // An item that changes size glides to where that puts it. The row, its\n  // parent, what sits beside it and its offset parent can move the row when\n  // they are resized (the window, a longer label beside it): that moves\n  // things with no glide, and they are measured again where they now are.\n  // Items stacked one under another (a table's rows) move only when one\n  // changes height, so a change of width, such as columns that glide, needs\n  // no glide.\n  const around = new Set<Element>(\n    [\n      row,\n      row.offsetParent,\n      row.parentElement,\n      ...(row.parentElement?.children ?? []),\n    ].filter((element): element is Element => element !== null),\n  )\n  const stacked =\n    row instanceof HTMLTableElement || row instanceof HTMLTableSectionElement\n  const heights = new WeakMap<Element, number>()\n  const widths = new WeakMap<Element, number>()\n  const aroundOnly = (entries: readonly ResizeObserverEntry[]) =>\n    entries.every((entry) => around.has(entry.target))\n  const resizes = new ResizeObserver((entries) => {\n    let moves = false\n    let narrowed = false\n    for (const entry of entries) {\n      if (around.has(entry.target)) {\n        const width = entry.borderBoxSize[0]?.inlineSize ?? 0\n        const was = widths.get(entry.target)\n        if (was !== undefined && Math.abs(was - width) >= 0.5) narrowed = true\n        widths.set(entry.target, width)\n        continue\n      }\n      const height = entry.borderBoxSize[0]?.blockSize ?? 0\n      if (\n        sizeMoves({\n          stacked,\n          heightChanged: heights.get(entry.target) !== height,\n          sizing:\n            runningTransitions(entry.target, {\n              property: 'height',\n              subtree: true,\n            }).length > 0,\n        })\n      )\n        moves = true\n      heights.set(entry.target, height)\n    }\n    const inside = changedInside\n    changedInside = false\n    const change = { moved: moves, narrowed, inside }\n    if (resizeGlides(change)) glide()\n    // What sits around the row only grew or shrank in height, such as the\n    // frame that follows it while it moves: nothing in the row moved\n    // against it, so what was seen still holds. Measuring every item on\n    // every frame of that move held the main thread (LGL-654: a Text\n    // diff's words, about 330 reads a frame).\n    else if (!aroundOnly(entries) || narrowed || inside) measure()\n    resized?.(resizeJumps(change))\n  })\n\n  // What changes inside the row since the last look, but not the styles and\n  // marks this code puts on its items as they glide.\n  let changedInside = false\n  let changeCount = 0\n  const own = new Set(['style', 'data-flow', 'data-flowing', 'data-leaving'])\n  const changes = new MutationObserver((records) => {\n    if (\n      records.some(\n        (record) => record.type !== 'attributes' || !own.has(record.attributeName ?? ''),\n      )\n    ) {\n      // Only for the frame it lands in: a resize it causes reaches the\n      // observer in that frame, and a later one comes from outside.\n      changedInside = true\n      const change = ++changeCount\n      requestAnimationFrame(() =>\n        requestAnimationFrame(() => {\n          if (change === changeCount) changedInside = false\n        }),\n      )\n    }\n  })\n\n  const mutations = new MutationObserver((records) => {\n    // Transitions that started this frame are read before an item leaves with them.\n    if (readFrame) {\n      cancelAnimationFrame(readFrame)\n      readStarted()\n    }\n    const moved: Taken[] = []\n    const gone: Leaving[] = []\n    let box: DOMRect | undefined\n    const inView = (spot: Placed) => {\n      box ??= row.getBoundingClientRect()\n      const top = box.top + spot.top + spot.rowTop - row.offsetTop\n      const left = box.left + spot.left + spot.rowLeft - row.offsetLeft\n      return (\n        top < innerHeight &&\n        top + spot.height > 0 &&\n        left < innerWidth &&\n        left + spot.width > 0\n      )\n    }\n    for (const record of records) {\n      for (const node of record.addedNodes) {\n        const was = node instanceof HTMLElement ? seen.get(node) : undefined\n        // One moved to another place (a list that reorders) is put back as it\n        // was: put in again, it would play its entrance's starting style, and\n        // taken out, it lost the glide it was on, so it takes up where that\n        // had got to.\n        // A held one keeps its other transitions, such as a lift, but its\n        // `translate` is its holder's.\n        if (node instanceof HTMLElement && was) {\n          const running = node.hasAttribute('data-flow-held')\n            ? was.running.filter(\n                ({ transition }) => transition.transitionProperty !== 'translate',\n              )\n            : was.running\n          // Its parts too: a part with an entrance of its own, such as a bar\n          // that grows, would play its starting style again once the node\n          // is back.\n          withoutTransition(node, () => moved.push(...takeOver(node, running)), {\n            subtree: true,\n          })\n        } else if (\n          node instanceof HTMLElement &&\n          key &&\n          !node.hasAttribute('data-leaving')\n        ) {\n          // Not a copy this code just put in for one that left.\n          const id = node.getAttribute(key)\n          const copy =\n            id === null\n              ? null\n              : row.querySelector<HTMLElement>(\n                  `:scope > [data-leaving][${key}=\"${CSS.escape(id)}\"]`,\n                )\n          if (copy) returnFromCopy(node, copy)\n        }\n      }\n      for (const node of record.removedNodes) {\n        const was = seen.get(node as Element)\n        // One moved to another place in the row (a list that reorders) is still there.\n        if (!(node instanceof HTMLElement) || !was || node.parentNode === row) continue\n        resizes.unobserve(node)\n        if (node.hasAttribute('data-flow-away')) continue\n        // A copy no one could see isn't made: many rows going at once, such\n        // as a long list cut back to a few, would each be styled and laid\n        // out for nothing.\n        if (!inView(was.spot)) continue\n        const next = record.nextSibling?.parentNode === row ? record.nextSibling : null\n        gone.push(leaving(node, was.spot, was.running, row, next))\n      }\n    }\n    if (gone.length > 0) leaveAsCopies(gone)\n    glide()\n    // Handed back to their transitions, from where they were.\n    for (const [part, property] of moved) part.style.removeProperty(property)\n    for (const item of matching()) resizes.observe(item)\n  })\n\n  // A transition that starts inside an item after it was measured (a\n  // marker's colours when its status changes) is read as it starts, so a\n  // copy of the item takes it up from where it got to. Each item is read\n  // once in the frame its transitions start, however many start: a row of\n  // cells that all change at once would read the row once for each.\n  const startedIn = new Set<HTMLElement>()\n  let readFrame = 0\n  const readStarted = () => {\n    readFrame = 0\n    for (const item of startedIn) {\n      const was = seen.get(item)\n      if (was && item.parentElement === row) was.running = runningOn(item)\n    }\n    startedIn.clear()\n  }\n  const started = (event: Event) => {\n    let item = event.target instanceof Element ? event.target : null\n    while (item && item.parentElement !== row) item = item.parentElement\n    if (!(item instanceof HTMLElement) || !seen.has(item)) return\n    startedIn.add(item)\n    // Animation frame callbacks run after the frame's transition events, in the same frame.\n    readFrame ||= requestAnimationFrame(readStarted)\n  }\n  row.addEventListener('transitionrun', started)\n  for (const element of around) resizes.observe(element)\n  for (const item of matching()) resizes.observe(item)\n  measure()\n  mutations.observe(row, { childList: true })\n  changes.observe(row, {\n    subtree: true,\n    childList: true,\n    characterData: true,\n    attributes: true,\n  })\n  return () => {\n    mutations.disconnect()\n    changes.disconnect()\n    row.removeEventListener('transitionrun', started)\n    cancelAnimationFrame(readFrame)\n    resizes.disconnect()\n  }\n}\n\n/**\n * An item of a list that flows, such as a directory's card or a changelog's\n * release: it glides to its place when the list changes, fades in when it\n * arrives after the list's first paint, and its copy fades out where it was\n * when it leaves. The list is `group/flow`, marked `data-mounted`\n * (`markMounted`).\n */\nexport const flowItemClassName =\n  '[transition:translate_var(--motion-layout-duration)_var(--motion-layout-easing),opacity_var(--motion-enter-duration)_var(--motion-enter-easing)] group-data-mounted/flow:starting:opacity-0 data-[flow=start]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing)] motion-reduce:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing)] data-leaving:opacity-0 data-leaving:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),translate_var(--motion-layout-duration)_var(--motion-layout-easing)] motion-reduce:data-leaving:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing)]'\n\n/**\n * A row whose `items` flow, in a frame that moves to the row's height as it\n * wraps: give `frame` and `row` to the two elements, the row inside the\n * frame. The frame needs a height transition and `overflow: clip`, and is\n * marked `data-sizing` while it moves.\n */\nexport function useFlow<Frame extends HTMLElement, Row extends HTMLElement>(\n  items: string,\n  /** The attribute that says which thing an item is: see `followFlow`. */\n  key?: string,\n) {\n  const frame = useRef<Frame>(null)\n  const row = useRef<Row>(null)\n  useEffect(() => {\n    if (!frame.current || !row.current) return\n    // Items that rewrap where they are, the row narrowed from outside, take\n    // the frame's new height at once too. The flow is followed first, so it\n    // has looked at each change before the frame does.\n    let jumps = false\n    const frameNode = frame.current\n    const rowNode = row.current\n    // The frame's height and the row's, as last laid out with nothing held.\n    let rest = { frame: frameNode.offsetHeight, row: rowNode.offsetHeight }\n    const remember = () => {\n      if (!frameNode.style.height)\n        rest = { frame: frameNode.offsetHeight, row: rowNode.offsetHeight }\n    }\n    const sizes = new ResizeObserver(remember)\n    sizes.observe(frameNode)\n    const stopFlow = followFlow(rowNode, items, {\n      key,\n      resized: (next) => {\n        jumps = next\n      },\n      // The frame keeps its old height while the items are measured, as it\n      // will on the first frame of its move to the new one: in a box that\n      // centres the frame, its new height would move the row, and every item\n      // would start from a place that much off. A frame already moving\n      // keeps its own height. Let go at once if the row's height didn't\n      // change, since the frame then has no move to make.\n      holding: () => {\n        if (frameNode.style.height) return undefined\n        const held = `${rest.frame}px`\n        frameNode.style.height = held\n        return () => {\n          if (rowNode.offsetHeight === rest.row) {\n            frameNode.style.height = ''\n            return\n          }\n          // The frame's own move takes the height from here, once the\n          // resize is seen, after this frame's callbacks. One that never\n          // starts, the height being the same after all, leaves it held, so\n          // it is let go the frame after.\n          requestAnimationFrame(() =>\n            requestAnimationFrame(() => {\n              if (\n                frameNode.style.height === held &&\n                runningTransitions(frameNode, { property: 'height' }).length === 0\n              ) {\n                frameNode.style.height = ''\n                remember()\n              }\n            }),\n          )\n        }\n      },\n    })\n    const stopHeight = followHeight(frame.current, row.current, {\n      instant: () => jumps,\n      // Marked while it moves to the row's height, so it can clip to its own\n      // edge then: a row taller than it would otherwise add to what a\n      // scroller around it can scroll, and show its scrollbar for the move.\n      moving: () => {\n        frameNode.dataset.sizing = ''\n        return undefined\n      },\n      // Its new height, once layout has it back: a frame already that tall\n      // doesn't change size then, so the observer wouldn't see it.\n      settled: () => {\n        delete frameNode.dataset.sizing\n        remember()\n      },\n    })\n    return () => {\n      stopHeight()\n      stopFlow()\n      sizes.disconnect()\n    }\n  }, [items, key])\n  return { frame, row }\n}\n\n/**\n * Once `item` has left its list, focus goes to the control `target` picks in\n * the item that took its place, else in the one before it, skipping copies\n * still leaving; when none stays, to what `otherwise` gives. Call it as the\n * item is taken out: it focuses on the next frame, once the item has gone.\n */\n/**\n * A list whose items glide when one comes or goes, keyed by `data-flow-key`:\n * give the ref to the list, which is `group/flow relative isolate`, and\n * `flowItemClassName` to each item. One that arrives after the first paint\n * fades in.\n */\nexport function useFlowList<List extends HTMLElement>(\n  items = ':scope > [data-flow-key]',\n) {\n  const list = useRef<List>(null)\n  useEffect(() => {\n    const node = list.current\n    if (!node) return\n    const stopMounted = markMounted(node)\n    const stopFlow = followFlow(node, items, { key: 'data-flow-key' })\n    return () => {\n      stopFlow()\n      stopMounted?.()\n    }\n  }, [items])\n  return list\n}\n\nexport function focusAfterLeaving(\n  item: HTMLElement | null,\n  target: string,\n  otherwise: () => HTMLElement | null,\n) {\n  const staying = (from: Element | null | undefined, step: 'next' | 'previous') => {\n    let at = from\n    while (at && at.hasAttribute('data-leaving'))\n      at = step === 'next' ? at.nextElementSibling : at.previousElementSibling\n    return at\n  }\n  const next =\n    staying(item?.nextElementSibling, 'next') ??\n    staying(item?.previousElementSibling, 'previous')\n  requestAnimationFrame(() => {\n    ;(next?.querySelector<HTMLElement>(target) ?? otherwise())?.focus()\n  })\n}\n",
      "type": "registry:lib",
      "target": "@lib/flow.ts"
    }
  ],
  "type": "registry:lib"
}