@vitavision/stage2d 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -564,7 +564,7 @@ function ImageStage({ image, view, onView, children, toolbar, readout, banner, p
564
564
  "data-fit": atFit ? "" : void 0,
565
565
  "data-panning": panning ? "" : void 0,
566
566
  "data-pan-mode": panMode ? "" : void 0,
567
- className: cn("relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
567
+ className: cn("relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none", "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal", panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default", className),
568
568
  onPointerDown,
569
569
  onPointerMove,
570
570
  onPointerUp: endDrag,
@@ -805,7 +805,7 @@ function MenuItem({ onClick, active, children }) {
805
805
  function StageReadout({ cursor, extra, className }) {
806
806
  const stage = useStage();
807
807
  return /* @__PURE__ */ jsxs("span", {
808
- className: cn("rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums", className),
808
+ className: cn("rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums", className),
809
809
  children: [
810
810
  cursor ? `${cursor.x.toFixed(1)}, ${cursor.y.toFixed(1)} px` : `${stage.image.width}×${stage.image.height}`,
811
811
  " · ",
@@ -983,7 +983,7 @@ function ZoomPanCanvas({ view, onView, children, className, style, label, native
983
983
  style,
984
984
  "data-panning": grabbing ? "" : void 0,
985
985
  "data-fit": view.zoom <= 1 ? "" : void 0,
986
- className: cn("relative overflow-hidden rounded border border-line bg-canvas select-none", grabbing ? "cursor-grabbing" : "cursor-grab", className),
986
+ className: cn("relative overflow-hidden rounded-control border border-line bg-canvas select-none", grabbing ? "cursor-grabbing" : "cursor-grab", className),
987
987
  onPointerDown: (event) => {
988
988
  draggingRef.current = {
989
989
  x: event.clientX - view.x,
@@ -1020,12 +1020,12 @@ function ZoomPanCanvas({ view, onView, children, className, style, label, native
1020
1020
  children
1021
1021
  }),
1022
1022
  label && /* @__PURE__ */ jsx("span", {
1023
- className: "pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white",
1023
+ className: "pointer-events-none absolute bottom-1 left-1 rounded-control bg-black/60 px-1 font-mono text-[10px] text-white",
1024
1024
  children: label
1025
1025
  }),
1026
1026
  fitLabel !== null && view.zoom > 1 && /* @__PURE__ */ jsx("button", {
1027
1027
  type: "button",
1028
- className: "absolute right-1 bottom-1 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80",
1028
+ className: "absolute right-1 bottom-1 rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80",
1029
1029
  onPointerDown: (event) => event.stopPropagation(),
1030
1030
  onClick: (event) => {
1031
1031
  event.stopPropagation();
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["clamp"],"sources":["../src/components/stage/view.ts","../src/components/stage/ImageStage.tsx","../src/components/stage/StageToolbar.tsx","../src/components/ZoomPanCanvas.tsx","../src/api/mapValues.ts","../src/components/measureGeometry.ts","../src/components/MeasureOverlay.tsx"],"sourcesContent":["/**\n * The image ↔ screen transform, as pure arithmetic.\n *\n * One transform, in absolute units: the stage element is laid out at exactly the source\n * image's pixel size and carries `translate(tx, ty) scale(scale)` about its top-left corner,\n * so an image point `p` lands at `p · scale + t` and nothing else participates. `scale` is\n * therefore *CSS pixels per image pixel* — `scale === 1` is 100%, and fit is whatever\n * `fitScale` returns for the current viewport, a value rather than a magic constant.\n *\n * The predecessor (`ZoomPanCanvas`) instead composed two scales it never named: a layout\n * scale from the frame's own size, and a CSS transform about the frame's centre. That\n * worked only while the frame's aspect ratio matched the image's, and the one consumer that\n * forgot to enforce that drew its overlays stretched against a letterboxed photograph — the\n * layers drifting apart on window resize, which is precisely the failure this replaces.\n * Laying the stage out at the image's own size removes the first scale entirely, so a child\n * `<svg viewBox=\"0 0 W H\">` is registered with the photograph by construction.\n *\n * Every function here is pure and tested, because this is arithmetic that goes wrong in a\n * way nothing on screen reveals: an overlay that is confidently off by a pan offset looks\n * exactly like an overlay that works.\n *\n * Points are in **viewport-local** CSS pixels — client coordinates with the viewport's\n * `getBoundingClientRect()` origin already subtracted. Keeping the rect out of these\n * signatures is what makes them testable without a DOM.\n *\n * **Image coordinates name pixel centres**, which is the convention every image-processing\n * result uses: `i` means the centre of pixel `i`, so an edge detected exactly between two\n * columns comes back as `i + 0.5`. CSS is the other convention: an `<img>` laid out at its\n * natural size puts pixel `i` across `[i, i + 1)`, so *its* `i` is the pixel's left edge.\n * The half-pixel between them is what `PIXEL_CENTRE` carries, and it is not cosmetic on a\n * metrology bench — at 8x it is four screen pixels of disagreement between an overlay and\n * the edge it claims to mark, and it is invisible at fit, which is where it gets missed.\n *\n * A layer drawn in image coordinates therefore uses `imageViewBox`, not `0 0 W H`.\n */\n\nimport type { Point } from \"../measureGeometry\";\n\n/** A `translate(tx, ty) scale(scale)` about the stage's top-left corner. */\nexport interface StageView {\n /** CSS pixels per image pixel. `1` is 100%. */\n scale: number;\n /** Horizontal offset of the image's top-left corner from the viewport's, in CSS pixels. */\n tx: number;\n /** Vertical offset of the image's top-left corner from the viewport's, in CSS pixels. */\n ty: number;\n}\n\n/** A size: the viewport's in CSS pixels, or the image's in image pixels. */\nexport interface Box {\n /** Horizontal extent. */\n width: number;\n /** Vertical extent. */\n height: number;\n}\n\n/** An axis-aligned rectangle in image coordinates, from its top-left corner. */\nexport interface Rect {\n /** Left edge. */\n x: number;\n /** Top edge. */\n y: number;\n /** Horizontal extent. */\n width: number;\n /** Vertical extent. */\n height: number;\n}\n\n/**\n * The offset between the two pixel conventions: an image coordinate `i` sits at CSS\n * `i + 0.5` inside a stage laid out at the image's natural size.\n */\nexport const PIXEL_CENTRE = 0.5;\n\n/**\n * The `viewBox` for an SVG layer drawn in image coordinates, over a stage of that image.\n *\n * Shifted by half a pixel so a primitive at image coordinate `i` lands on the *centre* of\n * pixel `i` rather than on its left edge. Its extent is unchanged — the box still covers\n * exactly the image — so nothing about sizing or `preserveAspectRatio` changes with it.\n */\nexport function imageViewBox(image: Box): string {\n return `${-PIXEL_CENTRE} ${-PIXEL_CENTRE} ${image.width} ${image.height}`;\n}\n\n/** The most a viewer may magnify: past this the resampler is the subject, not the sensor. */\nexport const MAX_SCALE = 32;\n\n/**\n * How far below fit zooming out may go.\n *\n * `ZoomPanCanvas` bottomed out *at* fit, on the reasoning that there is nothing further to\n * see. There is: room around the part, which is what you want when dragging an ROI out to\n * the frame edge or checking that a model's points do not run off the image.\n */\nexport const MIN_SCALE_VS_FIT = 0.25;\n\n/** Zoom in/out steps, as the percentages a readout can show without apologising. */\nconst SCALE_LADDER = [\n 0.05, 0.0833, 0.125, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32,\n];\n\n/** Relative tolerance for \"is this the same scale\" — a hair under a tenth of a percent. */\nconst SCALE_EPSILON = 1e-3;\n/** Absolute tolerance for \"is this the same offset\", in CSS pixels. */\nconst OFFSET_EPSILON = 0.5;\n\n/** The scale at which the whole image is just visible inside `box`. */\nexport function fitScale(box: Box, image: Box): number {\n if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;\n return Math.min(box.width / image.width, box.height / image.height);\n}\n\n/** Fit, centred — the view a viewer opens at and the one `0` returns to. */\nexport function fitView(box: Box, image: Box): StageView {\n const scale = fitScale(box, image);\n return centred(scale, box, image);\n}\n\n/** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */\nexport function initialView(box: Box, image: Box): StageView {\n return centred(Math.min(1, fitScale(box, image)), box, image);\n}\n\nfunction centred(scale: number, box: Box, image: Box): StageView {\n return {\n scale,\n tx: (box.width - image.width * scale) / 2,\n ty: (box.height - image.height * scale) / 2,\n };\n}\n\n/** Whether `view` is (indistinguishably) the fit view for this box and image. */\nexport function isFit(view: StageView, box: Box, image: Box): boolean {\n const fit = fitView(box, image);\n return (\n Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON &&\n Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON &&\n Math.abs(view.ty - fit.ty) <= OFFSET_EPSILON\n );\n}\n\n/** Where the **centre of** image pixel `p` lands in the viewport. */\nexport function toScreen(view: StageView, p: Point): Point {\n return {\n x: (p.x + PIXEL_CENTRE) * view.scale + view.tx,\n y: (p.y + PIXEL_CENTRE) * view.scale + view.ty,\n };\n}\n\n/**\n * Which image coordinate a viewport position is over, in the same pixel-centre convention:\n * the exact centre of the top-left pixel reads `0, 0`, and its top-left corner `-0.5, -0.5`.\n *\n * Unbounded — callers clamp if they care.\n */\nexport function toImage(view: StageView, p: Point): Point {\n return {\n x: (p.x - view.tx) / view.scale - PIXEL_CENTRE,\n y: (p.y - view.ty) / view.scale - PIXEL_CENTRE,\n };\n}\n\n/** Whether an image coordinate is inside the image, in the pixel-centre convention. */\nexport function insideImage(p: Point, image: Box): boolean {\n return (\n p.x >= -PIXEL_CENTRE &&\n p.y >= -PIXEL_CENTRE &&\n p.x < image.width - PIXEL_CENTRE &&\n p.y < image.height - PIXEL_CENTRE\n );\n}\n\n/** A length in image pixels that covers `css` screen pixels at this view. */\nexport function imageLengthFor(view: StageView, css: number): number {\n return view.scale > 0 ? css / view.scale : css;\n}\n\n/**\n * Change the scale while holding whatever is under `anchor` where it is.\n *\n * The one piece of arithmetic here that is silently wrong when centre-anchored instead:\n * magnifying a defect in a corner then costs a drag to undo every wheel notch.\n */\nexport function zoomAbout(view: StageView, scale: number, anchor: Point): StageView {\n if (!(view.scale > 0) || !(scale > 0)) return view;\n const ratio = scale / view.scale;\n return {\n scale,\n tx: anchor.x - (anchor.x - view.tx) * ratio,\n ty: anchor.y - (anchor.y - view.ty) * ratio,\n };\n}\n\n/** The scale range `clampView` and `scaleRange` allow. */\nexport interface ClampOptions {\n /** Lowest scale, as a multiple of fit. Defaults to `MIN_SCALE_VS_FIT`. */\n minScaleVsFit?: number;\n /** Highest scale, in CSS pixels per image pixel. Defaults to `MAX_SCALE`. */\n maxScale?: number;\n}\n\n/** The scale range a viewport allows for an image, as `[min, max]`. */\nexport function scaleRange(box: Box, image: Box, options: ClampOptions = {}): [number, number] {\n const fit = fitScale(box, image);\n const min = fit * (options.minScaleVsFit ?? MIN_SCALE_VS_FIT);\n const max = Math.max(min, options.maxScale ?? MAX_SCALE);\n return [min, max];\n}\n\n/**\n * Keep the view legal: scale inside its range, and the image never dragged off screen.\n *\n * An axis where the scaled image is smaller than the viewport is centred rather than left\n * where a drag put it — free-floating pixels in a grey field is a way to be lost with no\n * visible handle to get back. An axis where it is larger is held so the viewport stays\n * covered.\n */\nexport function clampView(\n view: StageView,\n box: Box,\n image: Box,\n options: ClampOptions = {},\n): StageView {\n const [min, max] = scaleRange(box, image, options);\n const scale = clamp(view.scale, min, max);\n return {\n scale,\n tx: clampAxis(view.tx, box.width, image.width * scale),\n ty: clampAxis(view.ty, box.height, image.height * scale),\n };\n}\n\nfunction clampAxis(t: number, boxLength: number, contentLength: number): number {\n if (contentLength <= boxLength) return (boxLength - contentLength) / 2;\n return clamp(t, boxLength - contentLength, 0);\n}\n\n/**\n * The view that puts `rect` (image coordinates) on screen with a margin around it.\n *\n * `pad` is a fraction of the rect's own size, so framing a long thin contour and framing a\n * blob both leave a proportionate border rather than a fixed one that swallows the small\n * one.\n */\nexport function frameRect(box: Box, image: Box, rect: Rect, pad = 0.15): StageView {\n const width = Math.max(rect.width, 1e-6) * (1 + 2 * pad);\n const height = Math.max(rect.height, 1e-6) * (1 + 2 * pad);\n const scale = Math.min(box.width / width, box.height / height);\n const centre = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };\n return clampView(\n {\n scale,\n tx: box.width / 2 - (centre.x + PIXEL_CENTRE) * scale,\n ty: box.height / 2 - (centre.y + PIXEL_CENTRE) * scale,\n },\n box,\n image,\n { maxScale: MAX_SCALE },\n );\n}\n\n/**\n * The same view, after the viewport changed size.\n *\n * The image point at the old centre stays at the new centre, at the same scale — so a\n * window resize moves the frame around the picture instead of moving the picture. A view\n * that was *fit* re-fits instead, because fit is a relationship to the viewport rather than\n * a particular pair of numbers.\n */\nexport function preserveCenter(\n view: StageView,\n from: Box,\n to: Box,\n image: Box,\n options: ClampOptions = {},\n): StageView {\n if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);\n if (isFit(view, from, image)) return fitView(to, image);\n\n const centre = toImage(view, { x: from.width / 2, y: from.height / 2 });\n return clampView(\n {\n scale: view.scale,\n tx: to.width / 2 - (centre.x + PIXEL_CENTRE) * view.scale,\n ty: to.height / 2 - (centre.y + PIXEL_CENTRE) * view.scale,\n },\n to,\n image,\n options,\n );\n}\n\n/**\n * The next scale up or down the ladder from `scale`, so the readout lands on a round\n * percentage rather than wherever a multiplier happened to leave it.\n */\nexport function steppedScale(scale: number, direction: 1 | -1, min: number, max: number): number {\n const ladder = SCALE_LADDER.filter((s) => s >= min - 1e-9 && s <= max + 1e-9);\n const candidates = ladder.length > 0 ? ladder : [clamp(scale, min, max)];\n if (direction > 0) {\n const next = candidates.find((s) => s > scale * (1 + SCALE_EPSILON));\n return next ?? Math.min(max, Math.max(scale, candidates[candidates.length - 1]!));\n }\n const previous = [...candidates].reverse().find((s) => s < scale * (1 - SCALE_EPSILON));\n return previous ?? Math.max(min, Math.min(scale, candidates[0]!));\n}\n\n/** `0.5` → `\"50%\"`, `1` → `\"100%\"`, `0.0833` → `\"8%\"`. */\nexport function formatScale(scale: number): string {\n const percent = scale * 100;\n if (percent >= 100) return `${Math.round(percent)}%`;\n if (percent >= 10) return `${Math.round(percent)}%`;\n return `${percent.toFixed(1)}%`;\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(high, Math.max(low, value));\n}\n","/**\n * A pannable, zoomable frame that transforms **everything stacked inside it together**.\n *\n * A result viewer over a stack — a photograph, an anomaly map, a model's segmentation, a\n * measurement overlay drawn in source-image pixel coordinates — and the layers only stay\n * registered with each other if one transform moves all of them.\n *\n * The stage element is laid out at **exactly the image's pixel size** and carries the whole\n * transform (see `view.ts`). Two things follow, and both are the point:\n *\n * - a child `<svg viewBox=\"0 0 W H\">` at `inset-0` is registered with the photograph at\n * every viewport size, with no letterbox correction to get wrong. Its predecessor\n * scaled layers by the *frame's* size, so an aspect mismatch between frame and image\n * drew the overlay stretched against a letterboxed picture — layers drifting apart on\n * window resize;\n * - `scale` means CSS pixels per image pixel, so \"100%\" is a value rather than a\n * coincidence, and zooming *out* past fit is expressible.\n *\n * Interactive children are supported, which is the other half of the rewrite. This stage\n * starts a pan only when the gesture is unclaimed — the press landed on the background, or\n * used the middle button, or held space, or the caller says the pan tool is active. A layer\n * that wants a press simply handles it. The predecessor called `setPointerCapture` on every\n * `pointerdown`, so an ROI handle or a clickable contour could not exist inside it at all,\n * and its consumers put those layers *outside* the transform — where they no longer moved\n * with the image.\n */\n\nimport {\n createContext,\n use,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type {\n CSSProperties,\n KeyboardEvent as ReactKeyboardEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\nimport type { Point } from \"../measureGeometry\";\nimport {\n clampView,\n fitView,\n frameRect,\n imageLengthFor,\n initialView,\n insideImage,\n isFit,\n preserveCenter,\n scaleRange,\n toImage,\n toScreen,\n zoomAbout,\n type Box,\n type ClampOptions,\n type Rect,\n type StageView,\n} from \"./view\";\n\nconst WHEEL_SENSITIVITY = 0.0015;\n/** How far a press may travel and still count as a click rather than a pan. */\nconst CLICK_SLOP = 3;\n/** The view before the viewport has been measured — nothing is on screen yet. */\nconst UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };\n\n/** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */\nexport interface StageContext {\n /** The view in effect — the controlled `view`, or the opening view while that is `null`. */\n view: StageView;\n /** Set a view, clamped to the legal range for the current viewport. */\n setView: (view: StageView) => void;\n /** The source image's pixel dimensions. */\n image: Box;\n /** The viewport's CSS size — `{0, 0}` until first measured. */\n box: Box;\n /** Client coordinates → image pixels. */\n toImage: (client: Point) => Point;\n /** Image pixels → client coordinates. */\n toClient: (image: Point) => Point;\n /** Image pixels → viewport-local CSS pixels. */\n toViewport: (image: Point) => Point;\n /** The image-pixel length that covers `css` screen pixels — for screen-constant geometry. */\n imageLength: (css: number) => number;\n /** Put a rect (image coordinates) on screen with a margin. */\n frame: (rect: Rect, pad?: number) => void;\n /** Fit the whole image. */\n fit: () => void;\n /** Set a scale about the viewport centre, or about `anchor` in client coordinates. */\n zoomTo: (scale: number, anchor?: Point) => void;\n /** Whether the view is (indistinguishably) fit. */\n isFit: boolean;\n /** True while a pan is in progress, so layers can suppress hover work. */\n panning: boolean;\n /**\n * True when panning must win over anything a layer would otherwise do with a press —\n * the hand tool, or space held. Layers check this before claiming a `pointerdown`; it is\n * the only way a modifier can outrank a child, since a child that stops propagation is\n * heard before this component is.\n */\n panMode: boolean;\n}\n\nconst ImageStageContext = createContext<StageContext | null>(null);\n\n/**\n * The stage a layer is drawn into: its view, the coordinate conversions, and the zoom\n * controls.\n *\n * @throws `Error` outside an `ImageStage`, which is always a wiring bug.\n */\nexport function useStage(): StageContext {\n const ctx = use(ImageStageContext);\n if (ctx === null) throw new Error(\"useStage must be used inside <ImageStage>.\");\n return ctx;\n}\n\n/** Props of `ImageStage`. */\nexport interface ImageStageProps {\n /** The source image's pixel dimensions — the stage's own layout size. */\n image: Box;\n /**\n * The view (controlled). `null` opens at a sensible view — 1:1 if the image fits,\n * otherwise fit — reported through `onView` once the viewport is measured. A non-null\n * view is kept on first measure, only clamped to the legal range.\n */\n view: StageView | null;\n /** Called with every view change: gestures, keys, toolbar, and viewport resizes. */\n onView: (view: StageView) => void;\n /** Layers, each `absolute inset-0` and sized by the stage. */\n children: ReactNode;\n /** Rendered floating over the bottom-left, outside the transform. */\n toolbar?: ReactNode;\n /** Rendered floating over the bottom-right, outside the transform. */\n readout?: ReactNode;\n /** Rendered over the top-left — a mode banner, a staleness warning. */\n banner?: ReactNode;\n /** Force panning regardless of where the press lands (a \"hand tool\"). */\n panTool?: boolean;\n /** Merged onto the viewport with `cn`. */\n className?: string;\n /** Inline style for the viewport. */\n style?: CSSProperties;\n /** Where the pointer is over the image, in image pixels, or `null` when it is outside. */\n onHover?: (point: Point | null) => void;\n /** A press on the background that was not a pan — how a layer hears \"deselect\". */\n onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>) => void;\n /** The legal scale range; see `clampView`. */\n clamp?: ClampOptions;\n /** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */\n shortcuts?: boolean;\n /**\n * Whether the arrow keys pan. On by default, and worth turning off in an app where the\n * arrows have a better job — stepping through a list of findings, say. The zoom keys\n * (`+`, `-`, `0`, `1`) are unaffected, and dragging still pans either way.\n */\n panKeys?: boolean;\n /** The viewport's accessible name. Defaults to \"Image canvas\". */\n label?: string;\n}\n\n/**\n * A pannable, zoomable viewport over a stack of layers laid out at the image's own pixel\n * size, so an overlay drawn in image coordinates stays registered with the photograph at\n * any zoom and window size. Layers read the transform through `useStage`.\n *\n * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag\n * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present\n * or absent.\n */\nexport function ImageStage({\n image,\n view,\n onView,\n children,\n toolbar,\n readout,\n banner,\n panTool = false,\n className,\n style,\n onHover,\n onBackgroundClick,\n clamp,\n shortcuts = true,\n panKeys = true,\n label = \"Image canvas\",\n}: ImageStageProps) {\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const [box, setBox] = useState<Box>({ width: 0, height: 0 });\n // The measured size, readable synchronously — `setBox`'s updater must stay pure, and the\n // resize handler needs the *previous* box to re-anchor the view against.\n const measuredRef = useRef<Box>({ width: 0, height: 0 });\n const [panning, setPanning] = useState(false);\n const [spaceHeld, setSpaceHeld] = useState(false);\n const panMode = panTool || spaceHeld;\n\n // What the handlers attached once (and the stable callbacks below) read: the props and\n // box of the last commit, so none of them closes over stale values.\n const latestRef = useRef({ view, box, image, clamp, onView });\n useLayoutEffect(() => {\n latestRef.current = { view, box, image, clamp, onView };\n });\n /** The view to come back to when a double-click leaves fit. */\n const previousRef = useRef<StageView | null>(null);\n const dragRef = useRef<{ x: number; y: number; tx: number; ty: number; moved: boolean } | null>(null);\n\n const effective = useMemo(\n () => view ?? (box.width > 0 ? initialView(box, image) : UNMEASURED_VIEW),\n [view, box, image],\n );\n\n const commit = useCallback((next: StageView) => {\n const { box: b, image: i, clamp: c, onView: report } = latestRef.current;\n report(b.width > 0 ? clampView(next, b, i, c) : next);\n }, []);\n\n /*\n * The viewport, measured and observed from the moment it mounts (a callback ref with a\n * cleanup, so the subscription lives exactly as long as the element).\n *\n * Its size is a *dependency* of the view, not just of the layout: fit is a relationship to\n * it, and a pan offset that was legal in a wide window is off-screen in a narrow one.\n * Without this the picture appeared to slide out from under its own overlay whenever the\n * window changed shape.\n *\n * The wheel listener is attached here by hand because React registers `wheel` at the root\n * as **passive**, which makes `preventDefault` in a synthetic handler a no-op — the page\n * would scroll behind the canvas while you zoom, which reads as the zoom being broken.\n */\n const attachViewport = useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element;\n if (!element) return;\n\n const measure = ({ width, height }: Box) => {\n if (!(width > 0) || !(height > 0)) return;\n const current = measuredRef.current;\n if (current.width === width && current.height === height) return;\n const next = { width, height };\n measuredRef.current = next;\n setBox(next);\n const { view: v, image: i, clamp: c, onView: report } = latestRef.current;\n if (v === null) report(initialView(next, i));\n // The first measurement: there is no previous viewport to re-anchor against, so the\n // caller's view is kept — only made legal for this one.\n else if (!(current.width > 0)) report(clampView(v, next, i, c));\n else report(preserveCenter(v, current, next, i, c));\n };\n\n // Synchronously, so the first paint already has the right view — and as the *content*\n // box, which is what the observer reports; measuring the border box here re-anchored\n // the view by the border's width as soon as the observer's first report arrived.\n measure(contentSize(element));\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry) measure(entry.contentRect);\n });\n observer.observe(element);\n\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;\n if (v === null || !(b.width > 0)) return;\n const origin = viewportOrigin(element);\n const [min, max] = scaleRange(b, i, c);\n const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);\n const scale = Math.min(max, Math.max(min, v.scale * factor));\n const anchor = { x: event.clientX - origin.x, y: event.clientY - origin.y };\n report(clampView(zoomAbout(v, scale, anchor), b, i, c));\n };\n element.addEventListener(\"wheel\", onWheel, { passive: false });\n\n return () => {\n observer.disconnect();\n element.removeEventListener(\"wheel\", onWheel);\n viewportRef.current = null;\n };\n }, []);\n\n /* Space is a *modifier*, not a command: held, it turns any press into a pan, which is the\n * one gesture that has to work no matter which layer is under the cursor. */\n useEffect(() => {\n if (!shortcuts) return;\n const down = (event: KeyboardEvent) => {\n if (event.code === \"Space\" && !isTypingTarget(event.target)) setSpaceHeld(true);\n };\n const up = (event: KeyboardEvent) => {\n if (event.code === \"Space\") setSpaceHeld(false);\n };\n const blur = () => setSpaceHeld(false);\n window.addEventListener(\"keydown\", down);\n window.addEventListener(\"keyup\", up);\n window.addEventListener(\"blur\", blur);\n return () => {\n window.removeEventListener(\"keydown\", down);\n window.removeEventListener(\"keyup\", up);\n window.removeEventListener(\"blur\", blur);\n };\n }, [shortcuts]);\n\n const clientToImage = useCallback((p: Point): Point => {\n const element = viewportRef.current;\n const { view: v } = latestRef.current;\n if (!element || v === null) return { x: 0, y: 0 };\n const origin = viewportOrigin(element);\n return toImage(v, { x: p.x - origin.x, y: p.y - origin.y });\n }, []);\n\n const imageToClient = useCallback((p: Point): Point => {\n const element = viewportRef.current;\n const { view: v } = latestRef.current;\n if (!element || v === null) return { x: 0, y: 0 };\n const origin = viewportOrigin(element);\n const local = toScreen(v, p);\n return { x: local.x + origin.x, y: local.y + origin.y };\n }, []);\n\n const fit = useCallback(() => {\n const { box: b, image: i, view: v, onView: report } = latestRef.current;\n if (!(b.width > 0)) return;\n if (v !== null && !isFit(v, b, i)) previousRef.current = v;\n report(fitView(b, i));\n }, []);\n\n const zoomTo = useCallback((scale: number, anchor?: Point) => {\n const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;\n const element = viewportRef.current;\n if (v === null || !(b.width > 0) || !element) return;\n const origin = viewportOrigin(element);\n const local = anchor\n ? { x: anchor.x - origin.x, y: anchor.y - origin.y }\n : { x: b.width / 2, y: b.height / 2 };\n const [min, max] = scaleRange(b, i, c);\n report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));\n }, []);\n\n const frame = useCallback((rect: Rect, pad?: number) => {\n const { box: b, image: i, onView: report } = latestRef.current;\n if (!(b.width > 0)) return;\n report(frameRect(b, i, rect, pad));\n }, []);\n\n const atFit = box.width > 0 && isFit(effective, box, image);\n\n const context = useMemo<StageContext>(\n () => ({\n view: effective,\n setView: commit,\n image,\n box,\n toImage: clientToImage,\n toClient: imageToClient,\n toViewport: (p: Point) => toScreen(effective, p),\n imageLength: (css: number) => imageLengthFor(effective, css),\n frame,\n fit,\n zoomTo,\n isFit: atFit,\n panning,\n panMode,\n }),\n [\n effective,\n commit,\n image,\n box,\n clientToImage,\n imageToClient,\n frame,\n fit,\n zoomTo,\n atFit,\n panning,\n panMode,\n ],\n );\n\n /*\n * Panning is the *default* reading of a press, and a layer opts out of it by handling the\n * event and stopping propagation — so the stage needs to know nothing about ROI handles or\n * clickable contours, and a layer needs no permission to exist. The predecessor inverted\n * this: it captured every `pointerdown` unconditionally, which is why its consumers had to\n * mount interactive layers outside the transform, where they stopped moving with the image.\n */\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0 && event.button !== 1) return;\n event.preventDefault();\n dragRef.current = {\n x: event.clientX,\n y: event.clientY,\n tx: effective.tx,\n ty: effective.ty,\n moved: false,\n };\n setPanning(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const origin = dragRef.current;\n if (!origin) {\n onHover?.(hoverPoint(event, viewportRef.current, effective, image));\n return;\n }\n const dx = event.clientX - origin.x;\n const dy = event.clientY - origin.y;\n if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;\n origin.moved = true;\n // During a pan the pointer is holding the image, not pointing at a pixel.\n onHover?.(null);\n commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n const origin = dragRef.current;\n dragRef.current = null;\n setPanning(false);\n if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);\n };\n\n /*\n * Fit ↔ **the view you were just at**, which is the gesture a reader actually wants: a\n * double-click to see the whole part, another to go back to the corner they were working\n * in. Toggling against 1:1 instead (the predecessor's behaviour) throws that place away.\n */\n const onDoubleClick = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!(box.width > 0)) return;\n if (atFit) {\n const restore = previousRef.current;\n if (restore) {\n onView(clampView(restore, box, image, clamp));\n } else {\n zoomTo(1, { x: event.clientX, y: event.clientY });\n }\n return;\n }\n previousRef.current = effective;\n onView(fitView(box, image));\n };\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (!shortcuts || isTypingTarget(event.target)) return;\n const [min, max] = scaleRange(box, image, clamp);\n const nudge = 60;\n switch (event.key) {\n case \"+\":\n case \"=\":\n zoomTo(Math.min(max, effective.scale * 1.5));\n break;\n case \"-\":\n case \"_\":\n zoomTo(Math.max(min, effective.scale / 1.5));\n break;\n case \"0\":\n fit();\n break;\n case \"1\":\n zoomTo(1);\n break;\n case \"ArrowLeft\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx + nudge });\n break;\n case \"ArrowRight\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx - nudge });\n break;\n case \"ArrowUp\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty + nudge });\n break;\n case \"ArrowDown\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty - nudge });\n break;\n default:\n return;\n }\n event.preventDefault();\n };\n\n return (\n <ImageStageContext value={context}>\n <div\n ref={attachViewport}\n role=\"application\"\n aria-label={label}\n tabIndex={0}\n style={style}\n data-fit={atFit ? \"\" : undefined}\n data-panning={panning ? \"\" : undefined}\n data-pan-mode={panMode ? \"\" : undefined}\n className={cn(\n \"relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none\",\n \"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal\",\n panning ? \"cursor-grabbing\" : panMode ? \"cursor-grab\" : \"cursor-default\",\n className,\n )}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n // A drag interrupted by a lost capture — a context menu, a browser gesture, the\n // pointer leaving the window — used to leave the drag set, so the next hover panned\n // the image with no button held down.\n onPointerCancel={endDrag}\n onLostPointerCapture={endDrag}\n onPointerLeave={() => onHover?.(null)}\n onDoubleClick={onDoubleClick}\n onKeyDown={onKeyDown}\n >\n {/* One transformed box holding every layer, laid out at the image's own pixel size. */}\n <div\n data-stage\n className=\"absolute top-0 left-0 origin-top-left\"\n style={{\n width: image.width,\n height: image.height,\n transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`,\n }}\n >\n {children}\n </div>\n\n {banner && <div className=\"pointer-events-none absolute top-2 left-2 z-10\">{banner}</div>}\n\n {/* One row, not two corners: as separate absolute boxes the toolbar and the readout\n overlapped as soon as the canvas was narrower than their combined width, which is\n an ordinary window on a two-column workbench. `justify-between` keeps them apart\n and lets the readout be the one that gives up room. */}\n {(toolbar || readout) && (\n <div className=\"pointer-events-none absolute inset-x-2 bottom-2 z-10 flex items-end justify-between gap-2\">\n <div className=\"pointer-events-auto shrink-0\">{toolbar}</div>\n <div className=\"min-w-0 truncate\">{readout}</div>\n </div>\n )}\n </div>\n </ImageStageContext>\n );\n}\n\nfunction hoverPoint(\n event: { clientX: number; clientY: number },\n element: HTMLDivElement | null,\n view: StageView,\n image: Box,\n): Point | null {\n if (!element) return null;\n const origin = viewportOrigin(element);\n const p = toImage(view, { x: event.clientX - origin.x, y: event.clientY - origin.y });\n return insideImage(p, image) ? p : null;\n}\n\n/**\n * Where viewport-local `(0, 0)` is in client coordinates: the *padding* box's corner, which\n * is where the absolutely positioned stage sits — not the border box's, which is what\n * `getBoundingClientRect` reports. The difference is the border's width, a whole image\n * pixel at 100% between the cursor and the pixel reported under it.\n */\nfunction viewportOrigin(element: HTMLElement): Point {\n const rect = element.getBoundingClientRect();\n return { x: rect.left + element.clientLeft, y: rect.top + element.clientTop };\n}\n\n/** The element's content-box size, the box `ResizeObserver` reports as `contentRect`. */\nfunction contentSize(element: HTMLElement): Box {\n const rect = element.getBoundingClientRect();\n const style = getComputedStyle(element);\n const px = (value: string) => Number.parseFloat(value) || 0;\n return {\n width:\n rect.width -\n px(style.borderLeftWidth) -\n px(style.borderRightWidth) -\n px(style.paddingLeft) -\n px(style.paddingRight),\n height:\n rect.height -\n px(style.borderTopWidth) -\n px(style.borderBottomWidth) -\n px(style.paddingTop) -\n px(style.paddingBottom),\n };\n}\n\nfunction isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\" || target.isContentEditable;\n}\n","/**\n * The viewer's own controls, floating over the image rather than filed in a side panel.\n *\n * Zoom, fit and 1:1 are properties of *the picture*, not of the task beside it, and a\n * workbench that puts them in the inspector spends inspector width on them on every screen\n * while leaving the canvas with no visible affordance at all — which is indistinguishable\n * from a canvas that cannot zoom.\n *\n * The bar is deliberately small and quiet: `bg-overlay/85` over a blur, one row of icon\n * buttons, no labels except the percentage. It is chrome over the subject, so it recedes\n * until aimed at.\n */\n\nimport { Maximize2, Minus, Plus, Scan } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, ReactNode } from \"react\";\n\nimport { cn, focusRing } from \"@vitavision/ui\";\nimport { useStage } from \"./ImageStage\";\nimport { MAX_SCALE, formatScale, scaleRange, steppedScale } from \"./view\";\n\n/** The presets the percentage menu offers, beside \"Fit\". */\nconst PRESETS = [0.25, 0.5, 1, 2, 4, 8];\n\n/** Props of `StageToolbar`. */\nexport interface StageToolbarProps {\n /** App-specific groups — a tool selector, a layers popover — after a divider. */\n children?: ReactNode;\n /** Merged onto the bar with `cn`. */\n className?: string;\n}\n\n/**\n * The stage's zoom controls — zoom out, a percentage menu (fit and presets), zoom in, fit,\n * and 100% — plus any app groups passed as children. Pass it as `ImageStage`'s `toolbar`;\n * it reads the stage through `useStage`.\n *\n * The bar carries `data-fit` while the view is fit; the percentage button carries\n * `data-state=\"open\"` or `\"closed\"` for its menu.\n */\nexport function StageToolbar({ children, className }: StageToolbarProps) {\n const stage = useStage();\n const [menuOpen, setMenuOpen] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n const [min, max] = scaleRange(stage.box, stage.image);\n\n useEffect(() => {\n if (!menuOpen) return;\n const close = (event: MouseEvent) => {\n if (!menuRef.current?.contains(event.target as Node)) setMenuOpen(false);\n };\n window.addEventListener(\"pointerdown\", close);\n return () => window.removeEventListener(\"pointerdown\", close);\n }, [menuOpen]);\n\n const step = (direction: 1 | -1) => stage.zoomTo(steppedScale(stage.view.scale, direction, min, max));\n\n return (\n <div\n data-fit={stage.isFit ? \"\" : undefined}\n className={cn(\n \"flex items-center gap-0.5 rounded-panel border border-line bg-overlay/85 p-1 shadow-lg backdrop-blur\",\n className,\n )}\n // Every press here is a control, never the start of a pan.\n onPointerDown={(event) => event.stopPropagation()}\n onDoubleClick={(event) => event.stopPropagation()}\n >\n <StageButton label=\"Zoom out\" onClick={() => step(-1)} disabled={stage.view.scale <= min + 1e-9}>\n <Minus className=\"size-4\" aria-hidden />\n </StageButton>\n\n <div className=\"relative\" ref={menuRef}>\n <button\n type=\"button\"\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen}\n data-state={menuOpen ? \"open\" : \"closed\"}\n onClick={() => setMenuOpen((open) => !open)}\n className={cn(\n \"h-7 min-w-14 rounded-control px-2 font-mono text-xs text-fg tabular-nums hover:bg-raised\",\n focusRing,\n )}\n >\n {stage.isFit ? \"Fit\" : formatScale(stage.view.scale)}\n </button>\n {menuOpen && (\n <div\n role=\"menu\"\n className=\"absolute bottom-9 left-0 z-20 min-w-28 rounded-panel border border-line bg-overlay p-1 shadow-lg\"\n >\n <MenuItem\n onClick={() => {\n stage.fit();\n setMenuOpen(false);\n }}\n active={stage.isFit}\n >\n Fit\n </MenuItem>\n {PRESETS.filter((scale) => scale >= min && scale <= max).map((scale) => (\n <MenuItem\n key={scale}\n onClick={() => {\n stage.zoomTo(scale);\n setMenuOpen(false);\n }}\n active={!stage.isFit && Math.abs(stage.view.scale - scale) < 1e-6}\n >\n {formatScale(scale)}\n </MenuItem>\n ))}\n </div>\n )}\n </div>\n\n <StageButton\n label=\"Zoom in\"\n onClick={() => step(1)}\n disabled={stage.view.scale >= Math.min(max, MAX_SCALE) - 1e-9}\n >\n <Plus className=\"size-4\" aria-hidden />\n </StageButton>\n\n <StageToolbarDivider />\n\n <StageButton label=\"Fit to window\" onClick={stage.fit} pressed={stage.isFit}>\n <Maximize2 className=\"size-4\" aria-hidden />\n </StageButton>\n <StageButton\n label=\"Actual size (100%)\"\n onClick={() => stage.zoomTo(1)}\n pressed={!stage.isFit && Math.abs(stage.view.scale - 1) < 1e-6}\n >\n <Scan className=\"size-4\" aria-hidden />\n </StageButton>\n\n {children && (\n <>\n <StageToolbarDivider />\n {children}\n </>\n )}\n </div>\n );\n}\n\n/** Props of `StageButton`: a `<button>`'s, less the ones it sets itself. */\nexport interface StageButtonProps\n extends Omit<ComponentPropsWithRef<\"button\">, \"type\" | \"title\" | \"aria-label\" | \"aria-pressed\" | \"children\"> {\n /** The accessible name, also shown as the tooltip. */\n label: string;\n /** A toggle's state; omit for a plain action button. */\n pressed?: boolean;\n /** The icon (mark it `aria-hidden`). */\n children: ReactNode;\n}\n\n/**\n * The bar's own button shape, exported so app groups match it exactly. An icon button\n * named by `label`; a toggle when `pressed` is given, exposed as `aria-pressed` and\n * `data-state=\"on\"` or `\"off\"`. Other button props (and `ref`) are passed through.\n */\nexport function StageButton({ label, pressed, className, children, ...props }: StageButtonProps) {\n return (\n <button\n {...props}\n type=\"button\"\n title={label}\n aria-label={label}\n aria-pressed={pressed}\n data-state={pressed === undefined ? undefined : pressed ? \"on\" : \"off\"}\n className={cn(\n \"grid size-7 place-items-center rounded-control text-fg-muted transition-colors\",\n \"hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40\",\n pressed && \"bg-signal/15 text-signal\",\n focusRing,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n\n/** Props of `StageToolbarDivider`. */\nexport interface StageToolbarDividerProps {\n /** Merged onto the divider with `cn`. */\n className?: string;\n}\n\n/** A thin vertical rule between groups of `StageButton`s. Decorative (`aria-hidden`). */\nexport function StageToolbarDivider({ className }: StageToolbarDividerProps) {\n return <span className={cn(\"mx-0.5 h-5 w-px bg-line\", className)} aria-hidden />;\n}\n\nfunction MenuItem({\n onClick,\n active,\n children,\n}: {\n onClick: () => void;\n active?: boolean;\n children: ReactNode;\n}) {\n return (\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={onClick}\n className={cn(\n \"block w-full rounded-control px-2 py-1 text-left font-mono text-xs tabular-nums hover:bg-raised\",\n active ? \"text-signal\" : \"text-fg\",\n focusRing,\n )}\n >\n {children}\n </button>\n );\n}\n\n/** Props of `StageReadout`. */\nexport interface StageReadoutProps {\n /** The pointer in image pixels (from `ImageStage`'s `onHover`); the image size shows without it. */\n cursor?: { x: number; y: number } | null;\n /** Appended after a separator — a pixel value, a channel. */\n extra?: ReactNode;\n /** Merged onto the readout with `cn`. */\n className?: string;\n}\n\n/**\n * The instrument's display line for the canvas: where the cursor is, and how magnified.\n * Pass it as `ImageStage`'s `readout`; it reads the stage through `useStage`.\n *\n * In image pixels, because that is the coordinate every number the backend returns is in —\n * a readout in screen pixels would be a second coordinate system to reconcile by hand.\n */\nexport function StageReadout({ cursor, extra, className }: StageReadoutProps) {\n const stage = useStage();\n return (\n <span\n className={cn(\n \"rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums\",\n className,\n )}\n >\n {cursor ? `${cursor.x.toFixed(1)}, ${cursor.y.toFixed(1)} px` : `${stage.image.width}×${stage.image.height}`}\n {\" · \"}\n {stage.isFit ? \"fit\" : formatScale(stage.view.scale)}\n {extra && <> · {extra}</>}\n </span>\n );\n}\n","/**\n * A pannable, zoomable frame that transforms **everything stacked inside it together**.\n *\n * Deprecated: use `ImageStage` (`components/stage`). Two limits of this component turned out\n * to be load-bearing rather than incidental, and neither can be lifted without changing what\n * its props mean:\n *\n * - it scales its layers by the *frame's* size, so every consumer must lay the frame out\n * at the source aspect ratio and the one that forgot drew its overlays stretched against\n * a letterboxed photograph — layers drifting apart on window resize, invisibly, at\n * every window size but one;\n * - it calls `setPointerCapture` on every `pointerdown` to pan, so an interactive child —\n * a draggable ROI handle, a clickable contour — cannot exist inside it, and consumers\n * mounted those layers *outside* the transform, where they stopped moving with the image.\n *\n * `ImageStage` lays the stage out at the image's own pixel size (so registration is\n * structural, not a caller's responsibility), treats `scale` as CSS pixels per image pixel\n * (so \"100%\" is a value and zooming out past fit is expressible), and pans only when a\n * gesture is unclaimed. This component stays exported and unchanged for consumers that have\n * not migrated.\n *\n * A result viewer over a stack -- a photograph, an anomaly map, a model's segmentation, a\n * measurement overlay drawn in source-image pixel coordinates (see `MeasureOverlay`) -- and\n * the layers only stay registered with each other if one transform moves all of them.\n * Transforming each layer separately would drift them apart at the exact zoom level where a\n * reader is trying to judge whether a caliper box lands on the edge it claims to measure.\n *\n * Zoom bottoms out at 1x and snaps the pan back to centre there, so there is always a\n * gesture that gets you unlost — and zoom 1 *is* fit-to-window, because the canvas is laid\n * out inside `max-h-full max-w-full` with the source aspect ratio. That is why the\n * double-click gesture toggles fit against **1:1 native pixels** rather than \"fitting\":\n * fitting is where you already are, and the thing a reader actually wants at a defect, or\n * at a subpixel edge, is the sensor's own resolution with no resampling between them and it.\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\n\n/**\n * `ZoomPanCanvas`'s view: `translate(x, y) scale(zoom)` about the frame's centre.\n * `ImageStage` uses `StageView` instead.\n */\nexport interface View {\n /** Magnification relative to fit; `1` is fit-to-window. */\n zoom: number;\n /** Horizontal pan, in CSS pixels, from the centred position. */\n x: number;\n /** Vertical pan, in CSS pixels, from the centred position. */\n y: number;\n}\n\n/** Zoom 1, centred — which is fit-to-window, given how the canvas is laid out. */\nexport const RESET_VIEW: View = { zoom: 1, x: 0, y: 0 };\n\n/** The lowest zoom `zoomAt` allows: fit. */\nexport const MIN_ZOOM = 1;\n/** The highest zoom `zoomAt` allows. */\nexport const MAX_ZOOM = 12;\nconst ZOOM_SENSITIVITY = 0.0015;\n\n/** The zoom past which a preview tier stops being enough and real pixels are wanted. */\nexport const FULL_TIER_ZOOM = 2;\n\n/**\n * Zoom by `factor` about a point, keeping whatever is under that point where it is.\n *\n * Pure, and exported, because it is the one piece of arithmetic here that can be silently\n * wrong: a centre-anchored zoom looks correct until someone tries to magnify a defect in a\n * corner, at which point every wheel notch has to be undone with a drag.\n *\n * The transform is `translate(t) scale(z)` about the box's centre, so a content point `c`\n * lands at `p = c·z + t`. Holding `c` fixed while `z` becomes `z'` gives\n * `t' = p − (p − t)·z'/z`, with `p` measured from the centre.\n */\nexport function zoomAt(\n view: View,\n pointer: { x: number; y: number },\n rect: { left: number; top: number; width: number; height: number },\n factor: number,\n): View {\n const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);\n // Bottoming out is a reset: at 1x the content fills the frame, so any offset is a way to\n // be lost with no visible handle to get back.\n if (zoom === MIN_ZOOM) return RESET_VIEW;\n\n const px = pointer.x - rect.left - rect.width / 2;\n const py = pointer.y - rect.top - rect.height / 2;\n const ratio = zoom / view.zoom;\n return {\n zoom,\n x: px - (px - view.x) * ratio,\n y: py - (py - view.y) * ratio,\n };\n}\n\n/**\n * Where a pointer is over the *content*, as fractions of the frame, or `null` outside it.\n *\n * The inverse of the transform `zoomAt` maintains, and pure for the same reason: this is\n * what turns a cursor position into an index into a value plane or a source-pixel\n * coordinate, and it is wrong in a way nothing on screen would reveal — a readout that is\n * confidently off by a pan offset looks exactly like a readout that works.\n *\n * The content fills the frame at zoom 1 by construction (the canvas is laid out with the\n * source aspect ratio), so `[0, 1)` over the frame *is* `[0, 1)` over the image, with no\n * letterbox correction to reconstruct.\n */\nexport function contentUnder(\n view: View,\n pointer: { clientX: number; clientY: number },\n rect: { left: number; top: number; width: number; height: number },\n): { u: number; v: number } | null {\n const px = pointer.clientX - rect.left - rect.width / 2;\n const py = pointer.clientY - rect.top - rect.height / 2;\n const u = (px - view.x) / view.zoom / rect.width + 0.5;\n const v = (py - view.y) / view.zoom / rect.height + 0.5;\n if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;\n return { u, v };\n}\n\n/**\n * The zoom at which one source pixel covers one CSS pixel.\n *\n * Clamped, so an image smaller than its frame reports 1: there are no further pixels to\n * reveal, and pretending otherwise would magnify the resampler rather than the sensor.\n */\nexport function nativeZoomFor(sourceWidth: number, boxWidth: number): number {\n if (!(sourceWidth > 0) || !(boxWidth > 0)) return FULL_TIER_ZOOM;\n return clamp(sourceWidth / boxWidth, MIN_ZOOM, MAX_ZOOM);\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(high, Math.max(low, value));\n}\n\n/**\n * Props of `ZoomPanCanvas`.\n *\n * @deprecated Use `ImageStage` and `ImageStageProps`.\n */\nexport interface ZoomPanCanvasProps {\n /** The current view (controlled). */\n view: View;\n /** Called with every view change — wheel, drag, double-click, the \"Fit\" button. */\n onView: (view: View) => void;\n /** The stacked layers, each filling the frame. */\n children: ReactNode;\n /** Height and any other framing, merged with `cn`; the transform and overflow are handled here. */\n className?: string;\n /** For `aspect-ratio`, which has to be a computed value rather than a utility class. */\n style?: CSSProperties;\n /** Drawn bottom-left over the image, where it cannot push the canvas down. */\n label?: ReactNode;\n /**\n * The source image's pixel width, so double-click can reach true 1:1. Without it the\n * gesture falls back to `FULL_TIER_ZOOM`, which is at least the tier boundary.\n */\n nativeWidth?: number;\n /** Hidden by passing `null` — a caller with its own fit button beside the canvas. */\n fitLabel?: ReactNode;\n /**\n * Where the pointer is over the *content*, as fractions in `[0, 1)`, or `null` when it\n * is outside. Reported through the same transform the layers use, so the coordinate is\n * the one a value plane or a measurement overlay is indexed by however the frame is\n * zoomed or panned. Suppressed while dragging: during a pan the pointer is holding the\n * image, not pointing at a pixel.\n */\n onHover?: (position: { u: number; v: number } | null) => void;\n}\n\n/**\n * A pannable, zoomable frame that transforms its stacked children together; zoom 1 is fit.\n *\n * State is exposed as `data-panning` (present during a drag) and `data-fit` (present at\n * zoom 1) on the frame.\n *\n * @deprecated Use `ImageStage`. This component scales its layers by the frame's size (so\n * the frame must be laid out at the image's aspect ratio) and captures every press to pan\n * (so no interactive layer can live inside it). It stays exported, unchanged in behaviour,\n * for consumers that have not migrated.\n */\nexport function ZoomPanCanvas({\n view,\n onView,\n children,\n className,\n style,\n label,\n nativeWidth,\n fitLabel = \"Fit\",\n onHover,\n}: ZoomPanCanvasProps) {\n const draggingRef = useRef<{ x: number; y: number } | null>(null);\n // Mirrored into state only so the cursor can change — the ref is what the move handler\n // reads, because a re-render per pointermove would be a cost for nothing.\n const [grabbing, setGrabbing] = useState(false);\n const boxRef = useRef<HTMLDivElement>(null);\n // What the wheel listener, attached once, reads: the view and callback of the last commit.\n const latestRef = useRef({ view, onView });\n useLayoutEffect(() => {\n latestRef.current = { view, onView };\n });\n\n /*\n * The wheel listener is attached by hand because React registers `wheel` at the root as\n * **passive**, which makes `preventDefault` in a synthetic handler a no-op. Without it\n * the page scrolls behind the canvas while you zoom, so a gesture aimed at the image\n * moves the document instead — which reads as the zoom being broken.\n */\n useEffect(() => {\n const element = boxRef.current;\n if (!element) return;\n\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const rect = element.getBoundingClientRect();\n const factor = 1 - event.deltaY * ZOOM_SENSITIVITY;\n const { view: current, onView: report } = latestRef.current;\n report(zoomAt(current, { x: event.clientX, y: event.clientY }, rect, factor));\n };\n\n element.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => element.removeEventListener(\"wheel\", onWheel);\n }, []);\n\n const toggleNative = (event: { clientX: number; clientY: number }) => {\n const element = boxRef.current;\n if (!element) return;\n const rect = element.getBoundingClientRect();\n const native = nativeZoomFor(nativeWidth ?? 0, rect.width);\n // Anywhere but fit goes back to fit; fit goes to 1:1 under the cursor.\n const target = view.zoom > MIN_ZOOM ? MIN_ZOOM : native;\n onView(zoomAt(view, { x: event.clientX, y: event.clientY }, rect, target / view.zoom));\n };\n\n const endDrag = () => {\n draggingRef.current = null;\n setGrabbing(false);\n };\n\n return (\n <div\n ref={boxRef}\n style={style}\n data-panning={grabbing ? \"\" : undefined}\n data-fit={view.zoom <= MIN_ZOOM ? \"\" : undefined}\n className={cn(\n \"relative overflow-hidden rounded border border-line bg-canvas select-none\",\n grabbing ? \"cursor-grabbing\" : \"cursor-grab\",\n className,\n )}\n onPointerDown={(event) => {\n draggingRef.current = { x: event.clientX - view.x, y: event.clientY - view.y };\n setGrabbing(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n }}\n onPointerMove={(event) => {\n const origin = draggingRef.current;\n if (!origin) {\n onHover?.(contentUnder(view, event, event.currentTarget.getBoundingClientRect()));\n return;\n }\n // During a pan the pointer is holding the image rather than pointing at a pixel.\n onHover?.(null);\n onView({ ...view, x: event.clientX - origin.x, y: event.clientY - origin.y });\n }}\n onPointerLeave={() => onHover?.(null)}\n onPointerUp={endDrag}\n // A drag interrupted by a lost capture — a context menu, a browser gesture, the\n // pointer leaving the window — used to leave `dragging` set, so the next hover\n // panned the image without a button held down.\n onPointerCancel={endDrag}\n onLostPointerCapture={endDrag}\n onDoubleClick={toggleNative}\n >\n {/* One transformed box holding every layer, so they cannot drift apart. */}\n <div\n className=\"h-full w-full\"\n style={{\n transform: `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`,\n transformOrigin: \"center\",\n }}\n >\n {children}\n </div>\n {label && (\n <span className=\"pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white\">\n {label}\n </span>\n )}\n {fitLabel !== null && view.zoom > MIN_ZOOM && (\n <button\n type=\"button\"\n className=\"absolute right-1 bottom-1 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80\"\n // Stopping `pointerdown` is what makes the button work at all: without it the\n // press bubbles to the canvas, which calls `setPointerCapture` on itself and\n // takes the click with it, so the button rendered and did nothing.\n onPointerDown={(event) => event.stopPropagation()}\n onClick={(event) => {\n event.stopPropagation();\n onView(RESET_VIEW);\n }}\n // The canvas swallows double-clicks to toggle 1:1; without this the second click\n // of a fast double-tap on the button reaches the canvas and zooms straight back.\n onDoubleClick={(event) => event.stopPropagation()}\n >\n {fitLabel}\n </button>\n )}\n </div>\n );\n}\n","/**\n * The numbers behind a picture.\n *\n * A rendered anomaly map or false-colour measurement overlay answers \"is this region\n * hotter than that one\" or \"roughly where does the edge fall\". The next question — *how\n * hot, in the units a metric is computed in* or *at what subpixel coordinate* — cannot be\n * answered from the picture: a colormap clips at both ends and quantizes to 256 entries,\n * and alpha is a gamma of the normalized value, so the inverse is multi-valued.\n *\n * So the values arrive as values, in a fixed 24-byte-header format that is deliberately\n * **not** `.npy` — there is no dtype string to parse and no shape tuple. This module\n * decodes them and indexes them. **It never draws.** Colour range and colormap stay wherever\n * the values were produced.\n */\n\nconst MAGIC = 0x56414d31; // \"VAM1\", read big-endian so the constant is legible.\nconst HEADER_SIZE = 24;\n\n/** A decoded value plane: the numbers behind a rendered map, one `Float32` per pixel and channel. */\nexport interface ValuePlane {\n /** Columns in the plane (after `stride` decimation). */\n width: number;\n /** Rows in the plane (after `stride` decimation). */\n height: number;\n /**\n * The integer decimation applied upstream. `1` means every source pixel is here;\n * anything more means the readout is sampled, and a caller should say so rather than\n * presenting an approximate number as exact.\n */\n stride: number;\n /**\n * How many planes are in `values`, stored one after another.\n *\n * Read from the header rather than assumed: a mono anomaly map is one plane, an RGB\n * source is three, and nothing here may encode which — channel count is data.\n */\n channels: number;\n /** The samples, plane-major: channel, then row, then column. */\n values: Float32Array;\n}\n\n/** Thrown by `decodePlane` when a buffer is not a well-formed value plane. */\nexport class PlaneFormatError extends Error {}\n\n/**\n * Decode a value plane from its binary form: a 24-byte header (big-endian magic `VAM1`,\n * then little-endian `u32` width, height, stride and channels, and 4 reserved bytes)\n * followed by `width · height · channels` little-endian `f32` values.\n *\n * The returned `values` is a view onto `buffer`, not a copy.\n *\n * @throws `PlaneFormatError` when the header is short, the magic is wrong, or the buffer\n * holds fewer values than the header promises.\n */\nexport function decodePlane(buffer: ArrayBuffer): ValuePlane {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new PlaneFormatError(\"a value plane is at least a 24-byte header\");\n }\n const header = new DataView(buffer);\n if (header.getUint32(0, false) !== MAGIC) {\n throw new PlaneFormatError(\"not a value plane — wrong magic\");\n }\n\n const width = header.getUint32(4, true);\n const height = header.getUint32(8, true);\n const stride = header.getUint32(12, true);\n const channels = header.getUint32(16, true);\n const expected = width * height * channels;\n\n if (buffer.byteLength - HEADER_SIZE < expected * 4) {\n throw new PlaneFormatError(`a ${width}x${height}x${channels} plane needs ${expected} values`);\n }\n return {\n width,\n height,\n stride,\n channels,\n values: new Float32Array(buffer, HEADER_SIZE, expected),\n };\n}\n\n/**\n * The value at a normalized position, or `null` outside the plane.\n *\n * `u` and `v` are fractions of the source frame. A stored anomaly map or model-input plane\n * is expected to already be projected into that frame, so crop and letterbox geometry is\n * resolved once upstream rather than reconstructed here. NaN marks an uncovered pixel.\n */\nexport function valueAt(plane: ValuePlane, u: number, v: number, channel = 0): number | null {\n if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;\n if (channel < 0 || channel >= plane.channels) return null;\n const x = Math.min(plane.width - 1, Math.floor(u * plane.width));\n const y = Math.min(plane.height - 1, Math.floor(v * plane.height));\n // Plane-major, so one channel is a single offset rather than a stride walk.\n const value = plane.values[channel * plane.width * plane.height + y * plane.width + x];\n return value !== undefined && Number.isFinite(value) ? value : null;\n}\n\n/** Every channel at one position, in order — one number for mono, three for RGB. */\nexport function valuesAt(plane: ValuePlane, u: number, v: number): number[] {\n const out: number[] = [];\n for (let channel = 0; channel < plane.channels; channel += 1) {\n const value = valueAt(plane, u, v, channel);\n if (value !== null) out.push(value);\n }\n return out;\n}\n\n/** Where a value sits in a range, as a fraction — `null` for a degenerate range. */\nexport function fractionOf(\n value: number,\n range: { low: number; high: number } | null | undefined,\n): number | null {\n if (!range || range.high <= range.low) return null;\n return (value - range.low) / (range.high - range.low);\n}\n\n/**\n * Fetch a value plane from `url` and decode it.\n *\n * @throws `Error` on a non-2xx response, or `PlaneFormatError` for a malformed body.\n */\nexport async function fetchPlane(url: string): Promise<ValuePlane> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`${response.status} fetching values`);\n return decodePlane(await response.arrayBuffer());\n}\n","/**\n * The arithmetic behind `MeasureOverlay`: everything that can be silently wrong, factored\n * out so it can be tested without a DOM.\n *\n * Every primitive `MeasureOverlay` draws is given in **source-image pixel coordinates** —\n * the same frame `ZoomPanCanvas`'s `nativeWidth`/`nativeHeight` describe, and the same one\n * `api/mapValues.ts`'s `u`/`v` fractions index into. Nothing here measures the DOM or knows\n * about zoom directly; `strokeWidthFor` is the one function that turns a *scale factor* a\n * caller already knows (or computes once from a `ZoomPanCanvas` `View`) into a stroke width\n * that reads as constant on screen.\n */\n\n/** A 2D point — in image pixels unless a signature says otherwise. */\nexport interface Point {\n /** Horizontal coordinate, increasing rightward. */\n x: number;\n /** Vertical coordinate, increasing downward. */\n y: number;\n}\n\n/**\n * The on-screen-constant stroke width for a shape drawn in native-pixel units.\n *\n * `MeasureOverlay` is rendered as an SVG whose `viewBox` is the native image size, sitting\n * inside `ZoomPanCanvas`'s own `scale(zoom)` transform. A stroke declared as `1` in that\n * SVG's user units is `1` *native pixel*, which is `strokeScale` screen pixels once both\n * transforms are applied (`strokeScale` = the SVG's own fit ratio × the canvas zoom, or\n * just the zoom when the overlay is already at native resolution). Dividing by it is what\n * keeps a 1px caliper edge looking like 1px at any zoom, rather than growing with it the\n * way a shape's own geometry does.\n *\n * `vector-effect=\"non-scaling-stroke\"` addresses only the SVG's *internal* transforms and\n * is inconsistently applied across browsers once a CSS transform sits above the `<svg>`\n * itself (exactly the situation inside `ZoomPanCanvas`), so this is computed explicitly\n * rather than left to the renderer.\n */\nexport function strokeWidthFor(strokeScale: number, screenPixels = 1): number {\n if (!Number.isFinite(strokeScale) || strokeScale <= 0) return screenPixels;\n return screenPixels / strokeScale;\n}\n\n/** Rotate `(x, y)` about the origin by `angle` radians. */\nexport function rotatePoint(x: number, y: number, angle: number): Point {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return { x: x * c - y * s, y: x * s + y * c };\n}\n\n/** `M x,y L x,y … Z` through `points`, or `\"\"` for fewer than two of them. */\nexport function polygonPath(points: readonly Point[]): string {\n if (points.length < 2) return \"\";\n const [first, ...rest] = points;\n const p0 = first as Point;\n const commands = [`M${p0.x.toFixed(2)} ${p0.y.toFixed(2)}`];\n for (const point of rest) commands.push(`L${point.x.toFixed(2)} ${point.y.toFixed(2)}`);\n commands.push(\"Z\");\n return commands.join(\" \");\n}\n\n/** The two line segments of a cross mark centred on `(x, y)`, each `2·size` long. */\nexport function crossSegments(x: number, y: number, size: number): [[Point, Point], [Point, Point]] {\n return [\n [{ x: x - size, y }, { x: x + size, y }],\n [{ x, y: y - size }, { x, y: y + size }],\n ];\n}\n\n/**\n * The angular sweep from `startAngle` to `endAngle`, going forward.\n *\n * Two angles alone cannot distinguish \"no sweep at all\" from \"swept exactly one full turn\"\n * — both have `endAngle - startAngle ≡ 0 (mod 2π)`. The raw (un-normalized) difference is\n * what carries that distinction: genuinely equal angles have a raw difference near zero,\n * while a caller asking for a full circle passes a raw difference of `2π` (or a multiple of\n * it). So only a raw difference near zero is treated as \"nothing to draw\"; every other\n * multiple of a full turn normalizes to `2π` itself rather than collapsing to `0`.\n */\nfunction sweepAngle(startAngle: number, endAngle: number): number {\n const turn = Math.PI * 2;\n const EPSILON = 1e-9;\n const raw = endAngle - startAngle;\n if (Math.abs(raw) < EPSILON) return 0;\n const delta = raw % turn;\n return delta <= EPSILON ? delta + turn : delta;\n}\n\n/**\n * An SVG arc path centred at `(cx, cy)` with radius `r`, sweeping forward from `startAngle`\n * to `endAngle` (radians, standard `x = cx + r·cos(a)`, `y = cy + r·sin(a)` convention —\n * clockwise on screen, since image-pixel `y` increases downward).\n *\n * A single SVG `A` command cannot express a full circle (its start and end point coincide,\n * which most renderers treat as a zero-length arc), so a sweep that reaches all the way\n * around is split into two half-circle arcs instead.\n */\nexport function arcPath(cx: number, cy: number, r: number, startAngle: number, endAngle: number): string {\n if (!(r > 0)) return \"\";\n\n const start = { x: cx + r * Math.cos(startAngle), y: cy + r * Math.sin(startAngle) };\n const sweep = sweepAngle(startAngle, endAngle);\n const FULL_TURN_EPSILON = 1e-9;\n\n if (sweep < FULL_TURN_EPSILON) {\n // A zero (or effectively zero) sweep is a point, not an arc.\n return \"\";\n }\n if (sweep >= Math.PI * 2 - FULL_TURN_EPSILON) {\n const mid = { x: cx + r * Math.cos(startAngle + Math.PI), y: cy + r * Math.sin(startAngle + Math.PI) };\n return (\n `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${mid.x.toFixed(2)} ${mid.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${start.x.toFixed(2)} ${start.y.toFixed(2)}`\n );\n }\n\n const end = { x: cx + r * Math.cos(endAngle), y: cy + r * Math.sin(endAngle) };\n const largeArc = sweep > Math.PI ? 1 : 0;\n return (\n `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${end.x.toFixed(2)} ${end.y.toFixed(2)}`\n );\n}\n\n/**\n * The four corners of a caliper box: a rectangle `width` (along its own measurement axis)\n * by `height`, centred at `(cx, cy)` and rotated by `angle` radians. Corner order is\n * suitable for `polygonPath` — around the box, not crossed.\n */\nexport function caliperCorners(\n cx: number,\n cy: number,\n width: number,\n height: number,\n angle: number,\n): [Point, Point, Point, Point] {\n const hw = width / 2;\n const hh = height / 2;\n const local: [number, number][] = [\n [-hw, -hh],\n [hw, -hh],\n [hw, hh],\n [-hw, hh],\n ];\n const [a, b, c, d] = local.map(([lx, ly]) => {\n const r = rotatePoint(lx, ly, angle);\n return { x: cx + r.x, y: cy + r.y };\n });\n return [a as Point, b as Point, c as Point, d as Point];\n}\n\n/**\n * The direction arrow for a caliper box: from its centre to just past its `+local-x` edge,\n * along the box's own measurement axis. What the arrow points at is the scan direction the\n * caliper was evaluated in, not merely a decoration on the box.\n */\nexport function caliperArrow(\n cx: number,\n cy: number,\n width: number,\n angle: number,\n): { from: Point; to: Point } {\n const reach = width / 2 + Math.max(4, width * 0.2);\n const tip = rotatePoint(reach, 0, angle);\n return { from: { x: cx, y: cy }, to: { x: cx + tip.x, y: cy + tip.y } };\n}\n\n/**\n * A small open chevron at `tip`, pointing along `angle` (radians), for a caliper's\n * direction arrow. Three points — left-back, tip, right-back — meant for an unfilled\n * `<polyline>`, which keeps the arrowhead's colour exactly the stroke colour of the line it\n * caps without the fill-vs-stroke bookkeeping a filled triangle would need per tone.\n */\nexport function arrowHeadPoints(tip: Point, angle: number, size: number): [Point, Point, Point] {\n const back = size * 1.6;\n const spread = size;\n const left = rotatePoint(-back, spread, angle);\n const right = rotatePoint(-back, -spread, angle);\n return [\n { x: tip.x + left.x, y: tip.y + left.y },\n tip,\n { x: tip.x + right.x, y: tip.y + right.y },\n ];\n}\n\n/** What `dimensionGeometry` computes: the lines and label placement of a dimension annotation. */\nexport interface DimensionGeometry {\n /** From the first measured point out to the dimension line. */\n extensionLine1: [Point, Point];\n /** From the second measured point out to the dimension line. */\n extensionLine2: [Point, Point];\n /** The offset line spanning the measured distance, parallel to the measured segment. */\n dimensionLine: [Point, Point];\n /** Midpoint of the dimension line — where the label sits. */\n labelAnchor: Point;\n /** The dimension line's own direction, in degrees, for an upright label rotation. */\n angleDegrees: number;\n}\n\n/**\n * The leader geometry for a dimension annotation between two measured points, offset by\n * `offset` native pixels to the line's left (so a positive offset with a left-to-right\n * measurement draws the dimension line above it, consistent with `y` increasing downward).\n *\n * Degenerate input (`x1 === x2 && y1 === y2`) falls back to an arbitrary rightward normal\n * rather than dividing by zero, so a caller need not special-case a zero-length dimension.\n */\nexport function dimensionGeometry(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n offset: number,\n): DimensionGeometry {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n const [ux, uy] = length > 1e-9 ? [dx / length, dy / length] : [1, 0];\n // The left-hand normal of the measured direction in a y-down frame: for a rightward\n // measurement (u = (1, 0)) this is (0, -1), i.e. \"up\" on screen, which is what makes a\n // positive offset draw the dimension line above a left-to-right span rather than below.\n const nx = uy;\n const ny = -ux;\n\n const p1: Point = { x: x1 + nx * offset, y: y1 + ny * offset };\n const p2: Point = { x: x2 + nx * offset, y: y2 + ny * offset };\n\n return {\n extensionLine1: [{ x: x1, y: y1 }, p1],\n extensionLine2: [{ x: x2, y: y2 }, p2],\n dimensionLine: [p1, p2],\n labelAnchor: { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 },\n angleDegrees: (Math.atan2(dy, dx) * 180) / Math.PI,\n };\n}\n","/**\n * A vector overlay layer for measurement primitives, drawn in source-image pixel\n * coordinates.\n *\n * Meant to sit as one of the transformed children inside `ZoomPanCanvas`, alongside the\n * image itself and any raster layers (a mask, a false-colour value plane). Because the\n * whole stack is transformed together (see `ZoomPanCanvas`'s own docs), a caliper box\n * drawn here stays registered with the pixel it measures at any zoom or pan — the overlay\n * never touches the DOM to find out where it is; it is told, in `nativeWidth` ×\n * `nativeHeight` pixel coordinates, via `primitives`.\n *\n * This component holds **no app state**: no fetch, no selection, no hover tracking. It is a\n * pure function of its props, on purpose — the app decides what a \"caliper box\" or a\n * \"detected edge\" *is*; this only knows how to draw one. The one piece of arithmetic it\n * owns is `strokeScale` compensation (see `measureGeometry.ts`'s `strokeWidthFor`), because\n * getting that wrong is invisible on screen until someone zooms in and a \"1px\" edge marker\n * has silently become 8px wide.\n */\n\nimport { imageViewBox } from \"./stage/view\";\nimport { arcPath, arrowHeadPoints, caliperArrow, caliperCorners, crossSegments, dimensionGeometry, polygonPath, strokeWidthFor } from \"./measureGeometry\";\nimport { cn, toneColor, type MeasureTone } from \"@vitavision/ui\";\n\nexport type { MeasureTone };\n\n/** A marked location: a dot, or a cross for a subpixel edge. */\nexport interface PointPrimitive {\n /** Discriminant. */\n kind: \"point\";\n /** Image x of the point. */\n x: number;\n /** Image y of the point. */\n y: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Native-pixel radius of the dot. Ignored when `cross` is set. */\n radius?: number;\n /** Drawn as a cross instead of a dot — the usual mark for a subpixel edge location. */\n cross?: boolean;\n /** Text drawn just above the mark. */\n label?: string;\n}\n\n/** A straight line between two image points. */\nexport interface SegmentPrimitive {\n /** Discriminant. */\n kind: \"segment\";\n /** Image x of the first end. */\n x1: number;\n /** Image y of the first end. */\n y1: number;\n /** Image x of the second end. */\n x2: number;\n /** Image y of the second end. */\n y2: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** A short dash pattern, e.g. for a fitted line shown against its inlier points. */\n dashed?: boolean;\n}\n\n/** A circle — a fitted bore, a tolerance ring. */\nexport interface CirclePrimitive {\n /** Discriminant. */\n kind: \"circle\";\n /** Image x of the centre. */\n cx: number;\n /** Image y of the centre. */\n cy: number;\n /** Radius, in image pixels. */\n r: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Filled rather than stroked — rare, but a small confidence disc wants it. */\n filled?: boolean;\n}\n\n/** A circular arc, swept forward (clockwise on screen) from `startAngle` to `endAngle`. */\nexport interface ArcPrimitive {\n /** Discriminant. */\n kind: \"arc\";\n /** Image x of the centre. */\n cx: number;\n /** Image y of the centre. */\n cy: number;\n /** Radius, in image pixels. */\n r: number;\n /** Radians. `x = cx + r·cos(a)`, `y = cy + r·sin(a)` — clockwise on screen. */\n startAngle: number;\n /** Radians, same convention as `startAngle`. A full turn past it draws a whole circle. */\n endAngle: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n}\n\n/** A caliper search box: a rotated rectangle with an arrow along its scan direction. */\nexport interface CaliperPrimitive {\n /** Discriminant. */\n kind: \"caliper\";\n /** Image x of the box centre. */\n cx: number;\n /** Image y of the box centre. */\n cy: number;\n /** Along the box's own measurement axis. */\n width: number;\n /** Perpendicular to the measurement axis — the search span. */\n height: number;\n /** Radians, the box's own rotation (and its measurement direction). */\n angle: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Draws the direction arrow along the box's +x axis. Defaults to on. */\n showDirection?: boolean;\n /** Text drawn at the box centre. */\n label?: string;\n}\n\n/** A dimension annotation: extension lines, an offset dimension line, and its value as text. */\nexport interface DimensionPrimitive {\n /** Discriminant. */\n kind: \"dimension\";\n /** Image x of the first measured point. */\n x1: number;\n /** Image y of the first measured point. */\n y1: number;\n /** Image x of the second measured point. */\n x2: number;\n /** Image y of the second measured point. */\n y2: number;\n /** The measured value as text, drawn along the dimension line. */\n label: string;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Native pixels the dimension line sits off the measured span. Defaults to 16. */\n offset?: number;\n}\n\n/** Anything `MeasureOverlay` can draw, discriminated by `kind`. */\nexport type MeasurePrimitive =\n | PointPrimitive\n | SegmentPrimitive\n | CirclePrimitive\n | ArcPrimitive\n | CaliperPrimitive\n | DimensionPrimitive;\n\nconst DEFAULT_LABEL_SIZE = 11;\nconst DEFAULT_POINT_RADIUS = 3;\nconst DEFAULT_CROSS_SIZE = 5;\nconst DEFAULT_DIMENSION_OFFSET = 16;\n\n/** Props of `MeasureOverlay`. */\nexport interface MeasureOverlayProps {\n /** The source image's pixel width — the overlay's `viewBox`, and every primitive's frame. */\n nativeWidth: number;\n /** The source image's pixel height. */\n nativeHeight: number;\n /** What to draw, in image pixel coordinates, bottom to top. */\n primitives: MeasurePrimitive[];\n /**\n * The combined image-pixel → screen-pixel scale currently in effect, so a stroke or a\n * label declared at \"1 screen pixel\" stays that size regardless of zoom. Inside an\n * `ImageStage` (which lays the overlay out at exactly `nativeWidth` × `nativeHeight` CSS\n * pixels) this is simply `useStage().view.scale`. See `strokeWidthFor`.\n */\n strokeScale: number;\n /** Merged onto the `<svg>` with `cn`. */\n className?: string;\n}\n\n/**\n * A vector overlay of measurement primitives — points, segments, circles, arcs, caliper\n * boxes, dimensions — drawn in source-image pixel coordinates.\n *\n * Place it as a layer inside `ImageStage` so it moves with the image. It is a pure function\n * of its props and decorative to assistive technology (`aria-hidden`), so a result drawn\n * only here must also be stated in text.\n */\nexport function MeasureOverlay({\n nativeWidth,\n nativeHeight,\n primitives,\n strokeScale,\n className,\n}: MeasureOverlayProps) {\n const hairline = strokeWidthFor(strokeScale, 1);\n const thick = strokeWidthFor(strokeScale, 1.5);\n const labelSize = strokeWidthFor(strokeScale, DEFAULT_LABEL_SIZE);\n\n return (\n <svg\n role=\"presentation\"\n aria-hidden\n viewBox={imageViewBox({ width: nativeWidth, height: nativeHeight })}\n preserveAspectRatio=\"none\"\n className={cn(\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\", className)}\n >\n {primitives.map((primitive, index) => (\n <Primitive\n // Primitives carry no identity and hold no state; a position is the only key.\n // eslint-disable-next-line @eslint-react/no-array-index-key\n key={index}\n primitive={primitive}\n hairline={hairline}\n thick={thick}\n labelSize={labelSize}\n strokeScale={strokeScale}\n />\n ))}\n </svg>\n );\n}\n\nfunction Primitive({\n primitive,\n hairline,\n thick,\n labelSize,\n strokeScale,\n}: {\n primitive: MeasurePrimitive;\n hairline: number;\n thick: number;\n labelSize: number;\n strokeScale: number;\n}) {\n const colour = toneColor(primitive.tone);\n\n switch (primitive.kind) {\n case \"point\": {\n if (primitive.cross) {\n const size = strokeWidthFor(strokeScale, DEFAULT_CROSS_SIZE);\n const [h, v] = crossSegments(primitive.x, primitive.y, size);\n return (\n <g stroke={colour} strokeWidth={hairline}>\n <line x1={h[0].x} y1={h[0].y} x2={h[1].x} y2={h[1].y} />\n <line x1={v[0].x} y1={v[0].y} x2={v[1].x} y2={v[1].y} />\n <Label x={primitive.x} y={primitive.y - size - 2} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n const radius = strokeWidthFor(strokeScale, primitive.radius ?? DEFAULT_POINT_RADIUS);\n return (\n <g>\n <circle cx={primitive.x} cy={primitive.y} r={radius} fill={colour} />\n <Label x={primitive.x} y={primitive.y - radius - 2} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n\n case \"segment\":\n return (\n <line\n x1={primitive.x1}\n y1={primitive.y1}\n x2={primitive.x2}\n y2={primitive.y2}\n stroke={colour}\n strokeWidth={hairline}\n strokeDasharray={primitive.dashed ? `${hairline * 4} ${hairline * 3}` : undefined}\n />\n );\n\n case \"circle\":\n return (\n <circle\n cx={primitive.cx}\n cy={primitive.cy}\n r={primitive.r}\n fill={primitive.filled ? colour : \"none\"}\n stroke={primitive.filled ? \"none\" : colour}\n strokeWidth={hairline}\n />\n );\n\n case \"arc\":\n return (\n <path\n d={arcPath(primitive.cx, primitive.cy, primitive.r, primitive.startAngle, primitive.endAngle)}\n fill=\"none\"\n stroke={colour}\n strokeWidth={hairline}\n strokeLinecap=\"round\"\n />\n );\n\n case \"caliper\": {\n const corners = caliperCorners(primitive.cx, primitive.cy, primitive.width, primitive.height, primitive.angle);\n const arrow = caliperArrow(primitive.cx, primitive.cy, primitive.width, primitive.angle);\n const head = arrowHeadPoints(arrow.to, primitive.angle, strokeWidthFor(strokeScale, 4));\n return (\n <g>\n <path d={polygonPath(corners)} fill=\"none\" stroke={colour} strokeWidth={hairline} />\n {primitive.showDirection !== false && (\n <g stroke={colour} strokeWidth={thick} strokeLinecap=\"round\" strokeLinejoin=\"round\" fill=\"none\">\n <line x1={arrow.from.x} y1={arrow.from.y} x2={arrow.to.x} y2={arrow.to.y} />\n <polyline points={head.map((p) => `${p.x},${p.y}`).join(\" \")} />\n </g>\n )}\n <Label x={primitive.cx} y={primitive.cy} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n\n case \"dimension\": {\n const offset = primitive.offset ?? DEFAULT_DIMENSION_OFFSET;\n const geometry = dimensionGeometry(primitive.x1, primitive.y1, primitive.x2, primitive.y2, offset);\n return (\n <g stroke={colour} strokeWidth={hairline}>\n <line x1={geometry.extensionLine1[0].x} y1={geometry.extensionLine1[0].y} x2={geometry.extensionLine1[1].x} y2={geometry.extensionLine1[1].y} opacity={0.5} />\n <line x1={geometry.extensionLine2[0].x} y1={geometry.extensionLine2[0].y} x2={geometry.extensionLine2[1].x} y2={geometry.extensionLine2[1].y} opacity={0.5} />\n <line x1={geometry.dimensionLine[0].x} y1={geometry.dimensionLine[0].y} x2={geometry.dimensionLine[1].x} y2={geometry.dimensionLine[1].y} />\n <text\n x={geometry.labelAnchor.x}\n y={geometry.labelAnchor.y}\n fontSize={labelSize}\n fill={colour}\n stroke=\"none\"\n textAnchor=\"middle\"\n dominantBaseline=\"text-after-edge\"\n transform={`rotate(${geometry.angleDegrees} ${geometry.labelAnchor.x} ${geometry.labelAnchor.y})`}\n >\n {primitive.label}\n </text>\n </g>\n );\n }\n\n default:\n return null;\n }\n}\n\nfunction Label({\n x,\n y,\n text,\n colour,\n size,\n}: {\n x: number;\n y: number;\n text?: string | undefined;\n colour: string;\n size: number;\n}) {\n if (!text) return null;\n return (\n <text x={x} y={y} fontSize={size} fill={colour} textAnchor=\"middle\" dominantBaseline=\"text-after-edge\">\n {text}\n </text>\n );\n}\n"],"mappings":";;;;;;;;;AAwEA,MAAa,eAAe;;;;;;;;AAS5B,SAAgB,aAAa,OAAoB;CAC/C,OAAO,aAAqC,MAAM,MAAM,GAAG,MAAM;AACnE;;AAGA,MAAa,YAAY;;;;;;;;AASzB,MAAa,mBAAmB;;AAGhC,MAAM,eAAe;CACnB;CAAM;CAAQ;CAAO;CAAQ;CAAM;CAAQ;CAAK;CAAQ;CAAG;CAAK;CAAG;CAAG;CAAG;CAAG;CAAG;CAAI;CAAI;CAAI;AAC7F;;AAGA,MAAM,gBAAgB;;AAEtB,MAAM,iBAAiB;;AAGvB,SAAgB,SAAS,KAAU,OAAoB;CACrD,IAAI,EAAE,IAAI,QAAQ,MAAM,EAAE,IAAI,SAAS,MAAM,EAAE,MAAM,QAAQ,MAAM,EAAE,MAAM,SAAS,IAAI,OAAO;CAC/F,OAAO,KAAK,IAAI,IAAI,QAAQ,MAAM,OAAO,IAAI,SAAS,MAAM,MAAM;AACpE;;AAGA,SAAgB,QAAQ,KAAU,OAAuB;CAEvD,OAAO,QADO,SAAS,KAAK,KACT,GAAG,KAAK,KAAK;AAClC;;AAGA,SAAgB,YAAY,KAAU,OAAuB;CAC3D,OAAO,QAAQ,KAAK,IAAI,GAAG,SAAS,KAAK,KAAK,CAAC,GAAG,KAAK,KAAK;AAC9D;AAEA,SAAS,QAAQ,OAAe,KAAU,OAAuB;CAC/D,OAAO;EACL;EACA,K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AAU,SAAS,aAAa,GAAG,SAAS,YAAY,EAAE,GAAG,SAAS,YAAY,EAAE;MAE9F,UAAA,UAAU;KACP,CAAA;IACL;;EAEP;EAEA,SACE,OAAO;CACX;AACF;AAEA,SAAS,MAAM,EACb,GACA,GACA,MACA,QACA,QAOC;CACD,IAAI,CAAC,MAAM,OAAO;CAClB,OACE,oBAAC,QAAD;EAAS;EAAM;EAAG,UAAU;EAAM,MAAM;EAAQ,YAAW;EAAS,kBAAiB;EAClF,UAAA;CACG,CAAA;AAEV"}
1
+ {"version":3,"file":"index.js","names":["clamp"],"sources":["../src/components/stage/view.ts","../src/components/stage/ImageStage.tsx","../src/components/stage/StageToolbar.tsx","../src/components/ZoomPanCanvas.tsx","../src/api/mapValues.ts","../src/components/measureGeometry.ts","../src/components/MeasureOverlay.tsx"],"sourcesContent":["/**\n * The image ↔ screen transform, as pure arithmetic.\n *\n * One transform, in absolute units: the stage element is laid out at exactly the source\n * image's pixel size and carries `translate(tx, ty) scale(scale)` about its top-left corner,\n * so an image point `p` lands at `p · scale + t` and nothing else participates. `scale` is\n * therefore *CSS pixels per image pixel* — `scale === 1` is 100%, and fit is whatever\n * `fitScale` returns for the current viewport, a value rather than a magic constant.\n *\n * The predecessor (`ZoomPanCanvas`) instead composed two scales it never named: a layout\n * scale from the frame's own size, and a CSS transform about the frame's centre. That\n * worked only while the frame's aspect ratio matched the image's, and the one consumer that\n * forgot to enforce that drew its overlays stretched against a letterboxed photograph — the\n * layers drifting apart on window resize, which is precisely the failure this replaces.\n * Laying the stage out at the image's own size removes the first scale entirely, so a child\n * `<svg viewBox=\"0 0 W H\">` is registered with the photograph by construction.\n *\n * Every function here is pure and tested, because this is arithmetic that goes wrong in a\n * way nothing on screen reveals: an overlay that is confidently off by a pan offset looks\n * exactly like an overlay that works.\n *\n * Points are in **viewport-local** CSS pixels — client coordinates with the viewport's\n * `getBoundingClientRect()` origin already subtracted. Keeping the rect out of these\n * signatures is what makes them testable without a DOM.\n *\n * **Image coordinates name pixel centres**, which is the convention every image-processing\n * result uses: `i` means the centre of pixel `i`, so an edge detected exactly between two\n * columns comes back as `i + 0.5`. CSS is the other convention: an `<img>` laid out at its\n * natural size puts pixel `i` across `[i, i + 1)`, so *its* `i` is the pixel's left edge.\n * The half-pixel between them is what `PIXEL_CENTRE` carries, and it is not cosmetic on a\n * metrology bench — at 8x it is four screen pixels of disagreement between an overlay and\n * the edge it claims to mark, and it is invisible at fit, which is where it gets missed.\n *\n * A layer drawn in image coordinates therefore uses `imageViewBox`, not `0 0 W H`.\n */\n\nimport type { Point } from \"../measureGeometry\";\n\n/** A `translate(tx, ty) scale(scale)` about the stage's top-left corner. */\nexport interface StageView {\n /** CSS pixels per image pixel. `1` is 100%. */\n scale: number;\n /** Horizontal offset of the image's top-left corner from the viewport's, in CSS pixels. */\n tx: number;\n /** Vertical offset of the image's top-left corner from the viewport's, in CSS pixels. */\n ty: number;\n}\n\n/** A size: the viewport's in CSS pixels, or the image's in image pixels. */\nexport interface Box {\n /** Horizontal extent. */\n width: number;\n /** Vertical extent. */\n height: number;\n}\n\n/** An axis-aligned rectangle in image coordinates, from its top-left corner. */\nexport interface Rect {\n /** Left edge. */\n x: number;\n /** Top edge. */\n y: number;\n /** Horizontal extent. */\n width: number;\n /** Vertical extent. */\n height: number;\n}\n\n/**\n * The offset between the two pixel conventions: an image coordinate `i` sits at CSS\n * `i + 0.5` inside a stage laid out at the image's natural size.\n */\nexport const PIXEL_CENTRE = 0.5;\n\n/**\n * The `viewBox` for an SVG layer drawn in image coordinates, over a stage of that image.\n *\n * Shifted by half a pixel so a primitive at image coordinate `i` lands on the *centre* of\n * pixel `i` rather than on its left edge. Its extent is unchanged — the box still covers\n * exactly the image — so nothing about sizing or `preserveAspectRatio` changes with it.\n */\nexport function imageViewBox(image: Box): string {\n return `${-PIXEL_CENTRE} ${-PIXEL_CENTRE} ${image.width} ${image.height}`;\n}\n\n/** The most a viewer may magnify: past this the resampler is the subject, not the sensor. */\nexport const MAX_SCALE = 32;\n\n/**\n * How far below fit zooming out may go.\n *\n * `ZoomPanCanvas` bottomed out *at* fit, on the reasoning that there is nothing further to\n * see. There is: room around the part, which is what you want when dragging an ROI out to\n * the frame edge or checking that a model's points do not run off the image.\n */\nexport const MIN_SCALE_VS_FIT = 0.25;\n\n/** Zoom in/out steps, as the percentages a readout can show without apologising. */\nconst SCALE_LADDER = [\n 0.05, 0.0833, 0.125, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32,\n];\n\n/** Relative tolerance for \"is this the same scale\" — a hair under a tenth of a percent. */\nconst SCALE_EPSILON = 1e-3;\n/** Absolute tolerance for \"is this the same offset\", in CSS pixels. */\nconst OFFSET_EPSILON = 0.5;\n\n/** The scale at which the whole image is just visible inside `box`. */\nexport function fitScale(box: Box, image: Box): number {\n if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;\n return Math.min(box.width / image.width, box.height / image.height);\n}\n\n/** Fit, centred — the view a viewer opens at and the one `0` returns to. */\nexport function fitView(box: Box, image: Box): StageView {\n const scale = fitScale(box, image);\n return centred(scale, box, image);\n}\n\n/** The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view. */\nexport function initialView(box: Box, image: Box): StageView {\n return centred(Math.min(1, fitScale(box, image)), box, image);\n}\n\nfunction centred(scale: number, box: Box, image: Box): StageView {\n return {\n scale,\n tx: (box.width - image.width * scale) / 2,\n ty: (box.height - image.height * scale) / 2,\n };\n}\n\n/** Whether `view` is (indistinguishably) the fit view for this box and image. */\nexport function isFit(view: StageView, box: Box, image: Box): boolean {\n const fit = fitView(box, image);\n return (\n Math.abs(view.scale - fit.scale) <= fit.scale * SCALE_EPSILON &&\n Math.abs(view.tx - fit.tx) <= OFFSET_EPSILON &&\n Math.abs(view.ty - fit.ty) <= OFFSET_EPSILON\n );\n}\n\n/** Where the **centre of** image pixel `p` lands in the viewport. */\nexport function toScreen(view: StageView, p: Point): Point {\n return {\n x: (p.x + PIXEL_CENTRE) * view.scale + view.tx,\n y: (p.y + PIXEL_CENTRE) * view.scale + view.ty,\n };\n}\n\n/**\n * Which image coordinate a viewport position is over, in the same pixel-centre convention:\n * the exact centre of the top-left pixel reads `0, 0`, and its top-left corner `-0.5, -0.5`.\n *\n * Unbounded — callers clamp if they care.\n */\nexport function toImage(view: StageView, p: Point): Point {\n return {\n x: (p.x - view.tx) / view.scale - PIXEL_CENTRE,\n y: (p.y - view.ty) / view.scale - PIXEL_CENTRE,\n };\n}\n\n/** Whether an image coordinate is inside the image, in the pixel-centre convention. */\nexport function insideImage(p: Point, image: Box): boolean {\n return (\n p.x >= -PIXEL_CENTRE &&\n p.y >= -PIXEL_CENTRE &&\n p.x < image.width - PIXEL_CENTRE &&\n p.y < image.height - PIXEL_CENTRE\n );\n}\n\n/** A length in image pixels that covers `css` screen pixels at this view. */\nexport function imageLengthFor(view: StageView, css: number): number {\n return view.scale > 0 ? css / view.scale : css;\n}\n\n/**\n * Change the scale while holding whatever is under `anchor` where it is.\n *\n * The one piece of arithmetic here that is silently wrong when centre-anchored instead:\n * magnifying a defect in a corner then costs a drag to undo every wheel notch.\n */\nexport function zoomAbout(view: StageView, scale: number, anchor: Point): StageView {\n if (!(view.scale > 0) || !(scale > 0)) return view;\n const ratio = scale / view.scale;\n return {\n scale,\n tx: anchor.x - (anchor.x - view.tx) * ratio,\n ty: anchor.y - (anchor.y - view.ty) * ratio,\n };\n}\n\n/** The scale range `clampView` and `scaleRange` allow. */\nexport interface ClampOptions {\n /** Lowest scale, as a multiple of fit. Defaults to `MIN_SCALE_VS_FIT`. */\n minScaleVsFit?: number;\n /** Highest scale, in CSS pixels per image pixel. Defaults to `MAX_SCALE`. */\n maxScale?: number;\n}\n\n/** The scale range a viewport allows for an image, as `[min, max]`. */\nexport function scaleRange(box: Box, image: Box, options: ClampOptions = {}): [number, number] {\n const fit = fitScale(box, image);\n const min = fit * (options.minScaleVsFit ?? MIN_SCALE_VS_FIT);\n const max = Math.max(min, options.maxScale ?? MAX_SCALE);\n return [min, max];\n}\n\n/**\n * Keep the view legal: scale inside its range, and the image never dragged off screen.\n *\n * An axis where the scaled image is smaller than the viewport is centred rather than left\n * where a drag put it — free-floating pixels in a grey field is a way to be lost with no\n * visible handle to get back. An axis where it is larger is held so the viewport stays\n * covered.\n */\nexport function clampView(\n view: StageView,\n box: Box,\n image: Box,\n options: ClampOptions = {},\n): StageView {\n const [min, max] = scaleRange(box, image, options);\n const scale = clamp(view.scale, min, max);\n return {\n scale,\n tx: clampAxis(view.tx, box.width, image.width * scale),\n ty: clampAxis(view.ty, box.height, image.height * scale),\n };\n}\n\nfunction clampAxis(t: number, boxLength: number, contentLength: number): number {\n if (contentLength <= boxLength) return (boxLength - contentLength) / 2;\n return clamp(t, boxLength - contentLength, 0);\n}\n\n/**\n * The view that puts `rect` (image coordinates) on screen with a margin around it.\n *\n * `pad` is a fraction of the rect's own size, so framing a long thin contour and framing a\n * blob both leave a proportionate border rather than a fixed one that swallows the small\n * one.\n */\nexport function frameRect(box: Box, image: Box, rect: Rect, pad = 0.15): StageView {\n const width = Math.max(rect.width, 1e-6) * (1 + 2 * pad);\n const height = Math.max(rect.height, 1e-6) * (1 + 2 * pad);\n const scale = Math.min(box.width / width, box.height / height);\n const centre = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };\n return clampView(\n {\n scale,\n tx: box.width / 2 - (centre.x + PIXEL_CENTRE) * scale,\n ty: box.height / 2 - (centre.y + PIXEL_CENTRE) * scale,\n },\n box,\n image,\n { maxScale: MAX_SCALE },\n );\n}\n\n/**\n * The same view, after the viewport changed size.\n *\n * The image point at the old centre stays at the new centre, at the same scale — so a\n * window resize moves the frame around the picture instead of moving the picture. A view\n * that was *fit* re-fits instead, because fit is a relationship to the viewport rather than\n * a particular pair of numbers.\n */\nexport function preserveCenter(\n view: StageView,\n from: Box,\n to: Box,\n image: Box,\n options: ClampOptions = {},\n): StageView {\n if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image), to, image, options);\n if (isFit(view, from, image)) return fitView(to, image);\n\n const centre = toImage(view, { x: from.width / 2, y: from.height / 2 });\n return clampView(\n {\n scale: view.scale,\n tx: to.width / 2 - (centre.x + PIXEL_CENTRE) * view.scale,\n ty: to.height / 2 - (centre.y + PIXEL_CENTRE) * view.scale,\n },\n to,\n image,\n options,\n );\n}\n\n/**\n * The next scale up or down the ladder from `scale`, so the readout lands on a round\n * percentage rather than wherever a multiplier happened to leave it.\n */\nexport function steppedScale(scale: number, direction: 1 | -1, min: number, max: number): number {\n const ladder = SCALE_LADDER.filter((s) => s >= min - 1e-9 && s <= max + 1e-9);\n const candidates = ladder.length > 0 ? ladder : [clamp(scale, min, max)];\n if (direction > 0) {\n const next = candidates.find((s) => s > scale * (1 + SCALE_EPSILON));\n return next ?? Math.min(max, Math.max(scale, candidates[candidates.length - 1]!));\n }\n const previous = [...candidates].reverse().find((s) => s < scale * (1 - SCALE_EPSILON));\n return previous ?? Math.max(min, Math.min(scale, candidates[0]!));\n}\n\n/** `0.5` → `\"50%\"`, `1` → `\"100%\"`, `0.0833` → `\"8%\"`. */\nexport function formatScale(scale: number): string {\n const percent = scale * 100;\n if (percent >= 100) return `${Math.round(percent)}%`;\n if (percent >= 10) return `${Math.round(percent)}%`;\n return `${percent.toFixed(1)}%`;\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(high, Math.max(low, value));\n}\n","/**\n * A pannable, zoomable frame that transforms **everything stacked inside it together**.\n *\n * A result viewer over a stack — a photograph, an anomaly map, a model's segmentation, a\n * measurement overlay drawn in source-image pixel coordinates — and the layers only stay\n * registered with each other if one transform moves all of them.\n *\n * The stage element is laid out at **exactly the image's pixel size** and carries the whole\n * transform (see `view.ts`). Two things follow, and both are the point:\n *\n * - a child `<svg viewBox=\"0 0 W H\">` at `inset-0` is registered with the photograph at\n * every viewport size, with no letterbox correction to get wrong. Its predecessor\n * scaled layers by the *frame's* size, so an aspect mismatch between frame and image\n * drew the overlay stretched against a letterboxed picture — layers drifting apart on\n * window resize;\n * - `scale` means CSS pixels per image pixel, so \"100%\" is a value rather than a\n * coincidence, and zooming *out* past fit is expressible.\n *\n * Interactive children are supported, which is the other half of the rewrite. This stage\n * starts a pan only when the gesture is unclaimed — the press landed on the background, or\n * used the middle button, or held space, or the caller says the pan tool is active. A layer\n * that wants a press simply handles it. The predecessor called `setPointerCapture` on every\n * `pointerdown`, so an ROI handle or a clickable contour could not exist inside it at all,\n * and its consumers put those layers *outside* the transform — where they no longer moved\n * with the image.\n */\n\nimport {\n createContext,\n use,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type {\n CSSProperties,\n KeyboardEvent as ReactKeyboardEvent,\n PointerEvent as ReactPointerEvent,\n ReactNode,\n} from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\nimport type { Point } from \"../measureGeometry\";\nimport {\n clampView,\n fitView,\n frameRect,\n imageLengthFor,\n initialView,\n insideImage,\n isFit,\n preserveCenter,\n scaleRange,\n toImage,\n toScreen,\n zoomAbout,\n type Box,\n type ClampOptions,\n type Rect,\n type StageView,\n} from \"./view\";\n\nconst WHEEL_SENSITIVITY = 0.0015;\n/** How far a press may travel and still count as a click rather than a pan. */\nconst CLICK_SLOP = 3;\n/** The view before the viewport has been measured — nothing is on screen yet. */\nconst UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };\n\n/** What `useStage` returns: the transform of the enclosing `ImageStage`, and its controls. */\nexport interface StageContext {\n /** The view in effect — the controlled `view`, or the opening view while that is `null`. */\n view: StageView;\n /** Set a view, clamped to the legal range for the current viewport. */\n setView: (view: StageView) => void;\n /** The source image's pixel dimensions. */\n image: Box;\n /** The viewport's CSS size — `{0, 0}` until first measured. */\n box: Box;\n /** Client coordinates → image pixels. */\n toImage: (client: Point) => Point;\n /** Image pixels → client coordinates. */\n toClient: (image: Point) => Point;\n /** Image pixels → viewport-local CSS pixels. */\n toViewport: (image: Point) => Point;\n /** The image-pixel length that covers `css` screen pixels — for screen-constant geometry. */\n imageLength: (css: number) => number;\n /** Put a rect (image coordinates) on screen with a margin. */\n frame: (rect: Rect, pad?: number) => void;\n /** Fit the whole image. */\n fit: () => void;\n /** Set a scale about the viewport centre, or about `anchor` in client coordinates. */\n zoomTo: (scale: number, anchor?: Point) => void;\n /** Whether the view is (indistinguishably) fit. */\n isFit: boolean;\n /** True while a pan is in progress, so layers can suppress hover work. */\n panning: boolean;\n /**\n * True when panning must win over anything a layer would otherwise do with a press —\n * the hand tool, or space held. Layers check this before claiming a `pointerdown`; it is\n * the only way a modifier can outrank a child, since a child that stops propagation is\n * heard before this component is.\n */\n panMode: boolean;\n}\n\nconst ImageStageContext = createContext<StageContext | null>(null);\n\n/**\n * The stage a layer is drawn into: its view, the coordinate conversions, and the zoom\n * controls.\n *\n * @throws `Error` outside an `ImageStage`, which is always a wiring bug.\n */\nexport function useStage(): StageContext {\n const ctx = use(ImageStageContext);\n if (ctx === null) throw new Error(\"useStage must be used inside <ImageStage>.\");\n return ctx;\n}\n\n/** Props of `ImageStage`. */\nexport interface ImageStageProps {\n /** The source image's pixel dimensions — the stage's own layout size. */\n image: Box;\n /**\n * The view (controlled). `null` opens at a sensible view — 1:1 if the image fits,\n * otherwise fit — reported through `onView` once the viewport is measured. A non-null\n * view is kept on first measure, only clamped to the legal range.\n */\n view: StageView | null;\n /** Called with every view change: gestures, keys, toolbar, and viewport resizes. */\n onView: (view: StageView) => void;\n /** Layers, each `absolute inset-0` and sized by the stage. */\n children: ReactNode;\n /** Rendered floating over the bottom-left, outside the transform. */\n toolbar?: ReactNode;\n /** Rendered floating over the bottom-right, outside the transform. */\n readout?: ReactNode;\n /** Rendered over the top-left — a mode banner, a staleness warning. */\n banner?: ReactNode;\n /** Force panning regardless of where the press lands (a \"hand tool\"). */\n panTool?: boolean;\n /** Merged onto the viewport with `cn`. */\n className?: string;\n /** Inline style for the viewport. */\n style?: CSSProperties;\n /** Where the pointer is over the image, in image pixels, or `null` when it is outside. */\n onHover?: (point: Point | null) => void;\n /** A press on the background that was not a pan — how a layer hears \"deselect\". */\n onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>) => void;\n /** The legal scale range; see `clampView`. */\n clamp?: ClampOptions;\n /** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */\n shortcuts?: boolean;\n /**\n * Whether the arrow keys pan. On by default, and worth turning off in an app where the\n * arrows have a better job — stepping through a list of findings, say. The zoom keys\n * (`+`, `-`, `0`, `1`) are unaffected, and dragging still pans either way.\n */\n panKeys?: boolean;\n /** The viewport's accessible name. Defaults to \"Image canvas\". */\n label?: string;\n}\n\n/**\n * A pannable, zoomable viewport over a stack of layers laid out at the image's own pixel\n * size, so an overlay drawn in image coordinates stays registered with the photograph at\n * any zoom and window size. Layers read the transform through `useStage`.\n *\n * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag\n * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present\n * or absent.\n */\nexport function ImageStage({\n image,\n view,\n onView,\n children,\n toolbar,\n readout,\n banner,\n panTool = false,\n className,\n style,\n onHover,\n onBackgroundClick,\n clamp,\n shortcuts = true,\n panKeys = true,\n label = \"Image canvas\",\n}: ImageStageProps) {\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const [box, setBox] = useState<Box>({ width: 0, height: 0 });\n // The measured size, readable synchronously — `setBox`'s updater must stay pure, and the\n // resize handler needs the *previous* box to re-anchor the view against.\n const measuredRef = useRef<Box>({ width: 0, height: 0 });\n const [panning, setPanning] = useState(false);\n const [spaceHeld, setSpaceHeld] = useState(false);\n const panMode = panTool || spaceHeld;\n\n // What the handlers attached once (and the stable callbacks below) read: the props and\n // box of the last commit, so none of them closes over stale values.\n const latestRef = useRef({ view, box, image, clamp, onView });\n useLayoutEffect(() => {\n latestRef.current = { view, box, image, clamp, onView };\n });\n /** The view to come back to when a double-click leaves fit. */\n const previousRef = useRef<StageView | null>(null);\n const dragRef = useRef<{ x: number; y: number; tx: number; ty: number; moved: boolean } | null>(null);\n\n const effective = useMemo(\n () => view ?? (box.width > 0 ? initialView(box, image) : UNMEASURED_VIEW),\n [view, box, image],\n );\n\n const commit = useCallback((next: StageView) => {\n const { box: b, image: i, clamp: c, onView: report } = latestRef.current;\n report(b.width > 0 ? clampView(next, b, i, c) : next);\n }, []);\n\n /*\n * The viewport, measured and observed from the moment it mounts (a callback ref with a\n * cleanup, so the subscription lives exactly as long as the element).\n *\n * Its size is a *dependency* of the view, not just of the layout: fit is a relationship to\n * it, and a pan offset that was legal in a wide window is off-screen in a narrow one.\n * Without this the picture appeared to slide out from under its own overlay whenever the\n * window changed shape.\n *\n * The wheel listener is attached here by hand because React registers `wheel` at the root\n * as **passive**, which makes `preventDefault` in a synthetic handler a no-op — the page\n * would scroll behind the canvas while you zoom, which reads as the zoom being broken.\n */\n const attachViewport = useCallback((element: HTMLDivElement | null) => {\n viewportRef.current = element;\n if (!element) return;\n\n const measure = ({ width, height }: Box) => {\n if (!(width > 0) || !(height > 0)) return;\n const current = measuredRef.current;\n if (current.width === width && current.height === height) return;\n const next = { width, height };\n measuredRef.current = next;\n setBox(next);\n const { view: v, image: i, clamp: c, onView: report } = latestRef.current;\n if (v === null) report(initialView(next, i));\n // The first measurement: there is no previous viewport to re-anchor against, so the\n // caller's view is kept — only made legal for this one.\n else if (!(current.width > 0)) report(clampView(v, next, i, c));\n else report(preserveCenter(v, current, next, i, c));\n };\n\n // Synchronously, so the first paint already has the right view — and as the *content*\n // box, which is what the observer reports; measuring the border box here re-anchored\n // the view by the border's width as soon as the observer's first report arrived.\n measure(contentSize(element));\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry) measure(entry.contentRect);\n });\n observer.observe(element);\n\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;\n if (v === null || !(b.width > 0)) return;\n const origin = viewportOrigin(element);\n const [min, max] = scaleRange(b, i, c);\n const factor = Math.exp(-event.deltaY * WHEEL_SENSITIVITY);\n const scale = Math.min(max, Math.max(min, v.scale * factor));\n const anchor = { x: event.clientX - origin.x, y: event.clientY - origin.y };\n report(clampView(zoomAbout(v, scale, anchor), b, i, c));\n };\n element.addEventListener(\"wheel\", onWheel, { passive: false });\n\n return () => {\n observer.disconnect();\n element.removeEventListener(\"wheel\", onWheel);\n viewportRef.current = null;\n };\n }, []);\n\n /* Space is a *modifier*, not a command: held, it turns any press into a pan, which is the\n * one gesture that has to work no matter which layer is under the cursor. */\n useEffect(() => {\n if (!shortcuts) return;\n const down = (event: KeyboardEvent) => {\n if (event.code === \"Space\" && !isTypingTarget(event.target)) setSpaceHeld(true);\n };\n const up = (event: KeyboardEvent) => {\n if (event.code === \"Space\") setSpaceHeld(false);\n };\n const blur = () => setSpaceHeld(false);\n window.addEventListener(\"keydown\", down);\n window.addEventListener(\"keyup\", up);\n window.addEventListener(\"blur\", blur);\n return () => {\n window.removeEventListener(\"keydown\", down);\n window.removeEventListener(\"keyup\", up);\n window.removeEventListener(\"blur\", blur);\n };\n }, [shortcuts]);\n\n const clientToImage = useCallback((p: Point): Point => {\n const element = viewportRef.current;\n const { view: v } = latestRef.current;\n if (!element || v === null) return { x: 0, y: 0 };\n const origin = viewportOrigin(element);\n return toImage(v, { x: p.x - origin.x, y: p.y - origin.y });\n }, []);\n\n const imageToClient = useCallback((p: Point): Point => {\n const element = viewportRef.current;\n const { view: v } = latestRef.current;\n if (!element || v === null) return { x: 0, y: 0 };\n const origin = viewportOrigin(element);\n const local = toScreen(v, p);\n return { x: local.x + origin.x, y: local.y + origin.y };\n }, []);\n\n const fit = useCallback(() => {\n const { box: b, image: i, view: v, onView: report } = latestRef.current;\n if (!(b.width > 0)) return;\n if (v !== null && !isFit(v, b, i)) previousRef.current = v;\n report(fitView(b, i));\n }, []);\n\n const zoomTo = useCallback((scale: number, anchor?: Point) => {\n const { view: v, box: b, image: i, clamp: c, onView: report } = latestRef.current;\n const element = viewportRef.current;\n if (v === null || !(b.width > 0) || !element) return;\n const origin = viewportOrigin(element);\n const local = anchor\n ? { x: anchor.x - origin.x, y: anchor.y - origin.y }\n : { x: b.width / 2, y: b.height / 2 };\n const [min, max] = scaleRange(b, i, c);\n report(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c));\n }, []);\n\n const frame = useCallback((rect: Rect, pad?: number) => {\n const { box: b, image: i, onView: report } = latestRef.current;\n if (!(b.width > 0)) return;\n report(frameRect(b, i, rect, pad));\n }, []);\n\n const atFit = box.width > 0 && isFit(effective, box, image);\n\n const context = useMemo<StageContext>(\n () => ({\n view: effective,\n setView: commit,\n image,\n box,\n toImage: clientToImage,\n toClient: imageToClient,\n toViewport: (p: Point) => toScreen(effective, p),\n imageLength: (css: number) => imageLengthFor(effective, css),\n frame,\n fit,\n zoomTo,\n isFit: atFit,\n panning,\n panMode,\n }),\n [\n effective,\n commit,\n image,\n box,\n clientToImage,\n imageToClient,\n frame,\n fit,\n zoomTo,\n atFit,\n panning,\n panMode,\n ],\n );\n\n /*\n * Panning is the *default* reading of a press, and a layer opts out of it by handling the\n * event and stopping propagation — so the stage needs to know nothing about ROI handles or\n * clickable contours, and a layer needs no permission to exist. The predecessor inverted\n * this: it captured every `pointerdown` unconditionally, which is why its consumers had to\n * mount interactive layers outside the transform, where they stopped moving with the image.\n */\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0 && event.button !== 1) return;\n event.preventDefault();\n dragRef.current = {\n x: event.clientX,\n y: event.clientY,\n tx: effective.tx,\n ty: effective.ty,\n moved: false,\n };\n setPanning(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const origin = dragRef.current;\n if (!origin) {\n onHover?.(hoverPoint(event, viewportRef.current, effective, image));\n return;\n }\n const dx = event.clientX - origin.x;\n const dy = event.clientY - origin.y;\n if (!origin.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;\n origin.moved = true;\n // During a pan the pointer is holding the image, not pointing at a pixel.\n onHover?.(null);\n commit({ scale: effective.scale, tx: origin.tx + dx, ty: origin.ty + dy });\n };\n\n const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n const origin = dragRef.current;\n dragRef.current = null;\n setPanning(false);\n if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);\n };\n\n /*\n * Fit ↔ **the view you were just at**, which is the gesture a reader actually wants: a\n * double-click to see the whole part, another to go back to the corner they were working\n * in. Toggling against 1:1 instead (the predecessor's behaviour) throws that place away.\n */\n const onDoubleClick = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (!(box.width > 0)) return;\n if (atFit) {\n const restore = previousRef.current;\n if (restore) {\n onView(clampView(restore, box, image, clamp));\n } else {\n zoomTo(1, { x: event.clientX, y: event.clientY });\n }\n return;\n }\n previousRef.current = effective;\n onView(fitView(box, image));\n };\n\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (!shortcuts || isTypingTarget(event.target)) return;\n const [min, max] = scaleRange(box, image, clamp);\n const nudge = 60;\n switch (event.key) {\n case \"+\":\n case \"=\":\n zoomTo(Math.min(max, effective.scale * 1.5));\n break;\n case \"-\":\n case \"_\":\n zoomTo(Math.max(min, effective.scale / 1.5));\n break;\n case \"0\":\n fit();\n break;\n case \"1\":\n zoomTo(1);\n break;\n case \"ArrowLeft\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx + nudge });\n break;\n case \"ArrowRight\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx - nudge });\n break;\n case \"ArrowUp\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty + nudge });\n break;\n case \"ArrowDown\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty - nudge });\n break;\n default:\n return;\n }\n event.preventDefault();\n };\n\n return (\n <ImageStageContext value={context}>\n <div\n ref={attachViewport}\n role=\"application\"\n aria-label={label}\n tabIndex={0}\n style={style}\n data-fit={atFit ? \"\" : undefined}\n data-panning={panning ? \"\" : undefined}\n data-pan-mode={panMode ? \"\" : undefined}\n className={cn(\n \"relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none\",\n \"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal\",\n panning ? \"cursor-grabbing\" : panMode ? \"cursor-grab\" : \"cursor-default\",\n className,\n )}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={endDrag}\n // A drag interrupted by a lost capture — a context menu, a browser gesture, the\n // pointer leaving the window — used to leave the drag set, so the next hover panned\n // the image with no button held down.\n onPointerCancel={endDrag}\n onLostPointerCapture={endDrag}\n onPointerLeave={() => onHover?.(null)}\n onDoubleClick={onDoubleClick}\n onKeyDown={onKeyDown}\n >\n {/* One transformed box holding every layer, laid out at the image's own pixel size. */}\n <div\n data-stage\n className=\"absolute top-0 left-0 origin-top-left\"\n style={{\n width: image.width,\n height: image.height,\n transform: `translate(${effective.tx}px, ${effective.ty}px) scale(${effective.scale})`,\n }}\n >\n {children}\n </div>\n\n {banner && <div className=\"pointer-events-none absolute top-2 left-2 z-10\">{banner}</div>}\n\n {/* One row, not two corners: as separate absolute boxes the toolbar and the readout\n overlapped as soon as the canvas was narrower than their combined width, which is\n an ordinary window on a two-column workbench. `justify-between` keeps them apart\n and lets the readout be the one that gives up room. */}\n {(toolbar || readout) && (\n <div className=\"pointer-events-none absolute inset-x-2 bottom-2 z-10 flex items-end justify-between gap-2\">\n <div className=\"pointer-events-auto shrink-0\">{toolbar}</div>\n <div className=\"min-w-0 truncate\">{readout}</div>\n </div>\n )}\n </div>\n </ImageStageContext>\n );\n}\n\nfunction hoverPoint(\n event: { clientX: number; clientY: number },\n element: HTMLDivElement | null,\n view: StageView,\n image: Box,\n): Point | null {\n if (!element) return null;\n const origin = viewportOrigin(element);\n const p = toImage(view, { x: event.clientX - origin.x, y: event.clientY - origin.y });\n return insideImage(p, image) ? p : null;\n}\n\n/**\n * Where viewport-local `(0, 0)` is in client coordinates: the *padding* box's corner, which\n * is where the absolutely positioned stage sits — not the border box's, which is what\n * `getBoundingClientRect` reports. The difference is the border's width, a whole image\n * pixel at 100% between the cursor and the pixel reported under it.\n */\nfunction viewportOrigin(element: HTMLElement): Point {\n const rect = element.getBoundingClientRect();\n return { x: rect.left + element.clientLeft, y: rect.top + element.clientTop };\n}\n\n/** The element's content-box size, the box `ResizeObserver` reports as `contentRect`. */\nfunction contentSize(element: HTMLElement): Box {\n const rect = element.getBoundingClientRect();\n const style = getComputedStyle(element);\n const px = (value: string) => Number.parseFloat(value) || 0;\n return {\n width:\n rect.width -\n px(style.borderLeftWidth) -\n px(style.borderRightWidth) -\n px(style.paddingLeft) -\n px(style.paddingRight),\n height:\n rect.height -\n px(style.borderTopWidth) -\n px(style.borderBottomWidth) -\n px(style.paddingTop) -\n px(style.paddingBottom),\n };\n}\n\nfunction isTypingTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\" || target.isContentEditable;\n}\n","/**\n * The viewer's own controls, floating over the image rather than filed in a side panel.\n *\n * Zoom, fit and 1:1 are properties of *the picture*, not of the task beside it, and a\n * workbench that puts them in the inspector spends inspector width on them on every screen\n * while leaving the canvas with no visible affordance at all — which is indistinguishable\n * from a canvas that cannot zoom.\n *\n * The bar is deliberately small and quiet: `bg-overlay/85` over a blur, one row of icon\n * buttons, no labels except the percentage. It is chrome over the subject, so it recedes\n * until aimed at.\n */\n\nimport { Maximize2, Minus, Plus, Scan } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, ReactNode } from \"react\";\n\nimport { cn, focusRing } from \"@vitavision/ui\";\nimport { useStage } from \"./ImageStage\";\nimport { MAX_SCALE, formatScale, scaleRange, steppedScale } from \"./view\";\n\n/** The presets the percentage menu offers, beside \"Fit\". */\nconst PRESETS = [0.25, 0.5, 1, 2, 4, 8];\n\n/** Props of `StageToolbar`. */\nexport interface StageToolbarProps {\n /** App-specific groups — a tool selector, a layers popover — after a divider. */\n children?: ReactNode;\n /** Merged onto the bar with `cn`. */\n className?: string;\n}\n\n/**\n * The stage's zoom controls — zoom out, a percentage menu (fit and presets), zoom in, fit,\n * and 100% — plus any app groups passed as children. Pass it as `ImageStage`'s `toolbar`;\n * it reads the stage through `useStage`.\n *\n * The bar carries `data-fit` while the view is fit; the percentage button carries\n * `data-state=\"open\"` or `\"closed\"` for its menu.\n */\nexport function StageToolbar({ children, className }: StageToolbarProps) {\n const stage = useStage();\n const [menuOpen, setMenuOpen] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n const [min, max] = scaleRange(stage.box, stage.image);\n\n useEffect(() => {\n if (!menuOpen) return;\n const close = (event: MouseEvent) => {\n if (!menuRef.current?.contains(event.target as Node)) setMenuOpen(false);\n };\n window.addEventListener(\"pointerdown\", close);\n return () => window.removeEventListener(\"pointerdown\", close);\n }, [menuOpen]);\n\n const step = (direction: 1 | -1) => stage.zoomTo(steppedScale(stage.view.scale, direction, min, max));\n\n return (\n <div\n data-fit={stage.isFit ? \"\" : undefined}\n className={cn(\n \"flex items-center gap-0.5 rounded-panel border border-line bg-overlay/85 p-1 shadow-lg backdrop-blur\",\n className,\n )}\n // Every press here is a control, never the start of a pan.\n onPointerDown={(event) => event.stopPropagation()}\n onDoubleClick={(event) => event.stopPropagation()}\n >\n <StageButton label=\"Zoom out\" onClick={() => step(-1)} disabled={stage.view.scale <= min + 1e-9}>\n <Minus className=\"size-4\" aria-hidden />\n </StageButton>\n\n <div className=\"relative\" ref={menuRef}>\n <button\n type=\"button\"\n aria-haspopup=\"menu\"\n aria-expanded={menuOpen}\n data-state={menuOpen ? \"open\" : \"closed\"}\n onClick={() => setMenuOpen((open) => !open)}\n className={cn(\n \"h-7 min-w-14 rounded-control px-2 font-mono text-xs text-fg tabular-nums hover:bg-raised\",\n focusRing,\n )}\n >\n {stage.isFit ? \"Fit\" : formatScale(stage.view.scale)}\n </button>\n {menuOpen && (\n <div\n role=\"menu\"\n className=\"absolute bottom-9 left-0 z-20 min-w-28 rounded-panel border border-line bg-overlay p-1 shadow-lg\"\n >\n <MenuItem\n onClick={() => {\n stage.fit();\n setMenuOpen(false);\n }}\n active={stage.isFit}\n >\n Fit\n </MenuItem>\n {PRESETS.filter((scale) => scale >= min && scale <= max).map((scale) => (\n <MenuItem\n key={scale}\n onClick={() => {\n stage.zoomTo(scale);\n setMenuOpen(false);\n }}\n active={!stage.isFit && Math.abs(stage.view.scale - scale) < 1e-6}\n >\n {formatScale(scale)}\n </MenuItem>\n ))}\n </div>\n )}\n </div>\n\n <StageButton\n label=\"Zoom in\"\n onClick={() => step(1)}\n disabled={stage.view.scale >= Math.min(max, MAX_SCALE) - 1e-9}\n >\n <Plus className=\"size-4\" aria-hidden />\n </StageButton>\n\n <StageToolbarDivider />\n\n <StageButton label=\"Fit to window\" onClick={stage.fit} pressed={stage.isFit}>\n <Maximize2 className=\"size-4\" aria-hidden />\n </StageButton>\n <StageButton\n label=\"Actual size (100%)\"\n onClick={() => stage.zoomTo(1)}\n pressed={!stage.isFit && Math.abs(stage.view.scale - 1) < 1e-6}\n >\n <Scan className=\"size-4\" aria-hidden />\n </StageButton>\n\n {children && (\n <>\n <StageToolbarDivider />\n {children}\n </>\n )}\n </div>\n );\n}\n\n/** Props of `StageButton`: a `<button>`'s, less the ones it sets itself. */\nexport interface StageButtonProps\n extends Omit<ComponentPropsWithRef<\"button\">, \"type\" | \"title\" | \"aria-label\" | \"aria-pressed\" | \"children\"> {\n /** The accessible name, also shown as the tooltip. */\n label: string;\n /** A toggle's state; omit for a plain action button. */\n pressed?: boolean;\n /** The icon (mark it `aria-hidden`). */\n children: ReactNode;\n}\n\n/**\n * The bar's own button shape, exported so app groups match it exactly. An icon button\n * named by `label`; a toggle when `pressed` is given, exposed as `aria-pressed` and\n * `data-state=\"on\"` or `\"off\"`. Other button props (and `ref`) are passed through.\n */\nexport function StageButton({ label, pressed, className, children, ...props }: StageButtonProps) {\n return (\n <button\n {...props}\n type=\"button\"\n title={label}\n aria-label={label}\n aria-pressed={pressed}\n data-state={pressed === undefined ? undefined : pressed ? \"on\" : \"off\"}\n className={cn(\n \"grid size-7 place-items-center rounded-control text-fg-muted transition-colors\",\n \"hover:bg-raised hover:text-fg disabled:pointer-events-none disabled:opacity-40\",\n pressed && \"bg-signal/15 text-signal\",\n focusRing,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n\n/** Props of `StageToolbarDivider`. */\nexport interface StageToolbarDividerProps {\n /** Merged onto the divider with `cn`. */\n className?: string;\n}\n\n/** A thin vertical rule between groups of `StageButton`s. Decorative (`aria-hidden`). */\nexport function StageToolbarDivider({ className }: StageToolbarDividerProps) {\n return <span className={cn(\"mx-0.5 h-5 w-px bg-line\", className)} aria-hidden />;\n}\n\nfunction MenuItem({\n onClick,\n active,\n children,\n}: {\n onClick: () => void;\n active?: boolean;\n children: ReactNode;\n}) {\n return (\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={onClick}\n className={cn(\n \"block w-full rounded-control px-2 py-1 text-left font-mono text-xs tabular-nums hover:bg-raised\",\n active ? \"text-signal\" : \"text-fg\",\n focusRing,\n )}\n >\n {children}\n </button>\n );\n}\n\n/** Props of `StageReadout`. */\nexport interface StageReadoutProps {\n /** The pointer in image pixels (from `ImageStage`'s `onHover`); the image size shows without it. */\n cursor?: { x: number; y: number } | null;\n /** Appended after a separator — a pixel value, a channel. */\n extra?: ReactNode;\n /** Merged onto the readout with `cn`. */\n className?: string;\n}\n\n/**\n * The instrument's display line for the canvas: where the cursor is, and how magnified.\n * Pass it as `ImageStage`'s `readout`; it reads the stage through `useStage`.\n *\n * In image pixels, because that is the coordinate every number the backend returns is in —\n * a readout in screen pixels would be a second coordinate system to reconcile by hand.\n */\nexport function StageReadout({ cursor, extra, className }: StageReadoutProps) {\n const stage = useStage();\n return (\n <span\n className={cn(\n \"rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums\",\n className,\n )}\n >\n {cursor ? `${cursor.x.toFixed(1)}, ${cursor.y.toFixed(1)} px` : `${stage.image.width}×${stage.image.height}`}\n {\" · \"}\n {stage.isFit ? \"fit\" : formatScale(stage.view.scale)}\n {extra && <> · {extra}</>}\n </span>\n );\n}\n","/**\n * A pannable, zoomable frame that transforms **everything stacked inside it together**.\n *\n * Deprecated: use `ImageStage` (`components/stage`). Two limits of this component turned out\n * to be load-bearing rather than incidental, and neither can be lifted without changing what\n * its props mean:\n *\n * - it scales its layers by the *frame's* size, so every consumer must lay the frame out\n * at the source aspect ratio and the one that forgot drew its overlays stretched against\n * a letterboxed photograph — layers drifting apart on window resize, invisibly, at\n * every window size but one;\n * - it calls `setPointerCapture` on every `pointerdown` to pan, so an interactive child —\n * a draggable ROI handle, a clickable contour — cannot exist inside it, and consumers\n * mounted those layers *outside* the transform, where they stopped moving with the image.\n *\n * `ImageStage` lays the stage out at the image's own pixel size (so registration is\n * structural, not a caller's responsibility), treats `scale` as CSS pixels per image pixel\n * (so \"100%\" is a value and zooming out past fit is expressible), and pans only when a\n * gesture is unclaimed. This component stays exported and unchanged for consumers that have\n * not migrated.\n *\n * A result viewer over a stack -- a photograph, an anomaly map, a model's segmentation, a\n * measurement overlay drawn in source-image pixel coordinates (see `MeasureOverlay`) -- and\n * the layers only stay registered with each other if one transform moves all of them.\n * Transforming each layer separately would drift them apart at the exact zoom level where a\n * reader is trying to judge whether a caliper box lands on the edge it claims to measure.\n *\n * Zoom bottoms out at 1x and snaps the pan back to centre there, so there is always a\n * gesture that gets you unlost — and zoom 1 *is* fit-to-window, because the canvas is laid\n * out inside `max-h-full max-w-full` with the source aspect ratio. That is why the\n * double-click gesture toggles fit against **1:1 native pixels** rather than \"fitting\":\n * fitting is where you already are, and the thing a reader actually wants at a defect, or\n * at a subpixel edge, is the sensor's own resolution with no resampling between them and it.\n */\n\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\n\n/**\n * `ZoomPanCanvas`'s view: `translate(x, y) scale(zoom)` about the frame's centre.\n * `ImageStage` uses `StageView` instead.\n */\nexport interface View {\n /** Magnification relative to fit; `1` is fit-to-window. */\n zoom: number;\n /** Horizontal pan, in CSS pixels, from the centred position. */\n x: number;\n /** Vertical pan, in CSS pixels, from the centred position. */\n y: number;\n}\n\n/** Zoom 1, centred — which is fit-to-window, given how the canvas is laid out. */\nexport const RESET_VIEW: View = { zoom: 1, x: 0, y: 0 };\n\n/** The lowest zoom `zoomAt` allows: fit. */\nexport const MIN_ZOOM = 1;\n/** The highest zoom `zoomAt` allows. */\nexport const MAX_ZOOM = 12;\nconst ZOOM_SENSITIVITY = 0.0015;\n\n/** The zoom past which a preview tier stops being enough and real pixels are wanted. */\nexport const FULL_TIER_ZOOM = 2;\n\n/**\n * Zoom by `factor` about a point, keeping whatever is under that point where it is.\n *\n * Pure, and exported, because it is the one piece of arithmetic here that can be silently\n * wrong: a centre-anchored zoom looks correct until someone tries to magnify a defect in a\n * corner, at which point every wheel notch has to be undone with a drag.\n *\n * The transform is `translate(t) scale(z)` about the box's centre, so a content point `c`\n * lands at `p = c·z + t`. Holding `c` fixed while `z` becomes `z'` gives\n * `t' = p − (p − t)·z'/z`, with `p` measured from the centre.\n */\nexport function zoomAt(\n view: View,\n pointer: { x: number; y: number },\n rect: { left: number; top: number; width: number; height: number },\n factor: number,\n): View {\n const zoom = clamp(view.zoom * factor, MIN_ZOOM, MAX_ZOOM);\n // Bottoming out is a reset: at 1x the content fills the frame, so any offset is a way to\n // be lost with no visible handle to get back.\n if (zoom === MIN_ZOOM) return RESET_VIEW;\n\n const px = pointer.x - rect.left - rect.width / 2;\n const py = pointer.y - rect.top - rect.height / 2;\n const ratio = zoom / view.zoom;\n return {\n zoom,\n x: px - (px - view.x) * ratio,\n y: py - (py - view.y) * ratio,\n };\n}\n\n/**\n * Where a pointer is over the *content*, as fractions of the frame, or `null` outside it.\n *\n * The inverse of the transform `zoomAt` maintains, and pure for the same reason: this is\n * what turns a cursor position into an index into a value plane or a source-pixel\n * coordinate, and it is wrong in a way nothing on screen would reveal — a readout that is\n * confidently off by a pan offset looks exactly like a readout that works.\n *\n * The content fills the frame at zoom 1 by construction (the canvas is laid out with the\n * source aspect ratio), so `[0, 1)` over the frame *is* `[0, 1)` over the image, with no\n * letterbox correction to reconstruct.\n */\nexport function contentUnder(\n view: View,\n pointer: { clientX: number; clientY: number },\n rect: { left: number; top: number; width: number; height: number },\n): { u: number; v: number } | null {\n const px = pointer.clientX - rect.left - rect.width / 2;\n const py = pointer.clientY - rect.top - rect.height / 2;\n const u = (px - view.x) / view.zoom / rect.width + 0.5;\n const v = (py - view.y) / view.zoom / rect.height + 0.5;\n if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;\n return { u, v };\n}\n\n/**\n * The zoom at which one source pixel covers one CSS pixel.\n *\n * Clamped, so an image smaller than its frame reports 1: there are no further pixels to\n * reveal, and pretending otherwise would magnify the resampler rather than the sensor.\n */\nexport function nativeZoomFor(sourceWidth: number, boxWidth: number): number {\n if (!(sourceWidth > 0) || !(boxWidth > 0)) return FULL_TIER_ZOOM;\n return clamp(sourceWidth / boxWidth, MIN_ZOOM, MAX_ZOOM);\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(high, Math.max(low, value));\n}\n\n/**\n * Props of `ZoomPanCanvas`.\n *\n * @deprecated Use `ImageStage` and `ImageStageProps`.\n */\nexport interface ZoomPanCanvasProps {\n /** The current view (controlled). */\n view: View;\n /** Called with every view change — wheel, drag, double-click, the \"Fit\" button. */\n onView: (view: View) => void;\n /** The stacked layers, each filling the frame. */\n children: ReactNode;\n /** Height and any other framing, merged with `cn`; the transform and overflow are handled here. */\n className?: string;\n /** For `aspect-ratio`, which has to be a computed value rather than a utility class. */\n style?: CSSProperties;\n /** Drawn bottom-left over the image, where it cannot push the canvas down. */\n label?: ReactNode;\n /**\n * The source image's pixel width, so double-click can reach true 1:1. Without it the\n * gesture falls back to `FULL_TIER_ZOOM`, which is at least the tier boundary.\n */\n nativeWidth?: number;\n /** Hidden by passing `null` — a caller with its own fit button beside the canvas. */\n fitLabel?: ReactNode;\n /**\n * Where the pointer is over the *content*, as fractions in `[0, 1)`, or `null` when it\n * is outside. Reported through the same transform the layers use, so the coordinate is\n * the one a value plane or a measurement overlay is indexed by however the frame is\n * zoomed or panned. Suppressed while dragging: during a pan the pointer is holding the\n * image, not pointing at a pixel.\n */\n onHover?: (position: { u: number; v: number } | null) => void;\n}\n\n/**\n * A pannable, zoomable frame that transforms its stacked children together; zoom 1 is fit.\n *\n * State is exposed as `data-panning` (present during a drag) and `data-fit` (present at\n * zoom 1) on the frame.\n *\n * @deprecated Use `ImageStage`. This component scales its layers by the frame's size (so\n * the frame must be laid out at the image's aspect ratio) and captures every press to pan\n * (so no interactive layer can live inside it). It stays exported, unchanged in behaviour,\n * for consumers that have not migrated.\n */\nexport function ZoomPanCanvas({\n view,\n onView,\n children,\n className,\n style,\n label,\n nativeWidth,\n fitLabel = \"Fit\",\n onHover,\n}: ZoomPanCanvasProps) {\n const draggingRef = useRef<{ x: number; y: number } | null>(null);\n // Mirrored into state only so the cursor can change — the ref is what the move handler\n // reads, because a re-render per pointermove would be a cost for nothing.\n const [grabbing, setGrabbing] = useState(false);\n const boxRef = useRef<HTMLDivElement>(null);\n // What the wheel listener, attached once, reads: the view and callback of the last commit.\n const latestRef = useRef({ view, onView });\n useLayoutEffect(() => {\n latestRef.current = { view, onView };\n });\n\n /*\n * The wheel listener is attached by hand because React registers `wheel` at the root as\n * **passive**, which makes `preventDefault` in a synthetic handler a no-op. Without it\n * the page scrolls behind the canvas while you zoom, so a gesture aimed at the image\n * moves the document instead — which reads as the zoom being broken.\n */\n useEffect(() => {\n const element = boxRef.current;\n if (!element) return;\n\n const onWheel = (event: WheelEvent) => {\n event.preventDefault();\n const rect = element.getBoundingClientRect();\n const factor = 1 - event.deltaY * ZOOM_SENSITIVITY;\n const { view: current, onView: report } = latestRef.current;\n report(zoomAt(current, { x: event.clientX, y: event.clientY }, rect, factor));\n };\n\n element.addEventListener(\"wheel\", onWheel, { passive: false });\n return () => element.removeEventListener(\"wheel\", onWheel);\n }, []);\n\n const toggleNative = (event: { clientX: number; clientY: number }) => {\n const element = boxRef.current;\n if (!element) return;\n const rect = element.getBoundingClientRect();\n const native = nativeZoomFor(nativeWidth ?? 0, rect.width);\n // Anywhere but fit goes back to fit; fit goes to 1:1 under the cursor.\n const target = view.zoom > MIN_ZOOM ? MIN_ZOOM : native;\n onView(zoomAt(view, { x: event.clientX, y: event.clientY }, rect, target / view.zoom));\n };\n\n const endDrag = () => {\n draggingRef.current = null;\n setGrabbing(false);\n };\n\n return (\n <div\n ref={boxRef}\n style={style}\n data-panning={grabbing ? \"\" : undefined}\n data-fit={view.zoom <= MIN_ZOOM ? \"\" : undefined}\n className={cn(\n \"relative overflow-hidden rounded-control border border-line bg-canvas select-none\",\n grabbing ? \"cursor-grabbing\" : \"cursor-grab\",\n className,\n )}\n onPointerDown={(event) => {\n draggingRef.current = { x: event.clientX - view.x, y: event.clientY - view.y };\n setGrabbing(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n }}\n onPointerMove={(event) => {\n const origin = draggingRef.current;\n if (!origin) {\n onHover?.(contentUnder(view, event, event.currentTarget.getBoundingClientRect()));\n return;\n }\n // During a pan the pointer is holding the image rather than pointing at a pixel.\n onHover?.(null);\n onView({ ...view, x: event.clientX - origin.x, y: event.clientY - origin.y });\n }}\n onPointerLeave={() => onHover?.(null)}\n onPointerUp={endDrag}\n // A drag interrupted by a lost capture — a context menu, a browser gesture, the\n // pointer leaving the window — used to leave `dragging` set, so the next hover\n // panned the image without a button held down.\n onPointerCancel={endDrag}\n onLostPointerCapture={endDrag}\n onDoubleClick={toggleNative}\n >\n {/* One transformed box holding every layer, so they cannot drift apart. */}\n <div\n className=\"h-full w-full\"\n style={{\n transform: `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`,\n transformOrigin: \"center\",\n }}\n >\n {children}\n </div>\n {label && (\n <span className=\"pointer-events-none absolute bottom-1 left-1 rounded-control bg-black/60 px-1 font-mono text-[10px] text-white\">\n {label}\n </span>\n )}\n {fitLabel !== null && view.zoom > MIN_ZOOM && (\n <button\n type=\"button\"\n className=\"absolute right-1 bottom-1 rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80\"\n // Stopping `pointerdown` is what makes the button work at all: without it the\n // press bubbles to the canvas, which calls `setPointerCapture` on itself and\n // takes the click with it, so the button rendered and did nothing.\n onPointerDown={(event) => event.stopPropagation()}\n onClick={(event) => {\n event.stopPropagation();\n onView(RESET_VIEW);\n }}\n // The canvas swallows double-clicks to toggle 1:1; without this the second click\n // of a fast double-tap on the button reaches the canvas and zooms straight back.\n onDoubleClick={(event) => event.stopPropagation()}\n >\n {fitLabel}\n </button>\n )}\n </div>\n );\n}\n","/**\n * The numbers behind a picture.\n *\n * A rendered anomaly map or false-colour measurement overlay answers \"is this region\n * hotter than that one\" or \"roughly where does the edge fall\". The next question — *how\n * hot, in the units a metric is computed in* or *at what subpixel coordinate* — cannot be\n * answered from the picture: a colormap clips at both ends and quantizes to 256 entries,\n * and alpha is a gamma of the normalized value, so the inverse is multi-valued.\n *\n * So the values arrive as values, in a fixed 24-byte-header format that is deliberately\n * **not** `.npy` — there is no dtype string to parse and no shape tuple. This module\n * decodes them and indexes them. **It never draws.** Colour range and colormap stay wherever\n * the values were produced.\n */\n\nconst MAGIC = 0x56414d31; // \"VAM1\", read big-endian so the constant is legible.\nconst HEADER_SIZE = 24;\n\n/** A decoded value plane: the numbers behind a rendered map, one `Float32` per pixel and channel. */\nexport interface ValuePlane {\n /** Columns in the plane (after `stride` decimation). */\n width: number;\n /** Rows in the plane (after `stride` decimation). */\n height: number;\n /**\n * The integer decimation applied upstream. `1` means every source pixel is here;\n * anything more means the readout is sampled, and a caller should say so rather than\n * presenting an approximate number as exact.\n */\n stride: number;\n /**\n * How many planes are in `values`, stored one after another.\n *\n * Read from the header rather than assumed: a mono anomaly map is one plane, an RGB\n * source is three, and nothing here may encode which — channel count is data.\n */\n channels: number;\n /** The samples, plane-major: channel, then row, then column. */\n values: Float32Array;\n}\n\n/** Thrown by `decodePlane` when a buffer is not a well-formed value plane. */\nexport class PlaneFormatError extends Error {}\n\n/**\n * Decode a value plane from its binary form: a 24-byte header (big-endian magic `VAM1`,\n * then little-endian `u32` width, height, stride and channels, and 4 reserved bytes)\n * followed by `width · height · channels` little-endian `f32` values.\n *\n * The returned `values` is a view onto `buffer`, not a copy.\n *\n * @throws `PlaneFormatError` when the header is short, the magic is wrong, or the buffer\n * holds fewer values than the header promises.\n */\nexport function decodePlane(buffer: ArrayBuffer): ValuePlane {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new PlaneFormatError(\"a value plane is at least a 24-byte header\");\n }\n const header = new DataView(buffer);\n if (header.getUint32(0, false) !== MAGIC) {\n throw new PlaneFormatError(\"not a value plane — wrong magic\");\n }\n\n const width = header.getUint32(4, true);\n const height = header.getUint32(8, true);\n const stride = header.getUint32(12, true);\n const channels = header.getUint32(16, true);\n const expected = width * height * channels;\n\n if (buffer.byteLength - HEADER_SIZE < expected * 4) {\n throw new PlaneFormatError(`a ${width}x${height}x${channels} plane needs ${expected} values`);\n }\n return {\n width,\n height,\n stride,\n channels,\n values: new Float32Array(buffer, HEADER_SIZE, expected),\n };\n}\n\n/**\n * The value at a normalized position, or `null` outside the plane.\n *\n * `u` and `v` are fractions of the source frame. A stored anomaly map or model-input plane\n * is expected to already be projected into that frame, so crop and letterbox geometry is\n * resolved once upstream rather than reconstructed here. NaN marks an uncovered pixel.\n */\nexport function valueAt(plane: ValuePlane, u: number, v: number, channel = 0): number | null {\n if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return null;\n if (channel < 0 || channel >= plane.channels) return null;\n const x = Math.min(plane.width - 1, Math.floor(u * plane.width));\n const y = Math.min(plane.height - 1, Math.floor(v * plane.height));\n // Plane-major, so one channel is a single offset rather than a stride walk.\n const value = plane.values[channel * plane.width * plane.height + y * plane.width + x];\n return value !== undefined && Number.isFinite(value) ? value : null;\n}\n\n/** Every channel at one position, in order — one number for mono, three for RGB. */\nexport function valuesAt(plane: ValuePlane, u: number, v: number): number[] {\n const out: number[] = [];\n for (let channel = 0; channel < plane.channels; channel += 1) {\n const value = valueAt(plane, u, v, channel);\n if (value !== null) out.push(value);\n }\n return out;\n}\n\n/** Where a value sits in a range, as a fraction — `null` for a degenerate range. */\nexport function fractionOf(\n value: number,\n range: { low: number; high: number } | null | undefined,\n): number | null {\n if (!range || range.high <= range.low) return null;\n return (value - range.low) / (range.high - range.low);\n}\n\n/**\n * Fetch a value plane from `url` and decode it.\n *\n * @throws `Error` on a non-2xx response, or `PlaneFormatError` for a malformed body.\n */\nexport async function fetchPlane(url: string): Promise<ValuePlane> {\n const response = await fetch(url);\n if (!response.ok) throw new Error(`${response.status} fetching values`);\n return decodePlane(await response.arrayBuffer());\n}\n","/**\n * The arithmetic behind `MeasureOverlay`: everything that can be silently wrong, factored\n * out so it can be tested without a DOM.\n *\n * Every primitive `MeasureOverlay` draws is given in **source-image pixel coordinates** —\n * the same frame `ZoomPanCanvas`'s `nativeWidth`/`nativeHeight` describe, and the same one\n * `api/mapValues.ts`'s `u`/`v` fractions index into. Nothing here measures the DOM or knows\n * about zoom directly; `strokeWidthFor` is the one function that turns a *scale factor* a\n * caller already knows (or computes once from a `ZoomPanCanvas` `View`) into a stroke width\n * that reads as constant on screen.\n */\n\n/** A 2D point — in image pixels unless a signature says otherwise. */\nexport interface Point {\n /** Horizontal coordinate, increasing rightward. */\n x: number;\n /** Vertical coordinate, increasing downward. */\n y: number;\n}\n\n/**\n * The on-screen-constant stroke width for a shape drawn in native-pixel units.\n *\n * `MeasureOverlay` is rendered as an SVG whose `viewBox` is the native image size, sitting\n * inside `ZoomPanCanvas`'s own `scale(zoom)` transform. A stroke declared as `1` in that\n * SVG's user units is `1` *native pixel*, which is `strokeScale` screen pixels once both\n * transforms are applied (`strokeScale` = the SVG's own fit ratio × the canvas zoom, or\n * just the zoom when the overlay is already at native resolution). Dividing by it is what\n * keeps a 1px caliper edge looking like 1px at any zoom, rather than growing with it the\n * way a shape's own geometry does.\n *\n * `vector-effect=\"non-scaling-stroke\"` addresses only the SVG's *internal* transforms and\n * is inconsistently applied across browsers once a CSS transform sits above the `<svg>`\n * itself (exactly the situation inside `ZoomPanCanvas`), so this is computed explicitly\n * rather than left to the renderer.\n */\nexport function strokeWidthFor(strokeScale: number, screenPixels = 1): number {\n if (!Number.isFinite(strokeScale) || strokeScale <= 0) return screenPixels;\n return screenPixels / strokeScale;\n}\n\n/** Rotate `(x, y)` about the origin by `angle` radians. */\nexport function rotatePoint(x: number, y: number, angle: number): Point {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return { x: x * c - y * s, y: x * s + y * c };\n}\n\n/** `M x,y L x,y … Z` through `points`, or `\"\"` for fewer than two of them. */\nexport function polygonPath(points: readonly Point[]): string {\n if (points.length < 2) return \"\";\n const [first, ...rest] = points;\n const p0 = first as Point;\n const commands = [`M${p0.x.toFixed(2)} ${p0.y.toFixed(2)}`];\n for (const point of rest) commands.push(`L${point.x.toFixed(2)} ${point.y.toFixed(2)}`);\n commands.push(\"Z\");\n return commands.join(\" \");\n}\n\n/** The two line segments of a cross mark centred on `(x, y)`, each `2·size` long. */\nexport function crossSegments(x: number, y: number, size: number): [[Point, Point], [Point, Point]] {\n return [\n [{ x: x - size, y }, { x: x + size, y }],\n [{ x, y: y - size }, { x, y: y + size }],\n ];\n}\n\n/**\n * The angular sweep from `startAngle` to `endAngle`, going forward.\n *\n * Two angles alone cannot distinguish \"no sweep at all\" from \"swept exactly one full turn\"\n * — both have `endAngle - startAngle ≡ 0 (mod 2π)`. The raw (un-normalized) difference is\n * what carries that distinction: genuinely equal angles have a raw difference near zero,\n * while a caller asking for a full circle passes a raw difference of `2π` (or a multiple of\n * it). So only a raw difference near zero is treated as \"nothing to draw\"; every other\n * multiple of a full turn normalizes to `2π` itself rather than collapsing to `0`.\n */\nfunction sweepAngle(startAngle: number, endAngle: number): number {\n const turn = Math.PI * 2;\n const EPSILON = 1e-9;\n const raw = endAngle - startAngle;\n if (Math.abs(raw) < EPSILON) return 0;\n const delta = raw % turn;\n return delta <= EPSILON ? delta + turn : delta;\n}\n\n/**\n * An SVG arc path centred at `(cx, cy)` with radius `r`, sweeping forward from `startAngle`\n * to `endAngle` (radians, standard `x = cx + r·cos(a)`, `y = cy + r·sin(a)` convention —\n * clockwise on screen, since image-pixel `y` increases downward).\n *\n * A single SVG `A` command cannot express a full circle (its start and end point coincide,\n * which most renderers treat as a zero-length arc), so a sweep that reaches all the way\n * around is split into two half-circle arcs instead.\n */\nexport function arcPath(cx: number, cy: number, r: number, startAngle: number, endAngle: number): string {\n if (!(r > 0)) return \"\";\n\n const start = { x: cx + r * Math.cos(startAngle), y: cy + r * Math.sin(startAngle) };\n const sweep = sweepAngle(startAngle, endAngle);\n const FULL_TURN_EPSILON = 1e-9;\n\n if (sweep < FULL_TURN_EPSILON) {\n // A zero (or effectively zero) sweep is a point, not an arc.\n return \"\";\n }\n if (sweep >= Math.PI * 2 - FULL_TURN_EPSILON) {\n const mid = { x: cx + r * Math.cos(startAngle + Math.PI), y: cy + r * Math.sin(startAngle + Math.PI) };\n return (\n `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${mid.x.toFixed(2)} ${mid.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 1 1 ${start.x.toFixed(2)} ${start.y.toFixed(2)}`\n );\n }\n\n const end = { x: cx + r * Math.cos(endAngle), y: cy + r * Math.sin(endAngle) };\n const largeArc = sweep > Math.PI ? 1 : 0;\n return (\n `M${start.x.toFixed(2)} ${start.y.toFixed(2)} ` +\n `A${r.toFixed(2)} ${r.toFixed(2)} 0 ${largeArc} 1 ${end.x.toFixed(2)} ${end.y.toFixed(2)}`\n );\n}\n\n/**\n * The four corners of a caliper box: a rectangle `width` (along its own measurement axis)\n * by `height`, centred at `(cx, cy)` and rotated by `angle` radians. Corner order is\n * suitable for `polygonPath` — around the box, not crossed.\n */\nexport function caliperCorners(\n cx: number,\n cy: number,\n width: number,\n height: number,\n angle: number,\n): [Point, Point, Point, Point] {\n const hw = width / 2;\n const hh = height / 2;\n const local: [number, number][] = [\n [-hw, -hh],\n [hw, -hh],\n [hw, hh],\n [-hw, hh],\n ];\n const [a, b, c, d] = local.map(([lx, ly]) => {\n const r = rotatePoint(lx, ly, angle);\n return { x: cx + r.x, y: cy + r.y };\n });\n return [a as Point, b as Point, c as Point, d as Point];\n}\n\n/**\n * The direction arrow for a caliper box: from its centre to just past its `+local-x` edge,\n * along the box's own measurement axis. What the arrow points at is the scan direction the\n * caliper was evaluated in, not merely a decoration on the box.\n */\nexport function caliperArrow(\n cx: number,\n cy: number,\n width: number,\n angle: number,\n): { from: Point; to: Point } {\n const reach = width / 2 + Math.max(4, width * 0.2);\n const tip = rotatePoint(reach, 0, angle);\n return { from: { x: cx, y: cy }, to: { x: cx + tip.x, y: cy + tip.y } };\n}\n\n/**\n * A small open chevron at `tip`, pointing along `angle` (radians), for a caliper's\n * direction arrow. Three points — left-back, tip, right-back — meant for an unfilled\n * `<polyline>`, which keeps the arrowhead's colour exactly the stroke colour of the line it\n * caps without the fill-vs-stroke bookkeeping a filled triangle would need per tone.\n */\nexport function arrowHeadPoints(tip: Point, angle: number, size: number): [Point, Point, Point] {\n const back = size * 1.6;\n const spread = size;\n const left = rotatePoint(-back, spread, angle);\n const right = rotatePoint(-back, -spread, angle);\n return [\n { x: tip.x + left.x, y: tip.y + left.y },\n tip,\n { x: tip.x + right.x, y: tip.y + right.y },\n ];\n}\n\n/** What `dimensionGeometry` computes: the lines and label placement of a dimension annotation. */\nexport interface DimensionGeometry {\n /** From the first measured point out to the dimension line. */\n extensionLine1: [Point, Point];\n /** From the second measured point out to the dimension line. */\n extensionLine2: [Point, Point];\n /** The offset line spanning the measured distance, parallel to the measured segment. */\n dimensionLine: [Point, Point];\n /** Midpoint of the dimension line — where the label sits. */\n labelAnchor: Point;\n /** The dimension line's own direction, in degrees, for an upright label rotation. */\n angleDegrees: number;\n}\n\n/**\n * The leader geometry for a dimension annotation between two measured points, offset by\n * `offset` native pixels to the line's left (so a positive offset with a left-to-right\n * measurement draws the dimension line above it, consistent with `y` increasing downward).\n *\n * Degenerate input (`x1 === x2 && y1 === y2`) falls back to an arbitrary rightward normal\n * rather than dividing by zero, so a caller need not special-case a zero-length dimension.\n */\nexport function dimensionGeometry(\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n offset: number,\n): DimensionGeometry {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const length = Math.hypot(dx, dy);\n const [ux, uy] = length > 1e-9 ? [dx / length, dy / length] : [1, 0];\n // The left-hand normal of the measured direction in a y-down frame: for a rightward\n // measurement (u = (1, 0)) this is (0, -1), i.e. \"up\" on screen, which is what makes a\n // positive offset draw the dimension line above a left-to-right span rather than below.\n const nx = uy;\n const ny = -ux;\n\n const p1: Point = { x: x1 + nx * offset, y: y1 + ny * offset };\n const p2: Point = { x: x2 + nx * offset, y: y2 + ny * offset };\n\n return {\n extensionLine1: [{ x: x1, y: y1 }, p1],\n extensionLine2: [{ x: x2, y: y2 }, p2],\n dimensionLine: [p1, p2],\n labelAnchor: { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 },\n angleDegrees: (Math.atan2(dy, dx) * 180) / Math.PI,\n };\n}\n","/**\n * A vector overlay layer for measurement primitives, drawn in source-image pixel\n * coordinates.\n *\n * Meant to sit as one of the transformed children inside `ZoomPanCanvas`, alongside the\n * image itself and any raster layers (a mask, a false-colour value plane). Because the\n * whole stack is transformed together (see `ZoomPanCanvas`'s own docs), a caliper box\n * drawn here stays registered with the pixel it measures at any zoom or pan — the overlay\n * never touches the DOM to find out where it is; it is told, in `nativeWidth` ×\n * `nativeHeight` pixel coordinates, via `primitives`.\n *\n * This component holds **no app state**: no fetch, no selection, no hover tracking. It is a\n * pure function of its props, on purpose — the app decides what a \"caliper box\" or a\n * \"detected edge\" *is*; this only knows how to draw one. The one piece of arithmetic it\n * owns is `strokeScale` compensation (see `measureGeometry.ts`'s `strokeWidthFor`), because\n * getting that wrong is invisible on screen until someone zooms in and a \"1px\" edge marker\n * has silently become 8px wide.\n */\n\nimport { imageViewBox } from \"./stage/view\";\nimport { arcPath, arrowHeadPoints, caliperArrow, caliperCorners, crossSegments, dimensionGeometry, polygonPath, strokeWidthFor } from \"./measureGeometry\";\nimport { cn, toneColor, type MeasureTone } from \"@vitavision/ui\";\n\nexport type { MeasureTone };\n\n/** A marked location: a dot, or a cross for a subpixel edge. */\nexport interface PointPrimitive {\n /** Discriminant. */\n kind: \"point\";\n /** Image x of the point. */\n x: number;\n /** Image y of the point. */\n y: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Native-pixel radius of the dot. Ignored when `cross` is set. */\n radius?: number;\n /** Drawn as a cross instead of a dot — the usual mark for a subpixel edge location. */\n cross?: boolean;\n /** Text drawn just above the mark. */\n label?: string;\n}\n\n/** A straight line between two image points. */\nexport interface SegmentPrimitive {\n /** Discriminant. */\n kind: \"segment\";\n /** Image x of the first end. */\n x1: number;\n /** Image y of the first end. */\n y1: number;\n /** Image x of the second end. */\n x2: number;\n /** Image y of the second end. */\n y2: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** A short dash pattern, e.g. for a fitted line shown against its inlier points. */\n dashed?: boolean;\n}\n\n/** A circle — a fitted bore, a tolerance ring. */\nexport interface CirclePrimitive {\n /** Discriminant. */\n kind: \"circle\";\n /** Image x of the centre. */\n cx: number;\n /** Image y of the centre. */\n cy: number;\n /** Radius, in image pixels. */\n r: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Filled rather than stroked — rare, but a small confidence disc wants it. */\n filled?: boolean;\n}\n\n/** A circular arc, swept forward (clockwise on screen) from `startAngle` to `endAngle`. */\nexport interface ArcPrimitive {\n /** Discriminant. */\n kind: \"arc\";\n /** Image x of the centre. */\n cx: number;\n /** Image y of the centre. */\n cy: number;\n /** Radius, in image pixels. */\n r: number;\n /** Radians. `x = cx + r·cos(a)`, `y = cy + r·sin(a)` — clockwise on screen. */\n startAngle: number;\n /** Radians, same convention as `startAngle`. A full turn past it draws a whole circle. */\n endAngle: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n}\n\n/** A caliper search box: a rotated rectangle with an arrow along its scan direction. */\nexport interface CaliperPrimitive {\n /** Discriminant. */\n kind: \"caliper\";\n /** Image x of the box centre. */\n cx: number;\n /** Image y of the box centre. */\n cy: number;\n /** Along the box's own measurement axis. */\n width: number;\n /** Perpendicular to the measurement axis — the search span. */\n height: number;\n /** Radians, the box's own rotation (and its measurement direction). */\n angle: number;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Draws the direction arrow along the box's +x axis. Defaults to on. */\n showDirection?: boolean;\n /** Text drawn at the box centre. */\n label?: string;\n}\n\n/** A dimension annotation: extension lines, an offset dimension line, and its value as text. */\nexport interface DimensionPrimitive {\n /** Discriminant. */\n kind: \"dimension\";\n /** Image x of the first measured point. */\n x1: number;\n /** Image y of the first measured point. */\n y1: number;\n /** Image x of the second measured point. */\n x2: number;\n /** Image y of the second measured point. */\n y2: number;\n /** The measured value as text, drawn along the dimension line. */\n label: string;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** Native pixels the dimension line sits off the measured span. Defaults to 16. */\n offset?: number;\n}\n\n/** Anything `MeasureOverlay` can draw, discriminated by `kind`. */\nexport type MeasurePrimitive =\n | PointPrimitive\n | SegmentPrimitive\n | CirclePrimitive\n | ArcPrimitive\n | CaliperPrimitive\n | DimensionPrimitive;\n\nconst DEFAULT_LABEL_SIZE = 11;\nconst DEFAULT_POINT_RADIUS = 3;\nconst DEFAULT_CROSS_SIZE = 5;\nconst DEFAULT_DIMENSION_OFFSET = 16;\n\n/** Props of `MeasureOverlay`. */\nexport interface MeasureOverlayProps {\n /** The source image's pixel width — the overlay's `viewBox`, and every primitive's frame. */\n nativeWidth: number;\n /** The source image's pixel height. */\n nativeHeight: number;\n /** What to draw, in image pixel coordinates, bottom to top. */\n primitives: MeasurePrimitive[];\n /**\n * The combined image-pixel → screen-pixel scale currently in effect, so a stroke or a\n * label declared at \"1 screen pixel\" stays that size regardless of zoom. Inside an\n * `ImageStage` (which lays the overlay out at exactly `nativeWidth` × `nativeHeight` CSS\n * pixels) this is simply `useStage().view.scale`. See `strokeWidthFor`.\n */\n strokeScale: number;\n /** Merged onto the `<svg>` with `cn`. */\n className?: string;\n}\n\n/**\n * A vector overlay of measurement primitives — points, segments, circles, arcs, caliper\n * boxes, dimensions — drawn in source-image pixel coordinates.\n *\n * Place it as a layer inside `ImageStage` so it moves with the image. It is a pure function\n * of its props and decorative to assistive technology (`aria-hidden`), so a result drawn\n * only here must also be stated in text.\n */\nexport function MeasureOverlay({\n nativeWidth,\n nativeHeight,\n primitives,\n strokeScale,\n className,\n}: MeasureOverlayProps) {\n const hairline = strokeWidthFor(strokeScale, 1);\n const thick = strokeWidthFor(strokeScale, 1.5);\n const labelSize = strokeWidthFor(strokeScale, DEFAULT_LABEL_SIZE);\n\n return (\n <svg\n role=\"presentation\"\n aria-hidden\n viewBox={imageViewBox({ width: nativeWidth, height: nativeHeight })}\n preserveAspectRatio=\"none\"\n className={cn(\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\", className)}\n >\n {primitives.map((primitive, index) => (\n <Primitive\n // Primitives carry no identity and hold no state; a position is the only key.\n // eslint-disable-next-line @eslint-react/no-array-index-key\n key={index}\n primitive={primitive}\n hairline={hairline}\n thick={thick}\n labelSize={labelSize}\n strokeScale={strokeScale}\n />\n ))}\n </svg>\n );\n}\n\nfunction Primitive({\n primitive,\n hairline,\n thick,\n labelSize,\n strokeScale,\n}: {\n primitive: MeasurePrimitive;\n hairline: number;\n thick: number;\n labelSize: number;\n strokeScale: number;\n}) {\n const colour = toneColor(primitive.tone);\n\n switch (primitive.kind) {\n case \"point\": {\n if (primitive.cross) {\n const size = strokeWidthFor(strokeScale, DEFAULT_CROSS_SIZE);\n const [h, v] = crossSegments(primitive.x, primitive.y, size);\n return (\n <g stroke={colour} strokeWidth={hairline}>\n <line x1={h[0].x} y1={h[0].y} x2={h[1].x} y2={h[1].y} />\n <line x1={v[0].x} y1={v[0].y} x2={v[1].x} y2={v[1].y} />\n <Label x={primitive.x} y={primitive.y - size - 2} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n const radius = strokeWidthFor(strokeScale, primitive.radius ?? DEFAULT_POINT_RADIUS);\n return (\n <g>\n <circle cx={primitive.x} cy={primitive.y} r={radius} fill={colour} />\n <Label x={primitive.x} y={primitive.y - radius - 2} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n\n case \"segment\":\n return (\n <line\n x1={primitive.x1}\n y1={primitive.y1}\n x2={primitive.x2}\n y2={primitive.y2}\n stroke={colour}\n strokeWidth={hairline}\n strokeDasharray={primitive.dashed ? `${hairline * 4} ${hairline * 3}` : undefined}\n />\n );\n\n case \"circle\":\n return (\n <circle\n cx={primitive.cx}\n cy={primitive.cy}\n r={primitive.r}\n fill={primitive.filled ? colour : \"none\"}\n stroke={primitive.filled ? \"none\" : colour}\n strokeWidth={hairline}\n />\n );\n\n case \"arc\":\n return (\n <path\n d={arcPath(primitive.cx, primitive.cy, primitive.r, primitive.startAngle, primitive.endAngle)}\n fill=\"none\"\n stroke={colour}\n strokeWidth={hairline}\n strokeLinecap=\"round\"\n />\n );\n\n case \"caliper\": {\n const corners = caliperCorners(primitive.cx, primitive.cy, primitive.width, primitive.height, primitive.angle);\n const arrow = caliperArrow(primitive.cx, primitive.cy, primitive.width, primitive.angle);\n const head = arrowHeadPoints(arrow.to, primitive.angle, strokeWidthFor(strokeScale, 4));\n return (\n <g>\n <path d={polygonPath(corners)} fill=\"none\" stroke={colour} strokeWidth={hairline} />\n {primitive.showDirection !== false && (\n <g stroke={colour} strokeWidth={thick} strokeLinecap=\"round\" strokeLinejoin=\"round\" fill=\"none\">\n <line x1={arrow.from.x} y1={arrow.from.y} x2={arrow.to.x} y2={arrow.to.y} />\n <polyline points={head.map((p) => `${p.x},${p.y}`).join(\" \")} />\n </g>\n )}\n <Label x={primitive.cx} y={primitive.cy} text={primitive.label} colour={colour} size={labelSize} />\n </g>\n );\n }\n\n case \"dimension\": {\n const offset = primitive.offset ?? DEFAULT_DIMENSION_OFFSET;\n const geometry = dimensionGeometry(primitive.x1, primitive.y1, primitive.x2, primitive.y2, offset);\n return (\n <g stroke={colour} strokeWidth={hairline}>\n <line x1={geometry.extensionLine1[0].x} y1={geometry.extensionLine1[0].y} x2={geometry.extensionLine1[1].x} y2={geometry.extensionLine1[1].y} opacity={0.5} />\n <line x1={geometry.extensionLine2[0].x} y1={geometry.extensionLine2[0].y} x2={geometry.extensionLine2[1].x} y2={geometry.extensionLine2[1].y} opacity={0.5} />\n <line x1={geometry.dimensionLine[0].x} y1={geometry.dimensionLine[0].y} x2={geometry.dimensionLine[1].x} y2={geometry.dimensionLine[1].y} />\n <text\n x={geometry.labelAnchor.x}\n y={geometry.labelAnchor.y}\n fontSize={labelSize}\n fill={colour}\n stroke=\"none\"\n textAnchor=\"middle\"\n dominantBaseline=\"text-after-edge\"\n transform={`rotate(${geometry.angleDegrees} ${geometry.labelAnchor.x} ${geometry.labelAnchor.y})`}\n >\n {primitive.label}\n </text>\n </g>\n );\n }\n\n default:\n return null;\n }\n}\n\nfunction Label({\n x,\n y,\n text,\n colour,\n size,\n}: {\n x: number;\n y: number;\n text?: string | undefined;\n colour: string;\n size: number;\n}) {\n if (!text) return null;\n return (\n <text x={x} y={y} fontSize={size} fill={colour} textAnchor=\"middle\" dominantBaseline=\"text-after-edge\">\n {text}\n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@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/stage2d",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "description": "The vitavision 2D image stage: view transform, zoom/pan, layered overlays, measurement.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.6.0",
49
+ "@vitavision/ui": "^0.7.0",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -247,7 +247,7 @@ export function ZoomPanCanvas({
247
247
  data-panning={grabbing ? "" : undefined}
248
248
  data-fit={view.zoom <= MIN_ZOOM ? "" : undefined}
249
249
  className={cn(
250
- "relative overflow-hidden rounded border border-line bg-canvas select-none",
250
+ "relative overflow-hidden rounded-control border border-line bg-canvas select-none",
251
251
  grabbing ? "cursor-grabbing" : "cursor-grab",
252
252
  className,
253
253
  )}
@@ -286,14 +286,14 @@ export function ZoomPanCanvas({
286
286
  {children}
287
287
  </div>
288
288
  {label && (
289
- <span className="pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white">
289
+ <span className="pointer-events-none absolute bottom-1 left-1 rounded-control bg-black/60 px-1 font-mono text-[10px] text-white">
290
290
  {label}
291
291
  </span>
292
292
  )}
293
293
  {fitLabel !== null && view.zoom > MIN_ZOOM && (
294
294
  <button
295
295
  type="button"
296
- className="absolute right-1 bottom-1 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80"
296
+ className="absolute right-1 bottom-1 rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80"
297
297
  // Stopping `pointerdown` is what makes the button work at all: without it the
298
298
  // press bubbles to the canvas, which calls `setPointerCapture` on itself and
299
299
  // takes the click with it, so the button rendered and did nothing.
@@ -496,7 +496,7 @@ export function ImageStage({
496
496
  data-panning={panning ? "" : undefined}
497
497
  data-pan-mode={panMode ? "" : undefined}
498
498
  className={cn(
499
- "relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none",
499
+ "relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none",
500
500
  "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal",
501
501
  panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default",
502
502
  className,
@@ -241,7 +241,7 @@ export function StageReadout({ cursor, extra, className }: StageReadoutProps) {
241
241
  return (
242
242
  <span
243
243
  className={cn(
244
- "rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",
244
+ "rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",
245
245
  className,
246
246
  )}
247
247
  >