{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "xy-pad",
  "type": "registry:component",
  "title": "XY Pad",
  "description": "Two numbers set with one drag: a point moved across a field.",
  "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/xy-pad.tsx",
      "type": "registry:component",
      "target": "@components/panelui/xy-pad.tsx",
      "content": "'use client';\n\n/**\n * XYPad — two numbers set with one drag: a point moved across a field.\n *\n * ```tsx\n * <XYPad label=\"Framing\" defaultValue={{ x: 0.2, y: -0.1 }}>\n *   <XYPad.Value />\n * </XYPad>\n * ```\n *\n * ## Two values that belong together\n *\n * A position, a pan, a balance between two pairs of things: values that the\n * hand thinks of as one place are set as one place. Two sliders would make\n * the reader find a point by turning two knobs in turn.\n *\n * ## The field reads like a chart\n *\n * A grid of dots marks the steps, two hairlines mark zero on each axis, and\n * two fainter lines run through the handle to the edges, so where it stands\n * can be read against both axes at once. While it is held, four brackets\n * close round it.\n *\n * ## Joystick and trail\n *\n * `snapBack` makes it a joystick: it springs back to the centre when let go,\n * for a value that only means something while it is held, such as a pan\n * speed. `trail` draws the last moves as a fading line, for a value whose\n * path matters as much as where it ends.\n */\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useMemo,\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\nexport type XYPadColor = 'primary' | 'info' | 'success' | 'warning' | 'destructive';\n\nexport interface XYPadPoint {\n  x: number;\n  y: number;\n}\n\n/** How many moves the trail remembers. */\nconst TRAIL = 28;\n\nconst xyPadVariants = tv({\n  slots: {\n    root: 'group/pad flex w-full flex-col gap-2 data-disabled:opacity-50',\n    field: [\n      'relative w-full cursor-crosshair touch-none overflow-hidden rounded-2xl bg-muted outline-none select-none',\n      'aspect-(--pad-aspect) ring-1 ring-inset ring-foreground/[0.04]',\n      'group-data-disabled/pad:cursor-not-allowed',\n    ],\n    // Positions are laid out on a plane set in from the field's edge, so a\n    // point at the very end of a range still shows whole.\n    plane: 'absolute inset-3',\n    dots: 'pointer-events-none absolute inset-0 size-full overflow-visible text-foreground [&_circle]:transition-[r,fill-opacity] [&_circle]:duration-150 motion-reduce:[&_circle]:transition-none',\n    axis: 'pointer-events-none absolute bg-foreground/15',\n    guide: [\n      'pointer-events-none absolute bg-(--pad-mark) opacity-20',\n      'transition-[left,top] duration-[520ms] ease-[cubic-bezier(0.3,1.35,0.4,1)] group-data-dragging/pad:duration-0 motion-reduce:transition-none',\n    ],\n    trail: 'pointer-events-none absolute inset-0 size-full overflow-visible',\n    handle: [\n      'absolute top-(--pad-y) left-(--pad-x) z-10 size-[18px] -translate-x-1/2 -translate-y-1/2 cursor-grab rounded-full outline-none',\n      'border-[2.5px] border-(--pad-mark) bg-background shadow-[0_1px_4px_rgb(0_0_0/0.25)]',\n      'transition-[left,top,scale] duration-[520ms] ease-[cubic-bezier(0.3,1.35,0.4,1)] group-data-dragging/pad:cursor-grabbing group-data-dragging/pad:duration-0',\n      'group-data-dragging/pad:scale-110 group-data-disabled/pad:cursor-not-allowed motion-reduce:transition-none',\n      'focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-muted',\n      // The point itself, in the middle of the ring.\n      \"after:absolute after:inset-[3px] after:rounded-full after:bg-(--pad-mark) after:content-['']\",\n    ],\n    bracket: [\n      'pointer-events-none absolute size-2 border-foreground/70 opacity-0 transition-[opacity,translate] duration-200',\n      'group-data-dragging/pad:translate-x-0 group-data-dragging/pad:translate-y-0 group-data-dragging/pad:opacity-100',\n      'motion-reduce:transition-none',\n    ],\n    value: 'flex items-center gap-3 text-xs font-medium tabular-nums text-muted-foreground',\n    axisName: 'me-1 text-foreground/50',\n  },\n  variants: {\n    color: {\n      primary: { root: '[--pad-mark:var(--primary)]' },\n      info: { root: '[--pad-mark:var(--info)]' },\n      success: { root: '[--pad-mark:var(--success)]' },\n      warning: { root: '[--pad-mark:var(--warning)]' },\n      destructive: { root: '[--pad-mark:var(--destructive)]' },\n    },\n  },\n  defaultVariants: { color: 'info' },\n});\n\ninterface PadContextValue {\n  value: XYPadPoint;\n  write(axis: 'x' | 'y', value: number): string;\n}\n\nconst PadContext = createContext<PadContextValue | null>(null);\n\nconst clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);\nconst snapTo = (value: number, step: number, min: number) => {\n  const decimals = (String(step).split('.')[1] ?? '').length;\n  return Number((Math.round((value - min) / step) * step + min).toFixed(Math.min(decimals + 2, 10)));\n};\n\nexport interface XYPadProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange' | 'children'> {\n  /** Where the point is, when the caller holds it. */\n  value?: XYPadPoint;\n  /** Where it starts, when the caller does not hold it. Default the centre. */\n  defaultValue?: XYPadPoint;\n  /** Called with the new point while it moves. */\n  onValueChange?: (value: XYPadPoint) => void;\n  /** Called once a move ends: on release, or after a key press. */\n  onValueCommitted?: (value: XYPadPoint) => void;\n  /** The range of `x`, left to right. Default `[-1, 1]`. */\n  x?: [number, number];\n  /** The range of `y`, bottom to top. Default `[-1, 1]`. */\n  y?: [number, number];\n  /** The granularity of both values. Default `0.01`. */\n  step?: number;\n  /** How many cells the dot grid has across. Default 8. */\n  grid?: number;\n  /** Snap the point to the dots of the grid. */\n  snapToGrid?: boolean;\n  /** Spring back to the centre on release, like a joystick. */\n  snapBack?: boolean;\n  /** Draw the last moves as a fading line behind the point. */\n  trail?: boolean;\n  /** The colour of the point, its guides and its trail. Default `info`. */\n  color?: XYPadColor;\n  /** The shape of the field, as a CSS aspect ratio. Default `16 / 10`. */\n  aspect?: string;\n  /** What it sets. Read out with its values. */\n  label?: string;\n  /** How each value is written, here and to a screen reader. Default two decimals. */\n  format?: (value: number, axis: 'x' | 'y') => string;\n  /** Turns it off. */\n  disabled?: boolean;\n  /** Submits `<name>.x` and `<name>.y` with a form. */\n  name?: string;\n  /** An `XYPad.Value` readout, set under the field. */\n  children?: ReactNode;\n}\n\n/** A field with a point in it, moved by a drag, a press or the arrow keys. */\nfunction XYPadRoot({\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  onValueCommitted,\n  x: xRange = [-1, 1],\n  y: yRange = [-1, 1],\n  step = 0.01,\n  grid = 8,\n  snapToGrid = false,\n  snapBack = false,\n  trail = false,\n  color,\n  aspect = '16 / 10',\n  label,\n  format,\n  disabled = false,\n  name,\n  className,\n  style,\n  children,\n  ...props\n}: XYPadProps) {\n  const slots = xyPadVariants({ color });\n  const [xMin, xMax] = xRange;\n  const [yMin, yMax] = yRange;\n  const centre = useMemo(() => ({ x: (xMin + xMax) / 2, y: (yMin + yMax) / 2 }), [xMin, xMax, yMin, yMax]);\n  const [inner, setInner] = useState<XYPadPoint>(defaultValue ?? centre);\n  const value = valueProp ?? inner;\n  const [dragging, setDragging] = useState(false);\n  const [path, setPath] = useState<XYPadPoint[]>([]);\n\n  const live = useRef({\n    value,\n    onValueChange,\n    onValueCommitted,\n    controlled: valueProp !== undefined,\n  });\n  live.current = {\n    value,\n    onValueChange,\n    onValueCommitted,\n    controlled: valueProp !== undefined,\n  };\n\n  const write = useCallback(\n    (axis: 'x' | 'y', number: number) =>\n      format ? format(number, axis) : `${number < 0 ? '−' : ''}${Math.abs(number).toFixed(2)}`,\n    [format]\n  );\n\n  // Square cells: as many rows as the field's shape fits at the width of a column.\n  const [wide, tall] = aspect.split('/').map((part) => Number(part) || 1);\n  const rows = Math.max(1, Math.round((grid * (tall ?? 1)) / (wide ?? 1)));\n\n  const tidy = useCallback(\n    (point: XYPadPoint): XYPadPoint => {\n      const xStep = snapToGrid ? (xMax - xMin) / grid : step;\n      const yStep = snapToGrid ? (yMax - yMin) / rows : step;\n      return {\n        x: clamp(snapTo(point.x, xStep, xMin), xMin, xMax),\n        y: clamp(snapTo(point.y, yStep, yMin), yMin, yMax),\n      };\n    },\n    [snapToGrid, grid, rows, step, xMin, xMax, yMin, yMax]\n  );\n\n  const change = useCallback(\n    (next: XYPadPoint) => {\n      const { value: last, controlled } = live.current;\n      if (next.x === last.x && next.y === last.y) return;\n      if (!controlled) setInner(next);\n      live.current.onValueChange?.(next);\n      if (trail) setPath((all) => [...all.slice(-(TRAIL - 1)), next]);\n    },\n    [trail]\n  );\n\n  // The trail fades away once the point is left alone.\n  useEffect(() => {\n    if (!trail || dragging || path.length === 0) return;\n    const timer = window.setInterval(() => {\n      setPath((all) => (all.length <= 1 ? [] : all.slice(Math.ceil(all.length / 6))));\n    }, 60);\n    return () => window.clearInterval(timer);\n  }, [trail, dragging, path.length]);\n\n  const field = useRef<HTMLDivElement>(null);\n  const plane = useRef<HTMLDivElement>(null);\n  // The plane's size in pixels, so the lens round the point is a circle.\n  const [size, setSize] = useState({ width: 0, height: 0 });\n  useEffect(() => {\n    const box = plane.current;\n    if (!box) return;\n    const observer = new ResizeObserver(() => setSize({ width: box.clientWidth, height: box.clientHeight }));\n    observer.observe(box);\n    return () => observer.disconnect();\n  }, []);\n  const handle = useRef<HTMLDivElement>(null);\n  const pointAt = (clientX: number, clientY: number): XYPadPoint => {\n    const box = plane.current!.getBoundingClientRect();\n    const across = clamp((clientX - box.left) / box.width, 0, 1);\n    const down = clamp((clientY - box.top) / box.height, 0, 1);\n    return tidy({\n      x: xMin + across * (xMax - xMin),\n      y: yMax - down * (yMax - yMin),\n    });\n  };\n\n  const press = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (disabled || event.button !== 0) return;\n    event.preventDefault();\n    try {\n      field.current?.setPointerCapture(event.pointerId);\n    } catch {\n      // A pointer the browser no longer tracks; the drag still follows moves over the field.\n    }\n    // Focused for the arrow keys, without the ring a keyboard user would see.\n    handle.current?.focus({ preventScroll: true, focusVisible: false } as FocusOptions);\n    setDragging(true);\n    change(pointAt(event.clientX, event.clientY));\n  };\n  const move = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (!dragging) return;\n    change(pointAt(event.clientX, event.clientY));\n  };\n  const release = () => {\n    if (!dragging) return;\n    setDragging(false);\n    if (snapBack) change(centre);\n    live.current.onValueCommitted?.(snapBack ? centre : live.current.value);\n  };\n\n  const keys = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    const by = (event.shiftKey ? 10 : 1) * (snapToGrid ? (xMax - xMin) / grid : step);\n    const byY = (event.shiftKey ? 10 : 1) * (snapToGrid ? (yMax - yMin) / rows : step);\n    const rtl = getComputedStyle(event.currentTarget).direction === 'rtl';\n    const moves: Record<string, () => XYPadPoint> = {\n      ArrowLeft: () => ({ ...value, x: value.x + (rtl ? by : -by) }),\n      ArrowRight: () => ({ ...value, x: value.x + (rtl ? -by : by) }),\n      ArrowUp: () => ({ ...value, y: value.y + byY }),\n      ArrowDown: () => ({ ...value, y: value.y - byY }),\n      Home: () => centre,\n    };\n    const next = moves[event.key];\n    if (!next) return;\n    event.preventDefault();\n    const point = tidy(next());\n    change(point);\n    live.current.onValueCommitted?.(point);\n  };\n\n  const toX = (x: number) => ((x - xMin) / (xMax - xMin)) * 100;\n  const toY = (y: number) => ((yMax - y) / (yMax - yMin)) * 100;\n  const left = ((value.x - xMin) / (xMax - xMin)) * 100;\n  const down = ((yMax - value.y) / (yMax - yMin)) * 100;\n  const zeroX = xMin < 0 && xMax > 0 ? ((0 - xMin) / (xMax - xMin)) * 100 : null;\n  const zeroY = yMin < 0 && yMax > 0 ? ((yMax - 0) / (yMax - yMin)) * 100 : null;\n  const valueText = `${label ? `${label}: ` : ''}x ${write('x', value.x)}, y ${write('y', value.y)}`;\n\n  // Each bracket closes in from its own corner.\n  const brackets = [\n    'border-s-[1.5px] border-t-[1.5px] -translate-x-1 -translate-y-1 left-[calc(var(--pad-x)-15px)] top-[calc(var(--pad-y)-15px)]',\n    'border-e-[1.5px] border-t-[1.5px] translate-x-1 -translate-y-1 left-[calc(var(--pad-x)+7px)] top-[calc(var(--pad-y)-15px)]',\n    'border-s-[1.5px] border-b-[1.5px] -translate-x-1 translate-y-1 left-[calc(var(--pad-x)-15px)] top-[calc(var(--pad-y)+7px)]',\n    'border-e-[1.5px] border-b-[1.5px] translate-x-1 translate-y-1 left-[calc(var(--pad-x)+7px)] top-[calc(var(--pad-y)+7px)]',\n  ];\n\n  return (\n    <PadContext.Provider value={useMemo(() => ({ value, write }), [value, write])}>\n      <div\n        data-slot=\"xy-pad\"\n        data-dragging={dragging ? '' : undefined}\n        data-disabled={disabled ? '' : undefined}\n        className={slots.root({ className })}\n        style={\n          {\n            ...style,\n            '--pad-aspect': aspect,\n            '--pad-x': `${left}%`,\n            '--pad-y': `${down}%`,\n          } as CSSProperties\n        }\n        {...props}\n      >\n        <div\n          ref={field}\n          data-slot=\"xy-pad-field\"\n          className={slots.field()}\n          onPointerDown={press}\n          onPointerMove={move}\n          onPointerUp={release}\n          onPointerCancel={release}\n          onLostPointerCapture={release}\n        >\n          <div ref={plane} data-slot=\"xy-pad-plane\" className={slots.plane()}>\n            <Dots\n              columns={grid}\n              rows={rows}\n              size={size}\n              at={{ x: left / 100, y: down / 100 }}\n              className={slots.dots()}\n            />\n            {zeroX !== null ? (\n              <span\n                aria-hidden\n                className={slots.axis({\n                  className: '-inset-y-3 w-px -translate-x-1/2',\n                })}\n                style={{ left: `${zeroX}%` }}\n              />\n            ) : null}\n            {zeroY !== null ? (\n              <span\n                aria-hidden\n                className={slots.axis({\n                  className: '-inset-x-3 h-px -translate-y-1/2',\n                })}\n                style={{ top: `${zeroY}%` }}\n              />\n            ) : null}\n            <span\n              aria-hidden\n              className={slots.guide({\n                className: '-inset-y-3 left-(--pad-x) w-px -translate-x-1/2',\n              })}\n            />\n            <span\n              aria-hidden\n              className={slots.guide({\n                className: '-inset-x-3 top-(--pad-y) h-px -translate-y-1/2',\n              })}\n            />\n            {trail && path.length > 1 ? (\n              <svg aria-hidden className={slots.trail()} viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\">\n                {/*\n                 * One unbroken line underneath in the tail's colour, then the\n                 * fade on top in flat-ended pieces. Round ends would overlap at\n                 * every join and show as beads.\n                 */}\n                <polyline\n                  points={path.map((point) => `${toX(point.x)},${toY(point.y)}`).join(' ')}\n                  fill=\"none\"\n                  stroke=\"color-mix(in oklab, var(--pad-mark) 12%, var(--muted))\"\n                  strokeWidth={2.5}\n                  strokeLinecap=\"round\"\n                  strokeLinejoin=\"round\"\n                  vectorEffect=\"non-scaling-stroke\"\n                />\n                {path.slice(1).map((point, at) => {\n                  const from = path[at]!;\n                  return (\n                    <line\n                      key={at}\n                      x1={toX(from.x)}\n                      y1={toY(from.y)}\n                      x2={toX(point.x)}\n                      y2={toY(point.y)}\n                      stroke={`color-mix(in oklab, var(--pad-mark) ${Math.round(12 + ((at + 1) / path.length) * 78)}%, var(--muted))`}\n                      strokeWidth={2.5}\n                      strokeLinecap=\"butt\"\n                      vectorEffect=\"non-scaling-stroke\"\n                    />\n                  );\n                })}\n              </svg>\n            ) : null}\n            {brackets.map((place, at) => (\n              <span key={at} aria-hidden className={slots.bracket({ className: place })} />\n            ))}\n            <div\n              ref={handle}\n              role=\"slider\"\n              data-slot=\"xy-pad-handle\"\n              tabIndex={disabled ? -1 : 0}\n              aria-label={label ?? 'Position'}\n              aria-valuetext={valueText}\n              aria-valuenow={value.x}\n              aria-valuemin={xMin}\n              aria-valuemax={xMax}\n              aria-disabled={disabled || undefined}\n              onKeyDown={keys}\n              className={slots.handle()}\n            />\n          </div>\n        </div>\n        {name ? (\n          <>\n            <input type=\"hidden\" name={`${name}.x`} value={value.x} />\n            <input type=\"hidden\" name={`${name}.y`} value={value.y} />\n          </>\n        ) : null}\n        {children}\n      </div>\n    </PadContext.Provider>\n  );\n}\nXYPadRoot.displayName = 'XYPad';\n\n/** How far round the point the dots swell: this share of the field's shorter side, at most 72px. */\nconst LENS = 0.3;\n\n/**\n * The dot grid, one dot at each crossing including the edges. The dots\n * within reach of the point swell and brighten, so the grid answers the\n * point as it moves.\n */\nfunction Dots({\n  columns,\n  rows,\n  size,\n  at,\n  className,\n}: {\n  columns: number;\n  rows: number;\n  size: { width: number; height: number };\n  at: { x: number; y: number };\n  className: string;\n}) {\n  const dots: ReactNode[] = [];\n  for (let column = 0; column <= columns; column++) {\n    for (let row = 0; row <= rows; row++) {\n      const x = column / columns;\n      const y = row / rows;\n      const distance = Math.hypot((x - at.x) * size.width, (y - at.y) * size.height);\n      const reach = Math.min(Math.min(size.width, size.height) * LENS, 72);\n      const near = reach ? Math.max(0, 1 - distance / reach) : 0;\n      dots.push(\n        <circle\n          key={`${column}-${row}`}\n          cx={`${x * 100}%`}\n          cy={`${y * 100}%`}\n          r={1.25 + near * 1.25}\n          fill=\"currentColor\"\n          fillOpacity={0.16 + near * 0.5}\n        />\n      );\n    }\n  }\n  return (\n    <svg aria-hidden className={className}>\n      {dots}\n    </svg>\n  );\n}\n\nexport interface XYPadValueProps extends ComponentProps<'div'> {}\n\n/** The two values written out, under the field. */\nfunction XYPadValue({ className, render, ...props }: XYPadValueProps & RenderProp<'div'>) {\n  const pad = useContext(PadContext);\n  if (!pad) throw new Error('XYPad.Value must be used inside an <XYPad>.');\n  const slots = xyPadVariants();\n  return useRender({\n    defaultTagName: 'div',\n    render,\n    props: mergeProps(\n      {\n        'aria-hidden': true,\n        'data-slot': 'xy-pad-value',\n        className: slots.value({ className }),\n        children: (\n          <>\n            <span>\n              <span className={slots.axisName()}>X</span>\n              {pad.write('x', pad.value.x)}\n            </span>\n            <span>\n              <span className={slots.axisName()}>Y</span>\n              {pad.write('y', pad.value.y)}\n            </span>\n          </>\n        ),\n      },\n      props\n    ),\n  });\n}\nXYPadValue.displayName = 'XYPad.Value';\n\nexport const XYPad = Object.assign(XYPadRoot, {\n  Value: XYPadValue,\n});\n\nexport { XYPadValue, xyPadVariants };\n"
    }
  ]
}
