{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sort",
  "title": "Sort",
  "description": "Lists put in a new order, and groups of lists whose items move between them, on ui-sdk’s reorder and transfer: a pointer drags a copy while the item shows as a slot, a finger holds an item to pick it up, the item glides from the copy into place, and each step is announced politely. The Sortable list is built on it.",
  "dependencies": [
    "@ui-sdk/core",
    "@ui-sdk/react"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/announce.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scroll.json"
  ],
  "files": [
    {
      "path": "registry/lib/sort.tsx",
      "content": "'use client'\n\nimport { announce } from '@/registry/lib/announce'\nimport { translateOf } from '@/registry/lib/highlight'\nimport { commitStyles } from '@/registry/lib/refs'\nimport { transitionsQuiet } from '@/registry/lib/resize'\nimport { revealOnceStill } from '@/registry/lib/scroll'\nimport {\n  bindHold,\n  type ChangeDetails,\n  createChange,\n  createReorder,\n  createTransfer,\n  definePrimitive,\n  elements,\n  isRTL,\n  type ReorderDraft,\n  type ReorderMessage,\n  type ReorderReason,\n  type SlotFactory,\n  type TransferDraft,\n  type TransferLists,\n  type TransferMessage,\n  type TransferReason,\n} from '@ui-sdk/core'\nimport { usePrimitive } from '@ui-sdk/react/primitive'\nimport {\n  Children,\n  Component,\n  createContext,\n  Fragment,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type RefObject,\n  use,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react'\n\n/*\n * Lists put in a new order, and groups of lists whose items move between\n * them, on ui-sdk's `createReorder` and `createTransfer`: they own the drag,\n * the keys, the draft order, the focus, edge scrolling and the steps a\n * screen reader hears. Kino adds the motion. A pointer drags a copy above the\n * page while the item shows where it would land as a dashed slot, its\n * neighbours glide aside on `layout` (the `flow` lib in each list, and a\n * glide of our own for an item that changes list), and let go, the item\n * glides from the copy into its slot. A finger holds an item still for a\n * moment to pick it up, so a card never blocks the page's scroll.\n */\n\n/** Rows in a column, or items that wrap in rows (`grid`). */\nexport type SortLayout = 'list' | 'grid'\n\n/** Where an item is: a list, and its index there, from 0. */\nexport interface SortPlace {\n  list: string\n  index: number\n}\n\n/** One item moved, named at both ends, for undo and logs. */\nexport interface SortMove {\n  item: string\n  from: SortPlace\n  to: SortPlace\n}\n\n/** Whether the list `to` takes `item` from the list `from`. */\nexport type SortAccepts = (item: string, to: string, from: string) => boolean\n\n/** What a lone list's `onValueChange` gets after the order: ui-sdk's change details. */\nexport type SortListDetails = ChangeDetails<ReorderReason>\n\n/** What a group's `onValueChange` gets after the move: ui-sdk's change details. */\nexport type SortGroupDetails = ChangeDetails<TransferReason>\n\n/** Whether two orders are the same. */\nexport function sameOrder(a: readonly string[], b: readonly string[]): boolean {\n  return a.length === b.length && a.every((value, index) => value === b[index])\n}\n\n/**\n * The order of the items there are: those in `order` that are still there,\n * then any new ones in the order they're given.\n */\nexport function reconcileOrder(\n  order: readonly string[],\n  present: readonly string[],\n): string[] {\n  const there = new Set(present)\n  const kept = order.filter((value) => there.has(value))\n  const known = new Set(kept)\n  return [...kept, ...present.filter((value) => !known.has(value))]\n}\n\n/**\n * A group's lists, with the items there are: each list keeps the items of\n * `lists` that some list renders, and takes at its end any it renders that\n * no list holds yet. `present` is what each list renders, by its id; a list\n * not in it yet, on the first render, keeps all of its items.\n */\nexport function reconcileLists(\n  lists: Readonly<TransferLists>,\n  present: Readonly<TransferLists>,\n): TransferLists {\n  const rendered = new Set(Object.values(present).flat())\n  const next: TransferLists = {}\n  for (const [list, keys] of Object.entries(lists))\n    next[list] = keys.filter((key) => rendered.has(key) || !(list in present))\n  const held = new Set(Object.values(next).flat())\n  for (const [list, keys] of Object.entries(present)) {\n    const added = keys.filter((key) => !held.has(key))\n    next[list] = [...(next[list] ?? []), ...added]\n    for (const key of added) held.add(key)\n  }\n  return next\n}\n\n/** The list that holds `item`, if one does. */\nexport function listOf(lists: Readonly<TransferLists>, item: string): string | undefined {\n  return Object.keys(lists).find((list) => lists[list]?.includes(item))\n}\n\n/** The items that are in another list in `next` than in `previous`. */\nexport function changedLists(\n  previous: Readonly<TransferLists>,\n  next: Readonly<TransferLists>,\n): string[] {\n  return Object.entries(next).flatMap(([list, keys]) =>\n    keys.filter((key) => {\n      const was = listOf(previous, key)\n      return was !== undefined && was !== list\n    }),\n  )\n}\n\n/** The move that takes `item` to `index` in the list `to`, from where it is in `lists`. */\nexport function moveOf(\n  lists: Readonly<TransferLists>,\n  item: string,\n  to: string,\n  index: number,\n): SortMove {\n  const from = listOf(lists, item) ?? to\n  return {\n    item,\n    from: { list: from, index: lists[from]?.indexOf(item) ?? -1 },\n    to: { list: to, index },\n  }\n}\n\n/** What a screen reader hears as an item in a list is picked up, moved, dropped or put back. */\nexport function sortMessage({ type, label, position, total }: ReorderMessage): string {\n  const at = `position ${position} of ${total}`\n  if (type === 'grab') return `Picked up ${label}, at ${at}.`\n  if (type === 'move') return `${label} moved to ${at}.`\n  if (type === 'drop') return `${label} dropped at ${at}.`\n  return `Move cancelled. ${label} is back at ${at}.`\n}\n\n/** The same in a group, naming the list each time: \"Write the brief, moved to Doing, 2 of 4.\" */\nexport function groupMessage({\n  type,\n  label,\n  list,\n  position,\n  total,\n}: TransferMessage): string {\n  const at = `${list}, ${position} of ${total}`\n  if (type === 'grab') return `Picked up ${label}, in ${at}.`\n  if (type === 'move') return `${label}, moved to ${at}.`\n  if (type === 'drop') return `${label}, dropped in ${at}.`\n  return `Move cancelled. ${label} is back in ${at}.`\n}\n\n/** What a list's handles say they do. */\nexport const sortInstructions =\n  'Press Space to pick it up. Then use the arrow keys to move it, Space to drop it, or Escape to put it back.'\n\n/** What a group's handles say they do. */\nexport const groupInstructions =\n  'Press Space to pick it up. Then use Up and Down to move it, Left and Right to move it to another list, Space to drop it, or Escape to put it back.'\n\n/**\n * What a press inside an item goes to, rather than starting a drag: a\n * control, named by its element, its role, or its slot where it draws none\n * (a Slider's control).\n */\nconst sortControls = [\n  'a[href]',\n  'button',\n  'input',\n  'select',\n  'textarea',\n  'label',\n  'summary',\n  '[contenteditable]',\n  '[role=button]',\n  '[role=link]',\n  '[role=checkbox]',\n  '[role=radio]',\n  '[role=switch]',\n  '[role=slider]',\n  '[role=spinbutton]',\n  '[role=textbox]',\n  '[role=searchbox]',\n  '[role=combobox]',\n  '[role=option]',\n  '[role=tab]',\n  '[role=treeitem]',\n  '[role=menuitem]',\n  '[role=menuitemcheckbox]',\n  '[role=menuitemradio]',\n  '[data-slot=slider-control]',\n] as const\nconst controls = sortControls.join(',')\n\n/** How near an edge, in px, a drag scrolls what it is in, and how far it scrolls each frame at most. */\nconst EDGE_SCROLL = { edge: 40, speed: 14 }\n/** How long, in ms, a finger holds an item before it is picked up, and how far, in px, it may move meanwhile. */\nconst HOLD_DELAY = 300\nconst HOLD_TOLERANCE = 8\n\n/** The handle's mark: a press on it drags, whatever the pointer. */\nconst HANDLE = 'data-sortable-handle'\n\n/** Whether a press on `target` in an item drags it: anywhere but a control, the handle aside. */\nfunction dragsFrom(target: EventTarget | null): boolean {\n  if (!(target instanceof Element)) return true\n  const control = target.closest(controls)\n  return !control || control.hasAttribute(HANDLE)\n}\n\n/** Whether a press on `target` is on the handle, which drags at once by touch too. */\nfunction onHandle(target: EventTarget | null): boolean {\n  return target instanceof Element && target.closest(`[${HANDLE}]`) !== null\n}\n\n/**\n * Starts `drag` from a press on an item: at once for a mouse or a pen, or a\n * finger on the handle. A finger elsewhere waits for `holdToDrag`, so it\n * scrolls the page if it moves first. A press inside an item of a list\n * nested in it, such as a card's checklist, is that item's.\n */\nfunction pressItem(\n  event: PointerEvent,\n  item: Element | null | undefined,\n  drag: (down: PointerEvent) => void,\n) {\n  if (!dragsFrom(event.target) || !ownPress(event, item)) return\n  if (event.pointerType === 'touch' && !onHandle(event.target)) return\n  drag(event)\n}\n\n/** The items of a lone list, of a group, and of either. */\nconst LIST_ITEM = '[data-slot=sortable-list-item]'\nconst GROUP_ITEM = '[data-slot=sortable-group-item]'\nconst ITEMS = `${LIST_ITEM},${GROUP_ITEM}`\n\n/** Whether a press is on `item` itself, rather than on an item of a list inside it. */\nfunction ownPress(event: Event, item: Element | null | undefined): boolean {\n  const target = event.target\n  return !(target instanceof Element) || target.closest(ITEMS) === item\n}\n\n/**\n * A finger held still on `el` for `HOLD_DELAY` starts `drag` with the press\n * it began with. While pressed, `el` has `data-holding`; once held, and\n * while the drag lasts, the page no longer scrolls under the finger, so the\n * drag follows it.\n */\nfunction holdToDrag(\n  el: HTMLElement,\n  drag: (down: PointerEvent) => void,\n  dragging: () => boolean,\n): () => void {\n  let held = false\n  // On the element from the start, so the browser waits for it before it scrolls.\n  const block = (event: TouchEvent) => {\n    if (held || dragging()) event.preventDefault()\n  }\n  el.addEventListener('touchmove', block, { passive: false })\n  const unbind = bindHold(el, {\n    delay: HOLD_DELAY,\n    tolerance: HOLD_TOLERANCE,\n    keys: [],\n    onPress: ({ event, input }) =>\n      input === 'touch' &&\n      dragsFrom(event.target) &&\n      !onHandle(event.target) &&\n      ownPress(event, el),\n    onHold: ({ event }) => {\n      held = true\n      drag(event as PointerEvent)\n    },\n    onEnd: () => {\n      held = false\n    },\n  })\n  return () => {\n    unbind()\n    el.removeEventListener('touchmove', block)\n  }\n}\n\n/** Says each step in our words, politely: ui-sdk's own announcements are urgent, so they get none. */\nfunction said<Message extends { type: string }>(\n  say: () => ((text: string) => void) | undefined,\n  words: (message: Message) => string,\n  pointer: () => boolean,\n) {\n  return (message: Message) => {\n    // A pointer's steps show as it drags; only where it was picked up and let go is said.\n    if (message.type !== 'move' || !pointer()) say()?.(words(message))\n    return ''\n  }\n}\n\n/**\n * Whether focus at `active` has left `key` while the keys move it: a press\n * elsewhere puts it back, as Tab does. Focus its own move takes away comes\n * back to it.\n */\nexport function leaves(\n  moving: { key: string; pointer: boolean } | null,\n  key: string,\n  active: Element | null,\n): boolean {\n  if (!moving || moving.pointer || moving.key !== key) return false\n  return active?.closest('[data-key]')?.getAttribute('data-key') !== key\n}\n\n/** Calls `check` with where focus went, once a move that took it away has given it back (`keepFocus`). */\nfunction leaveLater(event: Event, check: (active: Element | null) => void) {\n  const doc = (event.target as Node).ownerDocument\n  setTimeout(() => check(doc?.activeElement ?? null))\n}\n\n/** A box in the viewport, as `placeAt` reads it. */\ntype Box = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>\n\n/**\n * Where an item dragged to `point` goes among the others, from the boxes\n * they and its slot are laid out in: `others` in order and `slot` at\n * `current` among them. It goes past every box the point is past: in a\n * list, past its middle; in a grid, below it, or level with it and past its\n * middle across. A grid's point past the last box of a row, where the slot\n * would wrap below it, takes that box's place, so the slot reaches the end\n * of the row and the box wraps instead.\n */\nexport function placeAt(\n  others: readonly Box[],\n  slot: Box,\n  current: number,\n  point: { x: number; y: number },\n  layout: SortLayout,\n  rtl: boolean,\n): number {\n  if (layout === 'list')\n    return others.filter((box) => point.y > (box.top + box.bottom) / 2).length\n  const middle = (box: Box) => (box.left + box.right) / 2\n  const after = (box: Box, than: Box) =>\n    rtl ? middle(box) < middle(than) : middle(box) > middle(than)\n  const level = (box: Box) => point.y >= box.top && point.y <= box.bottom\n  const across = (box: Box) => (rtl ? point.x < middle(box) : point.x > middle(box))\n  const counted = others.filter(\n    (box) => point.y > box.bottom || (point.y >= box.top && across(box)),\n  ).length\n  if (counted !== current) return counted\n  const boxes = [...others, slot]\n  const lastOfRow = (box: Box) =>\n    !boxes.some(\n      (other) =>\n        other !== box &&\n        other.top < box.bottom &&\n        other.bottom > box.top &&\n        after(other, box),\n    )\n  const end = others.findIndex(\n    (box, index) => index < current && level(box) && across(box) && lastOfRow(box),\n  )\n  return end === -1 ? counted : end\n}\n\n/** What a list's and a group's state share: the item that moves, if one does. */\ntype SortState = { moving: { key: string; pointer: boolean } | null }\n\n/** An item and its label, as an agent names it. */\ninterface Named {\n  value: string\n  label: string\n  /** What the page shows of it, which an agent reads in `snapshot()`. */\n  shown?: string\n}\n\n/**\n * The text an item shows, as ui-sdk's `snapshot()` reads it: its text, in\n * order, past anything hidden from a screen reader or an agent and past the\n * items of a list inside it, with its spaces run together.\n */\nexport function shownText(item: Element): string {\n  let text = ''\n  const walk = (node: Node) => {\n    for (const child of node.childNodes) {\n      if (child.nodeType === Node.TEXT_NODE) text += child.textContent\n      else if (\n        child instanceof Element &&\n        !child.matches(ITEMS) &&\n        !child.hasAttribute('data-agent-hidden') &&\n        child.getAttribute('aria-hidden') !== 'true'\n      )\n        walk(child)\n    }\n  }\n  walk(item)\n  return text.replace(/\\s+/g, ' ').trim()\n}\n\n/**\n * What the items and handles of a lone list and of a group call: the same\n * parts on either, each primitive answering with its own engine, `reorder`\n * or `transfer`.\n */\ninterface SortParts<State> {\n  /** Whether the item can't move: it, or what it is in, is turned off. */\n  locked: (state: State, key: string) => boolean\n  /** Whether the keys move the item now. */\n  moved: (state: State, key: string) => boolean\n  /** Whether a pointer drags the item now. */\n  dragged: (state: State, key: string) => boolean\n  pointerdown: (event: PointerEvent, key: string) => void\n  keydown: (event: KeyboardEvent, key: string) => void\n  bindItem: (el: HTMLElement, part: { key: string; props: object }) => () => void\n  /** Whether a pointer drags an item now. */\n  dragging: () => boolean\n  /** Picks the item up by keys, or drops it if it is picked up: a screen reader's activate. */\n  toggle: (key: string) => void\n  /** Puts the item back if focus at `active` has left it while the keys move it. */\n  leave: (key: string, active: Element | null) => void\n  /** Where the copy of `key` was let go, once: the item glides from there into its place. */\n  settle: (key: string) => DOMRect | null\n  /** Follows a pointer's drags from the root's element. */\n  follow: (el: HTMLElement) => () => void\n}\n\n/**\n * Brings an item the keys carry into sight where it lands, past the glide\n * that takes it there and a list around it that opens for it: the focus\n * follows it, but focus scrolls to where it is on the way.\n */\nfunction revealCarried(handle: HTMLElement, key: string) {\n  const root = handle.closest('[data-slot=sortable-group], [data-slot=sortable-list]')\n  requestAnimationFrame(() => {\n    const item = root?.querySelector<HTMLElement>(\n      `[data-key=\"${CSS.escape(key)}\"][data-moving]`,\n    )\n    if (item) void revealOnceStill(item)\n  })\n}\n\n/** The item and handle slots, the same in a lone list and a group. */\nfunction itemSlots<State extends object & SortState, Api extends SortParts<State>>(\n  slot: SlotFactory<State, Api>,\n) {\n  return {\n    item: slot<{ value: string; label: string; disabled?: boolean }>({\n      props: { value: 'string', label: 'string', disabled: 'boolean' },\n      role: 'listitem',\n      attrs: (state, { api, key, props }) => ({\n        'data-key': key,\n        'data-moving': api.moved(state, key) ? '' : undefined,\n        'data-dragging': api.dragged(state, key) ? '' : undefined,\n        'data-disabled': props.disabled || api.locked(state, key) ? '' : undefined,\n      }),\n      on: {\n        pointerdown: (event, { api, el, key }) =>\n          pressItem(event as PointerEvent, el, (down) => api.pointerdown(down, key)),\n      },\n      bind: (el, { api, key, props }) => {\n        const cleanups = [\n          api.bindItem(el, { key, props }),\n          holdToDrag(el, (down) => api.pointerdown(down, key), api.dragging),\n        ]\n        return () => cleanups.forEach((cleanup) => cleanup())\n      },\n    }),\n    handle: slot<{ value: string; disabled?: boolean }>({\n      props: { value: 'string', disabled: 'boolean' },\n      role: 'button',\n      focus: 'native',\n      // A screen reader's activate sends a click with no press behind it; a pointer drags instead.\n      press: ({ api, key }, event) => {\n        if (event instanceof MouseEvent && event.detail === 0) api.toggle(key)\n      },\n      attrs: (state, { api, key, props }) => ({\n        type: 'button',\n        [HANDLE]: '',\n        'aria-pressed': String(api.moved(state, key) || api.dragged(state, key)),\n        disabled: props.disabled || api.locked(state, key) ? '' : undefined,\n      }),\n      on: {\n        keydown: (event, { api, el, key }) => {\n          api.keydown(event as KeyboardEvent, key)\n          if (el) revealCarried(el, key)\n        },\n        focusout: (event, { api, key }) =>\n          leaveLater(event, (active) => api.leave(key, active)),\n      },\n    }),\n  }\n}\n\n/** Finds `name` among `all` by its value, or else by its label or what it shows, in any case. */\nfunction named(all: readonly Named[], name: string): Named | undefined {\n  const lower = name.replace(/\\s+/g, ' ').trim().toLowerCase()\n  return (\n    all.find((one) => one.value === name) ??\n    all.find(\n      (one) => one.label.toLowerCase() === lower || one.shown?.toLowerCase() === lower,\n    )\n  )\n}\n\n/** Each item there is, by its value, its label and what it shows. */\nfunction itemsIn(\n  context: Parameters<typeof elements>[0],\n  values: readonly string[],\n  label: (value: string) => string | undefined,\n): Named[] {\n  const els = new Map(elements(context, 'item').map((part) => [part.key, part.el]))\n  return values.map((value) => {\n    const el = els.get(value)\n    return { value, label: label(value) ?? value, shown: el && shownText(el) }\n  })\n}\n\n/** How `all` reads in an error: each by its label. */\nfunction namesOf(all: readonly Named[]): string {\n  return all.map((one) => one.label).join(', ')\n}\n\ntype SortListOptions = {\n  /** The items' values, in order. */\n  value?: string[]\n  defaultValue?: string[]\n  /** Called with the new order once an item is dropped in a new place. */\n  onValueChange?: (value: string[], details: SortListDetails) => void\n  /** The values of the items the list renders. */\n  items?: string[]\n  layout?: SortLayout\n  disabled?: boolean\n  /** Says a step to a screen reader. */\n  announce?: (text: string) => void\n}\n\n/** A list put in a new order: the Sortable list's. */\nconst sortList = definePrimitive({\n  name: 'sortable-list',\n  options: {\n    value: 'list',\n    defaultValue: 'list',\n    onValueChange: 'callback',\n    items: 'list',\n    layout: 'string',\n    disabled: 'boolean',\n    announce: 'value',\n  },\n  controlled: ['value'],\n  state: (options: SortListOptions) => ({\n    value: reconcileOrder(\n      options.value ?? options.defaultValue ?? options.items ?? [],\n      options.items ?? [],\n    ),\n    moving: null as ReorderDraft | null,\n    layout: options.layout ?? 'list',\n    disabled: !!options.disabled,\n  }),\n  sync: (options) => ({\n    ...(options.value === undefined\n      ? {}\n      : { value: reconcileOrder(options.value, options.items ?? []) }),\n    layout: options.layout ?? 'list',\n    disabled: !!options.disabled,\n  }),\n  api: (context) => {\n    const { store, options } = context\n    const change = createChange(context)\n    // An item that comes or goes joins or leaves the order the list keeps itself.\n    let items = options().items ?? []\n    context.onOptions((next) => {\n      const now = next.items ?? []\n      if (sameOrder(now, items)) return\n      items = now\n      if (next.value === undefined)\n        store.set({ value: reconcileOrder(store.get().value, now) })\n    })\n    const itemProps = (key: string) =>\n      context.props<{ label?: string; disabled?: boolean }>('item', key)\n    const reorder = createReorder(context, {\n      slot: 'item',\n      key: 'value',\n      draft: 'moving',\n      set: (value, details) => change('value', value, details),\n      orientation: () => (store.get().layout === 'grid' ? 'grid' : 'vertical'),\n      preview: true,\n      createAutoScroll: EDGE_SCROLL,\n      disabled: ({ props }) =>\n        !!(props as { disabled?: boolean }).disabled || store.get().disabled,\n      label: (key) => itemProps(key)?.label,\n      message: said(\n        () => options().announce,\n        sortMessage,\n        () => store.get().moving?.pointer === true,\n      ),\n    })\n    const held = createHeld()\n    const all = () => itemsIn(context, store.get().value, (key) => itemProps(key)?.label)\n    const parts: SortParts<ReturnType<typeof store.get>> = {\n      locked: (state, key) => state.disabled || !!itemProps(key)?.disabled,\n      moved: (state, key) => reorder.moving(state, key) && !state.moving?.pointer,\n      dragged: (state, key) => reorder.dragging(state, key),\n      pointerdown: (event, key) => reorder.pointerdown(event, key),\n      keydown: (event, key) => {\n        reorder.keydown(event, key)\n      },\n      bindItem: (el, part) => reorder.bind(el, part),\n      dragging: () => store.get().moving?.pointer === true,\n      toggle: (key) => {\n        if (store.get().moving?.key === key) reorder.drop()\n        else reorder.grab(key)\n      },\n      leave: (key, active) => {\n        if (leaves(store.get().moving, key, active)) reorder.cancel()\n      },\n      settle: held.take,\n      follow: (el) => {\n        const unfollow = followDrag(el, store, held, LIST_ITEM)\n        const unplace = placeLaidOut(\n          el,\n          store,\n          reorder,\n          () => new Map(elements(context, 'item').map((part) => [part.key, part.el])),\n        )\n        return () => {\n          unplace()\n          unfollow()\n        }\n      },\n    }\n    return {\n      reorder,\n      ...parts,\n      /** Every item, by its value and its label. */\n      items: all,\n      /**\n       * Moves `item`, by its value or its label, to `index`, from 0, as a\n       * drop there would: an agent's move. Says which items there are, or how\n       * far `index` goes, when it names neither.\n       */\n      moveItem: (item: string, index: number) => {\n        const order = store.get().value\n        const found = named(all(), item)\n        if (!found) throw new Error(`No item \"${item}\". Its items: ${namesOf(all())}.`)\n        if (!Number.isInteger(index) || index < 0 || index >= order.length)\n          throw new Error(`No place ${index}. Places go from 0 to ${order.length - 1}.`)\n        if (parts.locked(store.get(), found.value))\n          throw new Error(`\"${found.label}\" can’t be moved.`)\n        return reorder.move(found.value, index)\n      },\n    }\n  },\n  slots: (slot) => ({\n    root: slot<object, { order: string[]; sorting: boolean }>({\n      role: 'list',\n      state: (state, { api }) => ({\n        order: api.reorder.order(state),\n        sorting: state.moving !== null,\n      }),\n      attrs: (state) => ({\n        'data-layout': state.layout,\n        'data-sorting': state.moving ? '' : undefined,\n        'data-disabled': state.disabled ? '' : undefined,\n      }),\n      bind: (el, { api }) => api.follow(el),\n    }),\n    ...itemSlots(slot),\n  }),\n  agent: { actions: ['moveItem'], items: (api) => api.items() },\n})\n\ntype SortGroupOptions = {\n  /** Each list's items, in order, by the list's id. */\n  value?: TransferLists\n  defaultValue?: TransferLists\n  onValueChange?: (value: TransferLists, details: SortGroupDetails) => void\n  accepts?: SortAccepts\n  /** What each list renders, by its id. */\n  present?: TransferLists\n  announce?: (text: string) => void\n}\n\n/** Lists whose items move between them: the Sortable group's. */\nconst sortGroup = definePrimitive({\n  name: 'sortable-group',\n  options: {\n    value: 'value',\n    defaultValue: 'value',\n    onValueChange: 'callback',\n    accepts: 'value',\n    present: 'value',\n    announce: 'value',\n  },\n  controlled: ['value'],\n  state: (options: SortGroupOptions) => ({\n    value: reconcileLists(\n      options.value ?? options.defaultValue ?? {},\n      options.present ?? {},\n    ),\n    moving: null as TransferDraft | null,\n  }),\n  sync: (options) =>\n    options.value === undefined\n      ? {}\n      : { value: reconcileLists(options.value, options.present ?? {}) },\n  api: (context) => {\n    const { store, options } = context\n    const change = createChange(context)\n    let present = options().present ?? {}\n    context.onOptions((next) => {\n      if (next.present === present) return\n      present = next.present ?? {}\n      if (next.value === undefined)\n        store.set({ value: reconcileLists(store.get().value, present) })\n    })\n    const listProps = (list: string | undefined) =>\n      list === undefined\n        ? undefined\n        : context.props<{ label?: string; disabled?: boolean }>('list', list)\n    const itemProps = (key: string) =>\n      context.props<{ label?: string; disabled?: boolean }>('item', key)\n    const locked = (key: string) =>\n      !!itemProps(key)?.disabled || !!listProps(listOf(store.get().value, key))?.disabled\n    const takes = (item: string, list: string) =>\n      !listProps(list)?.disabled &&\n      (options().accepts?.(item, list, listOf(store.get().value, item) ?? list) ?? true)\n    // Left and Right go through the lists in the order they are in the page.\n    const order = () => elements(context, 'list').map((list) => list.key)\n    const transfer = createTransfer(context, {\n      key: 'value',\n      draft: 'moving',\n      set: (value, { key, to, index, reason, event }) =>\n        change('value', value, {\n          reason,\n          event,\n          move: moveOf(store.get().value, key, to, index),\n        }),\n      order,\n      accepts: takes,\n      disabled: locked,\n      label: (key) => itemProps(key)?.label,\n      listLabel: (list) => listProps(list)?.label,\n      message: said(\n        () => options().announce,\n        groupMessage,\n        () => store.get().moving?.pointer === true,\n      ),\n      createAutoScroll: EDGE_SCROLL,\n    })\n    /** What a person sees as each list: the box a drop lands in. */\n    const boxes = new Map<string, HTMLElement>()\n    const held = createHeld()\n    const itemsOf = () =>\n      itemsIn(\n        context,\n        Object.values(store.get().value).flat(),\n        (key) => itemProps(key)?.label,\n      )\n    const listsOf = (): Named[] =>\n      Object.keys(store.get().value).map((value) => ({\n        value,\n        label: listProps(value)?.label ?? value,\n      }))\n    /** Says so when Left or Right is refused by the list beside, which the keys skip. */\n    const refused = (event: KeyboardEvent, was: TransferDraft) => {\n      const across = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0\n      if (!across || store.get().moving !== was) return\n      const lists = order()\n      const from = listOf(was.lists, was.key) ?? was.from\n      const rtl = event.target instanceof Element && isRTL(event.target)\n      const beside = lists[lists.indexOf(from) + (rtl ? -across : across)]\n      if (beside === undefined || takes(was.key, beside)) return\n      options().announce?.(\n        `${listProps(beside)?.label ?? beside} doesn’t take ${itemProps(was.key)?.label ?? was.key}.`,\n      )\n    }\n    const parts: SortParts<ReturnType<typeof store.get>> = {\n      locked: (_state, key) => locked(key),\n      moved: (state, key) => transfer.moving(state, key) && !state.moving?.pointer,\n      dragged: (state, key) => transfer.dragging(state, key),\n      pointerdown: (event, key) => transfer.pointerdown(event, key),\n      keydown: (event, key) => {\n        const was = store.get().moving\n        transfer.keydown(event, key)\n        if (was && !was.pointer) refused(event, was)\n      },\n      bindItem: (el, { key }) => transfer.bindItem(el, key),\n      dragging: () => store.get().moving?.pointer === true,\n      toggle: (key) => {\n        if (store.get().moving?.key === key) transfer.drop()\n        else transfer.grab(key)\n      },\n      leave: (key, active) => {\n        if (leaves(store.get().moving, key, active)) transfer.cancel()\n      },\n      settle: held.take,\n      follow: (el) => {\n        const stops = [\n          followDrag(el, store, held, GROUP_ITEM),\n          // Outside every box that takes it, a drop puts it back.\n          followOutside(\n            el,\n            store,\n            (x, y, key) =>\n              ![...boxes].some(\n                ([list, box]) =>\n                  box.isConnected &&\n                  inside(box, x, y) &&\n                  (list === listOf(store.get().value, key) || takes(key, list)),\n              ),\n            () => transfer.cancel(),\n          ),\n        ]\n        return () => stops.forEach((stop) => stop())\n      },\n    }\n    return {\n      transfer,\n      ...parts,\n      /** Whether a list takes the item now being moved: a drop on one that doesn't puts it back. */\n      takes,\n      /** Joins a list's box, so drags find it and a drop in it lands there. */\n      bindList: (el: HTMLElement, list: string) => {\n        const box = dropBoxOf(el)\n        boxes.set(list, box)\n        const unbind = transfer.bindList(box, list)\n        // While an item moves that it won't take, the box is marked, so it steps back as one.\n        const mark = () => {\n          const moving = store.get().moving\n          box.toggleAttribute(\n            'data-refused',\n            !!moving &&\n              listOf(store.get().value, moving.key) !== list &&\n              !takes(moving.key, list),\n          )\n        }\n        mark()\n        const stop = store.subscribe(mark)\n        return () => {\n          stop()\n          unbind()\n          box.removeAttribute('data-refused')\n          if (boxes.get(list) === box) boxes.delete(list)\n        }\n      },\n      /** Every item, by its value and its label. */\n      items: itemsOf,\n      /**\n       * Moves `item` to `index`, from 0, in the list `list`, each by its\n       * value or its label, as a drop there would: an agent's move. Says\n       * which items or lists there are, or how far `index` goes, when it\n       * names neither.\n       */\n      moveItem: (item: string, list: string, index: number) => {\n        const lists = store.get().value\n        const found = named(itemsOf(), item)\n        if (!found)\n          throw new Error(`No item \"${item}\". Its items: ${namesOf(itemsOf())}.`)\n        const into = named(listsOf(), list)\n        if (!into) throw new Error(`No list \"${list}\". Its lists: ${namesOf(listsOf())}.`)\n        const places = (lists[into.value] ?? []).filter(\n          (key) => key !== found.value,\n        ).length\n        if (!Number.isInteger(index) || index < 0 || index > places)\n          throw new Error(\n            `No place ${index} in \"${into.label}\". Places go from 0 to ${places}.`,\n          )\n        if (locked(found.value)) throw new Error(`\"${found.label}\" can’t be moved.`)\n        if (listOf(lists, found.value) !== into.value && !takes(found.value, into.value))\n          throw new Error(`\"${into.label}\" doesn’t take \"${found.label}\".`)\n        return transfer.move(found.value, into.value, index)\n      },\n    }\n  },\n  slots: (slot) => ({\n    root: slot<object, { lists: TransferLists; dragging: string | null }>({\n      role: 'group',\n      state: (state, { api }) => ({\n        lists: api.transfer.lists(state),\n        dragging: state.moving?.pointer ? state.moving.key : null,\n      }),\n      attrs: (state) => ({ 'data-sorting': state.moving ? '' : undefined }),\n      bind: (el, { api }) => api.follow(el),\n    }),\n    list: slot<{ value: string; label: string; disabled?: boolean }, { order: string[] }>(\n      {\n        props: { value: 'string', label: 'string', disabled: 'boolean' },\n        role: 'list',\n        state: (state, { api, key }) => ({\n          order: api.transfer.lists(state)[key] ?? NONE,\n        }),\n        attrs: (_state, { key, props }) => ({\n          'data-key': key,\n          'aria-label': props.label,\n          'data-disabled': props.disabled ? '' : undefined,\n        }),\n        bind: (el, { api, key }) => api.bindList(el, key),\n      },\n    ),\n    ...itemSlots(slot),\n  }),\n  agent: { actions: ['moveItem'], items: (api) => api.items() },\n})\n\nconst NONE: string[] = []\n\n/** Something with a `value`, as a sortable item has. */\ntype Valued = ReactElement<{ value: string }>\n\n/**\n * A list's items: its children, and those inside fragments, each with a\n * `value` to put it in order by. A component of the buyer's own that renders\n * an item takes the item's `value` too.\n */\nfunction valuedChildren(children: ReactNode): Valued[] {\n  return Children.toArray(children).flatMap((child): Valued[] => {\n    if (!isValidElement<{ value?: unknown; children?: ReactNode }>(child)) return []\n    if (child.type === Fragment) return valuedChildren(child.props.children)\n    if (typeof child.props.value === 'string') return [child as Valued]\n    // Anything else, such as a heading between items, has no place in the order.\n    return []\n  })\n}\n\n/** The item's place in the viewport without any `translate`: where it is laid out. */\nfunction laidOut(item: HTMLElement): DOMRect {\n  const box = item.getBoundingClientRect()\n  const [x, y] = translateOf(getComputedStyle(item).translate)\n  return new DOMRect(box.left - x, box.top - y, box.width, box.height)\n}\n\n/**\n * Glides `item` from `was`, a box in the viewport it was seen at, to where\n * it is laid out now, on its `translate` transition (`layout`): marked\n * `data-flow=start`, as the `flow` lib marks what it glides, while it is put\n * where it was.\n */\nfunction glideFrom(item: HTMLElement, was: DOMRect) {\n  const now = laidOut(item)\n  const x = was.left - now.left\n  const y = was.top - now.top\n  if (Math.abs(x) < 0.5 && Math.abs(y) < 0.5) return\n  item.dataset.flow = 'start'\n  item.style.translate = `${x}px ${y}px`\n  commitStyles(item)\n  delete item.dataset.flow\n  item.style.translate = ''\n}\n\n/** The attributes that set a look for what is inside them, read from the nearest element that has each. */\nconst scopes = [\n  'data-density',\n  'data-shape',\n  'data-feel',\n  'data-motion',\n  'data-theme-preset',\n  'data-primary',\n  'dir',\n] as const\n\n/**\n * Gives the copy a pointer drags the look of the item it came from: ui-sdk\n * puts it in `<body>`, outside a preview's density, shape, feel, motion and\n * theme, and outside its container. It takes the attributes around\n * `from`, the custom properties set inline on the way up, the\n * nearest first, and, where `from` is in a size container, becomes one, so\n * its container queries still match: the copy is as wide as the item.\n */\nfunction scopeCopy(copy: HTMLElement, from: HTMLElement) {\n  for (const name of scopes) {\n    const value = from.closest(`[${name}]`)?.getAttribute(name)\n    if (value !== null && value !== undefined) copy.setAttribute(name, value)\n  }\n  let contained = false\n  for (let at = from.parentElement; at; at = at.parentElement) {\n    for (const name of Array.from(at.style)) {\n      if (name.startsWith('--') && !copy.style.getPropertyValue(name))\n        copy.style.setProperty(name, at.style.getPropertyValue(name))\n    }\n    contained ||= getComputedStyle(at).containerType !== 'normal'\n  }\n  if (contained) copy.style.containerType = 'inline-size'\n}\n\n/** The copy that follows the pointer, once ui-sdk has put it in the page. */\nfunction copyOf(doc: Document): HTMLElement | null {\n  return doc.body.querySelector<HTMLElement>(':scope > [data-drag-preview]')\n}\n\n/** Where the copy was let go, and of which item, until that item is back in place. */\ninterface LetGo {\n  key: string\n  box: DOMRect\n}\n\n/** Holds where the copy was let go until its item takes it, once. */\nfunction createHeld() {\n  const held = {\n    letGo: null as LetGo | null,\n    take: (key: string) => {\n      const letGo = held.letGo\n      if (letGo?.key !== key) return null\n      held.letGo = null\n      return letGo.box\n    },\n  }\n  return held\n}\n\n/** An item of a list or a group, found by its slot, so a list's own `data-key` never answers. */\nfunction itemIn(root: Element, selector: string, key: string): HTMLElement | null {\n  return root.querySelector<HTMLElement>(\n    `:is(${selector})[data-key=\"${CSS.escape(key)}\"]`,\n  )\n}\n\n/** The item a pointer drags now, if one does. */\nfunction draggedIn(store: { get: () => SortState }): string | null {\n  const moving = store.get().moving\n  return moving?.pointer ? moving.key : null\n}\n\n/** What `followDrag` and `followOutside` read: a primitive's store. */\ninterface SortStore {\n  get: () => SortState\n  subscribe: (listener: () => void) => () => void\n}\n\n/**\n * Follows a pointer's drags from `root`, the list's or the group's element:\n * gives the copy its look, and as it is let go, holds where it was so the\n * item glides from there into its slot (`useSettle`).\n */\nfunction followDrag(\n  root: HTMLElement,\n  store: SortStore,\n  held: ReturnType<typeof createHeld>,\n  items: string,\n): () => void {\n  const doc = root.ownerDocument\n  let was: string | null = null\n  const stop = store.subscribe(() => {\n    const now = draggedIn(store)\n    if (now === was) return\n    const ended = was\n    was = now\n    if (now) {\n      // ui-sdk puts the copy in the page once the item is picked up, in the same task.\n      queueMicrotask(() => {\n        const copy = copyOf(doc)\n        const item = itemIn(root, items, now)\n        if (copy && item) scopeCopy(copy, item)\n      })\n      return\n    }\n    // Its item takes where it was let go as it renders; if it never does, nothing stays held.\n    requestAnimationFrame(() => {\n      if (!ended || !held.take(ended)) return\n      itemIn(root, items, ended)?.removeAttribute('data-flow-held')\n    })\n  })\n  const end = (event: Event) => {\n    if (event instanceof KeyboardEvent && event.key !== 'Escape') return\n    const key = draggedIn(store)\n    const copy = copyOf(doc)\n    if (!key || !copy) return\n    held.letGo = { key, box: copy.getBoundingClientRect() }\n    // Held, the `flow` lib leaves it to us: it glides from the copy.\n    itemIn(root, items, key)?.setAttribute('data-flow-held', '')\n  }\n  doc.addEventListener('pointerup', end, true)\n  doc.addEventListener('pointercancel', end, true)\n  doc.addEventListener('keydown', end, true)\n  return () => {\n    stop()\n    doc.removeEventListener('pointerup', end, true)\n    doc.removeEventListener('pointercancel', end, true)\n    doc.removeEventListener('keydown', end, true)\n  }\n}\n\n/**\n * Puts the item a pointer drags back where it came from when it is let go\n * at a point `outside`, such as outside every list of a group that takes\n * it, and marks `root` `data-outside` while the pointer is there. Bound\n * after `followDrag`, so where it was let go is held first.\n */\nfunction followOutside(\n  root: HTMLElement,\n  store: SortStore,\n  outside: (x: number, y: number, key: string) => boolean,\n  cancel: () => void,\n): () => void {\n  const doc = root.ownerDocument\n  const stop = store.subscribe(() => {\n    if (!draggedIn(store)) root.removeAttribute('data-outside')\n  })\n  const end = (event: PointerEvent) => {\n    const key = draggedIn(store)\n    if (key && outside(event.clientX, event.clientY, key)) cancel()\n  }\n  const move = (event: PointerEvent) => {\n    const key = draggedIn(store)\n    if (key)\n      root.toggleAttribute('data-outside', outside(event.clientX, event.clientY, key))\n  }\n  doc.addEventListener('pointerup', end, true)\n  doc.addEventListener('pointermove', move, true)\n  return () => {\n    stop()\n    doc.removeEventListener('pointerup', end, true)\n    doc.removeEventListener('pointermove', move, true)\n  }\n}\n\n/**\n * Moves the item a pointer drags in `root` to where the others are laid\n * out, not where they are drawn. ui-sdk 0.1.0-beta.18 finds the place from\n * each item's box as drawn, so a neighbour still gliding to its new place,\n * as one that wraps to the next row of a grid does, passes back under the\n * pointer and sends the item back, and the two swing to and fro; it takes\n * no boxes or place of ours. It still moves the item through\n * `reorder.moveTo`, which this takes over while a pointer drags, following\n * only the pointer that pressed, as ui-sdk does.\n */\nfunction placeLaidOut(\n  root: HTMLElement,\n  store: { get: () => { moving: ReorderDraft | null; layout: SortLayout } },\n  reorder: { moveTo: (index: number) => void },\n  itemOf: () => Map<string, HTMLElement>,\n): () => void {\n  const doc = root.ownerDocument\n  const moveTo = reorder.moveTo\n  let pointer: number | null = null\n  let point: { x: number; y: number } | null = null\n  const press = (event: PointerEvent) => {\n    pointer = event.pointerId\n    point = { x: event.clientX, y: event.clientY }\n  }\n  const move = (event: PointerEvent) => {\n    if (event.pointerId === pointer) point = { x: event.clientX, y: event.clientY }\n  }\n  reorder.moveTo = (index) => {\n    const { moving, layout } = store.get()\n    if (!moving?.pointer || !point) return moveTo(index)\n    const items = itemOf()\n    const slot = items.get(moving.key)\n    const others = moving.order\n      .filter((key) => !moving.keys.includes(key))\n      .map((key) => items.get(key))\n      .filter((item) => item !== undefined)\n    if (!slot) return moveTo(index)\n    const current = moving.order.indexOf(moving.keys[0]!)\n    moveTo(\n      placeAt(others.map(laidOut), laidOut(slot), current, point, layout, isRTL(slot)),\n    )\n  }\n  root.addEventListener('pointerdown', press, true)\n  doc.addEventListener('pointermove', move, true)\n  return () => {\n    reorder.moveTo = moveTo\n    root.removeEventListener('pointerdown', press, true)\n    doc.removeEventListener('pointermove', move, true)\n  }\n}\n\n/**\n * The box a person sees as a list of a group, which takes a drop anywhere\n * in it: the list's element, or the one around it that holds it alone, such\n * as a column with a heading, up to the group.\n */\nfunction dropBoxOf(list: HTMLElement): HTMLElement {\n  let box = list\n  for (\n    let up = box.parentElement;\n    up &&\n    up.getAttribute('data-slot') !== 'sortable-group' &&\n    up.querySelectorAll('[data-slot=sortable-group-list]').length <= 1;\n    up = up.parentElement\n  )\n    box = up\n  return box\n}\n\n/**\n * Glides `item` from `was` into its place, above its neighbours and past\n * its list's frame while it does (`data-settling`): from where its copy was\n * let go (`drop`), which keeps the copy's shadow on it until it lands and\n * hands it back to the `flow` lib the frame after, or from the list it left\n * (`across`).\n */\nfunction settleFrom(item: HTMLElement, was: DOMRect, settling: 'drop' | 'across') {\n  if (settling === 'drop') {\n    item.setAttribute('data-flow-held', '')\n    requestAnimationFrame(() => item.removeAttribute('data-flow-held'))\n  }\n  item.setAttribute('data-settling', settling)\n  glideFrom(item, was)\n  void transitionsQuiet(item).then(() => {\n    if (item.getAttribute('data-settling') === settling)\n      item.removeAttribute('data-settling')\n  })\n}\n\n/**\n * Glides an item let go by the pointer from where its copy was into its\n * place, as the drag ends: the item renders again then, whatever else does.\n */\nfunction useSettle(\n  handle: {\n    instance: {\n      get: () => SortState\n      subscribe: (listener: () => void) => () => void\n    }\n    api: Pick<SortParts<never>, 'settle'>\n  },\n  ref: RefObject<HTMLElement | null>,\n  value: string,\n) {\n  const { instance, api } = handle\n  const dragged = useSyncExternalStore(\n    instance.subscribe,\n    () => {\n      const moving = instance.get().moving\n      return moving?.pointer === true && moving.key === value\n    },\n    () => false,\n  )\n  useLayoutEffect(() => {\n    const item = ref.current\n    if (dragged || !item) return\n    const box = api.settle(value)\n    if (box) settleFrom(item, box, 'drop')\n  }, [dragged, api, ref, value])\n}\n\ntype SortListHandle = ReturnType<typeof usePrimitive<typeof sortList>>\ntype SortGroupHandle = ReturnType<typeof usePrimitive<typeof sortGroup>>\n\ninterface ListContextValue {\n  kind: 'list'\n  handle: SortListHandle\n  instructionsId: string\n}\n\ninterface GroupContextValue {\n  kind: 'group'\n  handle: SortGroupHandle\n  instructionsId: string\n  /** Each list's items as it last rendered them, so a list can show one that moved in. */\n  elements: Map<string, Valued>\n  /** Tells the group what a list renders. */\n  render: (list: string, items: string[] | null) => void\n}\n\nconst SortContext = createContext<ListContextValue | GroupContextValue | null>(null)\nconst SortItemContext = createContext<{\n  value: string\n  label: string\n  disabled: boolean\n} | null>(null)\n\n/** The list or group around a part. */\nfunction useSortContext() {\n  const context = use(SortContext)\n  if (!context) throw new Error('A sortable part must be inside a SortableList.')\n  return context\n}\n\nexport interface UseSortListOptions {\n  value?: string[]\n  defaultValue?: string[]\n  onValueChange?: (value: string[], details: SortListDetails) => void\n  layout: SortLayout\n  disabled: boolean\n}\n\n/** A lone list: its primitive, its children in the order shown, and what its parts read. */\nfunction useSortList(children: ReactNode, options: UseSortListOptions) {\n  const items = valuedChildren(children)\n  const present = items.map((item) => item.props.value)\n  const handle = usePrimitive(sortList, {\n    value: options.value,\n    defaultValue: options.defaultValue,\n    onValueChange: options.onValueChange,\n    items: present,\n    layout: options.layout,\n    disabled: options.disabled,\n    announce,\n  })\n  const instructionsId = useId()\n  const byValue = new Map(items.map((item) => [item.props.value, item]))\n  const ordered = (order: readonly string[]) =>\n    reconcileOrder(order, present).flatMap((value) => byValue.get(value) ?? [])\n  const context: ListContextValue = { kind: 'list', handle, instructionsId }\n  const extras = (\n    <>\n      <p id={instructionsId} hidden>\n        {sortInstructions}\n      </p>\n    </>\n  )\n  return { context, handle, ordered, extras }\n}\n\nexport interface UseSortGroupOptions {\n  value?: TransferLists\n  defaultValue?: TransferLists\n  onValueChange?: (\n    value: TransferLists,\n    move: SortMove,\n    details: SortGroupDetails,\n  ) => void\n  accepts?: SortAccepts\n}\n\n/** Whether a point is inside `el`'s box. */\nfunction inside(el: Element, x: number, y: number) {\n  const box = el.getBoundingClientRect()\n  return x >= box.left && x <= box.right && y >= box.top && y <= box.bottom\n}\n\n/**\n * A group of lists: its primitive and what its lists and parts read. Give\n * `root` to the group's element, which `ListsMove` glides across.\n */\nfunction useSortGroup(options: UseSortGroupOptions) {\n  const [present, setPresent] = useState<TransferLists>({})\n  const [elements] = useState(() => new Map<string, Valued>())\n  const { onValueChange } = options\n  const handle = usePrimitive(sortGroup, {\n    value: options.value,\n    defaultValue: options.defaultValue,\n    onValueChange:\n      onValueChange &&\n      ((value, details) =>\n        onValueChange(\n          value,\n          (details as { move: SortMove } & SortGroupDetails).move,\n          details,\n        )),\n    accepts: options.accepts,\n    present,\n    announce,\n  })\n  const root = useRef<HTMLElement>(null)\n  const instructionsId = useId()\n  const [render] = useState(\n    () => (list: string, items: string[] | null) =>\n      setPresent((was) => {\n        if (items === null) {\n          if (!(list in was)) return was\n          const rest = { ...was }\n          delete rest[list]\n          return rest\n        }\n        return was[list] && sameOrder(was[list], items) ? was : { ...was, [list]: items }\n      }),\n  )\n  const context: GroupContextValue = {\n    kind: 'group',\n    handle,\n    instructionsId,\n    elements,\n    render,\n  }\n  const extras = (\n    <>\n      <p id={instructionsId} hidden>\n        {groupInstructions}\n      </p>\n    </>\n  )\n  return { context, handle, root, extras }\n}\n\n/**\n * A list in a group: its items as the group orders them, the ones that moved\n * in from another list included, and the props its parts read.\n */\nfunction useGroupList(id: string, children: ReactNode) {\n  const context = useSortContext()\n  if (context.kind !== 'group')\n    throw new Error('A SortableList with an `id` must be inside a SortableGroup.')\n  const items = valuedChildren(children)\n  const present = items.map((item) => item.props.value)\n  const key = present.join('\\u0000')\n  const { elements, render } = context\n  useLayoutEffect(() => {\n    for (const item of items) elements.set(item.props.value, item)\n    render(id, key === '' ? [] : key.split('\\u0000'))\n  })\n  useLayoutEffect(() => () => render(id, null), [id, render])\n  const own = new Map(items.map((item) => [item.props.value, item]))\n  const ordered = (order: readonly string[]) => {\n    const shown = new Set(order)\n    return [\n      ...order.flatMap((value) => own.get(value) ?? elements.get(value) ?? []),\n      // Rendered here but in no list of the group's yet: at the end, until it is.\n      ...items.filter(\n        (item) =>\n          !shown.has(item.props.value) &&\n          !listOf(context.handle.state.value, item.props.value),\n      ),\n    ]\n  }\n  return { handle: context.handle, ordered }\n}\n\n/**\n * Glides each item that moved to another list from where it was, before the\n * page changed, across the group: the `flow` lib in each list glides what\n * moved inside it, and is told to leave no copy of what moved out\n * (`data-flow-away`). The item a pointer drags is its slot, which appears in\n * place. Read just before React changes the page, which only a class can.\n */\nclass ListsMove extends Component<{\n  lists: TransferLists\n  dragging: string | null\n  root: RefObject<HTMLElement | null>\n  children: ReactNode\n}> {\n  getSnapshotBeforeUpdate(previous: Readonly<{ lists: TransferLists }>) {\n    const root = this.props.root.current\n    if (!root || previous.lists === this.props.lists) return null\n    const seen = new Map<string, DOMRect>()\n    for (const key of changedLists(previous.lists, this.props.lists)) {\n      const item = itemIn(root, GROUP_ITEM, key)\n      if (!item) continue\n      item.setAttribute('data-flow-away', '')\n      if (key !== this.props.dragging) seen.set(key, item.getBoundingClientRect())\n    }\n    return seen\n  }\n\n  componentDidUpdate(\n    _previous: unknown,\n    _state: unknown,\n    seen: Map<string, DOMRect> | null,\n  ) {\n    const root = this.props.root.current\n    if (!root || !seen) return\n    for (const [key, box] of seen) {\n      const item = itemIn(root, GROUP_ITEM, key)\n      if (item) settleFrom(item, box, 'across')\n    }\n  }\n\n  render() {\n    return this.props.children\n  }\n}\n\nexport {\n  ListsMove,\n  SortContext,\n  sortControls,\n  sortGroup,\n  SortItemContext,\n  sortList,\n  useGroupList,\n  useSettle,\n  useSortContext,\n  useSortGroup,\n  useSortList,\n}\n",
      "type": "registry:lib",
      "target": "@lib/sort.tsx"
    }
  ],
  "type": "registry:lib"
}