@vitavision/stage2d 0.8.1 → 0.9.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/README.md +14 -0
- package/dist/index.d.ts +381 -3
- package/dist/index.js +1090 -61
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/PointSet.tsx +391 -0
- package/src/components/PolylineSet.tsx +39 -0
- package/src/components/markerShapes.ts +119 -0
- package/src/components/pointIndex.ts +320 -0
- package/src/components/stage/ImageStage.tsx +264 -59
- package/src/components/stage/gesture.ts +81 -0
- package/src/components/stage/hitContext.ts +16 -0
- package/src/components/stage/hitTest.ts +181 -0
- package/src/components/stage/useStageHitTest.ts +127 -0
- package/src/index.ts +35 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,IAA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ALO","HALO"],"sources":["../src/components/stage/view.ts","../src/components/stage/gesture.ts","../src/components/stage/hitContext.ts","../src/components/stage/hitTest.ts","../src/components/stage/ImageStage.tsx","../src/components/stage/useStageHitTest.ts","../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/markerShapes.ts","../src/components/pointIndex.ts","../src/components/PointSet.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 * The stage's pointer gestures as pure arithmetic: which mouse buttons pan, what a\n * two-finger pinch does to the view, and what counts as a tap.\n *\n * Points are viewport-local CSS pixels, as in `view.ts`.\n */\n\nimport type { Point } from \"../measureGeometry\";\nimport { zoomAbout, type StageView } from \"./view\";\n\n/** A mouse button that can pan the stage. */\nexport type StageMouseButton = \"left\" | \"middle\" | \"right\";\n\n/** How far a touch may travel and still be a tap, in CSS pixels. */\nexport const TAP_SLOP = 3;\n/** The longest a touch may last and still be a tap, in milliseconds. */\nexport const TAP_MS = 500;\n\nconst BUTTON_CODE: Record<StageMouseButton, number> = { left: 0, middle: 1, right: 2 };\n\n/**\n * The `PointerEvent.button` codes a `panButton` prop names.\n *\n * @param panButton - One button or a list; omitted means left and middle, the stage's\n * long-standing default.\n * @returns The codes: 0 left, 1 middle, 2 right.\n */\nexport function panButtonCodes(panButton: StageMouseButton | readonly StageMouseButton[] | undefined): ReadonlySet<number> {\n if (panButton === undefined) return new Set([0, 1]);\n const list = typeof panButton === \"string\" ? [panButton] : panButton;\n return new Set(list.map((button) => BUTTON_CODE[button]));\n}\n\n/**\n * The midpoint of two points.\n *\n * @param a - One point.\n * @param b - The other.\n * @returns Their centroid.\n */\nexport function centroid(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\n/**\n * The view a pinch has reached: scaled by how much the fingers spread, and carried by how\n * far their midpoint moved. The image point under the fingers' first midpoint stays under\n * their current one, so the gesture reads as holding the picture with two fingers.\n *\n * @param start - The view when the second finger went down.\n * @param startDistance - The fingers' distance then.\n * @param startCentre - Their midpoint then.\n * @param distance - Their distance now.\n * @param centre - Their midpoint now.\n * @param range - The `[min, max]` scale to stay within.\n * @returns The view; not yet clamped to the legal pan range.\n */\nexport function pinchView(\n start: StageView,\n startDistance: number,\n startCentre: Point,\n distance: number,\n centre: Point,\n range: readonly [number, number],\n): StageView {\n const ratio = startDistance > 0 ? distance / startDistance : 1;\n const scale = Math.min(range[1], Math.max(range[0], start.scale * ratio));\n const zoomed = zoomAbout(start, scale, startCentre);\n return { scale: zoomed.scale, tx: zoomed.tx + centre.x - startCentre.x, ty: zoomed.ty + centre.y - startCentre.y };\n}\n\n/**\n * Whether a touch that has ended was a tap.\n *\n * @param travel - The farthest it strayed from where it began, in CSS pixels.\n * @param elapsed - How long it lasted, in milliseconds.\n * @returns `true` for a short touch that stayed put.\n */\nexport function isTap(travel: number, elapsed: number): boolean {\n return travel <= TAP_SLOP && elapsed <= TAP_MS;\n}\n","/**\n * The context an `ImageStage` provides its layers' hit registry through. Its own module so\n * that `ImageStage` (which provides it) and `useStageHitTest` (which reads it, and reads\n * `useStage` from `ImageStage`) do not import each other.\n */\n\nimport { createContext } from \"react\";\nimport type { PointerEvent as ReactPointerEvent } from \"react\";\n\nimport type { HitRegistry } from \"./hitTest\";\n\n/** The press event a layer's `press` handler receives. */\nexport type StagePointerEvent = ReactPointerEvent<Element>;\n\n/** The enclosing stage's registry, or `null` outside a stage. */\nexport const StageHitContext = createContext<HitRegistry<StagePointerEvent> | null>(null);\n","/**\n * \"What is under the pointer?\", answered across layers.\n *\n * Each layer that can be picked registers a `pick` function over its own spatial index. The\n * stage asks every layer, ranks the answers and returns the best, so an app deciding what a\n * press means (select, draw or pan) asks one question instead of arbitrating between layers.\n * This module is the pure core: ranking, and a registry that also routes hover and presses.\n * The React wiring is `useStageHitTest.ts`. It imports neither React nor the DOM.\n *\n * Ranking: a higher `priority` wins outright (points above lines above areas above images),\n * then the smaller distance, then the layer id, so the result never depends on the order\n * layers mounted in.\n */\n\nimport type { Point } from \"../measureGeometry\";\n\n/** What a layer is picked as, and so how it ranks against the layers around it. */\nexport const STAGE_HIT_PRIORITY = {\n /** A raster layer: only picked when nothing else is. */\n image: 0,\n /** A filled region or heatmap cell. */\n area: 100,\n /** A line or contour. */\n line: 200,\n /** A marker: small, so it wins over what it sits on. */\n point: 300,\n} as const;\n\n/** An item's identity within its layer. */\nexport type HitId = string | number;\n\n/** What a layer's `pick` returns: the item, and how far from the pointer it is. */\nexport interface HitCandidate {\n /** The item's id. */\n id: HitId;\n /** Distance from the query point, in image pixels. Compared only within one priority. */\n dist: number;\n}\n\n/** One answer to a hit-test. */\nexport interface StageHit extends HitCandidate {\n /** The layer that answered. */\n layerId: string;\n /** The layer's priority. */\n priority: number;\n}\n\n/** What a layer registers. */\nexport interface StageHitLayerSpec<E = unknown> {\n /** Reported as `StageHit.layerId`. */\n id: string;\n /** Ranks this layer against others; see `STAGE_HIT_PRIORITY`. */\n priority: number;\n /**\n * The item under `point`, if any.\n *\n * @param point - The query, in image coordinates.\n * @param radius - The pointer's tolerance, in image pixels.\n */\n pick: (point: Point, radius: number) => HitCandidate | null;\n /** Whether a press on this layer's items does something (`press` is set and will claim). */\n readonly pressable?: boolean | undefined;\n /** The hovered item changed: an id, or `null` when the pointer left every item. */\n hover?: ((id: HitId | null) => void) | undefined;\n /** A press landed on an item. Return `false` to decline it. */\n press?: ((id: HitId, event: E) => boolean | void) | undefined;\n}\n\n/** Options of a hit-test. */\nexport interface StageHitOptions {\n /** Consider only layers whose presses are claimed (`pressable`). */\n pressable?: boolean | undefined;\n}\n\n/**\n * Order two hits, best first.\n *\n * @returns Negative when `a` ranks above `b`.\n */\nexport function compareHits(a: StageHit, b: StageHit): number {\n if (a.priority !== b.priority) return b.priority - a.priority;\n if (a.dist !== b.dist) return a.dist - b.dist;\n return a.layerId < b.layerId ? -1 : a.layerId > b.layerId ? 1 : 0;\n}\n\n/**\n * Sort hits, best first.\n *\n * @param hits - Any hits.\n * @returns A new, sorted array.\n */\nexport function sortHits(hits: readonly StageHit[]): StageHit[] {\n return [...hits].sort(compareHits);\n}\n\n/**\n * The best of some hits.\n *\n * @param hits - Any hits.\n * @returns The first by `compareHits`, or `null` when there are none.\n */\nexport function bestHit(hits: readonly StageHit[]): StageHit | null {\n let best: StageHit | null = null;\n for (const hit of hits) if (best === null || compareHits(hit, best) < 0) best = hit;\n return best;\n}\n\n/** The layers of one stage, and the routing of hover and presses between them. */\nexport interface HitRegistry<E = unknown> {\n /**\n * Add a layer.\n *\n * @returns The function that removes it.\n */\n register: (layer: StageHitLayerSpec<E>) => () => void;\n /** Every layer's best answer at `point`, sorted best first. */\n hitTestAll: (point: Point, radius: number, options?: StageHitOptions) => StageHit[];\n /** The best answer at `point`, or `null`. */\n hitTest: (point: Point, radius: number, options?: StageHitOptions) => StageHit | null;\n /**\n * Move hover to whatever is under `point`: the best hit among layers with a `hover`\n * handler gets `hover(id)`, and the layer that had it before gets `hover(null)`. Calls\n * nothing when the hovered item did not change.\n */\n routeHover: (point: Point, radius: number) => void;\n /** Clear hover, e.g. when the pointer leaves the stage or starts a pan. */\n clearHover: () => void;\n /**\n * Offer a press to the best pressable item under `point`, then the next, until one claims.\n *\n * @returns Whether a layer claimed it.\n */\n routePress: (point: Point, radius: number, event: E) => boolean;\n}\n\n/** Make an empty registry. */\nexport function createHitRegistry<E = unknown>(): HitRegistry<E> {\n const layers = new Set<StageHitLayerSpec<E>>();\n let hovered: { layer: StageHitLayerSpec<E>; id: HitId } | null = null;\n\n const answers = (point: Point, radius: number, options?: StageHitOptions): { hit: StageHit; layer: StageHitLayerSpec<E> }[] => {\n const out: { hit: StageHit; layer: StageHitLayerSpec<E> }[] = [];\n for (const layer of layers) {\n if (options?.pressable && layer.pressable !== true) continue;\n const found = layer.pick(point, radius);\n if (found) out.push({ hit: { id: found.id, dist: found.dist, layerId: layer.id, priority: layer.priority }, layer });\n }\n return out.sort((a, b) => compareHits(a.hit, b.hit));\n };\n\n const setHover = (next: { layer: StageHitLayerSpec<E>; id: HitId } | null) => {\n const previous = hovered;\n if (previous?.layer === next?.layer && previous?.id === next?.id) return;\n hovered = next;\n if (previous && previous.layer !== next?.layer) previous.layer.hover?.(null);\n next?.layer.hover?.(next.id);\n };\n\n return {\n register(layer) {\n layers.add(layer);\n return () => {\n layers.delete(layer);\n if (hovered?.layer === layer) hovered = null;\n };\n },\n hitTestAll: (point, radius, options) => answers(point, radius, options).map((a) => a.hit),\n hitTest: (point, radius, options) => answers(point, radius, options)[0]?.hit ?? null,\n routeHover(point, radius) {\n const best = answers(point, radius).find((a) => a.layer.hover !== undefined);\n setHover(best ? { layer: best.layer, id: best.hit.id } : null);\n },\n clearHover: () => setHover(null),\n routePress(point, radius, event) {\n for (const { hit, layer } of answers(point, radius, { pressable: true })) {\n if (layer.press?.(hit.id, event) !== false) return true;\n }\n return false;\n },\n };\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 { centroid, isTap, panButtonCodes, pinchView, type StageMouseButton } from \"./gesture\";\nimport { StageHitContext, type StagePointerEvent } from \"./hitContext\";\nimport { createHitRegistry } from \"./hitTest\";\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 pointer's tolerance for hover and presses, in screen pixels: a mouse, and a fingertip. */\nconst POINTER_RADIUS = 6;\nconst TOUCH_RADIUS = 12;\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/** A press that may become a pan, a click or a tap. */\ninterface Drag {\n x: number;\n y: number;\n tx: number;\n ty: number;\n /** Strayed past the click slop at some point, so it is not a click or a tap. */\n moved: boolean;\n /** Whether movement pans the view. */\n pan: boolean;\n /** A touch, which reports a tap rather than a click. */\n touch: boolean;\n /** `timeStamp` of the press. */\n at: number;\n /** The touch's pointer id, or `-1`. */\n pointerId: number;\n}\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 /**\n * The mouse buttons that pan on drag, over background no layer claimed. Defaults to\n * `[\"left\", \"middle\"]`. An app whose left button belongs to the active drawing tool passes\n * `\"right\"`; the context menu is then suppressed on the stage, since the button's job is\n * to drag. The hand tool and a held space bar still pan with the left button.\n */\n panButton?: StageMouseButton | readonly StageMouseButton[] | undefined;\n /**\n * Whether a double-click toggles fit and the previous view. On by default; turn it off in\n * an app whose tools use double-click, such as closing a polygon.\n */\n doubleClickFit?: boolean | undefined;\n /**\n * What one finger does on background no layer claimed: `\"one-finger\"` (the default) pans,\n * as the mouse does; `\"two-finger\"` leaves it to the app's tools and pans only with two.\n * Two fingers always pinch-zoom about their midpoint and pan with it. A tap (a touch that\n * stays put and is short) is a press: a layer's `onItemPress` hears it, or else\n * `onBackgroundClick`.\n */\n touchPan?: \"one-finger\" | \"two-finger\" | undefined;\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 panButton,\n doubleClickFit = true,\n touchPan = \"one-finger\",\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<Drag | null>(null);\n /** The touches down now, by pointer id, in client coordinates. */\n const touchesRef = useRef(new Map<number, Point>());\n /** The two-finger gesture in progress, from the moment the second finger went down. */\n const pinchRef = useRef<{ distance: number; centre: Point; view: StageView } | null>(null);\n /** The registry the stage's layers answer hit-tests through. */\n const [hits] = useState(() => createHitRegistry<StagePointerEvent>());\n const panButtons = useMemo(() => panButtonCodes(panButton), [panButton]);\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 /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */\n const hitRadius = (event: { pointerType: string }) =>\n imageLengthFor(effective, event.pointerType === \"touch\" ? TOUCH_RADIUS : POINTER_RADIUS);\n\n /** Offer a press to the items under it, topmost first; whether one claimed it. */\n const routePress = (event: ReactPointerEvent<HTMLDivElement>) =>\n hits.routePress(clientToImage({ x: event.clientX, y: event.clientY }), hitRadius(event), event);\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 * Layers that cannot own an element — a marker among thousands — register with the hit\n * registry instead, and the press reaches them here: after every element-level handler had\n * its say, before the stage reads the press as a pan.\n */\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.pointerType === \"touch\") {\n touchDown(event);\n return;\n }\n const primary = event.button === 0;\n if (primary && !panMode && routePress(event)) return;\n // The hand tool and a held space bar pan with the primary button whatever `panButton` says.\n const pan = panButtons.has(event.button) || (primary && panMode);\n if (!pan && !primary) 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 pan,\n touch: false,\n at: event.timeStamp,\n pointerId: event.pointerId,\n };\n if (pan) setPanning(true);\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n\n const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.pointerType === \"touch\") {\n touchMove(event);\n return;\n }\n const origin = dragRef.current;\n if (!origin?.pan) {\n onHover?.(hoverPoint(event, viewportRef.current, effective, image));\n hits.routeHover(clientToImage({ x: event.clientX, y: event.clientY }), hitRadius(event));\n if (origin && !origin.moved && Math.hypot(event.clientX - origin.x, event.clientY - origin.y) > CLICK_SLOP) {\n origin.moved = true;\n }\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 hits.clearHover();\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 if (origin?.touch) return; // a touch ends through `touchEnd`\n dragRef.current = null;\n setPanning(false);\n if (origin && !origin.moved && event.button === 0) onBackgroundClick?.(event);\n };\n\n /*\n * Touch. The first finger is a pan candidate (if `touchPan` says so) and a tap candidate;\n * the second turns the gesture into a pinch about the fingers' midpoint, which also\n * carries the view with it. A tap is a press and is reported on release, because on\n * `pointerdown` a finger might still be the first of two.\n */\n const touchDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n const touches = touchesRef.current;\n if (touches.size >= 2) return; // a third finger has no job\n event.preventDefault();\n touches.set(event.pointerId, { x: event.clientX, y: event.clientY });\n try {\n event.currentTarget.setPointerCapture(event.pointerId);\n } catch {\n // The touch ended or was taken by the browser before this handler ran. The gesture\n // still works from the events the viewport receives; capture only keeps a drag that\n // leaves the viewport.\n }\n if (touches.size === 1) {\n dragRef.current = {\n x: event.clientX,\n y: event.clientY,\n tx: effective.tx,\n ty: effective.ty,\n moved: false,\n pan: touchPan === \"one-finger\" || panMode,\n touch: true,\n at: event.timeStamp,\n pointerId: event.pointerId,\n };\n return;\n }\n const [a, b] = [...touches.values()] as [Point, Point];\n const origin = viewportOrigin(event.currentTarget);\n const mid = centroid(a, b);\n pinchRef.current = {\n distance: Math.hypot(a.x - b.x, a.y - b.y),\n centre: { x: mid.x - origin.x, y: mid.y - origin.y },\n view: effective,\n };\n if (dragRef.current) dragRef.current.moved = true; // two fingers are never a tap\n setPanning(true);\n onHover?.(null);\n hits.clearHover();\n };\n\n const touchMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n const touches = touchesRef.current;\n if (!touches.has(event.pointerId)) return;\n touches.set(event.pointerId, { x: event.clientX, y: event.clientY });\n const pinch = pinchRef.current;\n if (pinch && touches.size === 2) {\n if (!(box.width > 0)) return;\n const [a, b] = [...touches.values()] as [Point, Point];\n const origin = viewportOrigin(event.currentTarget);\n const mid = centroid(a, b);\n commit(\n pinchView(\n pinch.view,\n pinch.distance,\n pinch.centre,\n Math.hypot(a.x - b.x, a.y - b.y),\n { x: mid.x - origin.x, y: mid.y - origin.y },\n scaleRange(box, image, clamp),\n ),\n );\n return;\n }\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n const dx = event.clientX - drag.x;\n const dy = event.clientY - drag.y;\n if (!drag.moved && Math.hypot(dx, dy) <= CLICK_SLOP) return;\n drag.moved = true;\n if (!drag.pan) return;\n setPanning(true);\n onHover?.(null);\n commit({ scale: effective.scale, tx: drag.tx + dx, ty: drag.ty + dy });\n };\n\n const touchEnd = (event: ReactPointerEvent<HTMLDivElement>, cancelled: boolean) => {\n const touches = touchesRef.current;\n if (!touches.delete(event.pointerId)) return; // already ended (the capture is lost after the release)\n if (pinchRef.current) {\n pinchRef.current = null;\n const rest = [...touches.entries()][0];\n if (rest) {\n // One finger is still down: it carries on as a pan from where it is, never as a tap.\n dragRef.current = {\n x: rest[1].x,\n y: rest[1].y,\n tx: effective.tx,\n ty: effective.ty,\n moved: true,\n pan: touchPan === \"one-finger\" || panMode,\n touch: true,\n at: event.timeStamp,\n pointerId: rest[0],\n };\n return;\n }\n }\n if (touches.size > 0) return;\n const drag = dragRef.current;\n dragRef.current = null;\n setPanning(false);\n if (!drag || cancelled || drag.moved || !isTap(0, event.timeStamp - drag.at)) return;\n if (!routePress(event)) 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 (!doubleClickFit || !(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 <StageHitContext value={hits}>\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 touch-none 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={(event) => (event.pointerType === \"touch\" ? touchEnd(event, false) : endDrag(event))}\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={(event) => (event.pointerType === \"touch\" ? touchEnd(event, true) : endDrag(event))}\n onLostPointerCapture={(event) => (event.pointerType === \"touch\" ? touchEnd(event, true) : endDrag(event))}\n onPointerLeave={() => {\n onHover?.(null);\n hits.clearHover();\n }}\n onDoubleClick={onDoubleClick}\n // The button's job is to drag; a menu opening at the end of every pan would undo it.\n onContextMenu={panButtons.has(2) ? (event) => event.preventDefault() : undefined}\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 </StageHitContext>\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 * React wiring for the stage's hit-test registry: `useStageHitTest` for apps that ask \"what\n * is under the pointer\", and `useStageHitLayer` for layers that answer.\n */\n\nimport { use, useId, useLayoutEffect, useMemo, useRef } from \"react\";\n\nimport type { Point } from \"../measureGeometry\";\nimport { useStage } from \"./ImageStage\";\nimport { StageHitContext, type StagePointerEvent } from \"./hitContext\";\nimport {\n type HitCandidate,\n type HitId,\n type StageHit,\n type StageHitLayerSpec,\n type StageHitOptions,\n} from \"./hitTest\";\n\n/** The default pointer tolerance of `hitTest`, in screen pixels. */\nconst DEFAULT_RADIUS_PX = 6;\n\n/** What `useStageHitTest` returns. */\nexport interface StageHitTestApi {\n /**\n * The best item under a point across every layer, or `null`.\n *\n * @param point - In image coordinates, e.g. a `StagePress.point`.\n * @param radiusScreenPx - The pointer's tolerance in screen pixels. Defaults to 6.\n * @param options - `pressable` limits the answer to layers that claim presses.\n */\n hitTest: (point: Point, radiusScreenPx?: number, options?: StageHitOptions) => StageHit | null;\n /**\n * Every layer's best item under a point, best first: higher priority, then nearer.\n * Parameters as `hitTest`.\n */\n hitTestAll: (point: Point, radiusScreenPx?: number, options?: StageHitOptions) => StageHit[];\n}\n\n/**\n * The stage's one hit-test, across every registered layer (`PointSet`, `PolylineSet`, and\n * any layer built with `useStageHitLayer`). A press handler uses it to decide what a press\n * means: an item under the pointer is selected, bare image is drawn on or panned.\n *\n * The answer comes from each layer's spatial index, never from the DOM, so it costs\n * microseconds at any scene size.\n *\n * @returns `{ hitTest, hitTestAll }`.\n * @throws `Error` outside an `ImageStage`, which is always a wiring bug.\n */\nexport function useStageHitTest(): StageHitTestApi {\n const registry = use(StageHitContext);\n if (registry === null) throw new Error(\"useStageHitTest must be used inside <ImageStage>.\");\n const { imageLength } = useStage();\n return useMemo(\n () => ({\n hitTest: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) =>\n registry.hitTest(point, imageLength(radiusScreenPx), options),\n hitTestAll: (point, radiusScreenPx = DEFAULT_RADIUS_PX, options) =>\n registry.hitTestAll(point, imageLength(radiusScreenPx), options),\n }),\n [registry, imageLength],\n );\n}\n\n/** What a layer passes `useStageHitLayer`. */\nexport interface StageHitLayerOptions {\n /** The id hits report. Defaults to a generated, stable one; set it to tell layers apart. */\n layerId?: string | undefined;\n /** Rank against other layers; see `STAGE_HIT_PRIORITY`. */\n priority: number;\n /**\n * The item under `point`, if any, within `radius` image pixels. Use the layer's index\n * (`nearestPoint`, `nearestPolyline`), not the DOM.\n */\n pick: (point: Point, radius: number) => HitCandidate | null;\n /**\n * The hovered item changed. Setting this makes the stage route hover to the layer; the\n * best item under the pointer across layers is the hovered one.\n */\n onHover?: ((id: HitId | null) => void) | undefined;\n /**\n * A press landed on an item and nothing above it claimed it. Setting this makes the layer\n * claim presses on its items, so the stage does not pan from them. Return `false` to\n * decline one. For a touch tap this is the `pointerup`.\n */\n onPress?: ((id: HitId, event: StagePointerEvent) => boolean | void) | undefined;\n}\n\n/**\n * Register a layer with the stage's hit-test. The callbacks may change every render; the\n * registration does not, so a layer is never missing from a hit-test for a frame.\n *\n * @param options - How the layer answers `pick`, and whether it takes hover and presses.\n * @returns The layer's id, as hits report it.\n * @throws `Error` outside an `ImageStage`.\n */\nexport function useStageHitLayer(options: StageHitLayerOptions): string {\n const registry = use(StageHitContext);\n if (registry === null) throw new Error(\"useStageHitLayer must be used inside <ImageStage>.\");\n const generatedId = useId();\n const id = options.layerId ?? generatedId;\n const latestRef = useRef(options);\n useLayoutEffect(() => {\n latestRef.current = options;\n });\n const priority = options.priority;\n useLayoutEffect(() => {\n // Everything the registry reads goes through `latestRef`, so one registration serves the\n // layer's whole life; `priority` and `id` are the only things that re-register it.\n const layer: StageHitLayerSpec<StagePointerEvent> = {\n id,\n priority,\n pick: (point, radius) => latestRef.current.pick(point, radius),\n get pressable() {\n return latestRef.current.onPress !== undefined;\n },\n get hover() {\n return latestRef.current.onHover === undefined ? undefined : (hovered: HitId | null) => latestRef.current.onHover?.(hovered);\n },\n get press() {\n return latestRef.current.onPress === undefined ? undefined : (hit: HitId, event: StagePointerEvent) => latestRef.current.onPress?.(hit, event);\n },\n };\n return registry.register(layer);\n }, [registry, id, priority]);\n return id;\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 { STAGE_HIT_PRIORITY } from \"./stage/hitTest\";\nimport { useStageHitLayer, useStageHitTest } from \"./stage/useStageHitTest\";\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 when the line under the pointer changes: the same as `onHover`, under the name\n * `PointSet` uses, so an app handles every layer's hover alike.\n */\n onHoverChange?: ((id: PolylineId | null) => void) | undefined;\n /**\n * Called when a press lands on a line, with the `pointerdown`, before `onSelect`. It does\n * not fire for a rubber band, nor when a point of a `PointSet` over the line takes the\n * press instead.\n */\n onItemPress?: ((id: PolylineId, event: ReactPointerEvent<SVGPathElement>) => 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 /** The id hit-tests report for this layer. Defaults to a generated one. */\n layerId?: string | undefined;\n /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.line`. */\n priority?: number | 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 onHoverChange,\n onItemPress,\n onSelect,\n marquee = false,\n stroke = overlayRole(\"feature\"),\n selectionStroke = overlayRole(\"selection\"),\n hitWidth = 14,\n vertexScale = 3,\n label = \"Lines\",\n layerId,\n priority = STAGE_HIT_PRIORITY.line,\n}: PolylineSetProps) {\n const stage = useStage();\n const startDrag = useStageDrag();\n const px = useScreenPx();\n const { hitTestAll } = useStageHitTest();\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 // Answers the stage's hit-test, so an app can ask one question across layers. The line's\n // own hover and press stay on its hit path, which gives the pointer cursor and the claim.\n const ownId = useStageHitLayer({\n layerId,\n priority,\n pick: (point, radius) => {\n const hit = nearestPolyline(index, point, radius);\n return hit ? { id: hit.id, dist: hit.distance } : null;\n },\n });\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 onHoverChange?.(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 // A marker over the line is what the pointer is on: leave the press to the stage, which\n // hands it to the point layer.\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n if (hitTestAll(point, hitWidth / 2, { pressable: true }).some((hit) => hit.layerId !== ownId && hit.priority > priority)) 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 onItemPress?.(id, event);\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","/**\n * Marker glyphs for `PointSet`: one path generator per feature kind (overlay grammar,\n * `docs/visual-language.md` §5).\n *\n * A glyph is a function from a position to SVG path data, so a layer can append thousands of\n * them into one `<path>` per state and style. Sizes are screen pixels: a generator receives\n * `unit`, the image pixels per screen pixel (`useScreenPx()(1)`), and scales its constants by\n * it. A glyph whose `paint` is `\"disc\"` needs no `unit` at all (it is a zero-length segment\n * drawn with round caps, its size the stroke width), so it is not rebuilt when the zoom\n * changes.\n *\n * Pure: no React, no DOM.\n */\n\nimport type { OverlayRole } from \"./overlayRole\";\n\n/** One kind of marker. */\nexport interface MarkerShape {\n /**\n * How the path is painted:\n * - `\"disc\"`: `path` returns a zero-length segment per marker; the stroke width is the\n * disc's diameter. Independent of `unit`, so a batched path survives a zoom unchanged.\n * - `\"line\"`: `path` returns an outline, stroked at the state's width.\n */\n readonly paint: \"disc\" | \"line\";\n /** Half the glyph's extent in screen pixels at rest: a disc's radius, a plus's arm. */\n readonly size: number;\n /** The role a marker of this kind has unless the item says otherwise. Defaults to `feature`. */\n readonly role?: OverlayRole | undefined;\n /**\n * The path data for one marker.\n *\n * @param x - Centre x, in image coordinates.\n * @param y - Centre y, in image coordinates.\n * @param unit - Image pixels per screen pixel.\n * @param angle - The item's orientation in radians, `0` when it has none.\n * @returns Path commands, absolute at the start (`M x y …`) and self-contained.\n */\n path: (x: number, y: number, unit: number, angle: number) => string;\n}\n\n/** Round to 1/1000 of an image pixel: enough for any zoom, and half the characters. */\nfunction n(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n\n/**\n * A circle as two arcs, centred at `(x, y)`.\n *\n * @param x - Centre x.\n * @param y - Centre y.\n * @param r - Radius, in the units of `x` and `y`.\n * @returns Path data.\n */\nexport function circlePath(x: number, y: number, r: number): string {\n return `M${n(x + r)} ${n(y)}a${n(r)} ${n(r)} 0 1 0 ${n(-2 * r)} 0a${n(r)} ${n(r)} 0 1 0 ${n(2 * r)} 0`;\n}\n\n/** The names of the built-in marker kinds. */\nexport type BuiltinMarkerKind = \"dot\" | \"plus\" | \"cross\" | \"square\" | \"hollow\" | \"directed\";\n\n/** The built-in kinds, with the overlay grammar's glyph for each. */\nexport const MARKER_SHAPES: Readonly<Record<BuiltinMarkerKind, MarkerShape>> = {\n /** A blob, circle centre or keypoint: a dot of radius 2.5 px. */\n dot: {\n paint: \"disc\",\n size: 2.5,\n path: (x, y) => `M${n(x)} ${n(y)}h0`,\n },\n /** A corner or X-junction: a plus with 5 px arms, so the centre stays visible. */\n plus: {\n paint: \"line\",\n size: 5,\n path: (x, y, u) => {\n const a = 5 * u;\n return `M${n(x - a)} ${n(y)}h${n(2 * a)}M${n(x)} ${n(y - a)}v${n(2 * a)}`;\n },\n },\n /** A diagonal cross with 4 px arms: a second corner style, or \"rejected\". */\n cross: {\n paint: \"line\",\n size: 4,\n path: (x, y, u) => {\n const a = 4 * u;\n return `M${n(x - a)} ${n(y - a)}l${n(2 * a)} ${n(2 * a)}M${n(x - a)} ${n(y + a)}l${n(2 * a)} ${n(-2 * a)}`;\n },\n },\n /** A hollow square of half-side 3.5 px. */\n square: {\n paint: \"line\",\n size: 3.5,\n path: (x, y, u) => {\n const a = 3.5 * u;\n return `M${n(x - a)} ${n(y - a)}h${n(2 * a)}v${n(2 * a)}h${n(-2 * a)}Z`;\n },\n },\n /** A reprojected or predicted point: a hollow circle of radius 4 px, in the model colour. */\n hollow: {\n paint: \"line\",\n size: 4,\n role: \"model\",\n path: (x, y, u) => circlePath(x, y, 4 * u),\n },\n /**\n * A point with an orientation: a small ring and a tick of length 8 px from it along\n * `angle`, measured clockwise from +x in image coordinates (y points down).\n */\n directed: {\n paint: \"line\",\n size: 6,\n path: (x, y, u, angle) => {\n const c = Math.cos(angle);\n const s = Math.sin(angle);\n return (\n `${circlePath(x, y, 2 * u)}M${n(x + 2 * u * c)} ${n(y + 2 * u * s)}L${n(x + 8 * u * c)} ${n(y + 8 * u * s)}`\n );\n },\n },\n};\n","/**\n * A spatial index over many points: which one is under the pointer, which ones a rubber band\n * caught, and which ones are far enough apart to carry a label.\n *\n * The same uniform grid as `polylineIndex.ts`, in CSR layout (cell `c`'s entries are\n * `starts[c] .. starts[c + 1]`, no per-cell arrays), generalised from the L0-3 benchmark's\n * `grid.ts`. It answers in microseconds whichever engine draws the markers\n * (`docs/measurements/stage2d-bench-analysis.md`), and it imports neither React nor the DOM.\n *\n * Points are flat `[x0, y0, x1, y1, …]` arrays in image coordinates, the form a detector\n * returns and the cheapest to keep. A point with a non-finite coordinate is not indexed.\n */\n\nimport type { Rect } from \"./stage/view\";\n\n/** A point's identity. */\nexport type PointId = string | number;\n\n/** The shape `buildPointIndexFrom` reads from each item. */\nexport interface PointItem {\n /** Its identity, unique in the set. */\n id: PointId;\n /** Horizontal position, in image coordinates. */\n x: number;\n /** Vertical position, in image coordinates. */\n y: number;\n /** How far from the point a query still picks it, in image pixels. Defaults to `0`. */\n pickRadius?: number | undefined;\n}\n\n/** Options of `buildPointIndex`. */\nexport interface PointIndexOptions {\n /** Ids by point index. Defaults to the index itself. */\n ids?: ArrayLike<PointId> | undefined;\n /**\n * Per-point pick radius, in image pixels. A query at distance `d` from point `i` picks it\n * when `d ≤ radius + radii[i]`, so a ring marker whose circle is data (it scales with the\n * image) can be picked anywhere on it. Defaults to `0` for every point.\n */\n radii?: ArrayLike<number> | undefined;\n /**\n * The grid cell side, in image pixels. Defaults to a side that puts about two points in\n * each cell, bounded to `[4, 256]`.\n */\n cell?: number | undefined;\n}\n\n/**\n * An index built by `buildPointIndex`. Treat it as opaque and query it with `nearestPoint`,\n * `pointsInRect` and `thinPoints`; its layout may change.\n */\nexport interface PointIndex {\n /** The number of points given, indexed or not. */\n readonly count: number;\n /** The points, flat `[x0, y0, …]`. Not copied: do not change it after building. */\n readonly xy: ArrayLike<number>;\n /** Ids by point index, or `null` when a point's id is its index. */\n readonly ids: ArrayLike<PointId> | null;\n /** Per-point pick radii, or `null` when every point has none. */\n readonly radii: ArrayLike<number> | null;\n /** The largest pick radius, widening every query window. */\n readonly maxRadius: number;\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 `items[starts[c] .. starts[c + 1]]`. */\n readonly starts: Uint32Array;\n /** Point indices by cell, ascending within a cell. */\n readonly items: Uint32Array;\n}\n\n/** The nearest point to a query. */\nexport interface PointHit {\n /** Its index in the array the index was built from. */\n index: number;\n /** Its id. */\n id: PointId;\n /** The distance from the query to the point's centre, in image pixels. */\n dist: number;\n}\n\n/** The most grid cells an index allocates, whatever the cell side asks for. */\nconst MAX_CELLS = 4_000_000;\n\n/**\n * Index a set of points.\n *\n * @param xy - Flat `[x0, y0, x1, y1, …]` in image coordinates; a `Float32Array` or\n * `Float64Array` avoids a copy at the call site.\n * @param options - Ids, per-point pick radii and the cell side.\n * @returns The index.\n */\nexport function buildPointIndex(xy: ArrayLike<number>, options: PointIndexOptions = {}): PointIndex {\n const count = Math.floor(xy.length / 2);\n const ids = options.ids ?? null;\n const radii = options.radii ?? null;\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n let maxRadius = 0;\n let live = 0;\n for (let i = 0; i < count; i++) {\n const x = xy[2 * i]!;\n const y = xy[2 * i + 1]!;\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n live++;\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 if (radii) {\n const r = radii[i]!;\n if (r > maxRadius) maxRadius = r;\n }\n }\n if (live === 0) {\n return {\n count, xy, ids: ids, radii, maxRadius, cell: 1, x0: 0, y0: 0, cols: 1, rows: 1,\n starts: new Uint32Array(2), items: new Uint32Array(0),\n };\n }\n\n const width = maxX - minX;\n const height = maxY - minY;\n let cell = options.cell ?? Math.min(256, Math.max(4, Math.sqrt((Math.max(width, 1) * Math.max(height, 1) * 2) / live)));\n // A pathological extent (one far outlier, a tiny `cell`) must not allocate a huge grid.\n while ((Math.floor(width / cell) + 1) * (Math.floor(height / cell) + 1) > MAX_CELLS) cell *= 2;\n const cols = Math.floor(width / cell) + 1;\n const rows = Math.floor(height / cell) + 1;\n const cellOf = new Int32Array(count).fill(-1);\n const starts = new Uint32Array(cols * rows + 1);\n for (let i = 0; i < count; i++) {\n const x = xy[2 * i]!;\n const y = xy[2 * i + 1]!;\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n const c = Math.min(rows - 1, Math.floor((y - minY) / cell)) * cols + Math.min(cols - 1, Math.floor((x - minX) / cell));\n cellOf[i] = c;\n starts[c + 1]!++;\n }\n for (let c = 0; c < cols * rows; c++) starts[c + 1]! += starts[c]!;\n const fill = starts.slice(0, cols * rows);\n const items = new Uint32Array(live);\n for (let i = 0; i < count; i++) {\n const c = cellOf[i]!;\n if (c >= 0) items[fill[c]!++] = i;\n }\n return { count, xy, ids: ids, radii, maxRadius, cell, x0: minX, y0: minY, cols, rows, starts, items };\n}\n\n/**\n * Index items that carry their own position.\n *\n * @param items - The points, in order.\n * @param cell - The grid cell side; see `PointIndexOptions`.\n * @returns The index; its point indices are positions in `items`.\n */\nexport function buildPointIndexFrom(items: readonly PointItem[], cell?: number): PointIndex {\n const xy = new Float64Array(items.length * 2);\n const ids: PointId[] = new Array<PointId>(items.length);\n let radii: Float64Array | undefined;\n items.forEach((item, i) => {\n xy[2 * i] = item.x;\n xy[2 * i + 1] = item.y;\n ids[i] = item.id;\n if (item.pickRadius !== undefined && item.pickRadius > 0) {\n radii ??= new Float64Array(items.length);\n radii[i] = item.pickRadius;\n }\n });\n return buildPointIndex(xy, { ids, radii, cell });\n}\n\n/**\n * The point nearest to `(x, y)` whose pick disc reaches it, or `null`.\n *\n * @param index - The index.\n * @param x - The query's x, in image coordinates.\n * @param y - The query's y, in image coordinates.\n * @param radius - How far from a point's centre the query still picks it, in image pixels.\n * For a screen-constant tolerance, pass `useScreenPx()(css)`. A point's own `radii` entry\n * adds to it.\n * @returns The point nearest by centre distance; ties go to the lower index, so the result\n * does not depend on cell order.\n */\nexport function nearestPoint(index: PointIndex, x: number, y: number, radius: number): PointHit | null {\n if (!(radius >= 0) || index.items.length === 0) return null;\n const { cell, x0, y0, cols, rows, starts, items, xy, radii, maxRadius } = index;\n const reach = radius + maxRadius;\n const cx0 = Math.max(0, Math.floor((x - reach - x0) / cell));\n const cx1 = Math.min(cols - 1, Math.floor((x + reach - x0) / cell));\n const cy0 = Math.max(0, Math.floor((y - reach - y0) / cell));\n const cy1 = Math.min(rows - 1, Math.floor((y + reach - y0) / cell));\n let best = -1;\n let bestD = Infinity;\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 i = items[k]!;\n const dx = xy[2 * i]! - x;\n const dy = xy[2 * i + 1]! - y;\n const d = dx * dx + dy * dy;\n const reachI = radii ? radius + radii[i]! : radius;\n if (d <= reachI * reachI && (d < bestD || (d === bestD && i < best))) {\n bestD = d;\n best = i;\n }\n }\n }\n }\n return best < 0 ? null : { index: best, id: index.ids ? index.ids[best]! : best, dist: Math.sqrt(bestD) };\n}\n\n/**\n * The points whose centre is inside `rect`, edges included.\n *\n * @param index - The index.\n * @param rect - The band, in image coordinates. A negative extent is read as the box\n * between its corners.\n * @returns Their indices, ascending.\n */\nexport function pointsInRect(index: PointIndex, rect: Rect): number[] {\n if (index.items.length === 0) return [];\n const { cell, x0, y0, cols, rows, starts, items, xy } = index;\n const left = Math.min(rect.x, rect.x + rect.width);\n const right = Math.max(rect.x, rect.x + rect.width);\n const top = Math.min(rect.y, rect.y + rect.height);\n const bottom = Math.max(rect.y, rect.y + rect.height);\n const cx0 = Math.max(0, Math.floor((left - x0) / cell));\n const cx1 = Math.min(cols - 1, Math.floor((right - x0) / cell));\n const cy0 = Math.max(0, Math.floor((top - y0) / cell));\n const cy1 = Math.min(rows - 1, Math.floor((bottom - y0) / cell));\n const found: number[] = [];\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 i = items[k]!;\n const px = xy[2 * i]!;\n const py = xy[2 * i + 1]!;\n if (px >= left && px <= right && py >= top && py <= bottom) found.push(i);\n }\n }\n }\n return found.sort((a, b) => a - b);\n}\n\n/**\n * A greedy thinning: walk the points in `order` and keep each one that is at least `minDist`\n * from every point kept so far. This is how a label layer decides which labels the zoom has\n * room for.\n *\n * The result is *maximal*: every point left out is within `minDist` of one kept before it,\n * and every pair kept is at least `minDist` apart.\n *\n * @param xy - Flat points, in the units `minDist` is in (image pixels for a screen-px spacing\n * converted with `useScreenPx`).\n * @param minDist - The least distance between two kept points.\n * @param order - Point indices in priority order. Defaults to every point, in order.\n * Indices of non-finite points are skipped.\n * @returns The kept indices, in the order they were kept.\n */\nexport function thinPoints(xy: ArrayLike<number>, minDist: number, order?: Iterable<number>): number[] {\n const kept: number[] = [];\n if (!(minDist > 0)) {\n for (const i of order ?? range(Math.floor(xy.length / 2))) if (isLive(xy, i)) kept.push(i);\n return kept;\n }\n // Cells of side `minDist`: any kept point closer than `minDist` is in the 3×3 block around\n // the candidate's cell. The cell only bounds the search; the check compares true distances.\n // A key can alias for coordinates beyond ±2²¹ cells, which only adds candidates to a scan.\n const cells = new Map<number, number[]>();\n const key = (cx: number, cy: number) => cy * 4_194_304 + cx;\n const limit = minDist * minDist;\n for (const i of order ?? range(Math.floor(xy.length / 2))) {\n if (!isLive(xy, i)) continue;\n const x = xy[2 * i]!;\n const y = xy[2 * i + 1]!;\n const cx = Math.floor(x / minDist);\n const cy = Math.floor(y / minDist);\n let clear = true;\n scan: for (let dy = -1; dy <= 1; dy++) {\n for (let dx = -1; dx <= 1; dx++) {\n const bucket = cells.get(key(cx + dx, cy + dy));\n if (!bucket) continue;\n for (const j of bucket) {\n const ex = xy[2 * j]! - x;\n const ey = xy[2 * j + 1]! - y;\n if (ex * ex + ey * ey < limit) {\n clear = false;\n break scan;\n }\n }\n }\n }\n if (!clear) continue;\n kept.push(i);\n const k = key(cx, cy);\n const bucket = cells.get(k);\n if (bucket) bucket.push(i);\n else cells.set(k, [i]);\n }\n return kept;\n}\n\nfunction isLive(xy: ArrayLike<number>, i: number): boolean {\n return Number.isFinite(xy[2 * i]) && Number.isFinite(xy[2 * i + 1]);\n}\n\nfunction* range(n: number): Generator<number> {\n for (let i = 0; i < n; i++) yield i;\n}\n","/**\n * Many points over the image, hoverable and selectable: detected corners, ring centres,\n * keypoints, labelled landmarks.\n *\n * Drawn as a handful of batched paths, one per (state, style, marker kind), never one element\n * per point (ADR-0004 rules 1 and 3); the pointer is resolved by `nearestPoint` through the\n * stage's hit registry, never by the DOM (rule 2); markers are sized in screen pixels (rule\n * 4). A scene of 20,000 points is under a dozen DOM nodes plus at most 200 labels.\n */\n\nimport { useMemo, useState } from \"react\";\n\nimport { circlePath, MARKER_SHAPES, type MarkerShape } from \"./markerShapes\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\nimport { buildPointIndexFrom, nearestPoint, thinPoints, type PointId, type PointItem } from \"./pointIndex\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { StagePointerEvent } from \"./stage/hitContext\";\nimport { STAGE_HIT_PRIORITY } from \"./stage/hitTest\";\nimport { useStageHitLayer } from \"./stage/useStageHitTest\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox, type Rect } from \"./stage/view\";\n\n/** One point of a `PointSet`. */\nexport interface PointSetItem extends PointItem {\n /**\n * The marker kind: a built-in (`dot`, `plus`, `cross`, `square`, `hollow`, `directed`) or\n * a key of the layer's `markers`. Defaults to the layer's `kind`.\n */\n kind?: string | undefined;\n /** The overlay role it is painted in. Defaults to the marker kind's role, usually `feature`. */\n role?: OverlayRole | undefined;\n /** Its orientation in radians, clockwise from +x; read by `directed`. */\n angle?: number | undefined;\n /** Text drawn beside it, when the zoom leaves room (points at least 24 screen px apart). */\n label?: string | undefined;\n}\n\n/** Props of `PointSet`. */\nexport interface PointSetProps {\n /** The points, in image coordinates. */\n items: readonly PointSetItem[];\n /** The marker kind of an item that names none. Defaults to `\"dot\"`. */\n kind?: string | undefined;\n /** More marker kinds, or replacements for built-in ones, by name. */\n markers?: Readonly<Record<string, MarkerShape>> | undefined;\n /** The hovered id, when the app controls hover (a list beside the stage hovers points too). */\n hoveredId?: PointId | null | undefined;\n /** Called when the point under the pointer changes. `null` when it leaves every point. */\n onHoverChange?: ((id: PointId | null) => void) | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour with a ring. */\n selectedIds?: Iterable<PointId> | undefined;\n /**\n * Ids drawn at 35 % opacity, as a set or a predicate (outside the current filter, say).\n * They still take hover and presses. Pass a stable value: a new one re-batches the layer.\n */\n dimmed?: Iterable<PointId> | ((id: PointId) => boolean) | undefined;\n /**\n * A press landed on a point. Setting it makes the layer claim presses on its points, so\n * the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for a\n * touch tap), so `useStageDrag` can start a drag from it.\n *\n * A mounted `StageSurface` hears a press first; there, ask `useStageHitTest` what is\n * under it instead.\n */\n onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | undefined;\n /** Show the items' `label`s where the zoom leaves room for them. On by default. */\n labels?: boolean | undefined;\n /** Draw the dark band under every mark. On by default; off for a fast, flat layer. */\n halo?: boolean | undefined;\n /** CSS colour of selected points and rings. Defaults to the overlay `selection` role. */\n selectionStroke?: string | undefined;\n /** The id hit-tests report for this layer. Defaults to a generated one. */\n layerId?: string | undefined;\n /** Rank against other layers in hit-tests. Defaults to `STAGE_HIT_PRIORITY.point`. */\n priority?: number | undefined;\n /** The layer's accessible name. Defaults to \"Points\". */\n label?: string | undefined;\n}\n\n/** Labels need this much room between points, in screen pixels (overlay grammar §5). */\nconst LABEL_SPACING = 24;\n/** The most label elements drawn at once. */\nconst MAX_LABELS = 200;\n/** The most hovered-or-selected labels forced on regardless of spacing. */\nconst MAX_FORCED_LABELS = 50;\n/** Past this many points, outlines are generated for the visible part only. */\nconst CULL_ABOVE = 3000;\n/** How much bigger than a marker its selection ring is, in screen pixels. */\nconst RING_GAP = 4;\n\nconst HALO = overlayRole(\"halo\");\nconst LABEL = overlayRole(\"label\");\n\n/** The points of one batched path. */\ninterface Batch {\n key: string;\n shape: MarkerShape;\n role: OverlayRole;\n dim: boolean;\n /** Item positions, ascending. */\n indices: number[];\n /** The last generated path data and what it was generated for. */\n cache: { key: string; d: string } | null;\n}\n\n/**\n * A selectable set of points inside an `ImageStage`.\n *\n * - **Markers** by kind, from the overlay grammar: `dot`, `plus` (corner), `cross`, `square`,\n * `hollow` (predicted), `directed`. Add your own through `markers`.\n * - **States**, from visual-language §5: default 1.5 screen px, hover 2, selected 2.5 in the\n * selection colour with a ring, dimmed at 35 % opacity. Every mark has a halo.\n * - **Labels** only where points are at least 24 screen px apart, at most 200 at a time.\n * - **Picking** goes through the stage's hit registry: `onHoverChange` and `onItemPress` here,\n * and `useStageHitTest` for an app that arbitrates between layers.\n *\n * Outlines (`plus`, `cross`, …) are regenerated when the zoom changes, since their size is in\n * screen pixels; past 3,000 points only those near the viewport are generated. `dot` is a\n * zero-length stroke whose width is its size, so it is not regenerated at all.\n *\n * The SVG carries `data-hovered` (the hovered id).\n */\nexport function PointSet({\n items,\n kind = \"dot\",\n markers,\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n labels = true,\n halo = true,\n selectionStroke = overlayRole(\"selection\"),\n layerId,\n priority = STAGE_HIT_PRIORITY.point,\n label = \"Points\",\n}: PointSetProps) {\n const stage = useStage();\n const px = useScreenPx();\n const unit = px(1);\n\n const shapes = useMemo<Readonly<Record<string, MarkerShape>>>(() => ({ ...MARKER_SHAPES, ...markers }), [markers]);\n const index = useMemo(() => buildPointIndexFrom(items), [items]);\n const selectedSet = useMemo(() => new Set(selectedIds ?? []), [selectedIds]);\n const isDimmed = useMemo(() => {\n if (typeof dimmed === \"function\") return dimmed;\n const set = new Set(dimmed ?? []);\n return (id: PointId) => set.has(id);\n }, [dimmed]);\n const positionOf = useMemo(() => new Map(items.map((item, i) => [item.id, i])), [items]);\n\n const [ownHover, setOwnHover] = useState<PointId | null>(null);\n const hoverId = hoveredId !== undefined ? hoveredId : ownHover;\n\n useStageHitLayer({\n layerId,\n priority,\n pick: (point, radius) => {\n const hit = nearestPoint(index, point.x, point.y, radius);\n return hit ? { id: hit.id, dist: hit.dist } : null;\n },\n onHover: (id) => {\n setOwnHover(id);\n onHoverChange?.(id);\n },\n onPress: onItemPress ? (id, event) => onItemPress(id, event) : undefined,\n });\n\n // Items grouped by appearance. Rebuilt when the items or the selection change, never on\n // hover or on a view change.\n const groups = useMemo(() => {\n const normal = new Map<string, Batch>();\n const picked = new Map<string, Batch>();\n items.forEach((item, i) => {\n const kindName = item.kind ?? kind;\n const shape = shapes[kindName] ?? MARKER_SHAPES.dot;\n if (selectedSet.has(item.id)) {\n const key = kindName;\n let batch = picked.get(key);\n if (!batch) {\n batch = { key, shape, role: \"selection\", dim: false, indices: [], cache: null };\n picked.set(key, batch);\n }\n batch.indices.push(i);\n return;\n }\n const role = item.role ?? shape.role ?? \"feature\";\n const dim = isDimmed(item.id);\n const key = `${dim ? 1 : 0}|${role}|${kindName}`;\n let batch = normal.get(key);\n if (!batch) {\n batch = { key, shape, role, dim, indices: [], cache: null };\n normal.set(key, batch);\n }\n batch.indices.push(i);\n });\n const rings = [...picked.values()].map<Batch>((batch) => ({\n ...batch,\n key: `ring|${batch.key}`,\n shape: {\n paint: \"line\",\n size: 0,\n path: (x, y, u) => circlePath(x, y, (batch.shape.size + RING_GAP) * u),\n },\n cache: null,\n }));\n return { normal: [...normal.values()], picked: [...picked.values()], rings };\n }, [items, kind, shapes, selectedSet, isDimmed]);\n\n // The part of the scene to generate outlines for: everything for a small set, otherwise a\n // window around the viewport, snapped so panning rebuilds it once per half screen.\n const cull = cullWindow(stage.view, stage.box, items.length);\n const cullKey = cull ? `${cull.x}|${cull.y}|${cull.width}|${cull.height}` : \"\";\n\n // Each batch remembers the outline it last generated and what that was for, so this is\n // O(batches) on a render that changed neither the zoom nor the window (a hover, a pan).\n const build = (batches: Batch[]) => batches.map((batch) => ({ batch, d: batchPath(batch, items, unit, cull, cullKey) }));\n const paths = { normal: build(groups.normal), picked: build(groups.picked), rings: build(groups.rings) };\n\n const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : undefined;\n const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;\n const hoverShape = hoverItem ? (shapes[hoverItem.kind ?? kind] ?? MARKER_SHAPES.dot) : undefined;\n const hoverRole = hoverItem?.role ?? hoverShape?.role ?? \"feature\";\n\n // Labels: the spacing is a function of the zoom only, so panning does not reshuffle which\n // points carry one.\n const labelled = useMemo(() => {\n const list: number[] = [];\n items.forEach((item, i) => {\n if (item.label) list.push(i);\n });\n return list;\n }, [items]);\n const spacing = LABEL_SPACING * unit;\n const spaced = useMemo(\n () => (labels && labelled.length > 0 ? thinPoints(index.xy, spacing, labelled) : []),\n [labels, labelled, index, spacing],\n );\n const shownLabels = useMemo(() => {\n if (!labels || (spaced.length === 0 && !hoverItem?.label && selectedSet.size === 0)) return [];\n const view = visibleRect(stage.view, stage.box);\n const inView = (i: number) => {\n const item = items[i]!;\n return view === null || (item.x >= view.x && item.x <= view.x + view.width && item.y >= view.y && item.y <= view.y + view.height);\n };\n const shown = new Set<number>();\n const forced = [...(hoverItem ? [positionOf.get(hoverItem.id)!] : []), ...[...selectedSet].map((id) => positionOf.get(id) ?? -1)];\n for (const i of forced) {\n if (shown.size >= MAX_FORCED_LABELS) break;\n if (i >= 0 && items[i]!.label && inView(i)) shown.add(i);\n }\n for (const i of spaced) {\n if (shown.size >= MAX_LABELS) break;\n if (inView(i)) shown.add(i);\n }\n return [...shown];\n }, [labels, spaced, items, hoverItem, selectedSet, positionOf, stage.view, stage.box]);\n\n const widthOf = (shape: MarkerShape, role: OverlayRole, state: \"default\" | \"hover\" | \"selected\"): number => {\n const thin = role === \"model\" || role === \"structure\";\n const base = OVERLAY_STATE_WIDTH[state] - (thin && state !== \"selected\" ? 0.5 : 0);\n // A disc's size is its stroke width: grow the diameter by twice the state's extra width.\n return px(shape.paint === \"disc\" ? 2 * shape.size + (OVERLAY_STATE_WIDTH[state] - 1.5) * 2 : base);\n };\n const ringWidth = px(1.5);\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 role=\"img\"\n aria-label={`${label}: ${items.length} ${items.length === 1 ? \"point\" : \"points\"}, ${selectedSet.size} selected`}\n data-hovered={hoverId ?? undefined}\n >\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {halo &&\n paths.normal.map(({ batch, d }) => (\n <path\n key={`halo|${batch.key}`}\n d={d}\n stroke={HALO}\n strokeWidth={widthOf(batch.shape, batch.role, \"default\") + px(2)}\n opacity={0.6 * (batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1)}\n />\n ))}\n {paths.normal.map(({ batch, d }) => (\n <path\n key={batch.key}\n data-batch={batch.key}\n d={d}\n stroke={overlayRole(batch.role)}\n strokeWidth={widthOf(batch.shape, batch.role, \"default\")}\n opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : 1}\n />\n ))}\n {halo &&\n paths.picked.map(({ batch, d }) => (\n <path key={`halo|selected|${batch.key}`} d={d} stroke={HALO} strokeWidth={widthOf(batch.shape, batch.role, \"selected\") + px(2)} />\n ))}\n {halo &&\n paths.rings.map(({ batch, d }) => (\n <path key={`halo|${batch.key}`} d={d} stroke={HALO} strokeWidth={ringWidth + px(2)} />\n ))}\n {paths.picked.map(({ batch, d }) => (\n <path\n key={`selected|${batch.key}`}\n data-selected-points={batch.key}\n d={d}\n stroke={selectionStroke}\n strokeWidth={widthOf(batch.shape, batch.role, \"selected\")}\n />\n ))}\n {paths.rings.map(({ batch, d }) => (\n <path key={batch.key} data-selection-rings={batch.key} d={d} stroke={selectionStroke} strokeWidth={ringWidth} />\n ))}\n {hoverItem && hoverShape && (\n <>\n {halo && (\n <path\n d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}\n stroke={HALO}\n strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? \"selected\" : \"hover\") + px(2)}\n />\n )}\n <path\n data-hovered-point=\"\"\n d={hoverShape.path(hoverItem.x, hoverItem.y, unit, hoverItem.angle ?? 0)}\n stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}\n strokeWidth={widthOf(hoverShape, hoverRole, hoverSelected ? \"selected\" : \"hover\")}\n />\n </>\n )}\n </g>\n {shownLabels.length > 0 && (\n <g data-labels=\"\" fontSize={px(11)} className=\"font-mono\" stroke={HALO} strokeWidth={px(3)} paintOrder=\"stroke\" strokeLinejoin=\"round\">\n {shownLabels.map((i) => {\n const item = items[i]!;\n return (\n <text key={item.id} x={item.x + px(6)} y={item.y - px(5)} fill={LABEL} dominantBaseline=\"text-after-edge\">\n {item.label}\n </text>\n );\n })}\n </g>\n )}\n </svg>\n );\n}\n\n/**\n * The path data of a batch, generated again only when what it depends on changed: nothing\n * for a disc marker, the zoom and the window for an outline.\n */\nfunction batchPath(batch: Batch, items: readonly PointSetItem[], unit: number, cull: Rect | null, cullKey: string): string {\n const disc = batch.shape.paint === \"disc\";\n const key = disc ? \"\" : `${unit}|${cullKey}`;\n if (batch.cache?.key === key) return batch.cache.d;\n const window = disc ? null : cull;\n let d = \"\";\n for (const i of batch.indices) {\n const item = items[i]!;\n if (window && (item.x < window.x || item.x > window.x + window.width || item.y < window.y || item.y > window.y + window.height)) continue;\n d += batch.shape.path(item.x, item.y, unit, item.angle ?? 0);\n }\n batch.cache = { key, d };\n return d;\n}\n\n/** The image-space rectangle on screen, or `null` before the viewport is measured. */\nfunction visibleRect(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }): Rect | null {\n if (!(box.width > 0) || !(view.scale > 0)) return null;\n return { x: -view.tx / view.scale, y: -view.ty / view.scale, width: box.width / view.scale, height: box.height / view.scale };\n}\n\n/**\n * The window outlines are generated for: the viewport plus half a viewport on every side,\n * snapped outward to half-viewport steps. `null` for a small set, or an unmeasured stage.\n */\nfunction cullWindow(view: { scale: number; tx: number; ty: number }, box: { width: number; height: number }, count: number): Rect | null {\n if (count <= CULL_ABOVE) return null;\n const visible = visibleRect(view, box);\n if (visible === null) return null;\n const sx = visible.width / 2;\n const sy = visible.height / 2;\n const left = Math.floor((visible.x - sx) / sx) * sx;\n const top = Math.floor((visible.y - sy) / sy) * sy;\n const right = Math.ceil((visible.x + visible.width + sx) / sx) * sx;\n const bottom = Math.ceil((visible.y + visible.height + sy) / sy) * sy;\n return { x: left, y: top, width: right - left, height: bottom - top };\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,IAAI,SAAS,MAA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