{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-cropper",
  "title": "Image cropper",
  "description": "ui-sdk’s Image cropper: picks the part of an image to keep, by pointer, touch, wheel and keyboard, with a set shape, a circle or a free one. By default the image pans and zooms under a still frame; the `box` mode moves and resizes a selection over the whole image instead. Every move glides on the layout role, a turn pivots on the crop, and nothing renders while you drag.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/button.json",
    "https://kinoui.com/r/slider.json",
    "https://kinoui.com/r/spinner.json",
    "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/track.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/image-cropper.tsx",
      "content": "'use client'\n\nimport { Button } from '@/registry/components/kino/button'\nimport {\n  sliderThumbClassName,\n  sliderTrackClassName,\n} from '@/registry/components/kino/slider'\nimport { Spinner, useSpinner } from '@/registry/components/kino/spinner'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { announce } from '@/registry/lib/announce'\nimport { insetsOf, translateOf } from '@/registry/lib/highlight'\nimport { mergeRefs } from '@/registry/lib/refs'\nimport {\n  FOLLOWS_TRANSITION,\n  markResizing,\n  runningTransitions,\n} from '@/registry/lib/resize'\nimport { trackDirClassName, trackFillClassName } from '@/registry/lib/track'\nimport type { OptionsOf, TypesOf } from '@ui-sdk/core'\nimport type { ImageCrop } from '@ui-sdk/core/image'\nimport {\n  type ImageCropperCropChangeReason,\n  type ImageCropperHandlePosition,\n  type ImageCropperMode,\n  type ImageCropperShape,\n  imageCropper,\n} from '@ui-sdk/core/image-cropper'\nimport {\n  ImageCropperGrid as ImageCropperGridPrimitive,\n  ImageCropperHandle as ImageCropperHandlePrimitive,\n  ImageCropperImage as ImageCropperImagePrimitive,\n  ImageCropperRotate as ImageCropperRotatePrimitive,\n  ImageCropperSelection as ImageCropperSelectionPrimitive,\n  ImageCropperViewport as ImageCropperViewportPrimitive,\n  ImageCropperZoom as ImageCropperZoomPrimitive,\n} from '@ui-sdk/react/image-cropper'\nimport { type PrimitiveHandle, usePart, usePrimitive } from '@ui-sdk/react/primitive'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * ui-sdk's Image cropper holds the crop, the pointer, the wheel and the keys.\n * Kino draws it: ui-sdk places its parts in pixels with inline `left`, `top`,\n * `width` and `height`, which only move on the main thread, so the parts here\n * take their place from `translate`, `rotate`, `scale` and `clip-path`\n * instead, worked out from ui-sdk's state, and those glide on `layout` after a\n * key or a button, and follow at once while a pointer, the wheel or the zoom\n * thumb moves the crop (`data-following`).\n *\n * The image is the same way round in either text direction, so the layers\n * over it are placed from its physical top left, as ui-sdk places them, and\n * the corner marks' 3px arms and 17px offsets (a 20px mark less its arm) are\n * physical too.\n */\n\n// ---------------------------------------------------------------------------\n// The arithmetic ui-sdk keeps to itself\n\n/** A width and height in pixels. */\ninterface Size {\n  width: number\n  height: number\n}\n\ninterface Point {\n  x: number\n  y: number\n}\n\n/** A rectangle in pixels, from its top left corner. */\ninterface Rect extends Point, Size {}\n\ntype Crop = Required<ImageCrop>\n\n/** The image's size once it is turned `rotation` degrees. */\nfunction rotatedSize(size: Size, rotation: number): Size {\n  return rotation % 180 === 0 ? size : { width: size.height, height: size.width }\n}\n\n/** The point of the image as it was taken that shows at `point` once it is turned `rotation` degrees. */\nfunction toNatural(point: Point, natural: Size, rotation: number): Point {\n  if (rotation === 90) return { x: point.y, y: natural.height - point.x }\n  if (rotation === 180) return { x: natural.width - point.x, y: natural.height - point.y }\n  if (rotation === 270) return { x: natural.width - point.y, y: point.x }\n  return { ...point }\n}\n\n/** The smallest rectangle `aspect` wide for each pixel high that covers `bounds`, centred on it. */\nfunction coverRect(bounds: Rect, aspect: number): Rect {\n  const width = Math.max(bounds.width, bounds.height * aspect)\n  const height = width / aspect\n  return {\n    x: bounds.x + (bounds.width - width) / 2,\n    y: bounds.y + (bounds.height - height) / 2,\n    width,\n    height,\n  }\n}\n\n/** The whole of an image, as a rectangle. */\nfunction imageRect(size: Size): Rect {\n  return { x: 0, y: 0, ...size }\n}\n\n/** How the image is placed to show `view` in `frame`: how much it is scaled, and where its top left corner lands. */\n/**\n * The largest crop at `aspect` in the middle of an image of `natural` size,\n * in whole pixels, as ui-sdk works its crops out: the whole image when there\n * is no ratio.\n */\nfunction largestCrop(natural: Size, aspect: number | undefined): Crop {\n  const ratio = aspect && aspect > 0 ? aspect : natural.width / natural.height\n  const width = Math.round(Math.min(natural.width, natural.height * ratio))\n  const height = Math.round(Math.min(natural.height, natural.width / ratio))\n  return {\n    x: Math.round((natural.width - width) / 2),\n    y: Math.round((natural.height - height) / 2),\n    width,\n    height,\n    rotation: 0,\n    flipX: false,\n    flipY: false,\n  }\n}\n\n/** Whether two crops cover the same pixels. */\nfunction sameRect(one: Rect, other: Rect) {\n  return (\n    one.x === other.x &&\n    one.y === other.y &&\n    one.width === other.width &&\n    one.height === other.height\n  )\n}\n\nfunction viewTransform(view: Rect, frame: Rect) {\n  const scale = frame.width / view.width\n  return { scale, x: frame.x - view.x * scale, y: frame.y - view.y * scale }\n}\n\ntype ViewTransform = ReturnType<typeof viewTransform>\n\n/**\n * Where ui-sdk shows the image and the selection in its viewport's padding\n * box (`box`), as its own parts place them, so what Kino draws lies under\n * ui-sdk's pointer. A frame keeps the selection as large as it fits at the\n * ratio and scales the image to it; a box fits the whole image.\n */\nfunction cropLayout(\n  crop: Crop,\n  natural: Size,\n  box: Rect,\n  mode: ImageCropperMode,\n  aspect: number | undefined,\n): { transform: ViewTransform; selection: Rect } {\n  const shown = rotatedSize(natural, crop.rotation)\n  if (mode === 'frame') {\n    const ratio = aspect ?? crop.width / crop.height\n    const width = Math.min(box.width, box.height * ratio)\n    const height = width / ratio\n    const selection = {\n      x: box.x + (box.width - width) / 2,\n      y: box.y + (box.height - height) / 2,\n      width,\n      height,\n    }\n    const scale = width / crop.width\n    return {\n      transform: {\n        scale,\n        x: selection.x - crop.x * scale,\n        y: selection.y - crop.y * scale,\n      },\n      selection,\n    }\n  }\n  const scale = Math.min(box.width / shown.width, box.height / shown.height)\n  const transform = {\n    scale,\n    x: box.x + (box.width - shown.width * scale) / 2,\n    y: box.y + (box.height - shown.height * scale) / 2,\n  }\n  return {\n    transform,\n    selection: {\n      x: transform.x + crop.x * scale,\n      y: transform.y + crop.y * scale,\n      width: crop.width * scale,\n      height: crop.height * scale,\n    },\n  }\n}\n\n/** The angle the image is drawn at: the crop's rotation, reached by the shorter way round from the last one, so a turn past 270 keeps going. */\nfunction nextAngle(angle: number, rotation: number) {\n  const delta = ((((rotation - angle) % 360) + 540) % 360) - 180\n  return angle + delta\n}\n\nfunction round(value: number) {\n  return Math.round(value * 100) / 100\n}\n\n/**\n * Which of the image's own sides a crop mirrors: ui-sdk flips the image as it\n * shows, after its turn, so on a quarter turn a flip left to right mirrors\n * the image as taken top to bottom. A turn swaps ui-sdk's flips with its\n * sides, so these stay put through it.\n */\nfunction mirrorOf(crop: Crop): readonly [boolean, boolean] {\n  return crop.rotation % 180 === 0 ? [crop.flipX, crop.flipY] : [crop.flipY, crop.flipX]\n}\n\n/** Where a turn starts or ends: the frame's `translate`, `rotate` (degrees) and `scale`, the crop's centre in the image as drawn, and the crop on screen. */\ninterface TurnPose {\n  translate: readonly [number, number]\n  rotate: number\n  scale: number\n  pivot: readonly [number, number]\n  hole: Rect\n}\n\n/**\n * The image as drawn for `crop`: a frame at the crop's centre on screen,\n * turned `angle` degrees and scaled about it, with the image inside moved so\n * the crop's centre sits on the frame's corner. The image is drawn mirrored\n * for a flip, so `pivot` is the crop's centre in the mirrored image.\n */\nfunction imagePose(\n  natural: Size,\n  angle: number,\n  transform: ViewTransform,\n  crop: Crop,\n): Omit<TurnPose, 'hole'> {\n  const shown = rotatedSize(natural, crop.rotation)\n  const centre = { x: crop.x + crop.width / 2, y: crop.y + crop.height / 2 }\n  const unflipped = {\n    x: crop.flipX ? shown.width - centre.x : centre.x,\n    y: crop.flipY ? shown.height - centre.y : centre.y,\n  }\n  const taken = toNatural(unflipped, natural, crop.rotation)\n  const [mirrorX, mirrorY] = mirrorOf(crop)\n  return {\n    translate: [\n      transform.x + centre.x * transform.scale,\n      transform.y + centre.y * transform.scale,\n    ],\n    rotate: angle,\n    scale: transform.scale,\n    pivot: [\n      mirrorX ? natural.width - taken.x : taken.x,\n      mirrorY ? natural.height - taken.y : taken.y,\n    ],\n  }\n}\n\n/** `imagePose` as the styles that draw it: the frame's, and the `<img>`'s inside it. */\nfunction imagePlacement(\n  natural: Size,\n  angle: number,\n  transform: ViewTransform,\n  crop: Crop,\n) {\n  const { translate, scale, pivot } = imagePose(natural, angle, transform, crop)\n  const [mirrorX, mirrorY] = mirrorOf(crop)\n  return {\n    frame: {\n      translate: `${round(translate[0])}px ${round(translate[1])}px`,\n      rotate: `${angle}deg`,\n      scale: `${Math.round(scale * 10000) / 10000}`,\n    },\n    image: {\n      width: `${natural.width}px`,\n      height: `${natural.height}px`,\n      translate: `${round(-pivot[0])}px ${round(-pivot[1])}px`,\n      scale: `${mirrorX ? -1 : 1} ${mirrorY ? -1 : 1}`,\n    },\n  }\n}\n\n/**\n * How much larger the image is drawn `progress` of the way through a turn\n * from `from` to `to`, about the frame's corner, so it covers the crop at\n * that angle: 1 when it already does. Each value moves in a straight line,\n * as CSS moves it, by one progress for all of them or by each its own. A\n * `round` crop is the circle inside the hole.\n */\nfunction turnCover(\n  from: TurnPose,\n  to: TurnPose,\n  natural: Size,\n  progress: number | TurnProgress,\n  round = false,\n) {\n  const mix = (part: keyof TurnProgress, a: number, b: number) =>\n    a + (b - a) * (typeof progress === 'number' ? progress : progress[part])\n  const tx = mix('translate', from.translate[0], to.translate[0])\n  const ty = mix('translate', from.translate[1], to.translate[1])\n  const turn = (mix('rotate', from.rotate, to.rotate) * Math.PI) / 180\n  const scale = mix('scale', from.scale, to.scale)\n  const px = mix('pivot', from.pivot[0], to.pivot[0])\n  const py = mix('pivot', from.pivot[1], to.pivot[1])\n  const x = mix('hole', from.hole.x, to.hole.x)\n  const y = mix('hole', from.hole.y, to.hole.y)\n  const right = x + mix('hole', from.hole.width, to.hole.width)\n  const bottom = y + mix('hole', from.hole.height, to.hole.height)\n  const cos = Math.cos(turn)\n  const sin = Math.sin(turn)\n  // How far the image reaches from its pivot on each side, in its own pixels.\n  const reach = {\n    left: Math.max(px, 1e-6),\n    right: Math.max(natural.width - px, 1e-6),\n    top: Math.max(py, 1e-6),\n    bottom: Math.max(natural.height - py, 1e-6),\n  }\n  let cover = 1\n  if (round) {\n    // A round crop only needs its circle covered: its centre, and its radius each way.\n    const radius = Math.min(right - x, bottom - y) / 2 / scale\n    const ox = (x + right) / 2 - tx\n    const oy = (y + bottom) / 2 - ty\n    const dx = (ox * cos + oy * sin) / scale\n    const dy = (-ox * sin + oy * cos) / scale\n    return Math.max(\n      1,\n      (dx + radius) / reach.right,\n      (radius - dx) / reach.left,\n      (dy + radius) / reach.bottom,\n      (radius - dy) / reach.top,\n    )\n  }\n  for (const [cx, cy] of [\n    [x, y],\n    [right, y],\n    [right, bottom],\n    [x, bottom],\n  ] as const) {\n    // The corner in the image's own pixels from its pivot: turned back, and unscaled.\n    const dx = ((cx - tx) * cos + (cy - ty) * sin) / scale\n    const dy = (-(cx - tx) * sin + (cy - ty) * cos) / scale\n    cover = Math.max(\n      cover,\n      dx > 0 ? dx / reach.right : -dx / reach.left,\n      dy > 0 ? dy / reach.bottom : -dy / reach.top,\n    )\n  }\n  return cover\n}\n\nconst curves = new Map<string, (time: number) => number>()\n\n/** An easing, any CSS easing, as a function from time to progress, both from 0 to 1, as the browser reads it once and remembers. */\nfunction easingCurve(easing: string): (time: number) => number {\n  const known = curves.get(easing)\n  if (known) return known\n  // The probe never plays: it only reads progress at moments of a span of 1.\n  const duration = 1\n  const SAMPLES = 200\n  let curve: (time: number) => number\n  try {\n    const probe = new Animation(\n      new KeyframeEffect(null, null, { duration, easing, fill: 'both' }),\n      document.timeline,\n    )\n    const table = Array.from({ length: SAMPLES + 1 }, (_, step) => {\n      probe.currentTime = (step / SAMPLES) * duration\n      return Number(probe.effect?.getComputedTiming().progress ?? step / SAMPLES)\n    })\n    curve = (time) => {\n      const at = Math.min(SAMPLES, Math.max(0, time * SAMPLES))\n      const below = Math.floor(at)\n      const low = table[below] ?? 0\n      const high = table[Math.min(SAMPLES, below + 1)] ?? low\n      return low + (high - low) * (at - below)\n    }\n  } catch {\n    curve = (time) => time\n  }\n  curves.set(easing, curve)\n  return curve\n}\n\n/** The hole a clip of insets leaves in a box of `box`. */\nfunction holeOf(clip: string, box: Size): Rect | null {\n  const insets = insetsOf(clip)\n  if (!insets) return null\n  const [top, right, bottom, left] = insets\n  return {\n    x: left,\n    y: top,\n    width: box.width - left - right,\n    height: box.height - top - bottom,\n  }\n}\n\n/** How far each part of a turn has got, from 0 to 1, or past 1 when its easing overshoots. */\ninterface TurnProgress {\n  translate: number\n  rotate: number\n  scale: number\n  pivot: number\n  hole: number\n}\n\n/**\n * Scales `frames` up through a turn just enough to cover the crop, in step\n * with the transitions that make the turn: each one's own start value,\n * start, duration and easing, since a transition turned back runs shorter\n * and a nudge or drag mid-turn starts a part again. So the feel, a nested\n * `data-feel` and reduced motion all hold. Returns what it plays, for the\n * next paint to stop; it stops by itself if the turn is cut off.\n */\nfunction coverTurn(\n  frames: HTMLElement[],\n  image: HTMLElement | null,\n  hole: HTMLElement | null,\n  box: Size,\n  to: TurnPose,\n  natural: Size,\n  round: boolean,\n  again: () => void,\n): Animation[] {\n  const frame = frames[0]\n  if (!frame) return []\n  const turn = runningTransitions(frame, { property: 'rotate' })[0]\n  if (!turn) return []\n  // A part already moving when the turn began started a frame or two before it,\n  // which only shows once the turn has a start of its own.\n  if (turn.startTime === null) void turn.ready.then(again, () => {})\n  const running = {\n    translate: runningTransitions(frame, { property: 'translate' })[0],\n    rotate: turn,\n    scale: runningTransitions(frame, { property: 'scale' })[0],\n    pivot: image ? runningTransitions(image, { property: 'translate' })[0] : undefined,\n    hole: hole ? runningTransitions(hole, { property: 'clip-path' })[0] : undefined,\n  }\n  // Each part moves from where its own transition started, or is already where it goes.\n  const startOf = (transition: CSSTransition | undefined, property: string) => {\n    const value = (transition?.effect as KeyframeEffect | null)?.getKeyframes()[0]?.[\n      property\n    ]\n    return typeof value === 'string' ? value : null\n  }\n  const translate = startOf(running.translate, 'translate')\n  const rotate = startOf(running.rotate, 'rotate')\n  const scale = startOf(running.scale, 'scale')\n  const pivot = startOf(running.pivot, 'translate')\n  const clip = startOf(running.hole, 'clipPath')\n  const pivotFrom = pivot === null ? null : translateOf(pivot)\n  const from: TurnPose = {\n    translate: translate === null ? to.translate : translateOf(translate),\n    rotate: rotate === null ? to.rotate : Number.parseFloat(rotate) || 0,\n    scale: scale === null ? to.scale : Number.parseFloat(scale) || 1,\n    pivot: pivotFrom === null ? to.pivot : [-pivotFrom[0], -pivotFrom[1]],\n    hole: (clip === null ? null : holeOf(clip, box)) ?? to.hole,\n  }\n  const clockOf = (transition: CSSTransition | undefined) => {\n    if (!transition) return null\n    const effect = transition.effect as KeyframeEffect\n    const duration = Number(effect.getComputedTiming().duration) || 0\n    // A transition keeps its easing on its timing, not on its keyframes.\n    const easing = effect.getTiming().easing ?? 'linear'\n    return {\n      // How far into the turn it started, in the turn's own time, so a slowed turn\n      // holds too. Before the turn has a start, both read 0: it is asked again then.\n      delay: Number(turn.currentTime ?? 0) - Number(transition.currentTime ?? 0),\n      duration,\n      curve: easingCurve(easing),\n    }\n  }\n  const clocks = {\n    translate: clockOf(running.translate),\n    rotate: clockOf(running.rotate),\n    scale: clockOf(running.scale),\n    pivot: clockOf(running.pivot),\n    hole: clockOf(running.hole),\n  }\n  const span = Math.max(\n    ...Object.values(clocks).map((clock) =>\n      clock === null ? 0 : clock.delay + clock.duration,\n    ),\n  )\n  if (!(span > 0)) return []\n  const STEPS = 40\n  const scales = Array.from({ length: STEPS + 1 }, (_, step) => {\n    const time = (span * step) / STEPS\n    const at = (clock: (typeof clocks)['rotate']) =>\n      clock && clock.duration > 0\n        ? clock.curve(Math.min(1, Math.max(0, (time - clock.delay) / clock.duration)))\n        : 1\n    return turnCover(\n      from,\n      to,\n      natural,\n      {\n        translate: at(clocks.translate),\n        rotate: at(clocks.rotate),\n        scale: at(clocks.scale),\n        pivot: at(clocks.pivot),\n        hole: at(clocks.hole),\n      },\n      round,\n    )\n  })\n  if (scales.every((scale) => scale <= 1.0005)) return []\n  // While it covers, it reaches up to 2px past the crop, so the straight\n  // lines between its steps never leave a sliver; it tapers as it nears 1,\n  // so it never jumps, at the end or when a turn takes over from another.\n  const bleed = 2 / Math.max(1, Math.min(to.hole.width, to.hole.height) / 2)\n  const keyframes = scales.map((scale) => ({\n    transform: `scale(${scale + Math.min(bleed, scale - 1)})`,\n  }))\n  const covers = frames.map((element) => {\n    const cover = element.animate(keyframes, {\n      duration: span,\n      easing: 'linear',\n      id: FOLLOWS_TRANSITION,\n    })\n    // A transition that takes over from a running one starts on this frame's\n    // clock, a frame before a new animation would, so the cover takes its start.\n    cover.playbackRate = turn.playbackRate\n    if (turn.startTime != null) cover.startTime = turn.startTime\n    return cover\n  })\n  // A turn cut off (a resize turns transitions off) lands at rest, so its cover goes with it.\n  turn.addEventListener('cancel', () => covers.forEach((cover) => cover.cancel()), {\n    once: true,\n  })\n  return covers\n}\n\n/** A clip to `rect` inside a box of `size`, `grow` px larger on every side, and round for a circle. */\nfunction insetClip(rect: Rect, size: Size, circle: boolean, grow = 0) {\n  const top = round(rect.y - grow)\n  const right = round(size.width - rect.x - rect.width - grow)\n  const bottom = round(size.height - rect.y - rect.height - grow)\n  const left = round(rect.x - grow)\n  return `inset(${top}px ${right}px ${bottom}px ${left}px${circle ? ` round ${round(rect.width / 2 + grow)}px` : ''})`\n}\n\n/** Where each handle sits on the selection, as fractions of its width and height. */\nconst HANDLE_SPOTS: Record<ImageCropperHandlePosition, readonly [number, number]> = {\n  n: [0.5, 0],\n  e: [1, 0.5],\n  s: [0.5, 1],\n  w: [0, 0.5],\n  ne: [1, 0],\n  nw: [0, 0],\n  se: [1, 1],\n  sw: [0, 1],\n}\n\n/**\n * The styles that draw a crop in a viewport `stage` large: the image's\n * frame and `<img>`, the hole the crop shows through and the hairline round\n * it, the thirds and each handle's point, as the custom properties the parts\n * read.\n */\nfunction viewportStyles(\n  natural: Size,\n  angle: number,\n  layout: ReturnType<typeof cropLayout>,\n  crop: Crop,\n  stage: Size,\n  circle: boolean,\n): Record<string, string> {\n  const { transform, selection } = layout\n  const placement = imagePlacement(natural, angle, transform, crop)\n  const styles: Record<string, string> = {\n    '--image-cropper-frame-translate': placement.frame.translate,\n    '--image-cropper-frame-rotate': placement.frame.rotate,\n    '--image-cropper-frame-scale': placement.frame.scale,\n    '--image-cropper-image-width': placement.image.width,\n    '--image-cropper-image-height': placement.image.height,\n    '--image-cropper-image-translate': placement.image.translate,\n    '--image-cropper-image-scale': placement.image.scale,\n    '--image-cropper-hole': insetClip(selection, stage, circle),\n    '--image-cropper-ring': insetClip(selection, stage, circle, 1),\n    '--image-cropper-selection-width': `${round(selection.width)}px`,\n    '--image-cropper-selection-height': `${round(selection.height)}px`,\n  }\n  for (const third of [1, 2]) {\n    styles[`--image-cropper-third-x${third}`] =\n      `${round(selection.x + (selection.width * third) / 3)}px 0px`\n    styles[`--image-cropper-third-y${third}`] =\n      `0px ${round(selection.y + (selection.height * third) / 3)}px`\n  }\n  for (const [position, [across, down]] of Object.entries(HANDLE_SPOTS)) {\n    // Centred on its point: a percentage of the handle's own size.\n    styles[`--image-cropper-handle-${position}`] =\n      `calc(${round(selection.x + selection.width * across)}px - 50%) calc(${round(selection.y + selection.height * down)}px - 50%)`\n  }\n  return styles\n}\n\n// ---------------------------------------------------------------------------\n// The root\n\ntype CropperState = TypesOf<typeof imageCropper>['state']\n\n/** Changes a pointer, the wheel or the zoom thumb makes: what draws the crop follows them at once. */\nconst FOLLOWED = new Set<ImageCropperCropChangeReason>([\n  'drag',\n  'pinch',\n  'wheel',\n  'zoom-input',\n])\n\n/**\n * ui-sdk's state as it is this moment, for the parts that draw the crop: a\n * pointer changes it on every frame, and they read it and write their styles\n * themselves, so nothing re-renders while it moves.\n */\ninterface CropperFeed {\n  read: () => CropperState\n  subscribe: (listener: () => void) => () => void\n  /** Whether the last change came from a pointer, the wheel or the zoom thumb, and hasn't been committed yet. */\n  following: () => boolean\n}\n\ninterface ImageCropperContextValue {\n  handle: PrimitiveHandle<typeof imageCropper>\n  feed: CropperFeed\n  src: string | undefined\n}\n\nconst ImageCropperContext = createContext<ImageCropperContextValue | null>(null)\n\nfunction useImageCropper() {\n  const context = use(ImageCropperContext)\n  if (!context) throw new Error('Image cropper parts go inside an ImageCropper.')\n  return context\n}\n\n/** The crop can be drawn: the image has loaded and the viewport has room. */\nfunction drawable(state: CropperState) {\n  const { crop, natural, box } = state\n  if (state.status !== 'loaded' || !crop || !natural || !box) return null\n  if (box.width <= 0 || box.height <= 0) return null\n  return {\n    crop,\n    natural,\n    box: { x: box.left, y: box.top, width: box.width, height: box.height },\n  }\n}\n\ntype ImageCropperProps = OptionsOf<typeof imageCropper> &\n  Omit<ComponentProps<'div'>, 'children' | 'defaultValue' | 'onChange'> & {\n    children?: ReactNode\n  }\n\n/** Holds the image and its crop: ui-sdk's Image cropper. */\nfunction ImageCropper({\n  src,\n  crop,\n  defaultCrop,\n  onCropChange,\n  onCropCommit,\n  mode = 'frame',\n  aspectRatio,\n  shape = 'rectangle',\n  minWidth,\n  minHeight,\n  maxZoom = 3,\n  disabled,\n  controller,\n  debug,\n  className,\n  children,\n  ...props\n}: ImageCropperProps) {\n  const following = useRef(false)\n  const covering = useRef<Crop | null>(null)\n  const [committed] = useState(() => new Set<() => void>())\n  const handle = usePrimitive(imageCropper, {\n    src,\n    crop,\n    defaultCrop,\n    mode,\n    // A circle is always as wide as it is high.\n    aspectRatio: shape === 'circle' ? 1 : aspectRatio,\n    shape,\n    minWidth,\n    minHeight,\n    maxZoom,\n    disabled,\n    controller,\n    debug,\n    onCropChange: (next, details) => {\n      // ui-sdk starts a box at four fifths of the largest crop; Kino's starts at the largest,\n      // so the image opens whole at a zoom of 1. ui-sdk takes a crop only once it has one, so\n      // its first lands and the largest replaces it as the load commits, before a paint, and\n      // only the largest reaches a buyer.\n      const natural = handle.instance.get().natural\n      if (details.reason === 'image-load' && mode === 'box' && natural) {\n        const full = largestCrop(natural, shape === 'circle' ? 1 : aspectRatio)\n        if (!sameRect(next, full)) {\n          covering.current = full\n          return\n        }\n      }\n      following.current = FOLLOWED.has(details.reason)\n      onCropChange?.(next, details)\n    },\n    onCropCommit: (next, details) => {\n      const cover = covering.current\n      if (cover && details.reason === 'image-load') {\n        covering.current = null\n        handle.api.setCrop(cover, { reason: 'image-load', event: details.event })\n        return\n      }\n      following.current = false\n      for (const listener of committed) listener()\n      onCropCommit?.(next, details)\n      if (details.reason === 'rotate-press' || details.reason === 'rotate-key')\n        announce(`Rotated to ${next.rotation} degrees`)\n    },\n  })\n  const { instance } = handle\n  const feed = useMemo<CropperFeed>(\n    () => ({\n      read: () => instance.get(),\n      subscribe(listener) {\n        const unsubscribe = instance.subscribe(listener)\n        committed.add(listener)\n        return () => {\n          unsubscribe()\n          committed.delete(listener)\n        }\n      },\n      following: () => following.current,\n    }),\n    [instance, committed],\n  )\n  return usePart(\n    handle,\n    'root',\n    {},\n    {\n      ...props,\n      className: cn('flex w-full min-w-0 flex-col gap-3', className),\n      children: (\n        <ImageCropperContext value={{ handle, feed, src }}>\n          {children}\n        </ImageCropperContext>\n      ),\n    },\n    'div',\n  )\n}\n\n// ---------------------------------------------------------------------------\n// The viewport and what it shows\n\n/** A layer that glides on `layout`, and follows at once while followed or while the viewport resizes. */\nconst glideClassName =\n  'transition-[translate,scale,rotate,clip-path] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/cropper:duration-0 group-data-resizing/cropper:transition-none motion-reduce:transition-none'\n\n/** The image's frame: at the crop's centre, turned and scaled about it. */\nconst frameClassName = cn(\n  'absolute top-0 left-0 origin-top-left [translate:var(--image-cropper-frame-translate)] [rotate:var(--image-cropper-frame-rotate)] [scale:var(--image-cropper-frame-scale)]',\n  glideClassName,\n)\n\n/** The image in its frame: at its own size, moved so the crop's centre is on the frame's corner, and mirrored for a flip. */\nconst pictureClassName = cn(\n  'absolute top-0 left-0 h-(--image-cropper-image-height) w-(--image-cropper-image-width) max-w-none [translate:var(--image-cropper-image-translate)] [scale:var(--image-cropper-image-scale)]',\n  // The flip doesn't glide: the paint that changes it moves everything at once.\n  'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/cropper:duration-0 group-data-resizing/cropper:transition-none motion-reduce:transition-none',\n)\n\n/**\n * Where the image and its crop show: ui-sdk's viewport, which a pointer pans\n * in a frame and the wheel zooms, and whose padding keeps the crop off its\n * edges. It draws whatever is inside it from ui-sdk's state.\n */\nfunction ImageCropperViewport({\n  className,\n  ref,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperViewportPrimitive>, 'className'> & {\n  className?: string\n}) {\n  const { feed } = useImageCropper()\n  const own = useRef<HTMLDivElement>(null)\n  // Placed in pixels worked out from its size, so while it resizes nothing glides.\n  const refs = useMemo(() => mergeRefs(own, markResizing, ref), [ref])\n  useLayoutEffect(() => {\n    let painted = false\n    /** The angle last drawn, so a turn goes the shorter way round from it. */\n    let angle: number | null = null\n    let flips = ''\n    let covers: Animation[] = []\n    const paint = () => {\n      const element = own.current\n      const state = feed.read()\n      const ready = drawable(state)\n      if (!element || !ready) {\n        painted = false\n        angle = null\n        return\n      }\n      const { crop, natural, box } = ready\n      const mirrored = mirrorOf(crop).join()\n      // Nothing glides into place on first paint, and a flip lands at once.\n      const instant = !painted || mirrored !== flips\n      painted = true\n      flips = mirrored\n      element.toggleAttribute('data-following', feed.following() || instant)\n      const last = angle\n      angle = last === null ? crop.rotation : nextAngle(last, crop.rotation)\n      const stage = { width: element.clientWidth, height: element.clientHeight }\n      const layout = cropLayout(crop, natural, box, state.mode, state.aspectRatio)\n      const circle = state.shape === 'circle'\n      for (const [name, value] of Object.entries(\n        viewportStyles(natural, angle, layout, crop, stage, circle),\n      ))\n        element.style.setProperty(name, value)\n      const frames = [\n        ...element.querySelectorAll<HTMLElement>('[data-image-cropper-frame]'),\n      ]\n      // A turn, and any move while one plays, works its cover out again.\n      const recover =\n        !instant &&\n        ((last !== null && angle !== last) ||\n          (frames[0] !== undefined &&\n            runningTransitions(frames[0], { property: 'rotate' }).length > 0))\n      if (!recover) return\n      for (const cover of covers) cover.cancel()\n      // Once everything that turns has its transition.\n      const made = coverTurn(\n        frames,\n        frames[0]?.querySelector('img') ?? null,\n        element.querySelector('[data-image-cropper-hole]'),\n        stage,\n        { ...imagePose(natural, angle, layout.transform, crop), hole: layout.selection },\n        natural,\n        circle,\n        () => {\n          if (covers === made) paint()\n        },\n      )\n      covers = made\n    }\n    paint()\n    const unsubscribe = feed.subscribe(paint)\n    return () => {\n      unsubscribe()\n      for (const cover of covers) cover.cancel()\n    }\n  }, [feed])\n  // ui-sdk zooms on every wheel over a frame. It gets the wheel only once the crop has focus, or with Ctrl or Cmd, as a trackpad's pinch is sent, so the page still scrolls past it.\n  useEffect(() => {\n    const element = own.current\n    if (!element) return\n    const gate = (event: WheelEvent) => {\n      if (event.ctrlKey || event.metaKey || element.contains(document.activeElement))\n        return\n      event.stopImmediatePropagation()\n    }\n    element.addEventListener('wheel', gate, { capture: true })\n    return () => element.removeEventListener('wheel', gate, { capture: true })\n  }, [])\n  return (\n    <ImageCropperViewportPrimitive\n      ref={refs}\n      className={cn(\n        'group/cropper bg-muted relative isolate h-80 w-full overflow-hidden rounded-(--surface-radius) select-none',\n        // ui-sdk's box: room round a frame for the image around it, and round a box for its handles.\n        'data-[mode=box]:p-4 data-[mode=frame]:p-6',\n        // A frame is dragged; ui-sdk's own cursor for it is `move`.\n        'data-[mode=frame]:cursor-grab! data-[mode=frame]:data-dragging:cursor-grabbing! data-disabled:cursor-default!',\n        // The selection and the handles take focus inside it, and it shows the ring.\n        'has-focus-visible:ring-ring/50 has-focus-visible:ring-3 has-focus-visible:outline-hidden',\n        'data-disabled:pointer-events-none data-disabled:opacity-50',\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </ImageCropperViewportPrimitive>\n  )\n}\n\n/**\n * The image: dimmed outside the crop, with a hairline round the crop, and at\n * full brightness through it.\n * ui-sdk's image is the one at full brightness, which it loads and names.\n */\nfunction ImageCropperImage({\n  alt,\n  crossOrigin,\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperImagePrimitive>, 'className'> & {\n  alt: string\n  className?: string\n}) {\n  const { src } = useImageCropper()\n  return (\n    <>\n      {/* The whole image, dimmed outside the crop. */}\n      <div\n        aria-hidden\n        className='pointer-events-none absolute inset-0 group-data-error/cropper:hidden group-data-loading/cropper:invisible'\n      >\n        <div data-image-cropper-frame='' className={frameClassName}>\n          {/* oxlint-disable-next-line nextjs/no-img-element -- a registry item can't use next/image */}\n          <img\n            src={src}\n            alt=''\n            crossOrigin={crossOrigin}\n            draggable={false}\n            className={pictureClassName}\n          />\n        </div>\n        <div className='absolute inset-0 bg-black/55 forced-color-adjust-none' />\n      </div>\n      {/* A hairline round the crop, one pixel outside it, under the crop. */}\n      <div\n        aria-hidden\n        className={cn(\n          'pointer-events-none absolute inset-0 bg-white/80 [clip-path:var(--image-cropper-ring,inset(50%))] group-data-error/cropper:hidden group-data-loading/cropper:invisible forced-colors:bg-[CanvasText]',\n          glideClassName,\n        )}\n      />\n      {/* The crop at full brightness: the same image, clipped to it. */}\n      <div\n        data-image-cropper-hole=''\n        className={cn(\n          'pointer-events-none absolute inset-0 [clip-path:var(--image-cropper-hole,inset(50%))] group-data-error/cropper:hidden group-data-loading/cropper:invisible',\n          glideClassName,\n        )}\n      >\n        <div data-image-cropper-frame='' className={frameClassName}>\n          <ImageCropperImagePrimitive\n            alt={alt}\n            crossOrigin={crossOrigin}\n            // ui-sdk places the image with `left`, `top`, `width`, `height` and `transform`; its frame places it instead.\n            className={cn(\n              pictureClassName,\n              'top-0! left-0! h-(--image-cropper-image-height)! w-(--image-cropper-image-width)! transform-none!',\n              className,\n            )}\n            {...props}\n          />\n        </div>\n      </div>\n    </>\n  )\n}\n\n/**\n * The crop: ui-sdk's selection, a slider that a box drags and the keys move,\n * as large as the viewport and clipped to the crop.\n */\nfunction ImageCropperSelection({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperSelectionPrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <ImageCropperSelectionPrimitive\n      // ui-sdk places the selection with `left`, `top`, `width` and `height`; a clip places it instead, so its edge glides.\n      className={cn(\n        'top-0! left-0! h-full! w-full! [clip-path:var(--image-cropper-hole,inset(50%))] focus-visible:outline-hidden',\n        glideClassName,\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/** Thirds across the crop, while a pointer drags it. Goes inside the selection. */\nfunction ImageCropperGrid({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperGridPrimitive>, 'className' | 'children'> & {\n  className?: string\n}) {\n  return (\n    <ImageCropperGridPrimitive\n      className={cn(\n        'opacity-0 data-dragging:opacity-100',\n        // It fades in on `enter` and out on `exit`.\n        'transition-opacity duration-(--motion-exit-duration) ease-(--motion-exit-easing) data-dragging:duration-(--motion-enter-duration) data-dragging:ease-(--motion-enter-easing)',\n        className,\n      )}\n      {...props}\n    >\n      {(['x1', 'y1', 'x2', 'y2'] as const).map((third) => (\n        <span\n          key={third}\n          className={cn(\n            'absolute top-0 left-0 bg-white/60 forced-colors:bg-[CanvasText]',\n            third.startsWith('x') ? 'h-full w-px' : 'h-px w-full',\n            third === 'x1' && '[translate:var(--image-cropper-third-x1)]',\n            third === 'x2' && '[translate:var(--image-cropper-third-x2)]',\n            third === 'y1' && '[translate:var(--image-cropper-third-y1)]',\n            third === 'y2' && '[translate:var(--image-cropper-third-y2)]',\n            glideClassName,\n          )}\n        />\n      ))}\n    </ImageCropperGridPrimitive>\n  )\n}\n\n/** Each handle's point, in the classes Tailwind reads. */\nconst HANDLE_PLACES: Record<ImageCropperHandlePosition, string> = {\n  n: '[translate:var(--image-cropper-handle-n)]',\n  e: '[translate:var(--image-cropper-handle-e)]',\n  s: '[translate:var(--image-cropper-handle-s)]',\n  w: '[translate:var(--image-cropper-handle-w)]',\n  ne: '[translate:var(--image-cropper-handle-ne)]',\n  nw: '[translate:var(--image-cropper-handle-nw)]',\n  se: '[translate:var(--image-cropper-handle-se)]',\n  sw: '[translate:var(--image-cropper-handle-sw)]',\n}\n\n/** A corner's mark: its arms, and the offset that puts its outer edge on the crop's corner. */\nconst CORNER_MARKS: Partial<Record<ImageCropperHandlePosition, string>> = {\n  nw: 'top-[calc(50%-3px)] left-[calc(50%-3px)] border-t-[3px] border-l-[3px]',\n  ne: 'top-[calc(50%-3px)] left-[calc(50%-17px)] border-t-[3px] border-r-[3px]',\n  se: 'top-[calc(50%-17px)] left-[calc(50%-17px)] border-r-[3px] border-b-[3px]',\n  sw: 'top-[calc(50%-17px)] left-[calc(50%-3px)] border-b-[3px] border-l-[3px]',\n}\n\n/** A rectangle's side, as long as the selection less a corner's reach at each end. */\nconst EDGE_LENGTHS: Partial<Record<ImageCropperHandlePosition, string>> = {\n  n: 'w-[max(0px,calc(var(--image-cropper-selection-width)-1.5rem))] pointer-coarse:w-[max(0px,calc(var(--image-cropper-selection-width)-2.5rem))]',\n  s: 'w-[max(0px,calc(var(--image-cropper-selection-width)-1.5rem))] pointer-coarse:w-[max(0px,calc(var(--image-cropper-selection-width)-2.5rem))]',\n  e: 'h-[max(0px,calc(var(--image-cropper-selection-height)-1.5rem))] pointer-coarse:h-[max(0px,calc(var(--image-cropper-selection-height)-2.5rem))]',\n  w: 'h-[max(0px,calc(var(--image-cropper-selection-height)-1.5rem))] pointer-coarse:h-[max(0px,calc(var(--image-cropper-selection-height)-2.5rem))]',\n}\n\n/**\n * A side or corner of a box's selection, by `position`: ui-sdk's handle, a\n * slider whose arrows move its edges. A corner shows its mark, a side of a\n * rectangle runs along it, and a side of a circle shows a dot.\n */\nfunction ImageCropperHandle({\n  position,\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperHandlePrimitive>, 'className' | 'children'> & {\n  className?: string\n}) {\n  const corner = CORNER_MARKS[position]\n  return (\n    <ImageCropperHandlePrimitive\n      position={position}\n      className={(state) =>\n        cn(\n          // ui-sdk places a handle with `left` and `top`; it takes its point from `translate` instead, so it glides.\n          'group/handle top-0! left-0! rounded-full focus-visible:ring-3 focus-visible:ring-white focus-visible:outline-hidden',\n          // At least 24px to take hold of by mouse, the quality bar's smallest target, and 40px by touch.\n          'size-6 pointer-coarse:size-10',\n          // A rectangle's side runs along it, between its corners.\n          !corner && state.shape === 'rectangle' && EDGE_LENGTHS[position],\n          HANDLE_PLACES[position],\n          glideClassName,\n          className,\n        )\n      }\n      {...props}\n    >\n      {corner ? (\n        <span\n          aria-hidden\n          className={cn(\n            'pointer-events-none absolute size-5 border-white drop-shadow-[0_0_1px_rgb(0_0_0/0.6)] forced-colors:border-[CanvasText]',\n            corner,\n          )}\n        />\n      ) : (\n        <span\n          aria-hidden\n          className='pointer-events-none absolute top-1/2 left-1/2 hidden size-3 -translate-1/2 rounded-full bg-white shadow-[0_0_0_1px_rgb(0_0_0/0.25)] group-data-[shape=circle]/cropper:block forced-colors:bg-[CanvasText]'\n        />\n      )}\n    </ImageCropperHandlePrimitive>\n  )\n}\n\nconst INSTRUCTIONS: Record<ImageCropperMode, string> = {\n  frame:\n    'Drag or use the arrow keys to move the crop over the image, pinch, scroll or press plus and minus to zoom, and press R to rotate, or Shift and R to rotate back.',\n  box: 'Drag or use the arrow keys to move the selection, Tab to its edges and corners to resize it, press plus and minus to zoom, and press R to rotate, or Shift and R to rotate back.',\n}\n\n/** Says the image failed, once. */\nfunction LoadFailed() {\n  useEffect(() => {\n    announce('The image couldn’t be loaded.')\n  }, [])\n  return (\n    <div className='text-muted-foreground absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 text-center text-sm [&_svg]:size-5'>\n      <IconPlaceholder\n        lucide='ImageOffIcon'\n        tabler='IconPhotoOff'\n        phosphor='ImageBrokenIcon'\n        hugeicons='ImageNotFound01Icon'\n        remixicon='RiImageCircleLine'\n        aria-hidden\n      />\n      <span className='text-foreground'>The image couldn’t be loaded.</span>\n    </div>\n  )\n}\n\n/** A spinner once the image has taken a moment to load. */\nfunction Loading({ loading }: { loading: boolean }) {\n  const spinning = useSpinner(loading)\n  return loading && spinning ? (\n    <div className='text-muted-foreground absolute inset-0 flex items-center justify-center'>\n      <Spinner aria-label='Loading image' />\n    </div>\n  ) : null\n}\n\nconst RECTANGLE_HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const\nconst CIRCLE_HANDLES = ['n', 'e', 's', 'w'] as const\n\n/**\n * The ready-made area: the viewport with the image, the crop and its thirds,\n * the handles a box resizes with, and the loading and failed states.\n */\nfunction ImageCropperArea({\n  alt,\n  crossOrigin,\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperViewport>, 'children'> & {\n  /** What the image shows, for a screen reader. */\n  alt: string\n  crossOrigin?: ComponentProps<'img'>['crossOrigin']\n}) {\n  const instructionsId = useId()\n  return (\n    <ImageCropperViewport className={className} {...props}>\n      {({ loading, error, mode, shape }) => (\n        <>\n          {error ? (\n            <LoadFailed />\n          ) : (\n            <p id={instructionsId} className='sr-only'>\n              {INSTRUCTIONS[mode]}\n            </p>\n          )}\n          <Loading loading={loading} />\n          <ImageCropperImage alt={alt} crossOrigin={crossOrigin} />\n          <ImageCropperSelection aria-describedby={error ? undefined : instructionsId}>\n            <ImageCropperGrid />\n          </ImageCropperSelection>\n          {mode === 'box'\n            ? (shape === 'circle' ? CIRCLE_HANDLES : RECTANGLE_HANDLES).map(\n                (position) => <ImageCropperHandle key={position} position={position} />,\n              )\n            : null}\n        </>\n      )}\n    </ImageCropperViewport>\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Controls\n\n/** How much the zoom buttons zoom by, as ui-sdk's plus and minus keys do. */\nconst ZOOM_STEP = 1.25\n\n/** Where the zoom is between 1 and the most, from 0 to 100. */\nfunction zoomPercent(zoom: number, maxZoom: number) {\n  if (!(maxZoom > 1)) return 0\n  return Math.min(100, Math.max(0, ((zoom - 1) / (maxZoom - 1)) * 100))\n}\n\n/** Which ends of the zoom it is at, as one word, so a render only follows a change of it. */\nfunction zoomEnds(state: CropperState, zoom: number) {\n  if (state.disabled || state.status !== 'loaded' || !state.crop || !state.natural)\n    return 'inactive'\n  if (zoom <= 1.001) return 'out'\n  if (zoom >= state.maxZoom - 0.001) return 'in'\n  return 'between'\n}\n\n/**\n * Zooms the crop in and out: ui-sdk's zoom, a range input, drawn as Kino's\n * Slider, with a button at each end.\n */\nfunction ImageCropperZoom({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof ImageCropperZoomPrimitive>, 'className'> & {\n  /** For the row's layout: the buttons and the slider sit in it. */\n  className?: string\n}) {\n  const { handle, feed } = useImageCropper()\n  const ends = useSyncExternalStore(\n    feed.subscribe,\n    () => zoomEnds(feed.read(), handle.api.getZoom()),\n    () => 'inactive',\n  )\n  const controlRef = useRef<HTMLDivElement>(null)\n  useLayoutEffect(() => {\n    const paint = () => {\n      const control = controlRef.current\n      if (!control) return\n      control.toggleAttribute('data-following', feed.following())\n      control.style.setProperty(\n        '--image-cropper-zoom',\n        `${zoomPercent(handle.api.getZoom(), feed.read().maxZoom)}`,\n      )\n    }\n    paint()\n    return feed.subscribe(paint)\n  }, [feed, handle])\n  const inactive = ends === 'inactive'\n  const step = (factor: number) => {\n    handle.api.setZoom(handle.api.getZoom() * factor)\n    announce(`Zoom ${Math.round(handle.api.getZoom() * 100)}%`)\n  }\n  return (\n    <div\n      data-image-cropper-zoom=''\n      className={cn('flex min-w-0 items-center gap-4', className)}\n    >\n      <Button\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom out'\n        // It stays in the tab order at the end of its range, so focus isn't lost when it gets there.\n        focusableWhenDisabled={!inactive}\n        disabled={inactive || ends === 'out'}\n        onClick={() => step(1 / ZOOM_STEP)}\n      >\n        <IconPlaceholder\n          lucide='ZoomOutIcon'\n          tabler='IconZoomOut'\n          phosphor='MagnifyingGlassMinusIcon'\n          hugeicons='SearchMinusIcon'\n          remixicon='RiZoomOutLine'\n          aria-hidden\n        />\n      </Button>\n      <div\n        ref={controlRef}\n        className={cn(\n          trackDirClassName,\n          'group/thumb @container relative flex h-(--control-height-xs) min-w-0 flex-1 touch-none items-center select-none has-disabled:opacity-50',\n        )}\n      >\n        <span aria-hidden className={sliderTrackClassName}>\n          <span\n            className={cn(\n              trackFillClassName,\n              'pointer-events-none inset-x-0',\n              'transition-[clip-path] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/thumb:duration-0 motion-reduce:transition-none',\n              '[clip-path:inset(0_calc(100%-var(--image-cropper-zoom)*1%)_0_0_round_9999px)] rtl:[clip-path:inset(0_0_0_calc(100%-var(--image-cropper-zoom)*1%)_round_9999px)]',\n            )}\n          />\n        </span>\n        <span\n          aria-hidden\n          className={cn(\n            'pointer-events-none absolute start-0 top-1/2 flex size-6 [translate:calc(var(--track-dir)*(var(--image-cropper-zoom)*1cqw-50%))_-50%] items-center justify-center rounded-full',\n            'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/thumb:duration-0 motion-reduce:transition-none',\n          )}\n        >\n          <span className={sliderThumbClassName} />\n        </span>\n        <ImageCropperZoomPrimitive\n          // The range input takes the pointer and the keys; the track and thumb under it draw it.\n          className='absolute inset-0 m-0 size-full appearance-none opacity-0 disabled:pointer-events-none [&::-moz-range-thumb]:size-px [&::-webkit-slider-thumb]:size-px [&::-webkit-slider-thumb]:appearance-none'\n          {...props}\n        />\n      </div>\n      <Button\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom in'\n        focusableWhenDisabled={!inactive}\n        disabled={inactive || ends === 'in'}\n        onClick={() => step(ZOOM_STEP)}\n      >\n        <IconPlaceholder\n          lucide='ZoomInIcon'\n          tabler='IconZoomIn'\n          phosphor='MagnifyingGlassPlusIcon'\n          hugeicons='SearchAddIcon'\n          remixicon='RiZoomInLine'\n          aria-hidden\n        />\n      </Button>\n    </div>\n  )\n}\n\n/** Turns the image a quarter clockwise, keeping the same part of it in the crop: ui-sdk's rotate, as Kino's Button. */\nfunction ImageCropperRotate({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof Button>, 'onClick' | 'children'>) {\n  return (\n    <ImageCropperRotatePrimitive\n      render={\n        <Button\n          data-image-cropper-rotate=''\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Rotate clockwise'\n          className={className}\n          {...props}\n        />\n      }\n    >\n      <IconPlaceholder\n        lucide='RotateCwIcon'\n        tabler='IconRotateClockwise'\n        phosphor='ArrowClockwiseIcon'\n        hugeicons='RotateClockwiseIcon'\n        remixicon='RiClockwiseLine'\n        aria-hidden\n      />\n    </ImageCropperRotatePrimitive>\n  )\n}\n\n/**\n * The crop as it will look, live, such as the avatar it becomes: it fills\n * its own box, which its class sizes, and is round for a round crop.\n */\nfunction ImageCropperPreview({ className, ref, ...props }: ComponentProps<'div'>) {\n  const { src, feed } = useImageCropper()\n  const shape = useSyncExternalStore(\n    feed.subscribe,\n    () => feed.read().shape,\n    () => 'rectangle' as ImageCropperShape,\n  )\n  const loaded = useSyncExternalStore(\n    feed.subscribe,\n    () => feed.read().status === 'loaded',\n    () => false,\n  )\n  const [box, setBox] = useState<Size | null>(null)\n  const boxRef = useRef<HTMLDivElement>(null)\n  const boxRefs = useMemo(() => mergeRefs(boxRef, markResizing, ref), [ref])\n  const frameRef = useRef<HTMLDivElement>(null)\n  const imageRef = useRef<HTMLImageElement>(null)\n  useEffect(() => {\n    const element = boxRef.current\n    if (!element) return\n    const observer = new ResizeObserver(([entry]) =>\n      flushSync(() =>\n        setBox({\n          width: entry.contentRect.width,\n          height: entry.contentRect.height,\n        }),\n      ),\n    )\n    observer.observe(element)\n    return () => observer.disconnect()\n  }, [])\n  // It follows ui-sdk's state, so it keeps up with a drag without rendering.\n  useLayoutEffect(() => {\n    let angle: number | null = null\n    let flips = ''\n    let covers: Animation[] = []\n    const paint = () => {\n      const element = boxRef.current\n      const state = feed.read()\n      const { crop, natural } = state\n      if (!element || !natural || !crop || !box) return\n      const mirrored = mirrorOf(crop).join()\n      const instant = angle === null || mirrored !== flips\n      flips = mirrored\n      element.toggleAttribute('data-following', feed.following() || instant)\n      const last = angle\n      angle = last === null ? crop.rotation : nextAngle(last, crop.rotation)\n      const frame = coverRect(imageRect(box), crop.width / crop.height)\n      const transform = viewTransform(crop, frame)\n      const recover =\n        !instant &&\n        ((last !== null && angle !== last) ||\n          (frameRef.current !== null &&\n            runningTransitions(frameRef.current, { property: 'rotate' }).length > 0))\n      const placement = imagePlacement(natural, angle, transform, crop)\n      if (frameRef.current) Object.assign(frameRef.current.style, placement.frame)\n      if (imageRef.current) Object.assign(imageRef.current.style, placement.image)\n      if (!recover || !frameRef.current) return\n      for (const cover of covers) cover.cancel()\n      const made: Animation[] = coverTurn(\n        [frameRef.current],\n        imageRef.current,\n        null,\n        box,\n        { ...imagePose(natural, angle, transform, crop), hole: imageRect(box) },\n        natural,\n        state.shape === 'circle',\n        () => {\n          if (covers === made) paint()\n        },\n      )\n      covers = made\n    }\n    paint()\n    const unsubscribe = feed.subscribe(paint)\n    return () => {\n      unsubscribe()\n      for (const cover of covers) cover.cancel()\n    }\n  }, [feed, box, loaded])\n  return (\n    <div\n      ref={boxRefs}\n      data-image-cropper-preview=''\n      aria-hidden\n      className={cn(\n        'group/cropper bg-muted relative size-16 shrink-0 overflow-hidden',\n        shape === 'circle' ? 'rounded-full' : 'rounded-(--control-radius-capped)',\n        className,\n      )}\n      {...props}\n    >\n      {loaded && box ? (\n        <div\n          ref={frameRef}\n          className={cn('absolute top-0 left-0 origin-top-left', glideClassName)}\n        >\n          {/* oxlint-disable-next-line nextjs/no-img-element -- a registry item can't use next/image */}\n          <img\n            ref={imageRef}\n            src={src}\n            alt=''\n            draggable={false}\n            className={cn(\n              'absolute top-0 left-0 max-w-none',\n              'transition-[translate] duration-(--motion-layout-duration) ease-(--motion-layout-easing) group-data-following/cropper:duration-0 group-data-resizing/cropper:transition-none motion-reduce:transition-none',\n            )}\n          />\n        </div>\n      ) : null}\n    </div>\n  )\n}\n\nexport {\n  ImageCropper,\n  ImageCropperArea,\n  ImageCropperGrid,\n  ImageCropperHandle,\n  ImageCropperImage,\n  ImageCropperPreview,\n  ImageCropperRotate,\n  ImageCropperSelection,\n  ImageCropperViewport,\n  ImageCropperZoom,\n}\n\nexport {\n  cropLayout,\n  imagePlacement,\n  imagePose,\n  insetClip,\n  largestCrop,\n  mirrorOf,\n  nextAngle,\n  turnCover,\n  viewportStyles,\n  zoomPercent,\n}\n\nexport type { Rect, Size, TurnPose }\n",
      "type": "registry:component",
      "target": "@components/kino/image-cropper.tsx"
    }
  ],
  "type": "registry:component"
}