@vitavision/stage2d 0.7.1 → 0.8.0

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.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","../src/components/ContourEditor.tsx","../src/components/MaskEditor.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 </text>\n );\n}\n","/** Reusable source-image contour overlay and vertex editor for ImageStage. */\n\nimport { useRef, useState, type KeyboardEvent, type PointerEvent } from \"react\";\n\nimport { imageViewBox } from \"./stage/view\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { Point } from \"./measureGeometry\";\n\n/** An ordered, closed contour drawn in source-image pixel-center coordinates. */\nexport interface ContourEditorProps {\n /** Ordered vertices; the final vertex connects back to the first. */\n points: Point[];\n /** Receives a complete replacement point list after each edit. */\n onChange: (points: Point[]) => void;\n /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */\n onCommit?: () => void;\n /** Show draggable, keyboard-editable vertices. */\n editable?: boolean;\n /** Accessible name for the contour and its vertices. */\n label?: string;\n /** CSS stroke color. */\n stroke?: string;\n}\n\n/** Return the index of the closest segment, with the last vertex joined to the first. */\nexport function nearestContourSegment(points: Point[], point: Point): number {\n let nearest = 0;\n let distance = Infinity;\n for (let i = 0; i < points.length; i++) {\n const a = points[i];\n const b = points[(i + 1) % points.length];\n if (!a || !b) continue;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)));\n const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;\n if (d < distance) { distance = d; nearest = i; }\n }\n return nearest;\n}\n\n/** Edit contour vertices over an ImageStage using its shared source-image transform. */\nexport function ContourEditor({ points, onChange, onCommit, editable = false, label = \"Contour\", stroke = \"var(--signal)\" }: ContourEditorProps) {\n const stage = useStage();\n const draggingRef = useRef<number | null>(null);\n const movedRef = useRef(false);\n const [selected, setSelected] = useState<number | null>(null);\n const line = points.map((point) => `${point.x},${point.y}`).join(\" \");\n const radius = stage.imageLength(5);\n const hairline = stage.imageLength(1.5);\n\n function clamp(point: Point): Point {\n return {\n x: Math.max(0, Math.min(stage.image.width - 1, point.x)),\n y: Math.max(0, Math.min(stage.image.height - 1, point.y)),\n };\n }\n\n /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */\n function move(index: number, point: Point): boolean {\n const current = points[index];\n const target = clamp(point);\n if (!current || (current.x === target.x && current.y === target.y)) return false;\n const next = [...points];\n next[index] = target;\n onChange(next);\n return true;\n }\n\n function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {\n if (!editable || stage.panMode || event.button !== 0) return;\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n draggingRef.current = index;\n movedRef.current = false;\n setSelected(index);\n }\n\n function pointerMove(event: PointerEvent<SVGCircleElement>) {\n if (draggingRef.current === null) return;\n event.stopPropagation();\n if (move(draggingRef.current, stage.toImage({ x: event.clientX, y: event.clientY }))) movedRef.current = true;\n }\n\n function pointerUp(event: PointerEvent<SVGCircleElement>) {\n if (draggingRef.current === null) return;\n event.stopPropagation();\n draggingRef.current = null;\n if (movedRef.current) onCommit?.();\n }\n\n function keyDown(event: KeyboardEvent<SVGCircleElement>, index: number) {\n if (!editable || stage.panMode) return;\n const delta = event.shiftKey ? 0.1 : 1;\n const p = points[index];\n if (!p) return;\n const shift: Record<string, Point> = {\n ArrowLeft: { x: -delta, y: 0 }, ArrowRight: { x: delta, y: 0 },\n ArrowUp: { x: 0, y: -delta }, ArrowDown: { x: 0, y: delta },\n };\n if (shift[event.key]) {\n event.preventDefault();\n event.stopPropagation();\n if (move(index, { x: p.x + shift[event.key]!.x, y: p.y + shift[event.key]!.y })) onCommit?.();\n } else if ((event.key === \"Delete\" || event.key === \"Backspace\") && points.length > 3) {\n event.preventDefault();\n event.stopPropagation();\n onChange(points.filter((_, i) => i !== index));\n setSelected(null);\n onCommit?.();\n } else if (event.key === \"Insert\" && points.length >= 3) {\n event.preventDefault();\n event.stopPropagation();\n const next = points[(index + 1) % points.length]!;\n onChange([...points.slice(0, index + 1), { x: (p.x + next.x) / 2, y: (p.y + next.y) / 2 }, ...points.slice(index + 1)]);\n setSelected(index + 1);\n onCommit?.();\n }\n }\n\n return (\n <svg viewBox={imageViewBox(stage.image)} className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\" role={editable ? undefined : \"img\"} aria-label={label}>\n <polygon points={line} fill=\"none\" stroke={stroke} strokeWidth={hairline} />\n {editable && points.length >= 3 && (\n <polygon points={line} fill=\"none\" stroke=\"transparent\" strokeWidth={stage.imageLength(12)} className=\"pointer-events-auto\" onDoubleClick={(event) => {\n if (stage.panMode) return;\n event.stopPropagation();\n const point = clamp(stage.toImage({ x: event.clientX, y: event.clientY }));\n const index = nearestContourSegment(points, point);\n onChange([...points.slice(0, index + 1), point, ...points.slice(index + 1)]);\n setSelected(index + 1);\n onCommit?.();\n }} />\n )}\n {editable && points.map((point, index) => (\n // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.\n // eslint-disable-next-line @eslint-react/no-array-index-key\n <circle key={index} cx={point.x} cy={point.y} r={selected === index ? radius * 1.3 : radius} fill=\"var(--surface)\" stroke={stroke} strokeWidth={hairline} className=\"pointer-events-auto cursor-move\" tabIndex={0} role=\"button\" aria-label={`${label} point ${index + 1}`} onPointerDown={(event) => pointerDown(event, index)} onPointerMove={pointerMove} onPointerUp={pointerUp} onLostPointerCapture={pointerUp} onDoubleClick={(event) => { if (!stage.panMode) event.stopPropagation(); }} onKeyDown={(event) => keyDown(event, index)} onFocus={() => setSelected(index)} />\n ))}\n </svg>\n );\n}\n","/** A source-pixel raster mask layer with a small paint/erase brush. */\n\nimport { useEffect, useRef, useState, type FocusEvent, type KeyboardEvent, type PointerEvent } from \"react\";\n\nimport { imageViewBox } from \"./stage/view\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { Point } from \"./measureGeometry\";\n\n/** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */\nexport function paintMask(mask: Uint8Array, width: number, height: number, from: Point, to: Point, radius: number, value: 0 | 1): Uint8Array {\n if (mask.length !== width * height) throw new RangeError(\"Mask dimensions do not match its pixel data.\");\n if (![from.x, from.y, to.x, to.y, radius].every(Number.isFinite) || radius < 0) throw new RangeError(\"Brush coordinates and radius must be finite and nonnegative.\");\n const next = mask.slice();\n const clamp = (value: number, limit: number) => Math.max(0, Math.min(limit - 1, value));\n const start = { x: clamp(from.x, width), y: clamp(from.y, height) };\n const end = { x: clamp(to.x, width), y: clamp(to.y, height) };\n const steps = Math.max(1, Math.ceil(Math.hypot(end.x - start.x, end.y - start.y)));\n // A click between four pixel centers must still affect the nearest pixels.\n const r = Math.max(0.75, radius);\n for (let step = 0; step <= steps; step++) {\n const x = start.x + (end.x - start.x) * step / steps;\n const y = start.y + (end.y - start.y) * step / steps;\n for (let row = Math.max(0, Math.ceil(y - r)); row <= Math.min(height - 1, Math.floor(y + r)); row++) {\n for (let col = Math.max(0, Math.ceil(x - r)); col <= Math.min(width - 1, Math.floor(x + r)); col++) {\n if ((col - x) ** 2 + (row - y) ** 2 <= r * r) next[row * width + col] = value;\n }\n }\n }\n return next;\n}\n\n/** Binary mask values are 0 or 1, in row-major source-image coordinates. */\nexport interface MaskEditorProps {\n /** Exactly image width × image height bytes. */\n mask: Uint8Array;\n /** Receives a fresh array after each brush movement. */\n onChange: (mask: Uint8Array) => void;\n /** Called once when a pointer stroke or keyboard paint finishes. */\n onCommit?: () => void;\n /** Allow brush interaction; otherwise render only. */\n editable?: boolean;\n /** Source-image pixels, independent of zoom. */\n brushRadius?: number;\n /** Paint or erase. */\n mode?: \"paint\" | \"erase\";\n /** Accessible name for the brush control. */\n label?: string;\n /** RGBA overlay color. */\n color?: readonly [number, number, number, number];\n}\n\n/** Render and edit a binary raster mask within the enclosing ImageStage. */\nexport function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = \"paint\", label = \"Mask brush\", color = [0, 190, 220, 128] }: MaskEditorProps) {\n const stage = useStage();\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const draftRef = useRef(mask);\n const lastRef = useRef<Point | null>(null);\n // The keyboard brush; it starts at the image centre and follows the last pointer stroke.\n const cursorRef = useRef<Point | null>(null);\n // Where the keyboard brush is drawn, while the layer has keyboard focus.\n const [brush, setBrush] = useState<Point | null>(null);\n\n function cursor(): Point {\n return cursorRef.current ?? { x: Math.floor(stage.image.width / 2), y: Math.floor(stage.image.height / 2) };\n }\n\n useEffect(() => {\n if (mask.length !== stage.image.width * stage.image.height) throw new RangeError(\"Mask dimensions do not match ImageStage.\");\n const context = canvasRef.current?.getContext(\"2d\");\n if (!context) return;\n const pixels = context.createImageData(stage.image.width, stage.image.height);\n for (let i = 0; i < mask.length; i++) {\n if (mask[i]) pixels.data.set(color, i * 4);\n }\n context.putImageData(pixels, 0, 0);\n }, [mask, color, stage.image.width, stage.image.height]);\n\n function apply(from: Point, to: Point) {\n const next = paintMask(draftRef.current, stage.image.width, stage.image.height, from, to, brushRadius, mode === \"paint\" ? 1 : 0);\n draftRef.current = next;\n onChange(next);\n }\n\n function down(event: PointerEvent<HTMLCanvasElement>) {\n if (!editable || stage.panMode || event.button !== 0) return;\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n // Each stroke starts from the mask the caller holds, so an edit it rejected is not carried forward.\n draftRef.current = mask;\n lastRef.current = point;\n cursorRef.current = point;\n setBrush(null);\n apply(point, point);\n }\n\n function move(event: PointerEvent<HTMLCanvasElement>) {\n if (!lastRef.current) return;\n event.stopPropagation();\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n apply(lastRef.current, point);\n lastRef.current = point;\n cursorRef.current = point;\n }\n\n function up(event: PointerEvent<HTMLCanvasElement>) {\n if (!lastRef.current) return;\n event.stopPropagation();\n lastRef.current = null;\n onCommit?.();\n }\n\n function keyDown(event: KeyboardEvent<HTMLCanvasElement>) {\n if (!editable || stage.panMode) return;\n const shift: Record<string, Point> = {\n ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 },\n ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 },\n };\n const delta = shift[event.key];\n if (delta) {\n event.preventDefault();\n event.stopPropagation();\n const from = cursor();\n cursorRef.current = {\n x: Math.max(0, Math.min(stage.image.width - 1, from.x + delta.x)),\n y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y)),\n };\n setBrush(cursorRef.current);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n event.stopPropagation();\n const at = cursor();\n draftRef.current = mask;\n setBrush(at);\n apply(at, at);\n onCommit?.();\n }\n }\n\n function focus(event: FocusEvent<HTMLCanvasElement>) {\n if (editable && event.currentTarget.matches(\":focus-visible\")) setBrush(cursor());\n }\n\n return (\n <>\n <canvas ref={canvasRef} width={stage.image.width} height={stage.image.height} className={`absolute inset-0 h-full w-full ${editable ? \"pointer-events-auto cursor-crosshair\" : \"pointer-events-none\"}`} style={{ imageRendering: \"pixelated\" }} role={editable ? \"button\" : \"img\"} tabIndex={editable ? 0 : undefined} aria-label={label} aria-description={editable ? \"Arrow keys move the brush; Enter paints or erases.\" : undefined} onPointerDown={down} onPointerMove={move} onPointerUp={up} onLostPointerCapture={up} onDoubleClick={(event) => { if (editable && !stage.panMode) event.stopPropagation(); }} onKeyDown={keyDown} onFocus={focus} onBlur={() => setBrush(null)} />\n {brush && (\n <svg viewBox={imageViewBox(stage.image)} className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\" aria-hidden=\"true\">\n <circle cx={brush.x} cy={brush.y} r={Math.max(0.75, brushRadius)} fill=\"none\" stroke=\"var(--signal)\" strokeWidth={stage.imageLength(1.5)} />\n </svg>\n )}\n </>\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,SAA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ACxI,CAAA,CAEP,EAAA,CAAA;AAEN"}
1
+ {"version":3,"file":"index.js","names":["clamp","CLICK_SLOP","clamp","HALO"],"sources":["../src/components/stage/view.ts","../src/components/stage/ImageStage.tsx","../src/components/stage/ImageLayer.tsx","../src/components/stage/StageSurface.tsx","../src/components/stage/StageToolbar.tsx","../src/components/ZoomPanCanvas.tsx","../src/api/mapValues.ts","../src/components/measureGeometry.ts","../src/components/overlayRole.ts","../src/components/polylineIndex.ts","../src/components/MeasureOverlay.tsx","../src/components/stage/useScreenPx.ts","../src/components/ContourEditor.tsx","../src/components/roiEdit.ts","../src/components/RectRoiEditor.tsx","../src/components/PolylineSet.tsx","../src/components/MaskEditor.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 // Past the last step but short of the ceiling: the ceiling is the step, or \"zoom in\"\n // would stay enabled and do nothing.\n if (next === undefined) return scale < max * (1 - SCALE_EPSILON) ? max : Math.min(max, scale);\n return next;\n }\n const previous = [...candidates].reverse().find((s) => s < scale * (1 - SCALE_EPSILON));\n // Below the first step but above the floor: likewise, the floor is the step.\n if (previous === undefined) return scale > min * (1 + SCALE_EPSILON) ? min : Math.max(min, scale);\n return previous;\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 useImperativeHandle,\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 Ref,\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\n/**\n * The stage's controls for code outside it — an inspector's \"frame this contour\", a\n * \"fit on open\" — through `ImageStage`'s `ref`. Each is a no-op until the viewport has been\n * measured. Layers inside the stage use `useStage` instead.\n */\nexport interface StageHandle {\n /** Put a rect (image coordinates) on screen with a margin (CSS pixels, default 24). */\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}\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 * How a `null` view opens: `\"auto\"` (the default) at 1:1 when the image fits the viewport\n * and fit otherwise; `\"fit\"` always fit, for a viewer that should show the whole frame\n * whatever its size.\n */\n initialView?: \"auto\" | \"fit\" | undefined;\n /** The stage's controls for code outside it; see `StageHandle`. */\n ref?: Ref<StageHandle> | undefined;\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 initialView: opening = \"auto\",\n ref,\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, opening });\n useLayoutEffect(() => {\n latestRef.current = { view, box, image, clamp, onView, opening };\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 ? openingView(opening, box, image) : UNMEASURED_VIEW),\n [view, box, image, opening],\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, opening: o } = latestRef.current;\n if (v === null) report(openingView(o, 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 useImperativeHandle(ref, () => ({ frame, fit, zoomTo }), [frame, fit, zoomTo]);\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 // `@container/stage`: the toolbar and readout collapse by the canvas's own width,\n // not the window's — a canvas beside a wide inspector is narrow on a wide screen.\n \"@container/stage 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 // Wraps rather than clips: on a canvas too narrow for both, the readout moves onto\n // its own line above the toolbar instead of being truncated to nothing.\n <div className=\"pointer-events-none absolute inset-x-2 bottom-2 z-10 flex flex-wrap-reverse items-end justify-between gap-2\">\n <div className=\"pointer-events-auto max-w-full shrink-0\">{toolbar}</div>\n <div data-readout-slot=\"\" className=\"max-w-full min-w-0 truncate\">\n {readout}\n </div>\n </div>\n )}\n </div>\n </ImageStageContext>\n );\n}\n\n/** The view a `null` view opens at, by the `initialView` policy. */\nfunction openingView(opening: \"auto\" | \"fit\", box: Box, image: Box): StageView {\n return opening === \"fit\" ? fitView(box, image) : initialView(box, image);\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 photograph, as a stage layer.\n *\n * The stage is laid out at the image's own pixel size, so the photograph is drawn at its\n * natural size, with no `object-fit` letterbox for an overlay to disagree with.\n *\n * Two things every viewer of a large frame ends up doing by hand, done once here:\n *\n * - **A preview tier, then the full image.** A downscaled preview loads fast and is enough\n * until it would be magnified — until the screen shows more pixels than it has. Past that\n * point the full image is requested, and it stays once loaded, so zooming back out does\n * not swap back. The preview stays underneath while the full image loads, so the frame\n * never goes blank.\n * - **Pixelated past a zoom.** Above about 4× the browser's smoothing paints detail the\n * sensor never recorded; on a metrology bench the sensor's own samples are what is worth\n * looking at.\n */\n\nimport { useState } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\nimport { useStage } from \"./ImageStage\";\n\n/** A downscaled tier of the image, shown until the stage would magnify it. */\nexport interface ImageTier {\n /** Its URL. */\n src: string;\n /** Its width in pixels. The full image's width is the stage's own. */\n width: number;\n}\n\n/** Props of `ImageLayer`. */\nexport interface ImageLayerProps {\n /** The full-resolution image's URL. */\n src: string;\n /** A smaller tier to show first; without one, `src` is shown from the start. */\n preview?: ImageTier | undefined;\n /** The image's description, for assistive technology. `\"\"` marks it decorative. */\n alt: string;\n /** The zoom (CSS pixels per image pixel) from which pixels are drawn as blocks. Defaults to 4. */\n pixelatedAbove?: number | undefined;\n /** Called when the full image has loaded. */\n onLoad?: (() => void) | undefined;\n /** Called when the full image fails to load. */\n onError?: (() => void) | undefined;\n /** Merged onto both images with `cn`. */\n className?: string | undefined;\n}\n\n/**\n * The photograph at its natural size inside an `ImageStage`, with an optional preview tier\n * and pixelated rendering past `pixelatedAbove`. It takes no pointer events, so presses reach\n * the stage and the layers above.\n *\n * Each image carries `data-tier` (`preview` or `full`); the full image carries `data-loaded`\n * once it has loaded, and both carry `data-pixelated` while pixelated.\n */\nexport function ImageLayer({\n src,\n preview,\n alt,\n pixelatedAbove = 4,\n onLoad,\n onError,\n className,\n}: ImageLayerProps) {\n const stage = useStage();\n const scale = stage.view.scale;\n // The full image is wanted once the preview would be magnified on screen: its own pixels\n // per image pixel are `preview.width / image.width`. Not before the viewport is measured:\n // the placeholder view then is 1:1, which would fetch the full image on every open.\n const measured = stage.box.width > 0;\n const needsFull = preview === undefined || (measured && scale * stage.image.width > preview.width);\n // Requested once, kept: zooming back out should not drop the pixels already fetched.\n const [requested, setRequested] = useState<string | null>(needsFull ? src : null);\n if (needsFull && requested !== src) setRequested(src);\n const [loaded, setLoaded] = useState<string | null>(null);\n\n const showFull = requested === src;\n const fullReady = loaded === src;\n const pixelated = scale >= pixelatedAbove;\n const shared = cn(\"pointer-events-none absolute inset-0 h-full w-full select-none\", className);\n const rendering = pixelated ? (\"pixelated\" as const) : undefined;\n\n return (\n <>\n {preview && !fullReady && (\n <img\n src={preview.src}\n alt={showFull ? \"\" : alt}\n aria-hidden={showFull ? true : undefined}\n draggable={false}\n data-tier=\"preview\"\n data-pixelated={pixelated ? \"\" : undefined}\n className={shared}\n style={{ imageRendering: rendering }}\n />\n )}\n {showFull && (\n <img\n src={src}\n alt={alt}\n draggable={false}\n data-tier=\"full\"\n data-loaded={fullReady ? \"\" : undefined}\n data-pixelated={pixelated ? \"\" : undefined}\n onLoad={() => {\n setLoaded(src);\n onLoad?.();\n }}\n onError={() => onError?.()}\n className={cn(shared, preview && !fullReady && \"opacity-0\")}\n style={{ imageRendering: rendering }}\n />\n )}\n </>\n );\n}\n","/**\n * The stage's tool model: one place that decides what a press on the image means.\n *\n * Several layers usually want a full-frame target: one to draw a region, one to sweep a\n * selection, one to place a point. Only the topmost element under the pointer receives a press,\n * so two full-frame targets are one that always wins and one that never fires. Apps that grew\n * such layers one by one found this out the hard way.\n *\n * The rule here is one surface per stage, under the layers' own small targets (a handle, a\n * stroke). It asks the app what a press means, in priority order, and a press the app declines\n * bubbles to the stage, which pans.\n *\n * Drags listen on `window`, not on the pressed element. `setPointerCapture` routes every later\n * event to that one element, so a drag begun on a handle sent its moves to the handle, never\n * to the surface that held the move logic. Listening at the window also lets a drag survive\n * the pointer leaving the canvas, which is what dragging a corner outward does.\n */\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PointerEvent as ReactPointerEvent } from \"react\";\n\nimport type { Point } from \"../measureGeometry\";\nimport { useStage } from \"./ImageStage\";\nimport { imageViewBox } from \"./view\";\n\n/** What a drag does as the pointer moves and when it is released, in image coordinates. */\nexport interface StageDrag {\n /** Each move of the pointer while the button is held. */\n onMove?: ((point: Point, event: PointerEvent) => void) | undefined;\n /**\n * Release. `moved` is whether the pointer travelled more than a few screen pixels, which\n * tells a click from a drag.\n */\n onEnd?: ((point: Point, event: PointerEvent, moved: boolean) => void) | undefined;\n /** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag. */\n onCancel?: (() => void) | undefined;\n}\n\n/** How far a press may travel and still be a click, in screen pixels. */\nconst CLICK_SLOP = 3;\n\n/**\n * Start a drag from a press on any element inside an `ImageStage`.\n *\n * The press is claimed: propagation stops, so the stage does not pan. Later moves and the\n * release are read from `window` and converted to image coordinates. Call it from a\n * `pointerdown` handler.\n *\n * @returns `start(event, drag)`.\n */\nexport function useStageDrag(): (event: ReactPointerEvent<Element>, drag: StageDrag) => void {\n // `toImage` is stable for the stage's lifetime and reads the live view, so a drag converts\n // with the view in effect at each move.\n const { toImage } = useStage();\n const cleanupRef = useRef<(() => void) | null>(null);\n\n // A drag still in flight when the component unmounts is cancelled, not leaked.\n useEffect(() => () => cleanupRef.current?.(), []);\n\n return useCallback((event: ReactPointerEvent<Element>, drag: StageDrag) => {\n event.stopPropagation();\n event.preventDefault();\n cleanupRef.current?.();\n const from = { x: event.clientX, y: event.clientY };\n let moved = false;\n const at = (e: PointerEvent) => toImage({ x: e.clientX, y: e.clientY });\n\n const move = (e: PointerEvent) => {\n if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP) moved = true;\n drag.onMove?.(at(e), e);\n };\n const up = (e: PointerEvent) => {\n stop();\n drag.onEnd?.(at(e), e, moved);\n };\n const cancel = () => {\n stop();\n drag.onCancel?.();\n };\n const stop = () => {\n window.removeEventListener(\"pointermove\", move);\n window.removeEventListener(\"pointerup\", up);\n window.removeEventListener(\"pointercancel\", cancel);\n cleanupRef.current = null;\n };\n window.addEventListener(\"pointermove\", move);\n window.addEventListener(\"pointerup\", up);\n window.addEventListener(\"pointercancel\", cancel);\n cleanupRef.current = cancel;\n }, [toImage]);\n}\n\n/** A press on the surface, as the app's `onPress` sees it. */\nexport interface StagePress {\n /** Where, in image coordinates. */\n point: Point;\n /** Shift was held. */\n shiftKey: boolean;\n /** Alt / Option was held. */\n altKey: boolean;\n /** ⌘ (macOS) or Ctrl was held: the usual \"add to / toggle in the selection\" modifier. */\n metaKey: boolean;\n}\n\n/** Props of `StageSurface`. */\nexport interface StageSurfaceProps {\n /**\n * What a press means. Return a `StageDrag` to claim it (a click is a drag that never\n * moved), or nothing to decline it: a declined press reaches the stage, which pans.\n */\n onPress: (press: StagePress) => StageDrag | null | undefined | void;\n /** The cursor over the image while no drag is in flight, e.g. `crosshair` for a draw tool. */\n cursor?: string | undefined;\n /** Where the pointer is over the image while no drag is in flight, for hover feedback. */\n onHover?: ((point: Point) => void) | undefined;\n}\n\n/**\n * The stage's one full-frame press target. Put it inside an `ImageStage`, below the layers\n * that have their own small targets (handles, strokes). Each press is offered to `onPress`\n * unless the hand tool or a held space bar make it a pan; a declined press pans.\n *\n * The surface draws nothing. It carries `data-dragging` while a drag it started is in\n * flight.\n */\nexport function StageSurface({ onPress, cursor, onHover }: StageSurfaceProps) {\n const stage = useStage();\n const start = useStageDrag();\n const [dragging, setDragging] = useState(false);\n\n const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {\n if (event.button !== 0 || stage.panMode) return;\n const drag = onPress({\n point: stage.toImage({ x: event.clientX, y: event.clientY }),\n shiftKey: event.shiftKey,\n altKey: event.altKey,\n metaKey: event.metaKey || event.ctrlKey,\n });\n if (!drag) return; // Declined: the stage pans.\n setDragging(true);\n start(event, {\n onMove: drag.onMove,\n onEnd: (point, e, moved) => {\n setDragging(false);\n drag.onEnd?.(point, e, moved);\n },\n onCancel: () => {\n setDragging(false);\n drag.onCancel?.();\n },\n });\n };\n\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full\"\n data-dragging={dragging ? \"\" : undefined}\n aria-hidden\n >\n <rect\n data-stage-surface=\"\"\n x={-0.5}\n y={-0.5}\n width={stage.image.width}\n height={stage.image.height}\n fill=\"transparent\"\n className=\"pointer-events-auto\"\n style={{ cursor: stage.panMode ? undefined : cursor }}\n onPointerDown={onPointerDown}\n onPointerMove={(event) => {\n if (!dragging) onHover?.(stage.toImage({ x: event.clientX, y: event.clientY }));\n }}\n />\n </svg>\n );\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 { Layers, Maximize2, Minus, Plus, Scan } from \"lucide-react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, ReactNode } from \"react\";\n\nimport { DropdownMenu, Kbd, MenuCheckboxItem, MenuLabel, Tooltip, 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 *\n * On a canvas narrower than 30rem, zoom out, zoom in and 100% collapse: the percentage menu\n * and the `+` / `-` / `1` keys still reach them, so the app's own groups keep their room.\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 {/* Priority collapse on a narrow canvas: zoom out/in and 100% go first (the percentage\n menu and the + / - / 1 keys still reach them), so the app's own groups keep their\n room. */}\n <StageButton\n label=\"Zoom out\"\n onClick={() => step(-1)}\n disabled={stage.view.scale <= min + 1e-9}\n className=\"@max-[30rem]/stage:hidden\"\n >\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 className=\"@max-[30rem]/stage:hidden\"\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 className=\"@max-[30rem]/stage:hidden\"\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 /**\n * A longer explanation for the tooltip, after the label. Giving `hint` or `shortcut`\n * switches the native `title` for the ui `Tooltip`, which needs a `TooltipProvider` above\n * the stage.\n */\n hint?: ReactNode;\n /** The key that does the same, shown in the tooltip as a `Kbd`. Display only. */\n shortcut?: string | undefined;\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 *\n * Its tooltip is the native `title` (the label), or with `hint` / `shortcut` the ui\n * `Tooltip`: the label, the hint, and the shortcut as a key cap.\n */\nexport function StageButton({ label, pressed, hint, shortcut, className, children, ...props }: StageButtonProps) {\n const rich = hint !== undefined || shortcut !== undefined;\n const button = (\n <button\n {...props}\n type=\"button\"\n title={rich ? undefined : label}\n aria-label={label}\n aria-keyshortcuts={shortcut}\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 if (!rich) return button;\n return (\n <Tooltip\n content={\n <span className=\"flex items-center gap-2\">\n <span>\n <span className=\"font-medium\">{label}</span>\n {hint !== undefined && <span className=\"block text-fg-muted\">{hint}</span>}\n </span>\n {shortcut && <Kbd>{shortcut}</Kbd>}\n </span>\n }\n >\n {button}\n </Tooltip>\n );\n}\n\n/** One layer in a `StageLayersMenu`. */\nexport interface StageLayer {\n /** Its identity, passed back to `onVisibleChange`. */\n id: string;\n /** Its name in the menu. */\n label: string;\n /** Whether it is shown. */\n visible: boolean;\n /** Shown but not switchable, e.g. a layer that has nothing to draw yet. */\n disabled?: boolean | undefined;\n /** A key that toggles it, shown as a `Kbd`. Display only: binding it is the app's. */\n shortcut?: string | undefined;\n}\n\n/** Props of `StageLayersMenu`. */\nexport interface StageLayersMenuProps {\n /** The layers, in menu order. */\n layers: readonly StageLayer[];\n /** Called with a layer's id and its new visibility. */\n onVisibleChange: (id: string, visible: boolean) => void;\n /** The trigger's accessible name and the menu's heading. Defaults to \"Layers\". */\n label?: string | undefined;\n}\n\n/**\n * A `StageButton`-shaped trigger opening a menu of layer toggles, for `StageToolbar`'s\n * children. Each layer is a `menuitemcheckbox`; toggling one keeps the menu open for the\n * next. The trigger shows as pressed while any layer is hidden, so a canvas missing a layer\n * says so before the menu is opened.\n */\nexport function StageLayersMenu({ layers, onVisibleChange, label = \"Layers\" }: StageLayersMenuProps) {\n const hidden = layers.some((layer) => !layer.visible && !layer.disabled);\n return (\n <DropdownMenu\n side=\"top\"\n trigger={\n <StageButton label={label} pressed={hidden}>\n <Layers className=\"size-4\" aria-hidden />\n </StageButton>\n }\n >\n <MenuLabel>{label}</MenuLabel>\n {layers.map((layer) => (\n <MenuCheckboxItem\n key={layer.id}\n checked={layer.visible}\n onCheckedChange={(visible) => onVisibleChange(layer.id, visible)}\n disabled={layer.disabled}\n shortcut={layer.shortcut}\n >\n {layer.label}\n </MenuCheckboxItem>\n ))}\n </DropdownMenu>\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 * The overlay grammar's roles and states (docs/visual-language.md §5), for layers that paint\n * through SVG attributes rather than class names.\n */\n\n/**\n * What an overlay mark is.\n * - `feature`: detected or observed (corners, edges, contours).\n * - `model`: predicted (reprojections, fitted geometry).\n * - `structure`: context (a board outline, grid lines).\n * - `selection`: the selected item.\n * - `label`: ids and text.\n * - `halo`: the dark band under every stroke and label, so a mark holds on any image.\n */\nexport type OverlayRole = \"feature\" | \"model\" | \"structure\" | \"selection\" | \"label\" | \"halo\";\n\n/**\n * A mark's interaction state.\n * - `default` is drawn 1.5 screen px wide.\n * - `hover` is 2 px, and nothing else changes.\n * - `selected` is 2.5 px with a ring in the selection colour.\n * - `dimmed` is 35 % opacity.\n */\nexport type OverlayState = \"default\" | \"hover\" | \"selected\" | \"dimmed\";\n\n/** The roles, in the order the spec lists them. */\nexport const OVERLAY_ROLES: readonly OverlayRole[] = [\"feature\", \"model\", \"structure\", \"selection\", \"label\", \"halo\"];\n\n/**\n * The CSS paint for a role: a `var(--stage-…)` reference defined by `@vitavision/stage2d/styles.css`.\n *\n * @param role - The role.\n * @returns A CSS value usable as an SVG `stroke` or `fill`.\n */\nexport function overlayRole(role: OverlayRole): string {\n return `var(--stage-${role})`;\n}\n\n/** Screen-pixel stroke widths for each state, before the stage's scale is applied. */\nexport const OVERLAY_STATE_WIDTH: Readonly<Record<OverlayState, number>> = {\n default: 1.5,\n hover: 2,\n selected: 2.5,\n dimmed: 1.5,\n};\n\n/** Opacity for each state. */\nexport const OVERLAY_STATE_OPACITY: Readonly<Record<OverlayState, number>> = {\n default: 1,\n hover: 1,\n selected: 1,\n dimmed: 0.35,\n};\n","/**\n * A spatial index over many polylines: which one is under the pointer, and which ones a\n * rubber band caught.\n *\n * Asking the DOM is too slow at scale. The L0-3 benchmark measured `elementFromPoint` over\n * 20k elements at p95 ≈ 2.1 ms, over the 2 ms gate. A uniform grid of segments answers in\n * microseconds whichever engine draws the lines (`docs/measurements/stage2d-bench-analysis.md`).\n *\n * Points are flat `[x0, y0, x1, y1, …]` arrays in image coordinates, the form a backend\n * returns and the cheapest to keep.\n */\n\nimport type { Point } from \"./measureGeometry\";\nimport type { Rect } from \"./stage/view\";\n\n/** A polyline's identity. */\nexport type PolylineId = string | number;\n\n/** One polyline: an id, flat image-coordinate points, and whether its last point joins its first. */\nexport interface Polyline {\n /** Its identity, unique in the set. */\n id: PolylineId;\n /** `[x0, y0, x1, y1, …]` in image coordinates. */\n points: ArrayLike<number>;\n /** Join the last point to the first. */\n closed?: boolean | undefined;\n}\n\n/**\n * An index built by `buildPolylineIndex`. Treat it as opaque and query it with\n * `nearestPolyline` and `polylinesInRect`; its layout may change.\n */\nexport interface PolylineIndex {\n /** The polylines, in the order given. */\n readonly items: readonly Polyline[];\n /** Grid cell side, in image pixels. */\n readonly cell: number;\n /** The grid's origin x. */\n readonly x0: number;\n /** The grid's origin y. */\n readonly y0: number;\n /** Grid columns. */\n readonly cols: number;\n /** Grid rows. */\n readonly rows: number;\n /** CSR layout: cell `c`'s entries are `starts[c] .. starts[c + 1]`. */\n readonly starts: Uint32Array;\n /** Per entry, two numbers: the polyline's index and the segment's start point index. */\n readonly segs: Uint32Array;\n}\n\n/** The nearest polyline to a point. */\nexport interface PolylineHit {\n /** Its id. */\n id: PolylineId;\n /** The closest point on it. */\n point: Point;\n /** The distance to that point. */\n distance: number;\n}\n\n/**\n * The number of segments of a polyline.\n *\n * @param points - Flat points.\n * @param closed - Whether the last point joins the first.\n * @returns The segment count.\n */\nfunction segmentCount(points: ArrayLike<number>, closed: boolean): number {\n const n = Math.floor(points.length / 2);\n if (n < 2) return n === 1 ? 1 : 0; // a single point is a zero-length segment, still pickable\n return closed ? n : n - 1;\n}\n\n/** The start and end of segment `s` (a single point is its own segment). */\nfunction segment(points: ArrayLike<number>, s: number): [number, number, number, number] {\n const n = Math.floor(points.length / 2);\n // A single point is a zero-length segment; otherwise the next point, wrapping when closed.\n const b = n === 1 ? 0 : (s + 1) % n;\n return [points[2 * s]!, points[2 * s + 1]!, points[2 * b]!, points[2 * b + 1]!];\n}\n\n/**\n * Index a set of polylines.\n *\n * @param items - The polylines.\n * @param cell - The grid cell side in image pixels. Defaults to 32: a few segments per cell\n * at contour densities, and a pointer's search radius spans one or two cells.\n * @returns The index.\n */\nexport function buildPolylineIndex(items: readonly Polyline[], cell = 32): PolylineIndex {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const item of items) {\n const p = item.points;\n for (let i = 0; i + 1 < p.length; i += 2) {\n const x = p[i]!;\n const y = p[i + 1]!;\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n }\n if (!(maxX >= minX)) {\n return { items, cell, x0: 0, y0: 0, cols: 1, rows: 1, starts: new Uint32Array(2), segs: new Uint32Array(0) };\n }\n const cols = Math.max(1, Math.ceil((maxX - minX) / cell) + 1);\n const rows = Math.max(1, Math.ceil((maxY - minY) / cell) + 1);\n const cellX = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / cell)));\n const cellY = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / cell)));\n\n // Two passes (count, then fill) into a CSR layout: no per-cell arrays.\n const counts = new Uint32Array(cols * rows + 1);\n const visit = (fn: (c: number, item: number, s: number) => void) => {\n items.forEach((item, index) => {\n const closed = item.closed === true;\n const count = segmentCount(item.points, closed);\n for (let s = 0; s < count; s++) {\n const [ax, ay, bx, by] = segment(item.points, s);\n const cx0 = cellX(Math.min(ax, bx));\n const cx1 = cellX(Math.max(ax, bx));\n const cy0 = cellY(Math.min(ay, by));\n const cy1 = cellY(Math.max(ay, by));\n for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, index, s);\n }\n });\n };\n visit((c) => counts[c + 1]!++);\n for (let c = 0; c < cols * rows; c++) counts[c + 1]! += counts[c]!;\n const starts = counts;\n const fill = starts.slice(0, cols * rows);\n const segs = new Uint32Array(starts[cols * rows]! * 2);\n visit((c, item, s) => {\n const k = fill[c]!++;\n segs[2 * k] = item;\n segs[2 * k + 1] = s;\n });\n return { items, cell, x0: minX, y0: minY, cols, rows, starts, segs };\n}\n\n/**\n * The polyline nearest to `p` within `radius`, or `null`.\n *\n * @param index - The index.\n * @param p - The point, in image coordinates.\n * @param radius - The search radius, in image pixels.\n * @returns The nearest polyline, the closest point on it and the distance; ties go to the\n * earlier polyline, so the result does not depend on cell order.\n */\nexport function nearestPolyline(index: PolylineIndex, p: Point, radius: number): PolylineHit | null {\n const { items, cell, x0, y0, cols, rows, starts, segs } = index;\n const cx0 = Math.max(0, Math.floor((p.x - radius - x0) / cell));\n const cx1 = Math.min(cols - 1, Math.floor((p.x + radius - x0) / cell));\n const cy0 = Math.max(0, Math.floor((p.y - radius - y0) / cell));\n const cy1 = Math.min(rows - 1, Math.floor((p.y + radius - y0) / cell));\n let best: PolylineHit | null = null;\n let bestItem = Infinity;\n let bestD = radius * radius;\n for (let cy = cy0; cy <= cy1; cy++) {\n for (let cx = cx0; cx <= cx1; cx++) {\n const c = cy * cols + cx;\n for (let k = starts[c]!; k < starts[c + 1]!; k++) {\n const itemIndex = segs[2 * k]!;\n const item = items[itemIndex]!;\n const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]!);\n const q = closestOnSegment(p, ax, ay, bx, by);\n const d = (q.x - p.x) ** 2 + (q.y - p.y) ** 2;\n if (d < bestD || (d === bestD && itemIndex < bestItem)) {\n bestD = d;\n bestItem = itemIndex;\n best = { id: item.id, point: q, distance: Math.sqrt(d) };\n }\n }\n }\n }\n return best;\n}\n\n/**\n * The polylines with any part inside `rect`, in the order they were given.\n *\n * Any part, not any vertex: a long straight contour crossing a rubber band has no vertex\n * inside it and is still what the band was aimed at.\n *\n * @param index - The index.\n * @param rect - The band, in image coordinates.\n * @returns Their ids.\n */\nexport function polylinesInRect(index: PolylineIndex, rect: Rect): PolylineId[] {\n const { items, cell, x0, y0, cols, rows, starts, segs } = index;\n const hit = new Uint8Array(items.length);\n const cx0 = Math.max(0, Math.floor((rect.x - x0) / cell));\n const cx1 = Math.min(cols - 1, Math.floor((rect.x + rect.width - x0) / cell));\n const cy0 = Math.max(0, Math.floor((rect.y - y0) / cell));\n const cy1 = Math.min(rows - 1, Math.floor((rect.y + rect.height - y0) / cell));\n for (let cy = cy0; cy <= cy1; cy++) {\n for (let cx = cx0; cx <= cx1; cx++) {\n const c = cy * cols + cx;\n for (let k = starts[c]!; k < starts[c + 1]!; k++) {\n const itemIndex = segs[2 * k]!;\n if (hit[itemIndex]) continue;\n const item = items[itemIndex]!;\n const [ax, ay, bx, by] = segment(item.points, segs[2 * k + 1]!);\n if (segmentTouchesRect(ax, ay, bx, by, rect)) hit[itemIndex] = 1;\n }\n }\n }\n const ids: PolylineId[] = [];\n items.forEach((item, i) => {\n if (hit[i]) ids.push(item.id);\n });\n return ids;\n}\n\n/**\n * A polyline as an SVG path (`M … L … Z`).\n *\n * @param points - Flat points.\n * @param closed - Whether to close it.\n * @returns The path data; `\"\"` with no points.\n */\nexport function polylinePath(points: ArrayLike<number>, closed = false): string {\n if (points.length < 2) return \"\";\n let d = `M${points[0]} ${points[1]}`;\n // A single point draws as a zero-length segment, which round caps show as a dot.\n if (points.length < 4) return `${d}L${points[0]} ${points[1]}`;\n for (let i = 2; i + 1 < points.length; i += 2) d += `L${points[i]} ${points[i + 1]}`;\n return closed ? `${d}Z` : d;\n}\n\n/**\n * The bounding box of flat points.\n *\n * @param points - Flat points.\n * @returns The box, or `null` without points.\n */\nexport function polylineBounds(points: ArrayLike<number>): Rect | null {\n if (points.length < 2) return null;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (let i = 0; i + 1 < points.length; i += 2) {\n const x = points[i]!;\n const y = points[i + 1]!;\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\nfunction closestOnSegment(p: Point, ax: number, ay: number, bx: number, by: number): Point {\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy;\n const t = len2 > 0 ? Math.max(0, Math.min(1, ((p.x - ax) * dx + (p.y - ay) * dy) / len2)) : 0;\n return { x: ax + t * dx, y: ay + t * dy };\n}\n\n/** Whether segment ab has any point inside the closed rectangle (Liang–Barsky clip). */\nfunction segmentTouchesRect(ax: number, ay: number, bx: number, by: number, r: Rect): boolean {\n const xmin = r.x;\n const xmax = r.x + r.width;\n const ymin = r.y;\n const ymax = r.y + r.height;\n let t0 = 0;\n let t1 = 1;\n const dx = bx - ax;\n const dy = by - ay;\n const clip = (p: number, q: number): boolean => {\n if (p === 0) return q >= 0;\n const t = q / p;\n if (p < 0) {\n if (t > t1) return false;\n if (t > t0) t0 = t;\n } else {\n if (t < t0) return false;\n if (t < t1) t1 = t;\n }\n return true;\n };\n return clip(-dx, ax - xmin) && clip(dx, xmax - ax) && clip(-dy, ay - ymin) && clip(dy, ymax - ay);\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 layers inside `ImageStage`, alongside the image itself and any\n * raster layers (a mask, a false-colour value plane). Because the whole stack is transformed\n * together, a caliper box drawn here stays registered with the pixel it measures at any zoom\n * or pan. The overlay never touches the DOM to find out where it is; it is told, in\n * `nativeWidth` × `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 { OVERLAY_STATE_OPACITY, overlayRole, type OverlayRole, type OverlayState } from \"./overlayRole\";\nimport { polylinePath } from \"./polylineIndex\";\nimport { cn, toneColor, type MeasureTone } from \"@vitavision/ui\";\n\nexport type { MeasureTone };\n\n/**\n * Optional fields every primitive takes. All are additive: a primitive without them draws\n * exactly as before.\n */\nexport interface PrimitiveCommon {\n /** An identity, written to the primitive's `data-id`, for linking a mark to a row in a list. */\n id?: string | undefined;\n /** Interaction state: hover thickens, selected adds a ring, dimmed fades (overlay grammar). */\n state?: OverlayState | undefined;\n /** An overlay role colour, instead of `tone`: `feature`, `model`, `structure`. */\n role?: OverlayRole | undefined;\n}\n\n/** A marked location: a dot, or a cross for a subpixel edge. */\nexport interface PointPrimitive extends PrimitiveCommon {\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 extends PrimitiveCommon {\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 extends PrimitiveCommon {\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 extends PrimitiveCommon {\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 extends PrimitiveCommon {\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 extends PrimitiveCommon {\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/**\n * A polyline through image points, e.g. a model's contour. It replaces one `segment` per\n * edge, which runs to thousands of elements for a model outline.\n */\nexport interface PolylinePrimitive extends PrimitiveCommon {\n /** Discriminant. */\n kind: \"polyline\";\n /** `[x0, y0, x1, y1, …]` in image coordinates. */\n points: number[];\n /** Join the last point to the first. */\n closed?: boolean;\n /** Verdict colour. Defaults to the neutral tone. */\n tone?: MeasureTone;\n /** A short dash pattern. */\n dashed?: boolean;\n /** Text drawn just above the first point. */\n label?: string;\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 | PolylinePrimitive;\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, polylines, circles, arcs,\n * caliper 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 *\n * A primitive's colour is its `role` (overlay grammar) if given, else its verdict `tone`.\n * Its `state` follows the overlay grammar: `hover` thickens it, `selected` thickens it and\n * rings it in the selection colour, and `dimmed` fades it. Each primitive is a `<g>` carrying\n * `data-kind`, plus `data-id` and `data-state` when given.\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 const state = primitive.state ?? \"default\";\n const colour = primitive.role ? overlayRole(primitive.role) : toneColor(primitive.tone);\n // Hover and selected widen the strokes by the overlay grammar's ratios (2 and 2.5 to the\n // default's 1.5).\n const widen = state === \"hover\" ? 2 / 1.5 : state === \"selected\" ? 2.5 / 1.5 : 1;\n return (\n <g\n // Primitives carry no required identity; a position is the only stable key.\n // eslint-disable-next-line @eslint-react/no-array-index-key\n key={index}\n data-kind={primitive.kind}\n data-id={primitive.id}\n data-state={primitive.state}\n opacity={OVERLAY_STATE_OPACITY[state] === 1 ? undefined : OVERLAY_STATE_OPACITY[state]}\n >\n {state === \"selected\" && (\n <g opacity={0.6}>\n <Primitive\n primitive={primitive}\n colour={overlayRole(\"selection\")}\n hairline={hairline * widen + strokeWidthFor(strokeScale, 3)}\n thick={thick * widen + strokeWidthFor(strokeScale, 3)}\n labelSize={0}\n strokeScale={strokeScale}\n ring\n />\n </g>\n )}\n <Primitive\n primitive={primitive}\n colour={colour}\n hairline={hairline * widen}\n thick={thick * widen}\n labelSize={labelSize}\n strokeScale={strokeScale}\n />\n </g>\n );\n })}\n </svg>\n );\n}\n\nfunction Primitive({\n primitive,\n colour,\n hairline,\n thick,\n labelSize,\n strokeScale,\n ring = false,\n}: {\n primitive: MeasurePrimitive;\n colour: string;\n hairline: number;\n thick: number;\n labelSize: number;\n strokeScale: number;\n /** Drawn as the selection ring under the mark: no fill on a filled circle, a larger dot. */\n ring?: boolean;\n}) {\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 // The ring under a selected dot is the dot grown by 2 screen px.\n const radius = strokeWidthFor(strokeScale, (primitive.radius ?? DEFAULT_POINT_RADIUS) + (ring ? 2 : 0));\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 && !ring ? colour : \"none\"}\n stroke={primitive.filled && !ring ? \"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 \"polyline\":\n return (\n <g>\n <path\n d={polylinePath(primitive.points, primitive.closed === true)}\n fill=\"none\"\n stroke={colour}\n strokeWidth={hairline}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeDasharray={primitive.dashed ? `${hairline * 4} ${hairline * 3}` : undefined}\n />\n {primitive.points.length >= 2 && (\n <Label\n x={primitive.points[0]!}\n y={primitive.points[1]! - strokeWidthFor(strokeScale, 4)}\n text={primitive.label}\n colour={colour}\n size={labelSize}\n />\n )}\n </g>\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 || !(size > 0)) 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","/**\n * Screen-constant geometry for a layer inside an `ImageStage`.\n */\n\nimport { useStage } from \"./ImageStage\";\n\n/**\n * A function from screen pixels to image pixels at the current zoom. A stroke, handle or\n * label drawn `px(1.5)` wide stays 1.5 screen pixels at every zoom (the overlay grammar's\n * rule).\n *\n * @returns `px(css)`.\n */\nexport function useScreenPx(): (css: number) => number {\n return useStage().imageLength;\n}\n","/** Reusable source-image contour overlay and vertex editor for ImageStage. */\n\nimport { useRef, useState, type KeyboardEvent, type PointerEvent } from \"react\";\n\nimport { imageViewBox } from \"./stage/view\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { Point } from \"./measureGeometry\";\n\n/** An ordered, closed contour drawn in source-image pixel-center coordinates. */\nexport interface ContourEditorProps {\n /** Ordered vertices; the final vertex connects back to the first. */\n points: Point[];\n /** Receives a complete replacement point list after each edit. */\n onChange: (points: Point[]) => void;\n /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */\n onCommit?: () => void;\n /** Show draggable, keyboard-editable vertices. */\n editable?: boolean;\n /** Accessible name for the contour and its vertices. */\n label?: string;\n /** CSS stroke color. */\n stroke?: string;\n}\n\n/** Return the index of the closest segment, with the last vertex joined to the first. */\nexport function nearestContourSegment(points: Point[], point: Point): number {\n let nearest = 0;\n let distance = Infinity;\n for (let i = 0; i < points.length; i++) {\n const a = points[i];\n const b = points[(i + 1) % points.length];\n if (!a || !b) continue;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)));\n const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;\n if (d < distance) { distance = d; nearest = i; }\n }\n return nearest;\n}\n\n/** Edit contour vertices over an ImageStage using its shared source-image transform. */\nexport function ContourEditor({ points, onChange, onCommit, editable = false, label = \"Contour\", stroke = \"var(--signal)\" }: ContourEditorProps) {\n const stage = useStage();\n const draggingRef = useRef<number | null>(null);\n const movedRef = useRef(false);\n const [selected, setSelected] = useState<number | null>(null);\n const line = points.map((point) => `${point.x},${point.y}`).join(\" \");\n const radius = stage.imageLength(5);\n const hairline = stage.imageLength(1.5);\n\n function clamp(point: Point): Point {\n return {\n x: Math.max(0, Math.min(stage.image.width - 1, point.x)),\n y: Math.max(0, Math.min(stage.image.height - 1, point.y)),\n };\n }\n\n /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */\n function move(index: number, point: Point): boolean {\n const current = points[index];\n const target = clamp(point);\n if (!current || (current.x === target.x && current.y === target.y)) return false;\n const next = [...points];\n next[index] = target;\n onChange(next);\n return true;\n }\n\n function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {\n if (!editable || stage.panMode || event.button !== 0) return;\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n draggingRef.current = index;\n movedRef.current = false;\n setSelected(index);\n }\n\n function pointerMove(event: PointerEvent<SVGCircleElement>) {\n if (draggingRef.current === null) return;\n event.stopPropagation();\n if (move(draggingRef.current, stage.toImage({ x: event.clientX, y: event.clientY }))) movedRef.current = true;\n }\n\n function pointerUp(event: PointerEvent<SVGCircleElement>) {\n if (draggingRef.current === null) return;\n event.stopPropagation();\n draggingRef.current = null;\n if (movedRef.current) onCommit?.();\n }\n\n function keyDown(event: KeyboardEvent<SVGCircleElement>, index: number) {\n if (!editable || stage.panMode) return;\n const delta = event.shiftKey ? 0.1 : 1;\n const p = points[index];\n if (!p) return;\n const shift: Record<string, Point> = {\n ArrowLeft: { x: -delta, y: 0 }, ArrowRight: { x: delta, y: 0 },\n ArrowUp: { x: 0, y: -delta }, ArrowDown: { x: 0, y: delta },\n };\n if (shift[event.key]) {\n event.preventDefault();\n event.stopPropagation();\n if (move(index, { x: p.x + shift[event.key]!.x, y: p.y + shift[event.key]!.y })) onCommit?.();\n } else if ((event.key === \"Delete\" || event.key === \"Backspace\") && points.length > 3) {\n event.preventDefault();\n event.stopPropagation();\n onChange(points.filter((_, i) => i !== index));\n setSelected(null);\n onCommit?.();\n } else if (event.key === \"Insert\" && points.length >= 3) {\n event.preventDefault();\n event.stopPropagation();\n const next = points[(index + 1) % points.length]!;\n onChange([...points.slice(0, index + 1), { x: (p.x + next.x) / 2, y: (p.y + next.y) / 2 }, ...points.slice(index + 1)]);\n setSelected(index + 1);\n onCommit?.();\n }\n }\n\n return (\n <svg viewBox={imageViewBox(stage.image)} className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\" role={editable ? undefined : \"img\"} aria-label={label}>\n <polygon points={line} fill=\"none\" stroke={stroke} strokeWidth={hairline} />\n {editable && points.length >= 3 && (\n <polygon points={line} fill=\"none\" stroke=\"transparent\" strokeWidth={stage.imageLength(12)} className=\"pointer-events-auto\" onDoubleClick={(event) => {\n if (stage.panMode) return;\n event.stopPropagation();\n const point = clamp(stage.toImage({ x: event.clientX, y: event.clientY }));\n const index = nearestContourSegment(points, point);\n onChange([...points.slice(0, index + 1), point, ...points.slice(index + 1)]);\n setSelected(index + 1);\n onCommit?.();\n }} />\n )}\n {editable && points.map((point, index) => (\n // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.\n // eslint-disable-next-line @eslint-react/no-array-index-key\n <circle key={index} cx={point.x} cy={point.y} r={selected === index ? radius * 1.3 : radius} fill=\"var(--surface)\" stroke={stroke} strokeWidth={hairline} className=\"pointer-events-auto cursor-move\" tabIndex={0} role=\"button\" aria-label={`${label} point ${index + 1}`} onPointerDown={(event) => pointerDown(event, index)} onPointerMove={pointerMove} onPointerUp={pointerUp} onLostPointerCapture={pointerUp} onDoubleClick={(event) => { if (!stage.panMode) event.stopPropagation(); }} onKeyDown={(event) => keyDown(event, index)} onFocus={() => setSelected(index)} />\n ))}\n </svg>\n );\n}\n","/**\n * The arithmetic of editing an axis-aligned region: eight handles and an interior.\n *\n * Kept pure, so the cases that bite are tested without a pointer:\n * - a drag that turns the box inside out through itself;\n * - a handle pulled past the image edge;\n * - a box collapsed to nothing.\n *\n * Everything is in the stage's image coordinates; `bounds` is the area a region must stay in.\n */\n\nimport type { Rect } from \"./stage/view\";\nimport type { Point } from \"./measureGeometry\";\n\n/** A region's handle, by compass direction. */\nexport type RoiHandle = \"nw\" | \"n\" | \"ne\" | \"e\" | \"se\" | \"s\" | \"sw\" | \"w\";\n\n/** The eight handles, clockwise from the top-left corner. */\nexport const ROI_HANDLES: readonly RoiHandle[] = [\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"];\n\n/** The CSS resize cursor for each handle, so the affordance is legible before the press. */\nexport const ROI_HANDLE_CURSOR: Readonly<Record<RoiHandle, string>> = {\n nw: \"nwse-resize\",\n n: \"ns-resize\",\n ne: \"nesw-resize\",\n e: \"ew-resize\",\n se: \"nwse-resize\",\n s: \"ns-resize\",\n sw: \"nesw-resize\",\n w: \"ew-resize\",\n};\n\n/**\n * Where a handle sits.\n *\n * @param rect - The region.\n * @param handle - The handle.\n * @returns The handle's centre.\n */\nexport function roiHandlePoint(rect: Rect, handle: RoiHandle): Point {\n const { x, y, width: w, height: h } = rect;\n const cx = x + w / 2;\n const cy = y + h / 2;\n const px = handle.includes(\"w\") ? x : handle.includes(\"e\") ? x + w : cx;\n const py = handle.includes(\"n\") ? y : handle.includes(\"s\") ? y + h : cy;\n return { x: px, y: py };\n}\n\n/**\n * The box spanned by two corners, with positive width and height whichever way it was\n * dragged.\n *\n * @param a - One corner.\n * @param b - The opposite corner.\n * @returns The normalised box.\n */\nexport function rectFromCorners(a: Point, b: Point): Rect {\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n };\n}\n\n/**\n * A box held inside `bounds`, and no smaller than `minSize` on either side, unless `bounds`\n * itself is smaller.\n *\n * @param rect - The box.\n * @param bounds - The area it must stay in.\n * @param minSize - The smallest side.\n * @returns The clamped box.\n */\nexport function clampRect(rect: Rect, bounds: Rect, minSize: number): Rect {\n const width = Math.min(Math.max(rect.width, minSize), bounds.width);\n const height = Math.min(Math.max(rect.height, minSize), bounds.height);\n return {\n x: clamp(rect.x, bounds.x, bounds.x + bounds.width - width),\n y: clamp(rect.y, bounds.y, bounds.y + bounds.height - height),\n width,\n height,\n };\n}\n\n/**\n * Drag a handle to `to`.\n *\n * The dragged edge follows the pointer and the opposite edge stays put, which is what makes\n * a handle feel attached to the corner it is drawn on. Dragging an edge through its opposite\n * flips the box instead of clamping it to zero: a clamp leaves the pointer moving and the box\n * not, which reads as the drag having died.\n *\n * @param rect - The box before the drag.\n * @param handle - The handle being dragged.\n * @param to - The pointer, in image coordinates.\n * @param bounds - The area the box must stay in.\n * @param minSize - The smallest side.\n * @returns The resized box.\n */\nexport function resizeRect(rect: Rect, handle: RoiHandle, to: Point, bounds: Rect, minSize: number): Rect {\n let left = rect.x;\n let top = rect.y;\n let right = rect.x + rect.width;\n let bottom = rect.y + rect.height;\n const px = clamp(to.x, bounds.x, bounds.x + bounds.width);\n const py = clamp(to.y, bounds.y, bounds.y + bounds.height);\n if (handle.includes(\"w\")) left = px;\n if (handle.includes(\"e\")) right = px;\n if (handle.includes(\"n\")) top = py;\n if (handle.includes(\"s\")) bottom = py;\n return clampRect(rectFromCorners({ x: left, y: top }, { x: right, y: bottom }), bounds, minSize);\n}\n\n/**\n * Move the whole box, held inside `bounds` without changing its size.\n *\n * @param rect - The box.\n * @param dx - Horizontal shift.\n * @param dy - Vertical shift.\n * @param bounds - The area it must stay in.\n * @returns The moved box.\n */\nexport function moveRect(rect: Rect, dx: number, dy: number, bounds: Rect): Rect {\n return {\n x: clamp(rect.x + dx, bounds.x, Math.max(bounds.x, bounds.x + bounds.width - rect.width)),\n y: clamp(rect.y + dy, bounds.y, Math.max(bounds.y, bounds.y + bounds.height - rect.height)),\n width: rect.width,\n height: rect.height,\n };\n}\n\n/**\n * Whether two boxes are the same, to within `epsilon`. Useful for telling whether a region\n * still matches the one a result was computed for.\n *\n * @param a - A box, or `null`.\n * @param b - A box, or `null`.\n * @param epsilon - The tolerance. Defaults to 1e-6.\n * @returns `true` for two equal boxes, or two `null`s.\n */\nexport function sameRect(a: Rect | null, b: Rect | null, epsilon = 1e-6): boolean {\n if (a === null || b === null) return a === b;\n return (\n Math.abs(a.x - b.x) < epsilon &&\n Math.abs(a.y - b.y) < epsilon &&\n Math.abs(a.width - b.width) < epsilon &&\n Math.abs(a.height - b.height) < epsilon\n );\n}\n\nfunction clamp(value: number, low: number, high: number): number {\n return Math.min(high, Math.max(low, value));\n}\n","/**\n * A region of interest as an object rather than a gesture: drawn, moved and resized on the\n * image, kept inside it.\n *\n * Its predecessors in the apps could only draw a *new* box: every press started again from a\n * corner, so a box that was nearly right had to be redrawn, and one drawn at fit could not\n * be refined by zooming in first. Here the box has eight handles and an interior, and it lives\n * inside `ImageStage`'s transform, so it stays on the pixels it encloses at any zoom.\n */\n\nimport { useRef, useState, type KeyboardEvent, type PointerEvent } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport {\n ROI_HANDLES,\n ROI_HANDLE_CURSOR,\n clampRect,\n moveRect,\n rectFromCorners,\n resizeRect,\n roiHandlePoint,\n type RoiHandle,\n} from \"./roiEdit\";\nimport { overlayRole } from \"./overlayRole\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox, type Rect } from \"./stage/view\";\n\n/** Handle square side, in screen pixels. */\nconst HANDLE_PX = 9;\n/** Outline width, in screen pixels. */\nconst STROKE_PX = 1.5;\n/** The halo under the outline (visual-language §5), in screen pixels on each side. */\nconst HALO_PX = 1;\nconst HALO = overlayRole(\"halo\");\n\n/** Props of `RectRoiEditor`. */\nexport interface RectRoiEditorProps {\n /** The region in image coordinates, or `null` for none. */\n value: Rect | null;\n /** Called with the region as it changes: on every move of a drag, and on each key nudge. */\n onValueChange: (value: Rect) => void;\n /** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */\n onCommit?: ((value: Rect) => void) | undefined;\n /** Show handles and accept moves and resizes. Defaults to `true`. */\n editable?: boolean | undefined;\n /**\n * Draw a new region with a drag on the image, outside the current one. Only while the app's\n * region tool is active: in draw mode the layer claims presses that would otherwise pan.\n */\n draw?: boolean | undefined;\n /**\n * The area the region must stay in. Defaults to `{ x: 0, y: 0, width, height }` of the\n * image: a region given as a start pixel and a size.\n */\n bounds?: Rect | undefined;\n /** The smallest side, in image pixels; a smaller drawn box is a click, not a region. Defaults to 4. */\n minSize?: number | undefined;\n /** The region's accessible name. Defaults to \"Region\". */\n label?: string | undefined;\n /** CSS colour of the outline and handles. Defaults to the overlay `selection` role. */\n stroke?: string | undefined;\n}\n\ntype Drag =\n | { kind: \"move\"; from: Point; start: Rect; moved: boolean }\n | { kind: \"resize\"; handle: RoiHandle; start: Rect; moved: boolean }\n | { kind: \"draw\"; from: Point; moved: boolean };\n\n/**\n * An editable axis-aligned region inside an `ImageStage`.\n *\n * - **Handles.** The eight handles resize the region, and the interior moves it. A handle\n * dragged through the opposite edge flips the box.\n * - **Drawing.** With `draw`, a drag elsewhere on the image draws a new region.\n * - **Keyboard.** The region is focusable: arrow keys move it by one image pixel (ten with\n * Shift), and with Alt they grow or shrink it from the bottom-right corner.\n * - **Limits.** The region stays inside `bounds` and never gets smaller than `minSize`.\n * - **Rendering.** Handles and the outline are a constant size on screen at every zoom.\n * - **Panning.** A press with the hand tool, or with space held, still pans.\n *\n * The SVG carries `data-editable` and `data-drawing` (while a draw is in progress).\n */\nexport function RectRoiEditor({\n value,\n onValueChange,\n onCommit,\n editable = true,\n draw = false,\n bounds,\n minSize = 4,\n label = \"Region\",\n stroke = overlayRole(\"selection\"),\n}: RectRoiEditorProps) {\n const stage = useStage();\n const area = bounds ?? { x: 0, y: 0, width: stage.image.width, height: stage.image.height };\n const dragRef = useRef<Drag | null>(null);\n const lastRef = useRef<Rect | null>(null);\n const [drawing, setDrawing] = useState<Rect | null>(null);\n\n const px = useScreenPx();\n const shown = drawing ?? value;\n\n const report = (next: Rect) => {\n lastRef.current = next;\n onValueChange(next);\n };\n\n const begin = (event: PointerEvent<SVGElement>, drag: Drag) => {\n if (stage.panMode || event.button !== 0) return;\n event.stopPropagation();\n event.preventDefault();\n event.currentTarget.setPointerCapture(event.pointerId);\n dragRef.current = drag;\n lastRef.current = null;\n };\n\n const onMove = (event: PointerEvent<SVGElement>) => {\n const drag = dragRef.current;\n if (!drag) return;\n event.stopPropagation();\n const p = stage.toImage({ x: event.clientX, y: event.clientY });\n drag.moved = true;\n if (drag.kind === \"move\") {\n report(moveRect(drag.start, p.x - drag.from.x, p.y - drag.from.y, area));\n } else if (drag.kind === \"resize\") {\n report(resizeRect(drag.start, drag.handle, p, area, minSize));\n } else {\n const drawn = clampRect(rectFromCorners(clampPoint(drag.from, area), clampPoint(p, area)), area, 0);\n // Kept in the ref too: a pointer-up can arrive before the move's render, and the end of\n // the gesture must see the box the last move drew.\n lastRef.current = drawn;\n setDrawing(drawn);\n }\n };\n\n const onEnd = (event: PointerEvent<SVGElement>) => {\n const drag = dragRef.current;\n if (!drag) return;\n event.stopPropagation();\n dragRef.current = null;\n if (drag.kind === \"draw\") {\n const drawn = lastRef.current;\n setDrawing(null);\n // A drawn box smaller than `minSize` is a click, not a region.\n if (drawn && drawn.width >= minSize && drawn.height >= minSize) {\n onValueChange(drawn);\n onCommit?.(drawn);\n }\n return;\n }\n if (drag.moved && lastRef.current) onCommit?.(lastRef.current);\n };\n\n const onKeyDown = (event: KeyboardEvent<SVGElement>) => {\n if (!editable || value === null) return;\n const step = event.shiftKey ? 10 : 1;\n const delta: Record<string, Point> = {\n ArrowLeft: { x: -step, y: 0 },\n ArrowRight: { x: step, y: 0 },\n ArrowUp: { x: 0, y: -step },\n ArrowDown: { x: 0, y: step },\n };\n const d = delta[event.key];\n if (!d) return;\n event.preventDefault();\n event.stopPropagation();\n const next = event.altKey\n ? clampRect({ ...value, width: value.width + d.x, height: value.height + d.y }, area, minSize)\n : moveRect(value, d.x, d.y, area);\n onValueChange(next);\n onCommit?.(next);\n };\n\n const outline = shown && (\n <>\n <rect\n x={shown.x}\n y={shown.y}\n width={shown.width}\n height={shown.height}\n fill=\"none\"\n stroke={HALO}\n strokeWidth={px(STROKE_PX + 2 * HALO_PX)}\n />\n <rect\n x={shown.x}\n y={shown.y}\n width={shown.width}\n height={shown.height}\n fill={stroke}\n fillOpacity={0.06}\n stroke={stroke}\n strokeWidth={px(STROKE_PX)}\n strokeDasharray={`${px(6)} ${px(4)}`}\n />\n </>\n );\n\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n data-editable={editable ? \"\" : undefined}\n data-drawing={drawing ? \"\" : undefined}\n >\n {draw && editable && (\n <rect\n data-draw-surface=\"\"\n x={area.x}\n y={area.y}\n width={area.width}\n height={area.height}\n fill=\"transparent\"\n className=\"pointer-events-auto cursor-crosshair\"\n onPointerDown={(event) =>\n begin(event, { kind: \"draw\", from: stage.toImage({ x: event.clientX, y: event.clientY }), moved: false })\n }\n onPointerMove={onMove}\n onPointerUp={onEnd}\n onLostPointerCapture={onEnd}\n />\n )}\n {outline}\n {editable && value && !drawing && (\n <rect\n x={value.x}\n y={value.y}\n width={value.width}\n height={value.height}\n fill=\"transparent\"\n role=\"button\"\n tabIndex={0}\n aria-label={`${label}: ${fmt(value.x)}, ${fmt(value.y)}, ${fmt(value.width)} × ${fmt(value.height)} px`}\n aria-roledescription=\"region\"\n className=\"pointer-events-auto cursor-move outline-none focus-visible:stroke-signal\"\n onPointerDown={(event) =>\n begin(event, {\n kind: \"move\",\n from: stage.toImage({ x: event.clientX, y: event.clientY }),\n start: value,\n moved: false,\n })\n }\n onPointerMove={onMove}\n onPointerUp={onEnd}\n onLostPointerCapture={onEnd}\n onKeyDown={onKeyDown}\n onDoubleClick={(event) => event.stopPropagation()}\n />\n )}\n {editable &&\n value &&\n !drawing &&\n ROI_HANDLES.map((handle) => {\n const centre = roiHandlePoint(value, handle);\n const size = px(HANDLE_PX);\n return (\n <rect\n key={handle}\n data-handle={handle}\n x={centre.x - size / 2}\n y={centre.y - size / 2}\n width={size}\n height={size}\n fill={stroke}\n stroke={HALO}\n strokeWidth={px(1)}\n className=\"pointer-events-auto\"\n style={{ cursor: ROI_HANDLE_CURSOR[handle] }}\n onPointerDown={(event) => begin(event, { kind: \"resize\", handle, start: value, moved: false })}\n onPointerMove={onMove}\n onPointerUp={onEnd}\n onLostPointerCapture={onEnd}\n onDoubleClick={(event) => event.stopPropagation()}\n />\n );\n })}\n </svg>\n );\n}\n\nfunction clampPoint(p: Point, area: Rect): Point {\n return {\n x: Math.min(area.x + area.width, Math.max(area.x, p.x)),\n y: Math.min(area.y + area.height, Math.max(area.y, p.y)),\n };\n}\n\nfunction fmt(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(1);\n}\n","/**\n * Many polylines over the image, selectable: contours a model may be built from, a\n * document's segments, a batch's matches.\n *\n * Drawn as a handful of batched paths, one per state and colour, not one element per line. The\n * L0-3 benchmark shows the per-element form failing the 2 ms hit-test gate at scale, while the\n * batched form plus a spatial index passes on every candidate engine\n * (`docs/measurements/stage2d-bench-analysis.md`). The pointer is resolved to a line by\n * `nearestPolyline`, not by the DOM, which keeps this layer engine-agnostic for L6-1.\n */\n\nimport { useMemo, useState, type PointerEvent as ReactPointerEvent } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport {\n buildPolylineIndex,\n nearestPolyline,\n polylinePath,\n polylinesInRect,\n type Polyline,\n type PolylineId,\n} from \"./polylineIndex\";\nimport { overlayRole } from \"./overlayRole\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useStageDrag } from \"./stage/StageSurface\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox, type Rect } from \"./stage/view\";\n\n/** One polyline of a `PolylineSet`, with optional styling. */\nexport interface PolylineSetItem extends Polyline {\n /** CSS colour for this line, instead of the set's `stroke`. */\n stroke?: string | undefined;\n /** Draw dashed: a line that is present but not in play (a dropped contour). */\n dashed?: boolean | undefined;\n}\n\n/** How a gesture combines with the current selection. */\nexport type PolylineSelectMode = \"replace\" | \"toggle\" | \"add\";\n\n/** Props of `PolylineSet`. */\nexport interface PolylineSetProps {\n /** The polylines, in image coordinates. */\n items: readonly PolylineSetItem[];\n /** The selected ids. */\n selected?: Iterable<PolylineId> | undefined;\n /** Ids drawn at 35 % opacity, e.g. outside the current filter. They still take hover and clicks. */\n dimmed?: Iterable<PolylineId> | undefined;\n /** The hovered id, when the app controls hover (e.g. a list beside the stage hovers lines too). */\n hovered?: PolylineId | null | undefined;\n /** Called when the line under the pointer changes. */\n onHover?: ((id: PolylineId | null) => void) | undefined;\n /**\n * Called on a selection gesture.\n * - A click on a line → `[id]`, \"replace\".\n * - ⌘/Ctrl-click → `[id]`, \"toggle\".\n * - A rubber band → every line it touches, \"replace\", or \"add\" with ⌘/Ctrl held. An empty\n * band clears.\n */\n onSelect?: ((ids: PolylineId[], mode: PolylineSelectMode) => void) | undefined;\n /**\n * The sweep tool is active: a drag anywhere on the image draws a rubber band. Without it a\n * band starts only with Shift held on a line, and a press on bare image is left to the stage\n * and to the layers below.\n */\n marquee?: boolean | undefined;\n /** CSS colour of the lines. Defaults to the overlay `feature` role: they are detected lines. */\n stroke?: string | undefined;\n /** CSS colour of a selected line. Defaults to the overlay `selection` role. */\n selectionStroke?: string | undefined;\n /** How close the pointer must be to pick a line, in screen pixels (the hit band's full width). Defaults to 14. */\n hitWidth?: number | undefined;\n /** The zoom from which a hovered or selected line's points are drawn. Defaults to 3. */\n vertexScale?: number | undefined;\n /** The layer's accessible name. Defaults to \"Lines\". */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n/** The most points drawn as dots at once; past this the dots are noise and a cost. */\nconst MAX_VERTEX_DOTS = 5000;\n\n/**\n * A selectable set of polylines inside an `ImageStage`.\n *\n * - **States**, from visual-language §5:\n * - default 1.5 screen px;\n * - hover 2 px;\n * - selected 2.5 px in `selectionStroke`;\n * - dimmed at 35 % opacity.\n * - **Halo.** Every line has a halo, so it holds on any image.\n * - **Points.** Above `vertexScale`, the points of the hovered and selected lines are drawn.\n * - **Panning.** The hand tool and a held space bar still pan.\n *\n * The SVG carries `data-hovered` (the hovered id) and `data-sweeping` while a band is drawn.\n */\nexport function PolylineSet({\n items,\n selected,\n dimmed,\n hovered,\n onHover,\n onSelect,\n marquee = false,\n stroke = overlayRole(\"feature\"),\n selectionStroke = overlayRole(\"selection\"),\n hitWidth = 14,\n vertexScale = 3,\n label = \"Lines\",\n}: PolylineSetProps) {\n const stage = useStage();\n const startDrag = useStageDrag();\n const px = useScreenPx();\n\n const index = useMemo(() => buildPolylineIndex(items), [items]);\n const selectedSet = useMemo(() => new Set(selected ?? []), [selected]);\n const dimmedSet = useMemo(() => new Set(dimmed ?? []), [dimmed]);\n const byId = useMemo(() => new Map(items.map((item) => [item.id, item])), [items]);\n\n const [ownHover, setOwnHover] = useState<PolylineId | null>(null);\n const hoverId = hovered !== undefined ? hovered : ownHover;\n const [band, setBand] = useState<Rect | null>(null);\n\n // One path per (state, colour, dash) group, rebuilt only when the set or the selection\n // changes. Hover is drawn on top, separately, so moving the pointer never rebuilds these.\n const groups = useMemo(() => {\n const map = new Map<string, { d: string[]; stroke: string; dashed: boolean; dim: boolean }>();\n const hitParts: string[] = [];\n for (const item of items) {\n const d = polylinePath(item.points, item.closed === true);\n if (d === \"\") continue;\n hitParts.push(d);\n if (selectedSet.has(item.id)) continue;\n const colour = item.stroke ?? stroke;\n const dashed = item.dashed === true;\n const dim = dimmedSet.has(item.id);\n const key = `${dim ? 1 : 0}|${dashed ? 1 : 0}|${colour}`;\n let group = map.get(key);\n if (!group) {\n group = { d: [], stroke: colour, dashed, dim };\n map.set(key, group);\n }\n group.d.push(d);\n }\n const selectedPath = items\n .filter((item) => selectedSet.has(item.id))\n .map((item) => polylinePath(item.points, item.closed === true))\n .join(\"\");\n return {\n batches: [...map.values()].map((g) => ({ ...g, path: g.d.join(\"\") })),\n hit: hitParts.join(\"\"),\n selected: selectedPath,\n };\n }, [items, selectedSet, dimmedSet, stroke]);\n\n const hoverItem = hoverId !== null ? byId.get(hoverId) : undefined;\n const hoverPath = hoverItem ? polylinePath(hoverItem.points, hoverItem.closed === true) : \"\";\n\n const dots = useMemo(() => {\n if (stage.view.scale < vertexScale) return \"\";\n const shown: PolylineSetItem[] = [];\n if (hoverItem) shown.push(hoverItem);\n for (const item of items) if (selectedSet.has(item.id) && item !== hoverItem) shown.push(item);\n let d = \"\";\n let count = 0;\n for (const item of shown) {\n const p = item.points;\n for (let i = 0; i + 1 < p.length && count < MAX_VERTEX_DOTS; i += 2, count++) {\n d += `M${p[i]} ${p[i + 1]}h0`;\n }\n }\n return d;\n }, [stage.view.scale, vertexScale, hoverItem, items, selectedSet]);\n\n const pickAt = (event: { clientX: number; clientY: number }): PolylineId | null =>\n nearestPolyline(index, stage.toImage({ x: event.clientX, y: event.clientY }), px(hitWidth / 2))?.id ?? null;\n\n const setHover = (id: PolylineId | null) => {\n if (id === hoverId) return;\n setOwnHover(id);\n onHover?.(id);\n };\n\n const sweep = (event: ReactPointerEvent<SVGElement>) => {\n const from = stage.toImage({ x: event.clientX, y: event.clientY });\n const additive = event.metaKey || event.ctrlKey;\n setBand({ x: from.x, y: from.y, width: 0, height: 0 });\n setHover(null);\n startDrag(event, {\n onMove: (p) => setBand(boxBetween(from, p)),\n onEnd: (p) => {\n setBand(null);\n onSelect?.(polylinesInRect(index, boxBetween(from, p)), additive ? \"add\" : \"replace\");\n },\n onCancel: () => setBand(null),\n });\n };\n\n const onLinePointerDown = (event: ReactPointerEvent<SVGPathElement>) => {\n if (stage.panMode || event.button !== 0) return;\n // A band has to be able to start anywhere, and on a frame that is mostly lines \"anywhere\"\n // is usually on one. Declining here would hand the press to the stage (which pans), not to\n // a surface below, because only the topmost element is a press's target.\n if (event.shiftKey || marquee) {\n sweep(event);\n return;\n }\n const id = pickAt(event);\n if (id === null) return;\n // Claimed, and selected on the press: a selection that waits for the release feels like\n // lag on a canvas where every other gesture is immediate.\n event.stopPropagation();\n onSelect?.([id], event.metaKey || event.ctrlKey ? \"toggle\" : \"replace\");\n };\n\n const hairline = px(1.5);\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n role=\"img\"\n aria-label={`${label}: ${items.length} ${items.length === 1 ? \"line\" : \"lines\"}, ${selectedSet.size} selected`}\n data-hovered={hoverId ?? undefined}\n data-sweeping={band ? \"\" : undefined}\n >\n {marquee && (\n <rect\n data-marquee-surface=\"\"\n x={-0.5}\n y={-0.5}\n width={stage.image.width}\n height={stage.image.height}\n fill=\"transparent\"\n className=\"pointer-events-auto cursor-crosshair\"\n onPointerDown={(event) => {\n if (stage.panMode || event.button !== 0) return;\n sweep(event);\n }}\n />\n )}\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d={groups.hit} stroke={HALO} strokeWidth={px(1.5 + 2)} opacity={0.6} />\n {groups.batches.map((batch) => (\n <path\n key={`${batch.dim}|${batch.dashed}|${batch.stroke}`}\n d={batch.path}\n stroke={batch.stroke}\n strokeWidth={hairline}\n strokeDasharray={batch.dashed ? `${px(4)} ${px(4)}` : undefined}\n opacity={batch.dim ? 0.35 : 1}\n />\n ))}\n {groups.selected && (\n <>\n <path d={groups.selected} stroke={HALO} strokeWidth={px(2.5 + 2)} />\n <path data-selected-lines=\"\" d={groups.selected} stroke={selectionStroke} strokeWidth={px(2.5)} />\n </>\n )}\n {hoverPath && !band && (\n <>\n <path d={hoverPath} stroke={HALO} strokeWidth={px(2 + 2)} />\n <path\n data-hovered-line=\"\"\n d={hoverPath}\n stroke={hoverItem && selectedSet.has(hoverItem.id) ? selectionStroke : (hoverItem?.stroke ?? stroke)}\n strokeWidth={px(hoverItem && selectedSet.has(hoverItem.id) ? 2.5 : 2)}\n />\n </>\n )}\n {dots && <path data-points=\"\" d={dots} stroke={selectionStroke} strokeWidth={px(3)} />}\n {/* The one hit target: every line, transparent, wide. Which line it was is the\n index's answer, not the DOM's. */}\n <path\n data-hit=\"\"\n d={groups.hit}\n stroke=\"transparent\"\n strokeWidth={px(hitWidth)}\n style={{ pointerEvents: \"stroke\", cursor: stage.panMode ? undefined : marquee ? \"crosshair\" : \"pointer\" }}\n onPointerDown={onLinePointerDown}\n onPointerMove={(event) => {\n if (!band) setHover(pickAt(event));\n }}\n onPointerLeave={() => setHover(null)}\n />\n </g>\n {band && (\n <rect\n x={band.x}\n y={band.y}\n width={band.width}\n height={band.height}\n fill={selectionStroke}\n fillOpacity={0.12}\n stroke={selectionStroke}\n strokeWidth={px(1)}\n />\n )}\n </svg>\n );\n}\n\nfunction boxBetween(a: Point, b: Point): Rect {\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n };\n}\n","/** A source-pixel raster mask layer with a small paint/erase brush. */\n\nimport { useEffect, useRef, useState, type FocusEvent, type KeyboardEvent, type PointerEvent } from \"react\";\n\nimport { imageViewBox } from \"./stage/view\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { Point } from \"./measureGeometry\";\n\n/** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */\nexport function paintMask(mask: Uint8Array, width: number, height: number, from: Point, to: Point, radius: number, value: 0 | 1): Uint8Array {\n if (mask.length !== width * height) throw new RangeError(\"Mask dimensions do not match its pixel data.\");\n if (![from.x, from.y, to.x, to.y, radius].every(Number.isFinite) || radius < 0) throw new RangeError(\"Brush coordinates and radius must be finite and nonnegative.\");\n const next = mask.slice();\n const clamp = (value: number, limit: number) => Math.max(0, Math.min(limit - 1, value));\n const start = { x: clamp(from.x, width), y: clamp(from.y, height) };\n const end = { x: clamp(to.x, width), y: clamp(to.y, height) };\n const steps = Math.max(1, Math.ceil(Math.hypot(end.x - start.x, end.y - start.y)));\n // A click between four pixel centers must still affect the nearest pixels.\n const r = Math.max(0.75, radius);\n for (let step = 0; step <= steps; step++) {\n const x = start.x + (end.x - start.x) * step / steps;\n const y = start.y + (end.y - start.y) * step / steps;\n for (let row = Math.max(0, Math.ceil(y - r)); row <= Math.min(height - 1, Math.floor(y + r)); row++) {\n for (let col = Math.max(0, Math.ceil(x - r)); col <= Math.min(width - 1, Math.floor(x + r)); col++) {\n if ((col - x) ** 2 + (row - y) ** 2 <= r * r) next[row * width + col] = value;\n }\n }\n }\n return next;\n}\n\n/** Binary mask values are 0 or 1, in row-major source-image coordinates. */\nexport interface MaskEditorProps {\n /** Exactly image width × image height bytes. */\n mask: Uint8Array;\n /** Receives a fresh array after each brush movement. */\n onChange: (mask: Uint8Array) => void;\n /** Called once when a pointer stroke or keyboard paint finishes. */\n onCommit?: () => void;\n /** Allow brush interaction; otherwise render only. */\n editable?: boolean;\n /** Source-image pixels, independent of zoom. */\n brushRadius?: number;\n /** Paint or erase. */\n mode?: \"paint\" | \"erase\";\n /** Accessible name for the brush control. */\n label?: string;\n /** RGBA overlay color. */\n color?: readonly [number, number, number, number];\n}\n\n/** Render and edit a binary raster mask within the enclosing ImageStage. */\nexport function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = \"paint\", label = \"Mask brush\", color = [0, 190, 220, 128] }: MaskEditorProps) {\n const stage = useStage();\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const draftRef = useRef(mask);\n const lastRef = useRef<Point | null>(null);\n // The keyboard brush; it starts at the image centre and follows the last pointer stroke.\n const cursorRef = useRef<Point | null>(null);\n // Where the keyboard brush is drawn, while the layer has keyboard focus.\n const [brush, setBrush] = useState<Point | null>(null);\n\n function cursor(): Point {\n return cursorRef.current ?? { x: Math.floor(stage.image.width / 2), y: Math.floor(stage.image.height / 2) };\n }\n\n useEffect(() => {\n if (mask.length !== stage.image.width * stage.image.height) throw new RangeError(\"Mask dimensions do not match ImageStage.\");\n const context = canvasRef.current?.getContext(\"2d\");\n if (!context) return;\n const pixels = context.createImageData(stage.image.width, stage.image.height);\n for (let i = 0; i < mask.length; i++) {\n if (mask[i]) pixels.data.set(color, i * 4);\n }\n context.putImageData(pixels, 0, 0);\n }, [mask, color, stage.image.width, stage.image.height]);\n\n function apply(from: Point, to: Point) {\n const next = paintMask(draftRef.current, stage.image.width, stage.image.height, from, to, brushRadius, mode === \"paint\" ? 1 : 0);\n draftRef.current = next;\n onChange(next);\n }\n\n function down(event: PointerEvent<HTMLCanvasElement>) {\n if (!editable || stage.panMode || event.button !== 0) return;\n event.stopPropagation();\n event.currentTarget.setPointerCapture(event.pointerId);\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n // Each stroke starts from the mask the caller holds, so an edit it rejected is not carried forward.\n draftRef.current = mask;\n lastRef.current = point;\n cursorRef.current = point;\n setBrush(null);\n apply(point, point);\n }\n\n function move(event: PointerEvent<HTMLCanvasElement>) {\n if (!lastRef.current) return;\n event.stopPropagation();\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n apply(lastRef.current, point);\n lastRef.current = point;\n cursorRef.current = point;\n }\n\n function up(event: PointerEvent<HTMLCanvasElement>) {\n if (!lastRef.current) return;\n event.stopPropagation();\n lastRef.current = null;\n onCommit?.();\n }\n\n function keyDown(event: KeyboardEvent<HTMLCanvasElement>) {\n if (!editable || stage.panMode) return;\n const shift: Record<string, Point> = {\n ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 },\n ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 },\n };\n const delta = shift[event.key];\n if (delta) {\n event.preventDefault();\n event.stopPropagation();\n const from = cursor();\n cursorRef.current = {\n x: Math.max(0, Math.min(stage.image.width - 1, from.x + delta.x)),\n y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y)),\n };\n setBrush(cursorRef.current);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n event.stopPropagation();\n const at = cursor();\n draftRef.current = mask;\n setBrush(at);\n apply(at, at);\n onCommit?.();\n }\n }\n\n function focus(event: FocusEvent<HTMLCanvasElement>) {\n if (editable && event.currentTarget.matches(\":focus-visible\")) setBrush(cursor());\n }\n\n return (\n <>\n <canvas ref={canvasRef} width={stage.image.width} height={stage.image.height} className={`absolute inset-0 h-full w-full ${editable ? \"pointer-events-auto cursor-crosshair\" : \"pointer-events-none\"}`} style={{ imageRendering: \"pixelated\" }} role={editable ? \"button\" : \"img\"} tabIndex={editable ? 0 : undefined} aria-label={label} aria-description={editable ? \"Arrow keys move the brush; Enter paints or erases.\" : undefined} onPointerDown={down} onPointerMove={move} onPointerUp={up} onLostPointerCapture={up} onDoubleClick={(event) => { if (editable && !stage.panMode) event.stopPropagation(); }} onKeyDown={keyDown} onFocus={focus} onBlur={() => setBrush(null)} />\n {brush && (\n <svg viewBox={imageViewBox(stage.image)} className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\" aria-hidden=\"true\">\n <circle cx={brush.x} cy={brush.y} r={Math.max(0.75, brushRadius)} fill=\"none\" stroke=\"var(--signal)\" strokeWidth={stage.imageLength(1.5)} />\n </svg>\n )}\n </>\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,KAAK,IAAI,QAAQ,MAAM,QAAQ,SAAS;EACxC,KAAK,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