{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-annotator",
  "type": "registry:ui",
  "title": "Image Annotator",
  "description": "A picture on which areas are marked and named: drawn by dragging, or added with a button and placed with the keys (arrows move, plus and minus resize, Delete removes), each named in a list beside the picture; areas come out as fractions of the picture, every change said aloud.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/chart",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/image-annotator.tsx",
      "type": "registry:ui",
      "target": "components/ui/image-annotator.tsx",
      "content": "\"use client\";\n/**\n * @name image-annotator\n * @category ui\n * @description A picture on which areas are marked and named: drawn by dragging, or added with a button and placed with the keys (arrows move, plus and minus resize, Delete removes), each named in a list beside the picture; areas come out as fractions of the picture, every change said aloud.\n * @when Labelling what is in a picture: damage on a photo, rooms on a plan, objects for training a model, notes on a design. For cutting a picture use image-cropper; for named points that play at moments of a video use hotspots.\n * @example\n * <ImageAnnotator src=\"/plan.png\" alt=\"Ground floor plan\" defaultAreas={[{ id: \"a\", x: 0.1, y: 0.2, width: 0.3, height: 0.25, label: \"Kitchen\" }]} onAreasChange={save} />\n */\nimport { Plus, Trash2 } from \"lucide-react\";\nimport { useId, useRef, useState, type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport { chartSeries } from \"@/components/viz/chart\";\n\n/** A marked area as fractions of the picture's width and height, from its top left. */\nexport type ImageArea = { id: string; x: number; y: number; width: number; height: number; label: string };\n\nexport type ImageAnnotatorLabels = {\n  areas: string;\n  add: string;\n  remove: (label: string) => string;\n  name: (index: number) => string;\n  unnamed: (index: number) => string;\n  help: string;\n  added: (label: string) => string;\n  removed: (label: string) => string;\n  area: string;\n};\n\nconst LABELS: ImageAnnotatorLabels = {\n  areas: \"Marked areas\",\n  add: \"Add an area\",\n  remove: (label) => `Remove ${label}`,\n  name: (index) => `Name of area ${index}`,\n  unnamed: (index) => `Area ${index}`,\n  help: \"Arrow keys move the area, with Shift further; plus and minus resize it; Delete removes it.\",\n  added: (label) => `${label} added`,\n  removed: (label) => `${label} removed`,\n  area: \"area\",\n};\n\nexport type ImageAnnotatorProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  src: string;\n  alt: string;\n  areas?: readonly ImageArea[];\n  defaultAreas?: readonly ImageArea[];\n  onAreasChange?: (areas: readonly ImageArea[]) => void;\n  /** Areas can be looked at but not changed. */\n  readOnly?: boolean;\n  /** Draws the picture: the framework's image component. */\n  renderImage?: (props: { src: string; alt: string; className: string; draggable: false }) => ReactNode;\n  labels?: Partial<ImageAnnotatorLabels>;\n};\n\nconst MIN = 0.03;\n/** Literal class names, so Tailwind finds them: the series colours as borders. */\nconst BORDERS = [\"border-chart-1\", \"border-chart-2\", \"border-chart-3\", \"border-chart-4\", \"border-chart-5\"] as const;\nconst clamp = (a: ImageArea): ImageArea => {\n  const width = Math.max(MIN, Math.min(1, a.width));\n  const height = Math.max(MIN, Math.min(1, a.height));\n  return { ...a, width, height, x: Math.max(0, Math.min(1 - width, a.x)), y: Math.max(0, Math.min(1 - height, a.y)) };\n};\n\nexport function ImageAnnotator({ src, alt, areas: areasProp, defaultAreas = [], onAreasChange, readOnly = false, renderImage, labels: given, className, ...props }: ImageAnnotatorProps) {\n  const labels = { ...LABELS, ...given };\n  const [areas, setAreas] = useControllableState<readonly ImageArea[]>({ value: areasProp, defaultValue: defaultAreas, onChange: onAreasChange });\n  const [active, setActive] = useState<string | null>(null);\n  const frame = useRef<HTMLDivElement>(null);\n  const boxes = useRef(new Map<string, HTMLDivElement | null>());\n  const drawing = useRef<{ id: string; x: number; y: number } | null>(null);\n  const moving = useRef<{ id: string; x: number; y: number; from: ImageArea } | null>(null);\n  const helpId = useId();\n  const counter = useRef(areas.length);\n  const nameOf = (area: ImageArea, index: number): string => area.label || labels.unnamed(index + 1);\n  const update = (id: string, change: (a: ImageArea) => ImageArea): void => setAreas(areas.map((a) => (a.id === id ? clamp(change(a)) : a)));\n  const newId = (): string => {\n    counter.current += 1;\n    return `${helpId}-area-${counter.current}`;\n  };\n  const remove = (id: string): void => {\n    const index = areas.findIndex((a) => a.id === id);\n    const area = areas[index];\n    setAreas(areas.filter((a) => a.id !== id));\n    if (area) announce(labels.removed(nameOf(area, index)));\n    setActive(null);\n  };\n  const fraction = (event: PointerEvent<HTMLElement>): { x: number; y: number } => {\n    const box = frame.current?.getBoundingClientRect();\n    if (!box) return { x: 0, y: 0 };\n    return { x: Math.max(0, Math.min(1, (event.clientX - box.left) / box.width)), y: Math.max(0, Math.min(1, (event.clientY - box.top) / box.height)) };\n  };\n  const onBoxKeyDown = (area: ImageArea, event: KeyboardEvent<HTMLDivElement>): void => {\n    if (readOnly) return;\n    const step = event.shiftKey ? 0.05 : 0.01;\n    const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };\n    const move = moves[event.key];\n    const grow = event.key === \"+\" || event.key === \"=\" ? 0.02 : event.key === \"-\" || event.key === \"_\" ? -0.02 : 0;\n    if (move) {\n      event.preventDefault();\n      update(area.id, (a) => ({ ...a, x: a.x + move[0], y: a.y + move[1] }));\n    } else if (grow !== 0) {\n      event.preventDefault();\n      update(area.id, (a) => ({ x: a.x - grow / 2, y: a.y - grow / 2, width: a.width + grow, height: a.height + grow, id: a.id, label: a.label }));\n    } else if (event.key === \"Delete\" || event.key === \"Backspace\") {\n      event.preventDefault();\n      remove(area.id);\n    }\n  };\n\n  return (\n    <div data-slot=\"image-annotator\" className={cn(\"@container grid w-full min-w-0 gap-4 @2xl:grid-cols-[minmax(0,1fr)_16rem]\", className)} {...props}>\n      <div\n        ref={frame}\n        dir=\"ltr\"\n        className={cn(\"relative touch-none overflow-hidden rounded-surface border select-none\", !readOnly && \"cursor-crosshair\")}\n        onPointerDown={(event) => {\n          if (readOnly || event.target !== event.currentTarget.querySelector(\"[data-slot=image-annotator-surface]\")) return;\n          const p = fraction(event);\n          const id = newId();\n          drawing.current = { id, x: p.x, y: p.y };\n          event.currentTarget.setPointerCapture(event.pointerId);\n          setAreas([...areas, { id, x: p.x, y: p.y, width: MIN, height: MIN, label: \"\" }]);\n          setActive(id);\n        }}\n        onPointerMove={(event) => {\n          const p = fraction(event);\n          if (drawing.current) {\n            const d = drawing.current;\n            update(d.id, (a) => ({ ...a, x: Math.min(d.x, p.x), y: Math.min(d.y, p.y), width: Math.abs(p.x - d.x), height: Math.abs(p.y - d.y) }));\n          } else if (moving.current) {\n            const m = moving.current;\n            update(m.id, () => ({ ...m.from, x: m.from.x + p.x - m.x, y: m.from.y + p.y - m.y }));\n          }\n        }}\n        onPointerUp={() => {\n          if (drawing.current) {\n            const id = drawing.current.id;\n            const index = areas.findIndex((a) => a.id === id);\n            announce(labels.added(labels.unnamed(index + 1)));\n          }\n          drawing.current = null;\n          moving.current = null;\n        }}\n      >\n        {renderImage ? (\n          renderImage({ src, alt, className: \"block h-auto w-full\", draggable: false })\n        ) : (\n          // eslint-disable-next-line @next/next/no-img-element -- The library is not tied to one framework: the default is the plain element, and `renderImage` takes the framework's image component.\n          <img src={src} alt={alt} className=\"block h-auto w-full\" draggable={false} />\n        )}\n        <div data-slot=\"image-annotator-surface\" className=\"absolute inset-0\" />\n        {areas.map((area, index) => {\n          return (\n            <div\n              key={area.id}\n              ref={(node) => {\n                boxes.current.set(area.id, node);\n              }}\n              data-slot=\"image-annotator-area\"\n              role=\"group\"\n              aria-roledescription={labels.area}\n              aria-label={nameOf(area, index)}\n              aria-describedby={readOnly ? undefined : helpId}\n              tabIndex={0}\n              onFocus={() => setActive(area.id)}\n              onKeyDown={(event) => onBoxKeyDown(area, event)}\n              onPointerDown={(event) => {\n                if (readOnly) return;\n                event.stopPropagation();\n                const p = fraction(event);\n                moving.current = { id: area.id, x: p.x, y: p.y, from: area };\n                frame.current?.setPointerCapture(event.pointerId);\n                setActive(area.id);\n              }}\n              className={cn(\"absolute border-2\", BORDERS[index % 5], active === area.id ? \"outline-2 outline-offset-1 outline-foreground\" : \"\", !readOnly && \"cursor-move\")}\n              style={{ left: `${area.x * 100}%`, top: `${area.y * 100}%`, width: `${area.width * 100}%`, height: `${area.height * 100}%` }}\n            >\n              <span\n                aria-hidden=\"true\"\n                className={cn(\"absolute -top-px start-0 max-w-full -translate-y-full truncate rounded-t-[min(var(--radius),4px)] border-2 border-b-0 bg-background px-1.5 text-xs text-foreground\", BORDERS[index % 5])}\n              >\n                {index + 1}. {area.label}\n              </span>\n            </div>\n          );\n        })}\n      </div>\n      <div className=\"flex min-w-0 flex-col gap-2\">\n        <h3 className=\"text-sm font-medium\">{labels.areas}</h3>\n        <ol className=\"flex flex-col gap-2\">\n          {areas.map((area, index) => (\n            <li key={area.id} className={cn(\"flex items-center gap-2 rounded-control\", active === area.id && \"bg-highlight-soft\")}>\n              <span aria-hidden=\"true\" className={cn(\"size-3 shrink-0 rounded-[min(var(--radius),3px)]\", chartSeries(index % 5).background)} />\n              <input\n                aria-label={labels.name(index + 1)}\n                value={area.label}\n                readOnly={readOnly}\n                onFocus={() => setActive(area.id)}\n                onChange={(event) => setAreas(areas.map((a) => (a.id === area.id ? { ...a, label: event.target.value } : a)))}\n                placeholder={labels.unnamed(index + 1)}\n                className=\"h-control-sm min-w-0 flex-1 rounded-control border border-input bg-background px-2 text-sm pointer-coarse:h-control\"\n              />\n              {!readOnly ? (\n                <button\n                  type=\"button\"\n                  aria-label={labels.remove(nameOf(area, index))}\n                  onClick={() => remove(area.id)}\n                  className=\"flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-accent pointer-coarse:size-10\"\n                >\n                  <Trash2 aria-hidden=\"true\" className=\"size-4\" />\n                </button>\n              ) : null}\n            </li>\n          ))}\n        </ol>\n        {!readOnly ? (\n          <button\n            type=\"button\"\n            onClick={() => {\n              const id = newId();\n              const label = labels.unnamed(areas.length + 1);\n              setAreas([...areas, { id, x: 0.35, y: 0.35, width: 0.3, height: 0.3, label: \"\" }]);\n              setActive(id);\n              announce(labels.added(label));\n              requestAnimationFrame(() => boxes.current.get(id)?.focus());\n            }}\n            className=\"inline-flex h-control-sm items-center gap-1.5 self-start rounded-control border border-border-strong px-3 text-sm hover:bg-accent pointer-coarse:h-control\"\n          >\n            <Plus aria-hidden=\"true\" className=\"size-4\" />\n            {labels.add}\n          </button>\n        ) : null}\n        <span id={helpId} className=\"sr-only\">\n          {labels.help}\n        </span>\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Labelling what is in a picture: damage on a photo, rooms on a plan, objects for training a model, notes on a design. For cutting a picture use image-cropper; for named points that play at moments of a video use hotspots.",
    "example": "<ImageAnnotator src=\"/plan.png\" alt=\"Ground floor plan\" defaultAreas={[{ id: \"a\", x: 0.1, y: 0.2, width: 0.3, height: 0.25, label: \"Kitchen\" }]} onAreasChange={save} />",
    "client": true
  }
}
