{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "lane-board",
  "type": "registry:component",
  "title": "Lane Board",
  "description": "Lanes of cards that can be dragged within a lane and from one lane to another.",
  "dependencies": [
    "@base-ui/react",
    "tailwind-variants"
  ],
  "registryDependencies": [],
  "cssVars": {
    "light": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    },
    "dark": {
      "success": "oklch(0.696 0.17 162.48)",
      "warning": "oklch(0.769 0.188 70.08)",
      "info": "oklch(0.623 0.214 259.815)"
    }
  },
  "files": [
    {
      "path": "components/panelui/lane-board.tsx",
      "type": "registry:component",
      "target": "@components/panelui/lane-board.tsx",
      "content": "'use client';\n\n/**\n * LaneBoard — lanes side by side, each holding cards that can be dragged\n * within a lane and from one lane to another.\n *\n * ```tsx\n * <LaneBoard\n *   lanes={lanes}\n *   onLanesChange={setLanes}\n *   renderCard={(card) => (\n *     <>\n *       <LaneBoard.Title>{card.title}</LaneBoard.Title>\n *       <LaneBoard.Code>{card.code}</LaneBoard.Code>\n *     </>\n *   )}\n * />\n * ```\n *\n * ## The data is yours\n *\n * The board is given the lanes and their cards and says what they should\n * become. It keeps nothing you did not give it, so the order on screen is the\n * order in your state, and a move can be refused by not applying it.\n *\n * ## A card is carried, and the rest make room\n *\n * A dragged card is lifted off the board and follows the pointer. Where it\n * came from closes up, and a gap opens where it would land if it were let go\n * now, with the cards round it sliding to their new places. Nothing is\n * decided until the pointer is released, and Escape puts everything back.\n *\n * ## The board has a height\n *\n * The board is a fixed height and every lane fills it. A lane with more cards\n * than fit scrolls on its own, so a card added to a long lane moves nothing\n * else on the page. Pass `height=\"auto\"` for a board that grows with its\n * longest lane.\n *\n * ## It works without a pointer\n *\n * Space or Enter on a card picks it up. The arrow keys then move it, up and\n * down within its lane and left and right between lanes. Space or Enter sets\n * it down, Escape puts it back, and each step is said to a screen reader.\n */\nimport { ScrollArea } from '@base-ui/react/scroll-area';\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ComponentProps,\n  type CSSProperties,\n  type KeyboardEvent,\n  type PointerEvent as ReactPointerEvent,\n  type ReactNode,\n} from 'react';\nimport { tv } from 'tailwind-variants';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport type { ElementType as RenderElementType } from 'react';\n\n/** Draws a part as another element, or composes it with a component: `render={<a href=\"/\" />}`. */\ntype RenderProp<Tag extends RenderElementType> = { render?: useRender.ComponentProps<Tag>['render'] };\n\n/** Which of the theme's roles a part is drawn in. */\nexport type LaneBoardColor = 'primary' | 'info' | 'success' | 'warning' | 'destructive';\n\n/** A card is anything with an id that is its own across the whole board. */\nexport interface LaneBoardCard {\n  id: string;\n}\n\nexport interface LaneBoardLane<T extends LaneBoardCard = LaneBoardCard> {\n  id: string;\n  /** Written at the head of the lane. */\n  title: ReactNode;\n  cards: T[];\n  /** One of the theme's roles, drawn as a dot before the title. */\n  color?: LaneBoardColor;\n  /**\n   * How many cards the lane is meant to hold. The count is written against\n   * it, and drawn as a warning once the lane holds more. It is advice: the\n   * board does not refuse a card. Do that in `onLanesChange`.\n   */\n  limit?: number;\n}\n\n/** One card going from one place to another. */\nexport interface LaneBoardMove<T extends LaneBoardCard = LaneBoardCard> {\n  card: T;\n  from: { lane: string; index: number };\n  to: { lane: string; index: number };\n}\n\nconst laneBoardVariants = tv({\n  slots: {\n    root: 'relative w-full',\n    board: 'size-full',\n    // Lanes share the width when there is room and scroll sideways, one lane\n    // at a time, when there is not. Room is made under them for the bar only\n    // when there is something to scroll.\n    boardViewport: 'size-full snap-x outline-none data-has-overflow-x:pb-3',\n    lanes: 'flex h-full gap-3',\n    /*\n     * The border is the lane's own, inside its box, and not a ring round it:\n     * the board clips what is drawn outside a lane, and a ring would lose its\n     * top edge to that.\n     */\n    lane: 'flex min-h-0 min-w-50 flex-1 shrink-0 snap-start flex-col rounded-3xl border bg-muted py-2 transition-colors duration-200',\n    laneHeader: 'flex items-center justify-between gap-3 px-4.5 pb-1.5 pt-1.5 text-sm',\n    laneScroller: 'min-h-0 flex-1',\n    /*\n     * Padded on every side, so a card's focus ring and shadow have room and\n     * are not cut by the edge they scroll under. Where cards carry on past an\n     * edge, they fade out towards it.\n     */\n    laneViewport:\n      'h-full px-2 py-0.5 outline-none data-has-overflow-y:overscroll-y-contain data-has-overflow-y:[mask-image:linear-gradient(to_bottom,transparent,black_min(1.25rem,var(--scroll-area-overflow-y-start)),black_calc(100%-min(1.25rem,var(--scroll-area-overflow-y-end))),transparent)]',\n    laneFooter: 'flex flex-col px-2 pt-1.5 empty:hidden',\n    // A drawn bar, thin and rounded, that shows while the pointer is on the\n    // lane or it is being scrolled.\n    scrollbar:\n      'flex opacity-0 transition-opacity delay-300 data-hovering:opacity-100 data-hovering:delay-0 data-hovering:duration-100 data-scrolling:opacity-100 data-scrolling:delay-0 data-scrolling:duration-100 data-[orientation=horizontal]:mx-3 data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:flex-col data-[orientation=vertical]:my-1 data-[orientation=vertical]:me-px data-[orientation=vertical]:w-1.5',\n    thumb: 'relative flex-1 rounded-full bg-foreground/20',\n    laneHeading: 'flex min-w-0 items-center gap-2',\n    laneDot: 'size-2 shrink-0 rounded-full bg-[var(--pu-color)]',\n    laneTitle: 'truncate font-medium text-muted-foreground',\n    laneCount: 'tabular-nums text-muted-foreground',\n    // Tall enough when empty to be somewhere a card can be dropped.\n    list: 'flex min-h-20 flex-col gap-2',\n    card: 'flex cursor-grab touch-manipulation select-none flex-col gap-1 rounded-2xl border bg-card p-4 text-card-foreground shadow-xs outline-none transition-shadow duration-150 focus-visible:ring-2 focus-visible:ring-ring',\n    overlay:\n      'pointer-events-none fixed left-0 top-0 z-50 flex rotate-2 cursor-grabbing flex-col gap-1 rounded-2xl border bg-card p-4 text-card-foreground shadow-xl',\n    title: 'truncate text-base font-semibold',\n    code: 'truncate font-mono text-sm text-muted-foreground',\n    row: 'mt-2 flex items-center justify-between gap-3',\n    steps: 'flex items-center gap-1',\n    step: 'h-1 w-4 rounded-full',\n    tag: 'inline-flex items-center rounded-full border border-[color-mix(in_oklab,var(--pu-color)_35%,var(--card))] bg-[color-mix(in_oklab,var(--pu-color)_14%,transparent)] px-2 py-0.5 text-xs font-medium text-[var(--pu-color)]',\n    meta: 'font-mono text-sm tabular-nums text-foreground',\n    avatar:\n      'flex size-6 shrink-0 items-center justify-center rounded-full bg-muted text-[0.625rem] font-semibold text-muted-foreground',\n  },\n  variants: {\n    color: {\n      primary: {\n        steps: '[--pu-color:var(--primary)]',\n        tag: '[--pu-color:var(--primary)]',\n        laneDot: '[--pu-color:var(--primary)]',\n      },\n      info: {\n        steps: '[--pu-color:var(--info)]',\n        tag: '[--pu-color:var(--info)]',\n        laneDot: '[--pu-color:var(--info)]',\n      },\n      success: {\n        steps: '[--pu-color:var(--success)]',\n        tag: '[--pu-color:var(--success)]',\n        laneDot: '[--pu-color:var(--success)]',\n      },\n      warning: {\n        steps: '[--pu-color:var(--warning)]',\n        tag: '[--pu-color:var(--warning)]',\n        laneDot: '[--pu-color:var(--warning)]',\n      },\n      destructive: {\n        steps: '[--pu-color:var(--destructive)]',\n        tag: '[--pu-color:var(--destructive)]',\n        laneDot: '[--pu-color:var(--destructive)]',\n      },\n    },\n    // The lane a carried card is over: a firmer edge and a deeper tray.\n    over: { true: { lane: 'border-ring/70 bg-foreground/8' } },\n    // A lane holding more than its limit says so in its count.\n    full: { true: { laneCount: 'font-medium text-[var(--warning)]' } },\n    state: {\n      rest: {},\n      // Where a carried card would land: its room is kept and outlined, and\n      // what is on it is not drawn.\n      placeholder: { card: 'border-dashed border-ring/70 bg-transparent shadow-none *:invisible' },\n      // Picked up with the keyboard: it stays where it is and is ringed.\n      held: { card: 'cursor-grabbing shadow-lg ring-2 ring-ring' },\n    },\n    lit: {\n      true: { step: 'bg-[var(--pu-color)]' },\n      false: { step: 'bg-muted-foreground/20' },\n    },\n  },\n  defaultVariants: { color: 'primary', state: 'rest' },\n});\n\n/** How far a mouse has to move before a press becomes a drag, in pixels. */\nconst SLOP = 4;\n/** How long a finger has to rest on a card before it is picked up, in milliseconds. */\nconst HOLD = 220;\n/** How near an edge of the board the pointer has to be for it to scroll, in pixels. */\nconst EDGE = 48;\n\n/** Where something is laid out, measured from the board through whatever it is nested in. */\nfunction placeIn(node: HTMLElement, board: HTMLElement) {\n  let x = 0;\n  let y = 0;\n  let at: HTMLElement | null = node;\n  while (at && at !== board) {\n    x += at.offsetLeft;\n    y += at.offsetTop;\n    at = at.offsetParent as HTMLElement | null;\n  }\n  return { x, y };\n}\n\nconst reducedMotion = () =>\n  typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n/** The lanes with one card taken out and put somewhere else. */\nfunction moved<T extends LaneBoardCard>(\n  lanes: LaneBoardLane<T>[],\n  id: string,\n  toLane: string,\n  toIndex: number\n): LaneBoardLane<T>[] {\n  let card: T | undefined;\n  const without = lanes.map((lane) => {\n    const found = lane.cards.find((entry) => entry.id === id);\n    if (!found) return lane;\n    card = found;\n    return { ...lane, cards: lane.cards.filter((entry) => entry.id !== id) };\n  });\n  if (!card) return lanes;\n  const carried = card;\n  return without.map((lane) => {\n    if (lane.id !== toLane) return lane;\n    const cards = [...lane.cards];\n    cards.splice(Math.min(Math.max(0, toIndex), cards.length), 0, carried);\n    return { ...lane, cards };\n  });\n}\n\nfunction whereIs<T extends LaneBoardCard>(lanes: LaneBoardLane<T>[], id: string) {\n  for (const lane of lanes) {\n    const index = lane.cards.findIndex((card) => card.id === id);\n    if (index >= 0) return { lane: lane.id, index, card: lane.cards[index] as T };\n  }\n  return null;\n}\n\nexport interface LaneBoardProps<T extends LaneBoardCard> extends Omit<ComponentProps<'div'>, 'children' | 'onChange'> {\n  /** The lanes and their cards, when the caller holds them. */\n  lanes?: LaneBoardLane<T>[];\n  /** The lanes to begin with, when the caller does not hold them. */\n  defaultLanes?: LaneBoardLane<T>[];\n  /** Called with the lanes as they should now be, when a card is set down somewhere new. */\n  onLanesChange?: (lanes: LaneBoardLane<T>[]) => void;\n  /** Called with the one card that moved, and where from and to. */\n  onMove?: (move: LaneBoardMove<T>) => void;\n  /** Draws the inside of a card. */\n  renderCard: (card: T, state: { lane: LaneBoardLane<T>; carried: boolean }) => ReactNode;\n  /** Draws something under a lane's cards, such as a button that adds one. */\n  renderLaneFooter?: (lane: LaneBoardLane<T>) => ReactNode;\n  /** What a screen reader calls a card, where its id would not mean much. */\n  cardName?: (card: T) => string;\n  /** What a screen reader calls the board. */\n  label?: string;\n  /**\n   * How tall the board is: a number of pixels, or any CSS length. Lanes fill\n   * it, and one with more cards than fit scrolls. `'auto'` lets the board\n   * grow with its longest lane.\n   */\n  height?: number | string;\n}\n\nfunction LaneBoardRoot<T extends LaneBoardCard>({\n  lanes: controlled,\n  defaultLanes,\n  onLanesChange,\n  onMove,\n  renderCard,\n  renderLaneFooter,\n  cardName = (card) => card.id,\n  label = 'Board',\n  height = '28rem',\n  className,\n  style,\n  render,\n  ...props\n}: LaneBoardProps<T> & RenderProp<'div'>) {\n  const slots = laneBoardVariants();\n  const [internal, setInternal] = useState<LaneBoardLane<T>[]>(defaultLanes ?? []);\n  const settled = controlled ?? internal;\n\n  /** The lanes as they would be if the carried card were set down now. */\n  const [draft, setDraft] = useState<LaneBoardLane<T>[] | null>(null);\n  /** The card being carried, and whether by the pointer or the keyboard. */\n  const [carry, setCarry] = useState<{ id: string; by: 'pointer' | 'keys' } | null>(null);\n  const [said, setSaid] = useState('');\n  const shown = draft ?? settled;\n\n  const root = useRef<HTMLDivElement>(null);\n  const overlay = useRef<HTMLDivElement>(null);\n  const cards = useRef(new Map<string, HTMLElement>());\n  /** The board's own scroller, which moves sideways. */\n  const scroller = useRef<HTMLDivElement>(null);\n  const sections = useRef(new Map<string, HTMLElement>());\n  /** Each lane's scroller, which moves up and down. */\n  const viewports = useRef(new Map<string, HTMLElement>());\n  const places = useRef(new Map<string, { x: number; y: number; height: number; lane: string }>());\n  /** Everything about a pointer drag that changes too often to be state. */\n  const drag = useRef<{\n    id: string;\n    pointerId: number;\n    startX: number;\n    startY: number;\n    grabX: number;\n    grabY: number;\n    x: number;\n    y: number;\n    width: number;\n    started: boolean;\n    timer: number;\n    frame: number;\n  } | null>(null);\n  const latest = useRef({ settled, draft });\n  latest.current = { settled, draft };\n\n  const commit = useCallback(\n    (next: LaneBoardLane<T>[], id: string) => {\n      const from = whereIs(latest.current.settled, id);\n      const to = whereIs(next, id);\n      if (!from || !to) return;\n      if (from.lane === to.lane && from.index === to.index) return;\n      if (controlled === undefined) setInternal(next);\n      onLanesChange?.(next);\n      onMove?.({\n        card: from.card,\n        from: { lane: from.lane, index: from.index },\n        to: { lane: to.lane, index: to.index },\n      });\n    },\n    [controlled, onLanesChange, onMove]\n  );\n\n  /*\n   * Cards slide to where they now belong. Each card's place is remembered from\n   * one drawing to the next; a card found somewhere else in its lane is\n   * started from where it was and let go. Places are where a card is laid\n   * out, so scrolling the page, the board or a lane between two drawings\n   * moves nothing. A card that has changed lanes is not slid: each lane clips\n   * its own cards, and it would be seen coming in through the lane's side.\n   */\n  useLayoutEffect(() => {\n    const board = root.current;\n    if (!board) return;\n    const still = reducedMotion();\n    const laneOf = new Map<string, string>();\n    for (const lane of shown) for (const card of lane.cards) laneOf.set(card.id, lane.id);\n    const next = new Map<string, { x: number; y: number; height: number; lane: string }>();\n    cards.current.forEach((node, id) => {\n      // Where the card is laid out, measured from the board. Not its box on\n      // the page: a card that is still sliding has a box that is on its way,\n      // and what is wanted here is where it is going.\n      const place = {\n        ...placeIn(node, board),\n        height: node.offsetHeight,\n        lane: laneOf.get(id) ?? '',\n      };\n      next.set(id, place);\n      const before = places.current.get(id);\n      if (!before || still || before.lane !== place.lane) return;\n      const dx = before.x - place.x;\n      const dy = before.y - place.y;\n      if (Math.abs(dx) < 1 && Math.abs(dy) < 1) return;\n      node.animate([{ translate: `${dx}px ${dy}px` }, { translate: '0 0' }], {\n        duration: 220,\n        easing: 'cubic-bezier(0.2, 0, 0, 1)',\n      });\n    });\n    places.current = next;\n  });\n\n  /*\n   * Only for a board left to grow, with `height=\"auto\"`. It is then as tall\n   * as its tallest lane, and which lane that is changes as cards move. Left\n   * to follow, the board would grow and shrink under the pointer in the\n   * middle of a drag, and again when the card is set down. So it keeps the\n   * greatest height it has had, and only ever grows.\n   */\n  const tallest = useRef(0);\n  useLayoutEffect(() => {\n    const lanes = [...sections.current.values()];\n    for (const lane of lanes) lane.style.minHeight = '';\n    if (height !== 'auto') {\n      tallest.current = 0;\n      return;\n    }\n    const natural = Math.max(0, ...lanes.map((lane) => lane.offsetHeight));\n    // Only what has been set down counts. A card carried across a full lane\n    // makes it taller for a moment, and that is not a height to keep.\n    if (!carry) tallest.current = Math.max(tallest.current, natural);\n    const keep = Math.max(tallest.current, natural);\n    for (const lane of lanes) lane.style.minHeight = `${keep}px`;\n  });\n\n  /*\n   * Brings a card's place into view: its lane across the board, and the card\n   * down its lane. Worked out from where things are laid out, since a card\n   * that has just moved is still drawn on its way there.\n   */\n  const reveal = (id: string) => {\n    const board = root.current;\n    const spot = places.current.get(id);\n    if (!board || !spot) return;\n    const across = scroller.current;\n    const section = sections.current.get(spot.lane);\n    if (across && section) {\n      const before = placeIn(section, board).x - across.scrollLeft;\n      const after = before + section.offsetWidth - across.clientWidth;\n      if (before < 0) across.scrollLeft += before;\n      else if (after > 0) across.scrollLeft += after;\n    }\n    const lane = viewports.current.get(spot.lane);\n    if (lane) {\n      // A little clear of the edge, where cards fade out.\n      const above = spot.y - placeIn(lane, board).y - lane.scrollTop - 8;\n      const below = above + spot.height + 16 - lane.clientHeight;\n      if (above < 0) lane.scrollTop += above;\n      else if (below > 0) lane.scrollTop += below;\n    }\n  };\n\n  /* ------------------------------------------------------------------ */\n  /* Carrying with the pointer                                           */\n  /* ------------------------------------------------------------------ */\n\n  /** Which lane, and where in it, the carried card is over. */\n  const target = (x: number, y: number, id: string) => {\n    let lane: string | null = null;\n    let nearest = Infinity;\n    sections.current.forEach((node, laneId) => {\n      const box = node.getBoundingClientRect();\n      const distance = x < box.left ? box.left - x : x > box.right ? x - box.right : 0;\n      if (distance < nearest) {\n        nearest = distance;\n        lane = laneId;\n      }\n    });\n    if (lane === null) return null;\n    const over = (latest.current.draft ?? latest.current.settled).find((entry) => entry.id === lane);\n    /*\n     * Measured against where each card belongs, as last laid out, and not\n     * where it is drawn. Cards slide to their places, and a card read half\n     * way through its slide can be on the wrong side of the pointer, which\n     * moves the gap, which slides the card back: a flicker with no end.\n     * A place is where a card is laid out, so how far its lane has been\n     * scrolled is taken off the pointer and not off the card.\n     */\n    const top = root.current?.getBoundingClientRect().top ?? 0;\n    const scrolled = viewports.current.get(lane)?.scrollTop ?? 0;\n    let index = 0;\n    for (const card of over?.cards ?? []) {\n      if (card.id === id) continue;\n      const place = places.current.get(card.id);\n      if (place && y - top + scrolled > place.y + place.height / 2) index += 1;\n    }\n    return { lane: lane as string, index };\n  };\n\n  const place = () => {\n    const state = drag.current;\n    const node = overlay.current;\n    if (!state || !node) return;\n    node.style.translate = `${state.x - state.grabX}px ${state.y - state.grabY}px`;\n  };\n\n  const follow = () => {\n    const state = drag.current;\n    if (!state?.started) return;\n    const over = target(state.x, state.y, state.id);\n    if (over) {\n      const now = whereIs(latest.current.draft ?? latest.current.settled, state.id);\n      if (!now || now.lane !== over.lane || now.index !== over.index) {\n        setDraft(moved(latest.current.settled, state.id, over.lane, over.index));\n      }\n    }\n    // Near either end of the board, it scrolls towards that end.\n    const board = scroller.current;\n    if (board) {\n      const box = board.getBoundingClientRect();\n      if (state.x < box.left + EDGE) board.scrollLeft -= 10;\n      else if (state.x > box.right - EDGE) board.scrollLeft += 10;\n    }\n    // And near the top or bottom of the lane it is over, that lane scrolls.\n    const lane = over ? viewports.current.get(over.lane) : undefined;\n    if (lane) {\n      const box = lane.getBoundingClientRect();\n      if (state.y < box.top + EDGE) lane.scrollTop -= 8;\n      else if (state.y > box.bottom - EDGE) lane.scrollTop += 8;\n    }\n    state.frame = requestAnimationFrame(follow);\n  };\n\n  const begin = () => {\n    const state = drag.current;\n    if (!state || state.started) return;\n    state.started = true;\n    setDraft(latest.current.settled);\n    setCarry({ id: state.id, by: 'pointer' });\n    state.frame = requestAnimationFrame(follow);\n  };\n\n  const end = (drop: boolean) => {\n    const state = drag.current;\n    if (!state) return;\n    window.clearTimeout(state.timer);\n    cancelAnimationFrame(state.frame);\n    drag.current = null;\n    if (!state.started) return;\n    const next = latest.current.draft;\n    // Put back, the gap goes home first, so there is somewhere to fly to.\n    if (!drop) setDraft(latest.current.settled);\n\n    const finish = () => {\n      if (drop && next) commit(next, state.id);\n      setDraft(null);\n      setCarry(null);\n    };\n    /*\n     * The lifted card flies the last of the way into the gap that is waiting\n     * for it, and only then is the real card shown. Dropped where the pointer\n     * let go, it would vanish from one place and appear in another.\n     */\n    requestAnimationFrame(() => {\n      const lifted = overlay.current;\n      const board = root.current;\n      const slot = places.current.get(state.id);\n      if (!lifted || !board || !slot || reducedMotion()) return finish();\n      // The gap may have been left under an edge of its lane. It is brought\n      // into view first, so the card flies to somewhere that can be seen.\n      reveal(state.id);\n      const lane = viewports.current.get(slot.lane);\n      const box = board.getBoundingClientRect();\n      const left = box.left + slot.x - (scroller.current?.scrollLeft ?? 0);\n      const top = box.top + slot.y - (lane?.scrollTop ?? 0);\n      const flight = lifted.animate(\n        [\n          { translate: lifted.style.translate, rotate: '2deg' },\n          { translate: `${left}px ${top}px`, rotate: '0deg' },\n        ],\n        { duration: 180, easing: 'cubic-bezier(0.2, 0, 0, 1)', fill: 'forwards' }\n      );\n      flight.finished.then(finish, finish);\n    });\n  };\n\n  useEffect(() => {\n    const onMove = (event: PointerEvent) => {\n      const state = drag.current;\n      if (!state || event.pointerId !== state.pointerId) return;\n      state.x = event.clientX;\n      state.y = event.clientY;\n      if (!state.started) {\n        const travel = Math.hypot(state.x - state.startX, state.y - state.startY);\n        // A finger that moves before the hold is up is scrolling, not lifting.\n        if (event.pointerType === 'touch') {\n          if (travel > SLOP * 2) end(false);\n          return;\n        }\n        if (travel > SLOP) begin();\n        return;\n      }\n      place();\n    };\n    const onUp = (event: PointerEvent) => {\n      if (drag.current && event.pointerId === drag.current.pointerId) end(true);\n    };\n    const onCancel = () => end(false);\n    const onKey = (event: globalThis.KeyboardEvent) => {\n      if (event.key === 'Escape' && drag.current?.started) end(false);\n    };\n    // A carried card must not also scroll the page under the finger.\n    const onTouch = (event: TouchEvent) => {\n      if (drag.current?.started) event.preventDefault();\n    };\n    window.addEventListener('pointermove', onMove);\n    window.addEventListener('pointerup', onUp);\n    window.addEventListener('pointercancel', onCancel);\n    window.addEventListener('keydown', onKey);\n    window.addEventListener('touchmove', onTouch, { passive: false });\n    return () => {\n      window.removeEventListener('pointermove', onMove);\n      window.removeEventListener('pointerup', onUp);\n      window.removeEventListener('pointercancel', onCancel);\n      window.removeEventListener('keydown', onKey);\n      window.removeEventListener('touchmove', onTouch);\n      end(false);\n    };\n    // The handlers read everything through refs, so they are set up once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  // The lifted card is put under the pointer as soon as it exists.\n  useLayoutEffect(() => {\n    if (carry?.by === 'pointer') place();\n  });\n\n  const onPointerDown = (event: ReactPointerEvent<HTMLElement>, id: string) => {\n    if (event.button !== 0 || carry) return;\n    // A button or a link inside a card is pressed, not dragged by.\n    if ((event.target as HTMLElement).closest('button, a, input, textarea, select, [data-no-drag]')) {\n      return;\n    }\n    const box = event.currentTarget.getBoundingClientRect();\n    drag.current = {\n      id,\n      pointerId: event.pointerId,\n      startX: event.clientX,\n      startY: event.clientY,\n      grabX: event.clientX - box.left,\n      grabY: event.clientY - box.top,\n      x: event.clientX,\n      y: event.clientY,\n      width: box.width,\n      started: false,\n      timer: event.pointerType === 'touch' ? window.setTimeout(begin, HOLD) : 0,\n      frame: 0,\n    };\n  };\n\n  /* ------------------------------------------------------------------ */\n  /* Carrying with the keyboard                                          */\n  /* ------------------------------------------------------------------ */\n\n  const say = (card: T, lanes: LaneBoardLane<T>[], lead: string) => {\n    const at = whereIs(lanes, card.id);\n    const lane = lanes.find((entry) => entry.id === at?.lane);\n    if (!at || !lane) return;\n    const name = typeof lane.title === 'string' ? lane.title : lane.id;\n    setSaid(`${lead} ${cardName(card)}: ${name}, place ${at.index + 1} of ${lane.cards.length}.`);\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLElement>, card: T) => {\n    if (event.target !== event.currentTarget) return;\n    const held = carry?.by === 'keys' && carry.id === card.id;\n\n    if (!held) {\n      if (carry || (event.key !== ' ' && event.key !== 'Enter')) return;\n      event.preventDefault();\n      setDraft(settled);\n      setCarry({ id: card.id, by: 'keys' });\n      setSaid(`Picked up ${cardName(card)}. Arrow keys move it, Space sets it down, Escape puts it back.`);\n      return;\n    }\n\n    const lanes = draft ?? settled;\n    const at = whereIs(lanes, card.id);\n    if (!at) return;\n    const laneAt = lanes.findIndex((lane) => lane.id === at.lane);\n    const rtl = getComputedStyle(event.currentTarget).direction === 'rtl';\n\n    if (event.key === ' ' || event.key === 'Enter') {\n      event.preventDefault();\n      commit(lanes, card.id);\n      say(card, lanes, 'Set down');\n      setDraft(null);\n      setCarry(null);\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      setDraft(null);\n      setCarry(null);\n      setSaid(`Put ${cardName(card)} back.`);\n      return;\n    }\n\n    let next: LaneBoardLane<T>[] | null = null;\n    if (event.key === 'ArrowUp') next = moved(lanes, card.id, at.lane, at.index - 1);\n    else if (event.key === 'ArrowDown') next = moved(lanes, card.id, at.lane, at.index + 1);\n    else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {\n      const step = (event.key === 'ArrowRight' ? 1 : -1) * (rtl ? -1 : 1);\n      const other = lanes[laneAt + step];\n      if (other) next = moved(lanes, card.id, other.id, at.index);\n    }\n    if (!next) return;\n    event.preventDefault();\n    setDraft(next);\n    say(card, next, 'Moved');\n  };\n\n  // Moving to another lane redraws the card under a new parent, which would\n  // drop the focus it is being steered by.\n  // A move within a long lane can also take it under the lane's edge, where\n  // focus alone would not bring it back.\n  useLayoutEffect(() => {\n    if (carry?.by !== 'keys') return;\n    cards.current.get(carry.id)?.focus({ preventScroll: true });\n    reveal(carry.id);\n  });\n\n  const carried = carry ? whereIs(shown, carry.id) : null;\n  const carriedLane = carried ? shown.find((lane) => lane.id === carried.lane) : undefined;\n\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        ref: root,\n        role: 'group',\n        'aria-label': label,\n        className: slots.root({ className }),\n        style: { height: height === 'auto' ? undefined : height, ...style } as CSSProperties,\n        children: (\n          <>\n            <ScrollArea.Root className={slots.board()}>\n              <ScrollArea.Viewport ref={scroller} className={slots.boardViewport()}>\n                <div className={slots.lanes()}>\n                  {shown.map((lane) => (\n                    <section\n                      key={lane.id}\n                      ref={(node) => {\n                        if (node) sections.current.set(lane.id, node);\n                        else sections.current.delete(lane.id);\n                      }}\n                      aria-label={typeof lane.title === 'string' ? lane.title : undefined}\n                      data-over={carried?.lane === lane.id ? '' : undefined}\n                      className={laneBoardVariants({ over: carried?.lane === lane.id }).lane()}\n                    >\n                      <header className={slots.laneHeader()}>\n                        <div className={slots.laneHeading()}>\n                          {lane.color ? (\n                            <span aria-hidden=\"true\" className={laneBoardVariants({ color: lane.color }).laneDot()} />\n                          ) : null}\n                          <h3 className={slots.laneTitle()}>{lane.title}</h3>\n                        </div>\n                        <span\n                          className={laneBoardVariants({\n                            full: lane.limit !== undefined && lane.cards.length > lane.limit,\n                          }).laneCount()}\n                        >\n                          {lane.limit === undefined ? lane.cards.length : `${lane.cards.length}/${lane.limit}`}\n                        </span>\n                      </header>\n                      <ScrollArea.Root className={slots.laneScroller()}>\n                        <ScrollArea.Viewport\n                          ref={(node: HTMLDivElement | null) => {\n                            if (node) viewports.current.set(lane.id, node);\n                            else viewports.current.delete(lane.id);\n                          }}\n                          className={slots.laneViewport()}\n                        >\n                          <ol className={slots.list()}>\n                            {lane.cards.map((card) => {\n                              const isCarried = carry?.id === card.id;\n                              const state = !isCarried ? 'rest' : carry.by === 'pointer' ? 'placeholder' : 'held';\n                              return (\n                                <li\n                                  key={card.id}\n                                  ref={(node) => {\n                                    if (node) cards.current.set(card.id, node);\n                                    else cards.current.delete(card.id);\n                                  }}\n                                  tabIndex={0}\n                                  aria-roledescription=\"Card that can be moved\"\n                                  aria-label={cardName(card)}\n                                  data-card={card.id}\n                                  data-carried={isCarried ? carry.by : undefined}\n                                  className={laneBoardVariants({ state }).card()}\n                                  onPointerDown={(event) => onPointerDown(event, card.id)}\n                                  onKeyDown={(event) => onKeyDown(event, card)}\n                                  onBlur={() => {\n                                    // Focus leaving a card held with the keyboard puts it\n                                    // back: nothing is steering it any more.\n                                    if (\n                                      carry?.by === 'keys' &&\n                                      carry.id === card.id &&\n                                      !cards.current.get(card.id)?.matches(':focus')\n                                    ) {\n                                      requestAnimationFrame(() => {\n                                        if (document.activeElement !== cards.current.get(card.id)) {\n                                          setDraft(null);\n                                          setCarry(null);\n                                        }\n                                      });\n                                    }\n                                  }}\n                                >\n                                  {renderCard(card, { lane, carried: isCarried })}\n                                </li>\n                              );\n                            })}\n                          </ol>\n                        </ScrollArea.Viewport>\n                        <ScrollArea.Scrollbar orientation=\"vertical\" className={slots.scrollbar()}>\n                          <ScrollArea.Thumb className={slots.thumb()} />\n                        </ScrollArea.Scrollbar>\n                      </ScrollArea.Root>\n                      <div className={slots.laneFooter()}>{renderLaneFooter?.(lane)}</div>\n                    </section>\n                  ))}\n                </div>\n              </ScrollArea.Viewport>\n              <ScrollArea.Scrollbar orientation=\"horizontal\" className={slots.scrollbar()}>\n                <ScrollArea.Thumb className={slots.thumb()} />\n              </ScrollArea.Scrollbar>\n            </ScrollArea.Root>\n\n            {carry?.by === 'pointer' && carried && carriedLane ? (\n              <div ref={overlay} aria-hidden=\"true\" className={slots.overlay()} style={{ width: drag.current?.width }}>\n                {renderCard(carried.card, { lane: carriedLane, carried: true })}\n              </div>\n            ) : null}\n\n            <span aria-live=\"assertive\" className=\"sr-only\">\n              {said}\n            </span>\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nLaneBoardRoot.displayName = 'LaneBoard';\n\n/* -------------------------------------------------------------------------- */\n/* What goes on a card                                                        */\n/* -------------------------------------------------------------------------- */\n\nexport interface LaneBoardTitleProps extends ComponentProps<'div'> {}\n\n/** A card's name. */\nfunction LaneBoardTitle({ className, render, ...props }: LaneBoardTitleProps & RenderProp<'div'>) {\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps({ className: laneBoardVariants().title({ className }) }, props),\n  });\n}\nLaneBoardTitle.displayName = 'LaneBoard.Title';\n\nexport interface LaneBoardCodeProps extends ComponentProps<'div'> {}\n\n/** A card's reference, in a fixed-width face so a column of them lines up. */\nfunction LaneBoardCode({ className, render, ...props }: LaneBoardCodeProps & RenderProp<'div'>) {\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps({ className: laneBoardVariants().code({ className }) }, props),\n  });\n}\nLaneBoardCode.displayName = 'LaneBoard.Code';\n\nexport interface LaneBoardRowProps extends ComponentProps<'div'> {}\n\n/** The last line of a card: something at each end. */\nfunction LaneBoardRow({ className, render, ...props }: LaneBoardRowProps & RenderProp<'div'>) {\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps({ className: laneBoardVariants().row({ className }) }, props),\n  });\n}\nLaneBoardRow.displayName = 'LaneBoard.Row';\n\nexport interface LaneBoardStepsProps extends Omit<ComponentProps<'div'>, 'children' | 'color'> {\n  /** How many steps are done. */\n  value: number;\n  /** How many steps there are. */\n  max?: number;\n  /** Which of the theme's roles the done steps are drawn in. */\n  color?: LaneBoardColor;\n  /** What a screen reader calls it. */\n  label?: string;\n}\n\n/** How far along a card is, as a row of dashes with the done ones lit. */\nfunction LaneBoardSteps({\n  value,\n  max = 5,\n  color = 'primary',\n  label = 'Progress',\n  className,\n  render,\n  ...props\n}: LaneBoardStepsProps & RenderProp<'div'>) {\n  const slots = laneBoardVariants({ color });\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        role: 'img',\n        'aria-label': `${label}: ${value} of ${max}`,\n        className: slots.steps({ className }),\n        children: (\n          <>\n            {Array.from({ length: max }, (_, index) => (\n              <span key={index} className={laneBoardVariants({ lit: index < value }).step()} />\n            ))}\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nLaneBoardSteps.displayName = 'LaneBoard.Steps';\n\nexport interface LaneBoardTagProps extends Omit<ComponentProps<'span'>, 'color'> {\n  /** Which of the theme's roles the tag is drawn in. */\n  color?: LaneBoardColor;\n}\n\n/** A word in a pill, for a card's state. */\nfunction LaneBoardTag({ color = 'primary', className, render, ...props }: LaneBoardTagProps & RenderProp<'span'>) {\n  return useRender({\n    defaultTagName: 'span',\n    render,\n    props: mergeProps({ className: laneBoardVariants({ color }).tag({ className }) }, props),\n  });\n}\nLaneBoardTag.displayName = 'LaneBoard.Tag';\n\nexport interface LaneBoardMetaProps extends ComponentProps<'span'> {}\n\n/** A short figure at the end of a card's last line: a time, a count. */\nfunction LaneBoardMeta({ className, render, ...props }: LaneBoardMetaProps & RenderProp<'span'>) {\n  return useRender({\n    defaultTagName: 'span',\n    render,\n    props: mergeProps({ className: laneBoardVariants().meta({ className }) }, props),\n  });\n}\nLaneBoardMeta.displayName = 'LaneBoard.Meta';\n\nexport interface LaneBoardAvatarProps extends ComponentProps<'span'> {}\n\n/** Who a card belongs to, as initials in a small circle. */\nfunction LaneBoardAvatar({ className, render, ...props }: LaneBoardAvatarProps & RenderProp<'span'>) {\n  return useRender({\n    defaultTagName: 'span',\n    render,\n    props: mergeProps(\n      { 'data-slot': 'lane-board-avatar', className: laneBoardVariants().avatar({ className }) },\n      props\n    ),\n  });\n}\nLaneBoardAvatar.displayName = 'LaneBoard.Avatar';\n\nexport const LaneBoard = Object.assign(LaneBoardRoot, {\n  Title: LaneBoardTitle,\n  Code: LaneBoardCode,\n  Row: LaneBoardRow,\n  Steps: LaneBoardSteps,\n  Tag: LaneBoardTag,\n  Meta: LaneBoardMeta,\n  Avatar: LaneBoardAvatar,\n});\n\n/* By name as well, for a Server Component, which cannot dot into a client\n   module. */\nexport { LaneBoardTitle, LaneBoardCode, LaneBoardRow, LaneBoardSteps, LaneBoardTag, LaneBoardMeta, LaneBoardAvatar };\n"
    }
  ]
}
