{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "highlight",
  "title": "Highlight",
  "description": "One highlight that glides between the items of a group: it appears in place, slides from item to item and fades where it last was. Menus, Select, Tabs, Button group, Navigation menu and Date input share it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/theme.json",
    "https://kinoui.com/r/run-progress.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json"
  ],
  "files": [
    {
      "path": "registry/lib/highlight.ts",
      "content": "/*\n * One highlight that glides between the items of a group: a menu's rows, the\n * tabs, a button group's segments, a navigation menu's links. Its layer is as\n * large as the group and clipped to the item, whose box and corners it writes\n * as CSS variables, so nothing is laid out again; a CSS transition on\n * `layout` does the moving.\n *\n * It appears in place, slides from item to item, and fades out where it last\n * was. Brought back while it fades, it slides on from there; once it has\n * faded, it appears in place again (Greg, 2026-11-13).\n */\n\nimport { commitStyles } from '@/registry/lib/refs'\nimport {\n  FOLLOWS_TRANSITION,\n  runningTransitions,\n  withoutTransition,\n} from '@/registry/lib/resize'\nimport { registerProperties } from '@/registry/lib/run-progress'\n\n/** Where the highlight is in its life. The layer carries it as `data-highlight`. */\nexport type HighlightState = 'hidden' | 'shown' | 'fading'\n\n/** What happened: it was sent to an item, sent to none, or finished fading. */\nexport type HighlightEvent = 'item' | 'none' | 'faded'\n\n/**\n * What the layer does: appear in place, slide to the item, start to fade,\n * finish hiding, or nothing.\n */\nexport type HighlightStep = 'appear' | 'slide' | 'fade' | 'hide' | 'stay'\n\nconst STEPS: Record<\n  HighlightState,\n  Record<HighlightEvent, readonly [HighlightState, HighlightStep]>\n> = {\n  hidden: {\n    item: ['shown', 'appear'],\n    none: ['hidden', 'stay'],\n    faded: ['hidden', 'stay'],\n  },\n  shown: {\n    item: ['shown', 'slide'],\n    none: ['fading', 'fade'],\n    faded: ['shown', 'stay'],\n  },\n  fading: {\n    item: ['shown', 'slide'],\n    none: ['fading', 'stay'],\n    faded: ['hidden', 'hide'],\n  },\n}\n\n/** The state after `event`, and what the layer does to get there. */\nexport function highlightStep(\n  state: HighlightState,\n  event: HighlightEvent,\n): readonly [HighlightState, HighlightStep] {\n  return STEPS[state][event]\n}\n\ntype Box = Pick<DOMRect, 'top' | 'right' | 'bottom' | 'left' | 'width' | 'height'>\n\n/**\n * Where the highlight goes, in px from each edge of its layer, and the item's\n * four corners (top left, top right, bottom right, bottom left), so it takes\n * the item's exact shape. A pill's 9999px is capped at half the item's\n * shorter side, so a corner never animates from it. `scale` is how much the\n * group is drawn larger or smaller than it is laid out, as in a dialog that\n * scales in: the boxes are measured as drawn, and the highlight is placed in\n * the group's own px.\n */\nexport function highlightBox(\n  layer: Box,\n  item: Box,\n  corners: readonly string[],\n  scale = 1,\n) {\n  const cap = Math.min(item.width, item.height) / scale / 2\n  const [tl, tr, br, bl] = corners.map((corner) =>\n    Math.min(Number.parseFloat(corner) || 0, cap),\n  )\n  return {\n    top: (item.top - layer.top) / scale,\n    right: (layer.right - item.right) / scale,\n    bottom: (layer.bottom - item.bottom) / scale,\n    left: (item.left - layer.left) / scale,\n    tl,\n    tr,\n    br,\n    bl,\n  }\n}\n\n/** A computed `translate` (`Xpx Ypx`, `Xpx`, or `none`) as x and y in px. */\nexport function translateOf(translate: string): readonly [number, number] {\n  const [x = 0, y = 0] = translate\n    .split(' ')\n    .map((value) => Number.parseFloat(value) || 0)\n  return [x, y]\n}\n\n/**\n * A computed `clip-path: inset(…)` as its top, right, bottom and left in px,\n * however many of the four it writes out; null when it isn't an inset.\n */\nexport function insetsOf(\n  clipPath: string,\n): readonly [number, number, number, number] | null {\n  const match = /^inset\\(([^)]*?)(?:\\s+round\\s[^)]*)?\\)$/.exec(clipPath.trim())\n  if (!match) return null\n  const values = match[1]!\n    .trim()\n    .split(/\\s+/)\n    .map((value) => Number.parseFloat(value))\n  if (values.length === 0 || values.length > 4 || values.some(Number.isNaN)) return null\n  const [top, right = top, bottom = top, left = right] = values as [number, ...number[]]\n  return [top, right, bottom, left]\n}\n\n/**\n * Whether two placements put the highlight in the same place and shape, to\n * half a pixel: a row whose corners change as picked rows join is a new shape.\n */\nexport function sameBox(\n  a: ReturnType<typeof highlightBox>,\n  b: ReturnType<typeof highlightBox>,\n) {\n  return (['left', 'top', 'bottom', 'right', 'tl', 'tr', 'br', 'bl'] as const).every(\n    (edge) => Math.abs(a[edge] - b[edge]) < 0.5,\n  )\n}\n\n/**\n * Every box whose size can move `item` inside `group` without changing the\n * size of the item or the group: its ancestors' siblings, up to the group.\n * One section closing as another opens moves the rows of both and leaves the\n * list as tall as it was (2026-11-19: the docs sidebar's current page tint\n * stayed where the Blocks section's first row had been).\n */\nexport function boxesAround(item: Element, group: Element) {\n  const boxes: Element[] = []\n  for (let node = item; node !== group;) {\n    const parent = node.parentElement\n    if (!parent) break\n    for (const sibling of parent.children) if (sibling !== node) boxes.push(sibling)\n    node = parent\n  }\n  return boxes\n}\n\n/** Whether `item` is sliding into a new place on a translate transition. */\n/**\n * The `translate` transitions sliding `item` into a new place: its own, and\n * those of the boxes around it inside `within`, such as a list's row that\n * glides when the list changes (the `flow` lib) with the item inside it.\n * Boxes from `within` up move the highlight's layer too, so they don't count.\n */\nfunction slidesOf(item: HTMLElement, within?: Element | null): CSSTransition[] {\n  const slides: CSSTransition[] = []\n  for (\n    let at: HTMLElement | null = item;\n    at && at !== within && (within ? within.contains(at) : at === item);\n    at = at.parentElement\n  )\n    slides.push(...runningTransitions(at, { property: 'translate' }))\n  return slides\n}\n\nfunction sliding(item: HTMLElement, within?: Element | null) {\n  return slidesOf(item, within).length > 0\n}\n\n/**\n * Where `item` is, or where it is going while it slides there on a\n * `translate` transition: its box with those transitions seeked to their\n * end and straight back, in one task, so nothing is drawn in between. That\n * reads the end whatever the translate is written in, such as a `calc()`\n * with percentages, which can't be added up from outside.\n */\nfunction boxOf(item: HTMLElement, within?: Element | null): Box {\n  const moving = slidesOf(item, within)\n  if (moving.length === 0) return item.getBoundingClientRect()\n  const times = moving.map((transition) => transition.currentTime)\n  for (const transition of moving) {\n    const end = Number(transition.effect?.getComputedTiming().endTime ?? 0)\n    transition.currentTime = Math.max(0, end - 0.01)\n  }\n  const box = item.getBoundingClientRect()\n  moving.forEach((transition, at) => {\n    transition.currentTime = times[at] ?? null\n  })\n  return box\n}\n\n// Written out whole, once per role, so Tailwind finds every class.\nconst highlightClasses = {\n  layout:\n    'pointer-events-none absolute inset-0 opacity-0 [clip-path:inset(var(--highlight-top)_var(--highlight-right)_var(--highlight-bottom)_var(--highlight-left)_round_var(--highlight-tl)_var(--highlight-tr)_var(--highlight-br)_var(--highlight-bl))] [transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing)] data-[highlight=shown]:opacity-100 motion-safe:data-[highlight=shown]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),clip-path_var(--motion-layout-duration)_var(--motion-layout-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] motion-reduce:data-[highlight=shown]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] motion-safe:data-[highlight=fading]:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),clip-path_var(--motion-layout-duration)_var(--motion-layout-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)]',\n  morph:\n    'pointer-events-none absolute inset-0 opacity-0 [clip-path:inset(var(--highlight-top)_var(--highlight-right)_var(--highlight-bottom)_var(--highlight-left)_round_var(--highlight-tl)_var(--highlight-tr)_var(--highlight-br)_var(--highlight-bl))] [transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing)] data-[highlight=shown]:opacity-100 motion-safe:data-[highlight=shown]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),clip-path_var(--motion-morph-duration)_var(--motion-morph-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] motion-reduce:data-[highlight=shown]:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)] motion-safe:data-[highlight=fading]:[transition:opacity_var(--motion-exit-duration)_var(--motion-exit-easing),clip-path_var(--motion-morph-duration)_var(--motion-morph-easing),background-color_var(--motion-press-duration)_var(--motion-press-fade-easing)]',\n}\n\n/**\n * The layer's classes: it fades in on `enter` and out on `exit`, slides on\n * `layout`, and changes colour (a press, a destructive row) on `press`. Under\n * reduced motion it only fades. Give it a colour, and a `z-` that puts it\n * behind or over the items.\n */\nexport const highlightClassName = highlightClasses.layout\n\n/**\n * `highlightClassName` for a highlight that marks the pick, as a segmented\n * control's thumb: it moves on `morph`, as the Tabs' pill does, where one\n * that follows the pointer moves on `layout`.\n */\nexport const pickClassName = highlightClasses.morph\n\n/** The tint of a row under the highlight, which a row that marks where you are shares. */\nexport const rowTintClassName = 'bg-foreground/5 dark:bg-foreground/7'\n\n/**\n * The layer over a group of rows, as the Table's and the Tree's: a faint\n * tint over the rows, under nothing else.\n */\nexport const rowHighlightClassName = `${highlightClassName} z-20 ${rowTintClassName}`\n\n/**\n * `tintedRowTextClassName` for a link or a button that takes a tint of its\n * own under the pointer, as an Item outside a group does.\n */\nexport const hoveredRowTextClassName =\n  '[&:is(a[href],button)]:hover:[--muted-foreground:color-mix(in_oklab,var(--foreground)_70%,var(--background))]'\n\n/**\n * A picked row's tint, as the Tree's and the Listbox's: the muted colour, and\n * the system's own colours under forced colours. On the row, which carries\n * `data-selected` when picked.\n */\nexport const pickedRowClassName =\n  '[&[data-selected]]:bg-muted forced-colors:[&[data-selected]]:bg-[Highlight] forced-colors:[&[data-selected]]:text-[HighlightText] forced-colors:[&[data-selected]]:forced-color-adjust-none forced-colors:[&[data-selected]]:**:text-[HighlightText]'\n\n/**\n * Muted text in a tinted row (picked, or under the highlight) is darker, so\n * it keeps 4.5:1 on the tint. On the row, picked when its list says so:\n * `data-selected`, `aria-selected`, a radio row's `aria-checked` or\n * `aria-current`.\n */\nexport const tintedRowTextClassName =\n  '[&:is([data-selected],[aria-selected=true],[aria-checked=true],[aria-current=true])]:[--muted-foreground:color-mix(in_oklab,var(--foreground)_70%,var(--background))] [&[data-glided]]:[--muted-foreground:color-mix(in_oklab,var(--foreground)_70%,var(--background))]'\n\nexport interface Highlight {\n  /** Where it is in its life. */\n  readonly state: () => HighlightState\n  /**\n   * Sends it to `item`, or with null fades it out where it is. `from` is the\n   * box it first appears on before sliding to `item`, used only when it\n   * appears.\n   */\n  move: (item: HTMLElement | null, from?: Box) => void\n  /**\n   * Hides it for a popup that opens: at once (`instant`) when the popup had\n   * gone, or from where it is when the popup opens again while it closes.\n   */\n  reset: (instant: boolean) => void\n  /**\n   * The group changed under it, as a list does when it filters: it goes with\n   * its item to the item's new place, sliding when the item slides there and\n   * at once when the item was simply laid out there. It fades once its item\n   * has gone.\n   */\n  refit: () => void\n  /**\n   * Puts it on `item` at once, shown, with nothing moving or fading: where a\n   * pick already is when the page paints.\n   */\n  jump: (item: HTMLElement) => void\n  /** The item it is on, or null. */\n  item: () => HTMLElement | null\n  stop: () => void\n}\n\n/**\n * The window's variables, as lengths that don't inherit. Inherited, every\n * element inside the layer, such as a chart axis's copy of each name, has\n * its style worked out again on each step of the highlight.\n */\nfunction registerHighlightProperties() {\n  registerProperties(\n    ['left', 'top', 'bottom', 'right', 'tl', 'tr', 'br', 'bl'].map((key) => ({\n      name: `--highlight-${key}`,\n      syntax: '<length>',\n      inherits: false,\n      initialValue: '0px',\n    })),\n  )\n}\n\n/**\n * Drives `layer` through its states. The item under it gets `data-glided`,\n * so what's inside can follow, and its `data-variant` is copied to the layer\n * (a destructive menu row tints it). It follows its item when the item or\n * the group changes size, and fades when the item goes. Kept outside any\n * component: the React Compiler can drop the forced style read it makes.\n */\nexport function createHighlight(layer: HTMLElement): Highlight {\n  registerHighlightProperties()\n  let state: HighlightState = 'hidden'\n  let item: HTMLElement | null = null\n  // Where it was last sent, from each edge of the layer.\n  let placed: ReturnType<typeof highlightBox> | null = null\n  // The item it fades out over, followed until it has faded, so it fades\n  // where that item is even as the group changes size under it.\n  let fadingOver: HTMLElement | null = null\n\n  const measure = (box: Box, of: HTMLElement) => {\n    const style = getComputedStyle(of)\n    const area = layer.getBoundingClientRect()\n    // Its laid-out width, unrounded and untouched by a transform: `offsetWidth`\n    // rounds to whole px, which would read a group at rest as scaled.\n    const laid = Number.parseFloat(getComputedStyle(layer).width)\n    return highlightBox(\n      area,\n      box,\n      [\n        style.borderTopLeftRadius,\n        style.borderTopRightRadius,\n        style.borderBottomRightRadius,\n        style.borderBottomLeftRadius,\n      ],\n      laid > 0 ? area.width / laid : 1,\n    )\n  }\n\n  const write = (values: ReturnType<typeof highlightBox>) => {\n    placed = values\n    for (const [key, value] of Object.entries(values)) {\n      layer.style.setProperty(`--highlight-${key}`, `${value}px`)\n    }\n  }\n\n  const place = (box: Box, of: HTMLElement) => {\n    // A glide that was following its moving item hands over from where it is\n    // drawn: the transition to the new place starts there, not at the end of\n    // the pursuit, which the variables already hold.\n    if (pursuit) {\n      const drawn = insetsOf(getComputedStyle(layer).clipPath)\n      stopPursuit()\n      if (drawn && placed) {\n        const [top, right, bottom, left] = drawn\n        const from = { ...placed, top, right, bottom, left }\n        jump(() => write(from))\n      }\n    }\n    write(measure(box, of))\n    layer.dataset.variant = of.dataset.variant ?? 'default'\n  }\n\n  // A glide that goes on while the group changes size under it (a branch\n  // above opening): the same move, for the time it had left, toward where its\n  // item is now, retargeted each frame without starting again.\n  let pursuit: { animation: Animation; from: number[] } | null = null\n  const stopPursuit = () => {\n    const running = pursuit\n    pursuit = null\n    running?.animation.cancel()\n  }\n  const clipOf = (insets: readonly number[], to: ReturnType<typeof highlightBox>) =>\n    `inset(${insets.map((value) => `${value}px`).join(' ')} round ${to.tl}px ${to.tr}px ${to.br}px ${to.bl}px)`\n  const insetsOfBox = (box: ReturnType<typeof highlightBox>) => [\n    box.top,\n    box.right,\n    box.bottom,\n    box.left,\n  ]\n  const pursue = (on: HTMLElement, wider: number, taller: number) => {\n    const target = measure(boxOf(on, layer.parentElement), on)\n    if (pursuit) {\n      // The layer's own end and bottom edges moved: where it started stays put.\n      const [top = 0, right = 0, bottom = 0, left = 0] = pursuit.from\n      pursuit.from = [top, right + wider, bottom + taller, left]\n      ;(pursuit.animation.effect as KeyframeEffect).setKeyframes([\n        { clipPath: clipOf(pursuit.from, target) },\n        { clipPath: clipOf(insetsOfBox(target), target) },\n      ])\n      jump(() => write(target))\n      return true\n    }\n    const [transition] = runningTransitions(layer, { property: 'clip-path' })\n    const timing = transition?.effect?.getComputedTiming()\n    const drawn = insetsOf(getComputedStyle(layer).clipPath)\n    if (!transition || !timing || !drawn) return false\n    const left = Number(timing.endTime) - Number(timing.localTime ?? 0)\n    if (!(left > 0)) return false\n    const from = [drawn[0], drawn[1] + wider, drawn[2] + taller, drawn[3]]\n    const easing = transition.effect?.getTiming().easing ?? 'linear'\n    const rate = transition.playbackRate\n    jump(() => write(target))\n    const animation = layer.animate(\n      [\n        { clipPath: clipOf(from, target) },\n        { clipPath: clipOf(insetsOfBox(target), target) },\n      ],\n      { duration: left, easing },\n    )\n    animation.playbackRate = rate\n    // Chromium holds a clip-path animation at its start while its keyframes\n    // change every frame, unless its start time is set.\n    animation.startTime = document.timeline.currentTime\n    const mine = { animation, from }\n    pursuit = mine\n    animation.finished.then(\n      () => {\n        if (pursuit === mine) pursuit = null\n      },\n      () => {},\n    )\n    return true\n  }\n\n  /**\n   * Moves with `on` as `slide` carries it: from where the slide started it,\n   * offset by the slide's first `translate`, to where it ends, at the\n   * slide's own time, easing and rate. The insets move in px as the\n   * translate does, so the highlight stays on the item every frame. False\n   * when the slide can't be read, and the highlight moves its own way.\n   */\n  const ride = (on: HTMLElement, slide: CSSTransition) => {\n    const effect = slide.effect\n    if (!(effect instanceof KeyframeEffect)) return false\n    const [first, last] = [effect.getKeyframes()[0], effect.getKeyframes().at(-1)]\n    const timing = effect.getComputedTiming()\n    if (!first || !last || slide.currentTime === null) return false\n    const [fromX, fromY] = translateOf(String(first.translate ?? '0px'))\n    const [toX, toY] = translateOf(String(last.translate ?? '0px'))\n    const target = measure(boxOf(on, layer.parentElement), on)\n    const [dx, dy] = [fromX - toX, fromY - toY]\n    const from = [\n      target.top + dy,\n      target.right - dx,\n      target.bottom - dy,\n      target.left + dx,\n    ]\n    stopPursuit()\n    jump(() => {\n      write(target)\n      layer.dataset.variant = on.dataset.variant ?? 'default'\n    })\n    const animation = layer.animate(\n      [\n        { clipPath: clipOf(from, target) },\n        { clipPath: clipOf(insetsOfBox(target), target) },\n      ],\n      {\n        duration: Number(timing.duration) || 0,\n        delay: Number(effect.getTiming().delay) || 0,\n        easing: effect.getTiming().easing ?? 'linear',\n        id: FOLLOWS_TRANSITION,\n      },\n    )\n    animation.playbackRate = slide.playbackRate\n    animation.currentTime = slide.currentTime\n    const mine = { animation, from }\n    pursuit = mine\n    animation.finished.then(\n      () => {\n        if (pursuit === mine) pursuit = null\n      },\n      () => {},\n    )\n    return true\n  }\n\n  const enter = (next: HighlightState) => {\n    state = next\n    layer.dataset.highlight = next\n  }\n\n  // The boxes around the item it is on, watched for a size change that moves it.\n  let around: Element[] = []\n  // A box stops being watched only once nothing it is watched for still needs it.\n  const release = (boxes: Iterable<Element | null>) => {\n    for (const box of boxes) {\n      if (!box || box === layer || box === item || box === fadingOver) continue\n      if (!around.includes(box)) sizes.unobserve(box)\n    }\n  }\n  const watchAround = () => {\n    const before = around\n    const group = layer.parentElement\n    around = item && group?.contains(item) ? boxesAround(item, group) : []\n    for (const box of around) sizes.observe(box)\n    release(before)\n  }\n  const follow = (next: HTMLElement | null) => {\n    if (next === item) return\n    const last = item\n    last?.removeAttribute('data-glided')\n    item = next\n    if (next) {\n      next.setAttribute('data-glided', '')\n      sizes.observe(next)\n    }\n    watchAround()\n    release([last])\n  }\n\n  const send = (event: HighlightEvent, next: HTMLElement | null, from?: Box) => {\n    const [to, step] = highlightStep(state, event)\n    if (step === 'stay') return\n    if (step === 'appear' && next) {\n      // Where the item is drawn now, which is not yet where it is going\n      // when it slides into a new place.\n      place(from ?? next.getBoundingClientRect(), next)\n      // Painted where it appears before it may slide.\n      commitStyles(layer)\n    }\n    enter(to)\n    if (next) place(boxOf(next, layer.parentElement), next)\n    const last = item\n    follow(next)\n    const faded = fadingOver\n    fadingOver = step === 'fade' ? last : null\n    if (fadingOver) sizes.observe(fadingOver)\n    release([faded])\n    // With no fade to wait for (a feel or a test that takes no time), it has faded now.\n    if (step === 'fade' && !fadingOut()) send('faded', null)\n  }\n\n  const fadingOut = () => runningTransitions(layer, { property: 'opacity' }).length > 0\n  const gliding = () =>\n    pursuit !== null || runningTransitions(layer, { property: 'clip-path' }).length > 0\n\n  const faded = (event: TransitionEvent) => {\n    if (event.target === layer && event.propertyName === 'opacity') send('faded', null)\n  }\n\n  let layerSize = [layer.offsetWidth, layer.offsetHeight]\n  // A layer that changes size mid-glide (rows that leave shorten their table\n  // at once) would move the edges its insets are measured from: the glide\n  // goes on from where it is drawn, kept there against the new size.\n  const resized = () => {\n    const [width, height] = [layer.offsetWidth, layer.offsetHeight]\n    const [wider, taller] = [width - layerSize[0]!, height - layerSize[1]!]\n    layerSize = [width, height]\n    return [wider, taller] as const\n  }\n  const rebase = (wider: number, taller: number) => {\n    if ((wider === 0 && taller === 0) || !gliding()) return\n    const drawn = insetsOf(getComputedStyle(layer).clipPath)\n    if (!drawn) return\n    // A pursuit drawn over the variables would hide what this writes.\n    stopPursuit()\n    jump(() => {\n      layer.style.setProperty('--highlight-top', `${drawn[0]}px`)\n      layer.style.setProperty('--highlight-right', `${drawn[1] + wider}px`)\n      layer.style.setProperty('--highlight-bottom', `${drawn[2] + taller}px`)\n      layer.style.setProperty('--highlight-left', `${drawn[3]}px`)\n    })\n  }\n\n  // Moves it at once, while a fade it is in keeps running.\n  const jump = (write: () => void) =>\n    withoutTransition(layer, write, {\n      properties: ['clip-path', 'background-color'],\n    })\n\n  // Its item moved or changed size under it, not to a new item: on its way\n  // there (a glide not yet done, or the item sliding to a new place), it turns\n  // toward where the item is now, from where it is; at rest, it goes with the\n  // item at once, since a transition restarted every frame (a branch above\n  // closing) would hold it where it was until the move ends.\n  const refit = (moving = false) => {\n    const on = item ?? (state === 'fading' ? fadingOver : null)\n    if (!on || state === 'hidden') return\n    if (!on.isConnected) {\n      if (item) send('none', null)\n      return\n    }\n    // Fading over an item that moves, it goes on toward it if it was on its\n    // way there, else with it at once: a transition started every frame\n    // would hold it where it was.\n    if (on !== item && !sliding(on, layer.parentElement)) {\n      const next = measure(boxOf(on, layer.parentElement), on)\n      if (placed && sameBox(placed, next)) return\n      if (!(gliding() && pursue(on, 0, 0)))\n        jump(() => place(boxOf(on, layer.parentElement), on))\n      return\n    }\n    // Its item slides to a new place (a pinned row gliding up its list): it\n    // goes with it, on the slide's own timing, so the two never part.\n    const [slide] = slidesOf(on, layer.parentElement)\n    if (on === item && slide && ride(on, slide)) return\n    if (moving || sliding(on, layer.parentElement) || gliding()) {\n      // A glide already following its moving item goes on following it.\n      if (pursuit && on === item && !sliding(on, layer.parentElement)) pursue(on, 0, 0)\n      else place(boxOf(on, layer.parentElement), on)\n      return\n    }\n    const next = measure(boxOf(on, layer.parentElement), on)\n    if (placed && sameBox(placed, next)) return\n    jump(() => place(boxOf(on, layer.parentElement), on))\n  }\n\n  const sizes = new ResizeObserver(() => {\n    const on = item ?? (state === 'fading' ? fadingOver : null)\n    const [wider, taller] = resized()\n    // Its item moved with the group while it glides there: the glide goes on.\n    // Only when something moved: an item just observed reports its size at\n    // once, and a pursuit started then would stand in for the glide.\n    if (\n      on?.isConnected &&\n      state !== 'hidden' &&\n      gliding() &&\n      !sliding(on, layer.parentElement) &&\n      (wider !== 0 ||\n        taller !== 0 ||\n        !placed ||\n        !sameBox(placed, measure(boxOf(on, layer.parentElement), on))) &&\n      pursue(on, wider, taller)\n    ) {\n      return\n    }\n    const moving = gliding() || (on !== null && sliding(on, layer.parentElement))\n    rebase(wider, taller)\n    refit(moving)\n  })\n  sizes.observe(layer)\n  // The shape can change the item's corners without changing its size: the\n  // highlight takes the new corners at once.\n  const reshape = () => {\n    if (!item || state === 'hidden' || !item.isConnected) return\n    // A glide on its way keeps going; it takes the new corners where it lands.\n    if (sliding(item, layer.parentElement) || gliding()) return\n    const shown = item\n    withoutTransition(layer, () => place(boxOf(shown, layer.parentElement), shown))\n  }\n  const shaped = new MutationObserver(reshape)\n  shaped.observe(document.documentElement, {\n    subtree: true,\n    attributes: true,\n    attributeFilter: ['data-shape'],\n  })\n  // The radius is a variable on the root's own style; watching style below\n  // it would see the highlight's own writes.\n  const rounded = new MutationObserver(reshape)\n  rounded.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['style'],\n  })\n  layer.addEventListener('transitionend', faded)\n\n  return {\n    state: () => state,\n    item: () => item,\n    move: (next, from) => send(next ? 'item' : 'none', next, from),\n    jump: (next) =>\n      withoutTransition(layer, () => {\n        if (state !== 'shown') enter('hidden')\n        send('item', next)\n      }),\n    // Asked from outside when the items around may have changed, so it rewatches them.\n    refit: () => {\n      watchAround()\n      refit()\n    },\n    reset: (instant) => {\n      stopPursuit()\n      follow(null)\n      const faded = fadingOver\n      fadingOver = null\n      release([faded])\n      // Still on screen, it turns back from where it is. Out of sight, it hides\n      // at once, so the next item it is sent to appears the way it did the\n      // first time, in place of turning a fade round at full.\n      if (!instant) {\n        enter('hidden')\n        return\n      }\n      withoutTransition(layer, () => enter('hidden'))\n    },\n    stop: () => {\n      stopPursuit()\n      follow(null)\n      sizes.disconnect()\n      shaped.disconnect()\n      rounded.disconnect()\n      layer.removeEventListener('transitionend', faded)\n    },\n  }\n}\n\n/**\n * Follows the row ui-sdk marks `data-highlighted` in a menu or a list, or the\n * row whose submenu is open. While the pointer is over `bounds` (the\n * popup, by default) the highlight stays where it is when no row is\n * highlighted, as when it crosses a separator or a label, or in the moment\n * between one submenu closing and the next opening, so it always slides on.\n * It fades once the pointer has left. A submenu's first highlight starts on\n * the row of the item that opened it. Over a popup kept mounted while\n * closed, it starts afresh on every open.\n */\n/**\n * A popup's life as its rows' highlight sees it: `closing` once `data-open`\n * goes, `ending` while its exit runs, `closed` once that has ended.\n */\nexport type PopupPhase = 'closed' | 'open' | 'closing' | 'ending'\n\n/**\n * The popup's next phase from its attributes now, and how its highlight\n * starts when it opens: `appear` after the popup had gone, `turn` (from where\n * it is) when it opens again before its close has ended. `endingChanged`: the\n * exit attribute came or went since the last look, which tells an exit\n * that ran between two looks (one with no transition) from one not yet begun.\n */\nexport function popupNext(\n  phase: PopupPhase,\n  {\n    open,\n    ending,\n    endingChanged,\n  }: { open: boolean; ending: boolean; endingChanged: boolean },\n): readonly [PopupPhase, 'appear' | 'turn' | null] {\n  if (open) {\n    if (phase === 'open') return ['open', null]\n    return ['open', phase === 'closed' ? 'appear' : 'turn']\n  }\n  if (phase === 'closed') return ['closed', null]\n  if (ending) return ['ending', null]\n  if (phase === 'ending' || endingChanged) return ['closed', null]\n  return ['closing', null]\n}\n\n/** Whether a mutation added or removed an element, not just text. */\nfunction elementsCameOrWent(record: MutationRecord) {\n  return [...record.addedNodes, ...record.removedNodes].some(\n    (node) => node instanceof Element,\n  )\n}\n\n/** Whether a mutation added or removed rows, not just something inside one (a tick that mounts). */\nfunction rowsCameOrWent(record: MutationRecord) {\n  return [...record.addedNodes, ...record.removedNodes].some(\n    (node) =>\n      node instanceof Element &&\n      (node.matches('[data-menu-row]') || node.querySelector('[data-menu-row]') !== null),\n  )\n}\n\n/**\n * Whether the person's last move was a key rather than the pointer. A\n * highlight sent by a key jumps there: arrowing through a list many times a\n * day answers as fast as the key, while the pointer's glide shows where the\n * pointer went (Greg, 2026-11-28, from Emil Kowalski's \"never animate\n * keyboard-triggered actions\").\n */\nlet keyedLast = false\nlet watchingInput = false\nfunction pressedKeyLast() {\n  watchInput()\n  return keyedLast\n}\n\n/** Starts telling keys from the pointer, once a page has a highlight, so the key that opens a menu counts. */\nfunction watchInput() {\n  if (watchingInput) return\n  watchingInput = true\n  const keyed = () => {\n    keyedLast = true\n  }\n  const pointed = () => {\n    keyedLast = false\n  }\n  document.addEventListener('keydown', keyed, true)\n  document.addEventListener('pointerdown', pointed, true)\n  document.addEventListener('pointermove', pointed, true)\n  // Before an area's own `pointerover`, which moves its highlight.\n  document.addEventListener('pointerover', pointed, true)\n}\n\nexport function followRows(\n  list: HTMLElement,\n  layer: HTMLElement,\n  { popup, bounds = popup }: { popup: HTMLElement; bounds?: HTMLElement },\n) {\n  watchInput()\n  const highlight = createHighlight(layer)\n  const opener = popup.hasAttribute('data-nested')\n    ? document.getElementById(popup.getAttribute('aria-labelledby') ?? '')\n    : null\n  let phase: PopupPhase = 'closed'\n  let first = true\n  let waiting = false\n  let inside = false\n  let frame = 0\n\n  // A submenu renders inside the list that opened it: its rows are its own highlight's.\n  const own = (row: Element) => {\n    const nested = row.parentElement?.closest('[data-nested]')\n    return !nested || !list.contains(nested)\n  }\n  const ownRow = (selector: string) =>\n    [...list.querySelectorAll<HTMLElement>(selector)].find(own) ?? null\n  const target = () =>\n    ownRow(':scope [data-menu-row][data-highlighted]') ??\n    ownRow(':scope [data-menu-row][data-open]')\n\n  const go = (row: HTMLElement) =>\n    pressedKeyLast() ? highlight.jump(row) : highlight.move(row)\n\n  const fromOpener = (opener: HTMLElement) => {\n    waiting = false\n    const row = target()\n    if (phase !== 'open' || !row) {\n      sync()\n      return\n    }\n    if (pressedKeyLast()) {\n      highlight.jump(row)\n      return\n    }\n    const from = opener.getBoundingClientRect()\n    const box = row.getBoundingClientRect()\n    highlight.move(row, {\n      top: from.top,\n      bottom: from.bottom,\n      height: from.height,\n      left: box.left,\n      right: box.right,\n      width: box.width,\n    })\n  }\n\n  const sync = () => {\n    if (phase !== 'open' || waiting) return\n    const row = target()\n    if (!row) {\n      // Across a gap, a separator or a label the highlight holds; another\n      // item in the list that took the highlight, such as a theme switcher's\n      // icon, has a look of its own, so this one fades.\n      if (!inside || ownRow(':scope [data-highlighted]')) highlight.move(null)\n      return\n    }\n    if (first && opener) {\n      // A submenu is placed a frame or two after it mounts; measured before\n      // that, the item that opened it is in the wrong place.\n      first = false\n      waiting = true\n      frame = requestAnimationFrame(() => {\n        frame = requestAnimationFrame(() => fromOpener(opener))\n      })\n      return\n    }\n    first = false\n    go(row)\n  }\n\n  const opened = (records: MutationRecord[] = []) => {\n    const [next, start] = popupNext(phase, {\n      open: popup.hasAttribute('data-open'),\n      ending: popup.hasAttribute('data-ending-style'),\n      endingChanged: records.some(\n        (record) => record.attributeName === 'data-ending-style',\n      ),\n    })\n    phase = next\n    if (start) {\n      highlight.reset(start === 'appear')\n      first = true\n    }\n    sync()\n  }\n\n  // A menu can stop pointer events while a submenu opens, which fires\n  // `pointerleave` with the pointer still over it; the document still sees\n  // every move. The box is the popup's, since a list that scrolls is\n  // taller than what shows of it.\n  const moved = (event: PointerEvent) => {\n    const box = bounds.getBoundingClientRect()\n    inside =\n      event.clientX >= box.left &&\n      event.clientX <= box.right &&\n      event.clientY >= box.top &&\n      event.clientY <= box.bottom\n    if (!inside && phase === 'open' && !target()) highlight.move(null)\n  }\n\n  // Rows came or went, as in a list that filters: the highlight goes with its\n  // row, or fades when no row is highlighted any more, wherever the pointer\n  // is. Rows are looked at once every other observer has run, so a row that\n  // is set sliding to its new place already is.\n  const changed = () =>\n    queueMicrotask(() => {\n      if (phase !== 'open' || waiting) return\n      const row = target()\n      if (!row) highlight.move(null)\n      else if (row === highlight.item()) highlight.refit()\n      else go(row)\n    })\n\n  opened()\n  document.addEventListener('pointermove', moved)\n  const rows = new MutationObserver((records) => {\n    if (records.some(rowsCameOrWent)) changed()\n    else queueMicrotask(sync)\n  })\n  rows.observe(list, {\n    subtree: true,\n    childList: true,\n    attributes: true,\n    attributeFilter: ['data-highlighted', 'data-open'],\n  })\n  const state = new MutationObserver(opened)\n  state.observe(popup, {\n    attributes: true,\n    attributeFilter: ['data-open', 'data-ending-style'],\n  })\n  return () => {\n    rows.disconnect()\n    state.disconnect()\n    cancelAnimationFrame(frame)\n    document.removeEventListener('pointermove', moved)\n    highlight.stop()\n  }\n}\n\n/**\n * What the pointer or focus is on, for `followPointer`: an item the\n * highlight lands on, something it doesn't (`none`: it leaves, as over a\n * disabled tab), or the space between items (`gap`: it stays where it is).\n */\nexport type HighlightTarget = HTMLElement | 'none' | 'gap'\n\n/**\n * The item matching `selector` that `node` is in, inside `area`; a disabled\n * one is `none`. With `rows`, a row of the group that isn't an item, such as\n * an Item that doesn't act, is `none` too, and so is a disabled item that\n * lets the pointer through to its row.\n */\nexport function itemMatching(\n  area: HTMLElement,\n  selector: string,\n  { rows }: { rows?: string } = {},\n) {\n  return (node: EventTarget | null): HighlightTarget => {\n    const element = node instanceof Element ? node : null\n    const item = element?.closest<HTMLElement>(selector)\n    if (!item || !area.contains(item)) {\n      const row = rows ? element?.closest(rows) : null\n      return row && area.contains(row) ? 'none' : 'gap'\n    }\n    return item.matches(\n      '[data-disabled], [data-readonly], :disabled, [aria-disabled=\"true\"]',\n    )\n      ? 'none'\n      : item\n  }\n}\n\n/**\n * Follows the pointer over the items of `area`, and with `focus`, the item\n * with visible focus; whichever moved last wins. Off them, it goes to the\n * `current` item (an open trigger), or fades. It stays where it is across a\n * gap. Touch moves nothing: there is no hover to show.\n */\nexport function followPointer(\n  area: HTMLElement,\n  layer: HTMLElement,\n  {\n    itemOf,\n    current,\n    focus = false,\n  }: {\n    itemOf: (node: EventTarget | null) => HighlightTarget\n    current?: string\n    focus?: boolean\n  },\n) {\n  watchInput()\n  const highlight = createHighlight(layer)\n  let hovered: HTMLElement | null = null\n  let focused: HTMLElement | null = null\n  let last: 'pointer' | 'focus' = 'pointer'\n  let frame = 0\n  let shown: HTMLElement | null = null\n  // The item whose popup just closed with focus still inside it: the popup\n  // hands focus back once it has gone, so the highlight waits on the item\n  // instead of fading and coming back.\n  let held: HTMLElement | null = null\n\n  const target = () =>\n    (last === 'focus' ? (focused ?? hovered) : (hovered ?? focused)) ??\n    (current ? area.querySelector<HTMLElement>(current) : null) ??\n    held\n\n  const move = (item: HTMLElement | null) => {\n    shown = item\n    if (item && pressedKeyLast()) highlight.jump(item)\n    else highlight.move(item)\n  }\n\n  const sync = () => {\n    cancelAnimationFrame(frame)\n    const item = target()\n    if (item || !current) {\n      move(item)\n      return\n    }\n    // A bar clears one trigger before it opens the next: wait a frame.\n    frame = requestAnimationFrame(() => {\n      // Only while focus is in the popup that is still closing.\n      if (!target() && shown && document.activeElement?.closest('[data-ending-style]')) {\n        held = shown\n      }\n      move(target())\n    })\n  }\n\n  // Focus has gone somewhere, back to an item or not, or the pointer went down:\n  // the item no longer waits.\n  const release = () => {\n    if (!held) return\n    held = null\n    // After the area's own focus handler, which may take the item.\n    queueMicrotask(sync)\n  }\n\n  const over = (event: PointerEvent) => {\n    if (event.pointerType === 'touch') return\n    const under = itemOf(event.target)\n    if (under === 'gap') return\n    const next = under === 'none' ? null : under\n    if (next === hovered && last === 'pointer') return\n    hovered = next\n    last = 'pointer'\n    sync()\n  }\n  const leave = () => {\n    hovered = null\n    sync()\n  }\n  const focusIn = (event: FocusEvent) => {\n    const under = itemOf(event.target)\n    // What took focus may sit inside the item, as a row's checkbox does.\n    if (\n      under instanceof HTMLElement &&\n      event.target instanceof Element &&\n      event.target.matches(':focus-visible')\n    ) {\n      focused = under\n      last = 'focus'\n      sync()\n    }\n  }\n  const focusOut = (event: FocusEvent) => {\n    if (!focused || itemOf(event.target) !== focused) return\n    focused = null\n    // Focus moving to another item settles there on its own `focusin`.\n    if (!(itemOf(event.relatedTarget) instanceof HTMLElement)) sync()\n  }\n\n  sync()\n  document.addEventListener('focusin', release, true)\n  document.addEventListener('pointerdown', release, true)\n  area.addEventListener('pointerover', over)\n  area.addEventListener('pointerleave', leave)\n  if (focus) {\n    area.addEventListener('focusin', focusIn)\n    area.addEventListener('focusout', focusOut)\n  }\n  // Items came or went, as rows do in a table that sorts or grows: the\n  // highlight goes with its item to the item's new place, once every other\n  // observer has run, so an item set sliding there already is.\n  const items = new MutationObserver((records) => {\n    if (!records.some(elementsCameOrWent)) return\n    queueMicrotask(() => {\n      if (hovered && !hovered.isConnected) hovered = null\n      if (focused && !focused.isConnected) focused = null\n      if (shown && shown.isConnected && shown === target()) highlight.refit()\n      else sync()\n    })\n  })\n  items.observe(area, { subtree: true, childList: true })\n  // A pick changes a row's corners, as picked rows next to each other join\n  // into one block: the highlight takes the shape its row has now.\n  const picked = new MutationObserver(() => queueMicrotask(() => highlight.refit()))\n  picked.observe(area, {\n    attributes: true,\n    subtree: true,\n    attributeFilter: ['data-selected'],\n  })\n  const opened = new MutationObserver(sync)\n  if (current) {\n    opened.observe(area, {\n      attributes: true,\n      subtree: true,\n      attributeFilter: ['data-open'],\n    })\n  }\n  return () => {\n    cancelAnimationFrame(frame)\n    items.disconnect()\n    picked.disconnect()\n    opened.disconnect()\n    document.removeEventListener('focusin', release, true)\n    document.removeEventListener('pointerdown', release, true)\n    area.removeEventListener('pointerover', over)\n    area.removeEventListener('pointerleave', leave)\n    area.removeEventListener('focusin', focusIn)\n    area.removeEventListener('focusout', focusOut)\n    highlight.stop()\n  }\n}\n\n/**\n * Keeps the highlight on the item that holds focus, as a date input's\n * segments do, whether focus came from a key or a press. It glides as a\n * press moves focus from item to item, jumps as a key does, and fades once\n * focus leaves them.\n */\nexport function followFocus(\n  area: HTMLElement,\n  layer: HTMLElement,\n  itemOf: (node: EventTarget | null) => HTMLElement | null,\n) {\n  watchInput()\n  const highlight = createHighlight(layer)\n  const focusIn = (event: FocusEvent) => {\n    const item = itemOf(event.target)\n    if (item && pressedKeyLast()) highlight.jump(item)\n    else if (item) highlight.move(item)\n  }\n  const focusOut = (event: FocusEvent) => {\n    // Focus moving to another item settles there on its own `focusin`.\n    if (!itemOf(event.relatedTarget)) highlight.move(null)\n  }\n  const item = itemOf(document.activeElement)\n  if (item) highlight.move(item)\n  area.addEventListener('focusin', focusIn)\n  area.addEventListener('focusout', focusOut)\n  return () => {\n    area.removeEventListener('focusin', focusIn)\n    area.removeEventListener('focusout', focusOut)\n    highlight.stop()\n  }\n}\n\n/**\n * Keeps the highlight on the picked item of a group that holds one choice,\n * as a segmented control's thumb: there when the page paints, sliding as\n * the pick changes and following its item at once when sizes change. It fades when\n * nothing is picked. `attributes` are the ones that change when the pick does, such as `data-checked`.\n */\nexport function followPick(\n  area: HTMLElement,\n  layer: HTMLElement,\n  { picked, attributes }: { picked: () => HTMLElement | null; attributes: string[] },\n) {\n  const highlight = createHighlight(layer)\n  // A pick made before the first frame, such as a saved value restored as the\n  // page hydrates, is where the item starts: nothing moves on first paint.\n  let settled = false\n  const frame = requestAnimationFrame(() => {\n    settled = true\n  })\n\n  const sync = () => {\n    const item = picked()\n    if (item === highlight.item()) return\n    if (settled || !item) highlight.move(item)\n    else highlight.jump(item)\n  }\n\n  const first = picked()\n  if (first) highlight.jump(first)\n  // Items that come or go change the boxes around the picked one.\n  // Once every observer of the same change has run: a list that glides its\n  // rows (the `flow` lib) has started their slides by then, and the\n  // highlight goes with the picked one.\n  let stopped = false\n  const changed = new MutationObserver(() =>\n    queueMicrotask(() => {\n      if (stopped) return\n      highlight.refit()\n      sync()\n    }),\n  )\n  // An item can also arrive already picked, as options that load late do.\n  changed.observe(area, {\n    subtree: true,\n    childList: true,\n    attributes: true,\n    attributeFilter: attributes,\n  })\n  return () => {\n    stopped = true\n    cancelAnimationFrame(frame)\n    changed.disconnect()\n    highlight.stop()\n  }\n}\n",
      "type": "registry:lib",
      "target": "@lib/highlight.ts"
    }
  ],
  "type": "registry:lib"
}