@vitavision/stage2d 0.10.0 → 0.12.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 +12 -3
- package/dist/index.d.ts +437 -36
- package/dist/index.js +1406 -338
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/AreaSet.tsx +83 -52
- package/src/components/ContourEditor.tsx +12 -3
- package/src/components/DraftShape.tsx +56 -11
- package/src/components/EllipseSet.tsx +292 -0
- package/src/components/MaskEditor.tsx +22 -9
- package/src/components/PointSet.tsx +19 -9
- package/src/components/PolylineSet.tsx +56 -15
- package/src/components/RectRoiEditor.tsx +5 -4
- package/src/components/ShapeEditor.tsx +117 -37
- package/src/components/areaBatching.ts +111 -0
- package/src/components/areaIndex.ts +7 -4
- package/src/components/ellipseIndex.ts +279 -0
- package/src/components/markerShapes.ts +3 -1
- package/src/components/shapeEdit.ts +67 -1
- package/src/components/stage/ImageStage.tsx +250 -127
- package/src/components/stage/StageSurface.tsx +117 -17
- package/src/components/stage/gesture.ts +15 -0
- package/src/components/stage/touchWatch.ts +85 -0
- package/src/components/stage/useCoarsePointer.ts +30 -0
- package/src/components/stage/view.ts +88 -20
- package/src/index.ts +20 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["clamp","CLICK_SLOP","clamp","HANDLE_PX","STROKE_PX","HALO","fmt","HALO","MAX_CELLS","HALO","LABEL","HALO","HALO","STROKE_PX","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/labelLod.ts","../src/components/PointSet.tsx","../src/components/areaIndex.ts","../src/components/AreaSet.tsx","../src/components/gridEdges.ts","../src/components/GridLayer.tsx","../src/components/heatmapRaster.ts","../src/components/HeatmapLayer.tsx","../src/components/shapeEdit.ts","../src/components/ShapeEditor.tsx","../src/components/DraftShape.tsx","../src/components/useShapeDrag.ts","../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\n/** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */\nexport function 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). Shared with `areaIndex.ts`. */\nexport function 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 * Which labels a layer draws: the level-of-detail rule of the overlay grammar\n * (`docs/visual-language.md` §5), shared by `PointSet`, `AreaSet` and `GridLayer`.\n *\n * Labels are 11 px mono. They are shown only where their anchors are at least 24 screen\n * pixels apart (so a zoomed-out scene shows none and a zoomed-in one shows all), at most 200 at\n * a time, and only inside the viewport. The hovered and selected items always carry theirs.\n */\n\nimport { useMemo } from \"react\";\n\nimport { thinPoints } from \"./pointIndex\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport type { Rect } from \"./stage/view\";\n\n/** Labels need this much room between anchors, in screen pixels (overlay grammar §5). */\nexport const LABEL_SPACING = 24;\n/** The most label elements drawn at once. */\nexport const MAX_LABELS = 200;\n/** The most hovered-or-selected labels forced on regardless of spacing. */\nexport const MAX_FORCED_LABELS = 50;\n\n/** The image-space rectangle on screen, or `null` before the viewport is measured. */\nexport function 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 * Choose the labels to draw.\n *\n * @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).\n * @param forced - Anchors that always carry a label: the hovered and the selected.\n * @param inView - Whether an anchor is inside the viewport.\n * @returns The anchor indices to label: the forced ones first (at most 50), then the spaced\n * ones, 200 in all.\n */\nexport function pickLabelIndices(spaced: readonly number[], forced: readonly number[], inView: (index: number) => boolean): number[] {\n const shown = new Set<number>();\n for (const i of forced) {\n if (shown.size >= MAX_FORCED_LABELS) break;\n if (i >= 0 && 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}\n\n/** What `useLabelIndices` reads. */\nexport interface LabelAnchors {\n /** Whether labels are shown at all. */\n enabled: boolean;\n /** Flat `[x0, y0, x1, y1, …]` anchors, in image coordinates. */\n xy: ArrayLike<number>;\n /** The anchors that have a label, in priority order. Pass a stable array. */\n labelled: readonly number[];\n /** The anchors that must carry theirs (hovered, selected) and have one. Pass a stable array. */\n forced: readonly number[];\n}\n\n/**\n * The anchors to label at the stage's current zoom and viewport. The spacing depends on the\n * zoom only, so panning does not reshuffle which anchors carry a label.\n *\n * @param anchors - See `LabelAnchors`.\n * @returns Anchor indices.\n */\nexport function useLabelIndices({ enabled, xy, labelled, forced }: LabelAnchors): number[] {\n const stage = useStage();\n const unit = useScreenPx()(1);\n const spacing = LABEL_SPACING * unit;\n const spaced = useMemo(\n () => (enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : []),\n [enabled, labelled, xy, spacing],\n );\n return useMemo(() => {\n if (!enabled || (spaced.length === 0 && forced.length === 0)) return [];\n const view = visibleRect(stage.view, stage.box);\n const inView = (i: number) => {\n if (view === null) return true;\n const x = xy[2 * i]!;\n const y = xy[2 * i + 1]!;\n return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;\n };\n return pickLabelIndices(spaced, forced, inView);\n }, [enabled, spaced, forced, xy, stage.view, stage.box]);\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 { useLabelIndices, visibleRect } from \"./labelLod\";\nimport { buildPointIndexFrom, nearestPoint, 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/** 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 forced = useMemo(() => {\n const list: number[] = [];\n if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);\n for (const id of selectedSet) {\n const i = positionOf.get(id);\n if (i !== undefined && items[i]!.label) list.push(i);\n }\n return list;\n }, [hoverItem, selectedSet, positionOf, items]);\n const shownLabels = useLabelIndices({ enabled: labels, xy: index.xy, labelled, forced });\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/**\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","/**\n * A spatial index over many closed polygons: which one is under the pointer, and which ones a\n * rubber band touched.\n *\n * The same uniform grid as `polylineIndex.ts` and `pointIndex.ts` (CSR layout, built once per\n * change of the items), but over each polygon's bounding box: a query looks at the polygons\n * whose box is near the pointer and runs the exact tests (even-odd containment, distance to\n * the outline) on those few only. It imports neither React nor the DOM.\n *\n * Polygons are flat `[x0, y0, x1, y1, …]` rings in image coordinates, implicitly closed. A\n * ring with fewer than three vertices has no interior: it is still pickable along its outline\n * (a two-vertex ring is a segment, a one-vertex ring a point), but never \"inside\".\n */\n\nimport type { Point } from \"./measureGeometry\";\nimport { closestOnSegment, segmentTouchesRect } from \"./polylineIndex\";\nimport type { Rect } from \"./stage/view\";\n\n/** An area's identity. */\nexport type AreaId = string | number;\n\n/** One closed polygon. */\nexport interface Area {\n /** Its identity, unique in the set. */\n id: AreaId;\n /** `[x0, y0, x1, y1, …]` in image coordinates; the last vertex joins the first. */\n points: ArrayLike<number>;\n}\n\n/**\n * An index built by `buildAreaIndex`. Treat it as opaque and query it with `nearestArea` and\n * `areasInRect`; its layout may change.\n */\nexport interface AreaIndex {\n /** The areas, in the order given. */\n readonly items: readonly Area[];\n /** Per area, `[minX, minY, maxX, maxY]`; `NaN`s for an area with no finite vertex. */\n readonly bounds: Float64Array;\n /** Per area, its unsigned area (shoelace), used to prefer the smaller of nested areas. */\n readonly size: Float64Array;\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 `entries[starts[c] .. starts[c + 1]]`. */\n readonly starts: Uint32Array;\n /** Area indices by cell. */\n readonly entries: Uint32Array;\n}\n\n/** The area `nearestArea` picked. */\nexport interface AreaHit {\n /** Its id. */\n id: AreaId;\n /** Its position in the array the index was built from. */\n index: number;\n /** Whether the query is inside the polygon (even-odd rule). */\n inside: boolean;\n /** The distance from the query to the polygon's outline, in image pixels. */\n distance: number;\n}\n\n/** The most grid cells an index allocates, and the most area-to-cell entries. */\nconst MAX_CELLS = 4_000_000;\nconst MAX_ENTRIES = 8_000_000;\n\nfunction vertexCount(points: ArrayLike<number>): number {\n return Math.floor(points.length / 2);\n}\n\n/**\n * Whether `(x, y)` is inside the polygon, by the even-odd rule.\n *\n * @param points - Flat ring, implicitly closed.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns `false` for a ring with fewer than three vertices. A point exactly on the outline\n * may be either; `nearestArea` treats the outline separately.\n */\nexport function pointInPolygon(points: ArrayLike<number>, x: number, y: number): boolean {\n const n = vertexCount(points);\n if (n < 3) return false;\n let inside = false;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const xi = points[2 * i]!;\n const yi = points[2 * i + 1]!;\n const xj = points[2 * j]!;\n const yj = points[2 * j + 1]!;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n return inside;\n}\n\n/**\n * The distance from `(x, y)` to the outline of a polygon (its closing edge included).\n *\n * @param points - Flat ring, implicitly closed.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns The distance; `Infinity` for an empty ring.\n */\nexport function distanceToOutline(points: ArrayLike<number>, x: number, y: number): number {\n const n = vertexCount(points);\n if (n === 0) return Infinity;\n const p = { x, y };\n let best = Infinity;\n const edges = n === 1 ? 1 : n === 2 ? 1 : n;\n for (let i = 0; i < edges; i++) {\n const j = n === 1 ? 0 : (i + 1) % n;\n const q = closestOnSegment(p, points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!);\n const d = Math.hypot(q.x - x, q.y - y);\n if (d < best) best = d;\n }\n return best;\n}\n\n/**\n * The unsigned area of a polygon (shoelace).\n *\n * @param points - Flat ring, implicitly closed.\n * @returns The area; `0` for fewer than three vertices.\n */\nexport function polygonArea(points: ArrayLike<number>): number {\n const n = vertexCount(points);\n if (n < 3) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n sum += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;\n }\n return Math.abs(sum) / 2;\n}\n\n/**\n * A polygon as an SVG path (`M … L … Z`) from its first vertex, wound the same way whatever the\n * input's winding.\n * A batched path of overlapping polygons filled with the nonzero rule would otherwise cut a\n * hole where a clockwise ring overlaps an anticlockwise one.\n *\n * @param points - Flat ring.\n * @returns Path data; `\"\"` with no vertices.\n */\nexport function areaPath(points: ArrayLike<number>): string {\n const n = vertexCount(points);\n if (n === 0) return \"\";\n let signed = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) signed += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;\n const reversed = signed < 0;\n const at = (k: number) => (reversed ? (n - k) % n : k); // still starts at vertex 0\n let d = `M${points[2 * at(0)]} ${points[2 * at(0) + 1]}`;\n if (n === 1) return `${d}h0`;\n for (let k = 1; k < n; k++) d += `L${points[2 * at(k)]} ${points[2 * at(k) + 1]}`;\n return `${d}Z`;\n}\n\n/**\n * The centre a label is drawn at: the mean of the vertices.\n *\n * @param points - Flat ring.\n * @returns The mean, or `null` for an empty ring.\n */\nexport function areaCentre(points: ArrayLike<number>): Point | null {\n const n = vertexCount(points);\n if (n === 0) return null;\n let sx = 0;\n let sy = 0;\n for (let i = 0; i < n; i++) {\n sx += points[2 * i]!;\n sy += points[2 * i + 1]!;\n }\n return { x: sx / n, y: sy / n };\n}\n\n/**\n * Index a set of polygons.\n *\n * @param items - The polygons.\n * @param cell - The grid cell side in image pixels. Defaults to the median of the polygons'\n * larger bounding-box sides, within `[8, 256]`, doubled if the grid would be huge.\n * @returns The index.\n */\nexport function buildAreaIndex(items: readonly Area[], cell?: number): AreaIndex {\n const count = items.length;\n const bounds = new Float64Array(count * 4).fill(Number.NaN);\n const size = new Float64Array(count);\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n const sides: number[] = [];\n items.forEach((item, a) => {\n const p = item.points;\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (let i = 0; i + 1 < p.length; i += 2) {\n const x = p[i]!;\n const y = p[i + 1]!;\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n }\n if (!(x1 >= x0)) return;\n bounds[4 * a] = x0;\n bounds[4 * a + 1] = y0;\n bounds[4 * a + 2] = x1;\n bounds[4 * a + 3] = y1;\n size[a] = polygonArea(p);\n minX = Math.min(minX, x0);\n minY = Math.min(minY, y0);\n maxX = Math.max(maxX, x1);\n maxY = Math.max(maxY, y1);\n sides.push(Math.max(x1 - x0, y1 - y0));\n });\n if (sides.length === 0) {\n return { items, bounds, size, cell: 1, x0: 0, y0: 0, cols: 1, rows: 1, starts: new Uint32Array(2), entries: new Uint32Array(0) };\n }\n sides.sort((a, b) => a - b);\n let side = cell ?? Math.min(256, Math.max(8, sides[sides.length >> 1]!));\n const width = maxX - minX;\n const height = maxY - minY;\n const cellsAt = (s: number) => (Math.floor(width / s) + 1) * (Math.floor(height / s) + 1);\n const entriesAt = (s: number) => {\n let total = 0;\n for (let a = 0; a < count; a++) {\n if (Number.isNaN(bounds[4 * a]!)) continue;\n total += (Math.floor((bounds[4 * a + 2]! - bounds[4 * a]!) / s) + 1) * (Math.floor((bounds[4 * a + 3]! - bounds[4 * a + 1]!) / s) + 1);\n }\n return total;\n };\n // A pathological extent (one far outlier, a tiny `cell`) must not allocate a huge grid.\n while (cellsAt(side) > MAX_CELLS || entriesAt(side) > MAX_ENTRIES) side *= 2;\n const cols = Math.floor(width / side) + 1;\n const rows = Math.floor(height / side) + 1;\n const cellX = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / side)));\n const cellY = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / side)));\n\n // Two passes (count, then fill) into a CSR layout: no per-cell arrays.\n const starts = new Uint32Array(cols * rows + 1);\n const visit = (fn: (c: number, a: number) => void) => {\n for (let a = 0; a < count; a++) {\n if (Number.isNaN(bounds[4 * a]!)) continue;\n const cx0 = cellX(bounds[4 * a]!);\n const cx1 = cellX(bounds[4 * a + 2]!);\n const cy0 = cellY(bounds[4 * a + 1]!);\n const cy1 = cellY(bounds[4 * a + 3]!);\n for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, a);\n }\n };\n visit((c) => starts[c + 1]!++);\n for (let c = 0; c < cols * rows; c++) starts[c + 1]! += starts[c]!;\n const fill = starts.slice(0, cols * rows);\n const entries = new Uint32Array(starts[cols * rows]!);\n visit((c, a) => {\n entries[fill[c]!++] = a;\n });\n return { items, bounds, size, cell: side, x0: minX, y0: minY, cols, rows, starts, entries };\n}\n\n/** Visit each distinct area whose bounding box meets `[left, right] × [top, bottom]`, ascending by index. */\nfunction candidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {\n const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;\n if (entries.length === 0) return [];\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 seen = new Set<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 a = entries[k]!;\n if (seen.has(a)) continue;\n if (bounds[4 * a]! <= right && bounds[4 * a + 2]! >= left && bounds[4 * a + 1]! <= bottom && bounds[4 * a + 3]! >= top) seen.add(a);\n }\n }\n }\n return [...seen].sort((a, b) => a - b);\n}\n\n/**\n * The area under a point: one whose outline passes within `radius`, or else one that contains it.\n *\n * An outline is the more precise gesture, so it wins: among areas whose outline is within\n * `radius` the nearest is picked, and only without one the containing area. Ties (equal\n * distance, or several containing areas) go to the smaller area, so a quad drawn inside a\n * region is picked rather than the region, then to the earlier one. The result does not depend\n * on cell order.\n *\n * @param index - The index.\n * @param p - The query, in image coordinates.\n * @param radius - How far from an outline the query still picks it, in image pixels.\n * @returns The area, or `null`.\n */\nexport function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit | null {\n if (!(radius >= 0)) return null;\n const { items, size } = index;\n let edge: AreaHit | null = null;\n let inner: AreaHit | null = null;\n for (const a of candidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {\n const points = items[a]!.points;\n const distance = distanceToOutline(points, p.x, p.y);\n const inside = pointInPolygon(points, p.x, p.y);\n const hit: AreaHit = { id: items[a]!.id, index: a, inside, distance };\n if (distance <= radius) {\n if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;\n } else if (inside && (inner === null || size[a]! < size[inner.index]!)) {\n inner = hit;\n }\n }\n return edge ?? inner;\n}\n\n/**\n * The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole\n * rectangle lying inside the polygon.\n *\n * @param index - The index.\n * @param rect - The band, in image coordinates. A negative extent is read as the box between\n * its corners.\n * @returns Their ids, in the order the areas were given.\n */\nexport function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {\n const box = {\n x: Math.min(rect.x, rect.x + rect.width),\n y: Math.min(rect.y, rect.y + rect.height),\n width: Math.abs(rect.width),\n height: Math.abs(rect.height),\n };\n const out: AreaId[] = [];\n for (const a of candidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {\n if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);\n }\n return out;\n}\n\nfunction polygonTouchesRect(points: ArrayLike<number>, rect: Rect): boolean {\n const n = vertexCount(points);\n const right = rect.x + rect.width;\n const bottom = rect.y + rect.height;\n for (let i = 0; i < n; i++) {\n const x = points[2 * i]!;\n const y = points[2 * i + 1]!;\n if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;\n }\n const edges = n < 2 ? 0 : n === 2 ? 1 : n;\n for (let i = 0; i < edges; i++) {\n const j = (i + 1) % n;\n if (segmentTouchesRect(points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!, rect)) return true;\n }\n return pointInPolygon(points, rect.x, rect.y);\n}\n","/**\n * Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,\n * region annotations, defect outlines.\n *\n * Drawn as a handful of batched paths, one per (state, role), each outline with its 12 % fill\n * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the\n * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen\n * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.\n */\n\nimport { useMemo, useState } from \"react\";\n\nimport { areaCentre, areaPath, buildAreaIndex, nearestArea, type Area, type AreaId } from \"./areaIndex\";\nimport { useLabelIndices } from \"./labelLod\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\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 } from \"./stage/view\";\n\n/** One region of an `AreaSet`. */\nexport interface AreaSetItem extends Area {\n /** The overlay role it is painted in. Defaults to the layer's `role`. */\n role?: OverlayRole | undefined;\n /** Text drawn at its centre (the mean of its vertices), when the zoom leaves room. */\n label?: string | undefined;\n}\n\n/** Props of `AreaSet`. */\nexport interface AreaSetProps {\n /** The regions, as closed rings in image coordinates. */\n items: readonly AreaSetItem[];\n /** The role of an item that names none. Defaults to `\"feature\"`: they are detected regions. */\n role?: OverlayRole | undefined;\n /** The hovered id, when the app controls hover (a list beside the stage hovers regions too). */\n hoveredId?: AreaId | null | undefined;\n /** Called when the region under the pointer changes. `null` when it leaves every region. */\n onHoverChange?: ((id: AreaId | null) => void) | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour. */\n selectedIds?: Iterable<AreaId> | 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<AreaId> | ((id: AreaId) => boolean) | undefined;\n /**\n * A press landed on a region. Setting it makes the layer claim presses inside its regions,\n * so the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for\n * a touch tap), so `useShapeDrag` 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: AreaId, 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 /**\n * Tick the first vertex: a short line from vertex 0 towards the centre, so the orientation\n * of a marker quad reads (the overlay grammar's \"corner 0 ticked\"). Off by default.\n */\n firstVertexTick?: boolean | undefined;\n /** Draw the dark band under every outline. On by default; off for a fast, flat layer. */\n halo?: boolean | undefined;\n /** CSS colour of selected regions. 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.area`. */\n priority?: number | undefined;\n /** The layer's accessible name. Defaults to \"Areas\". */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\nconst LABEL = overlayRole(\"label\");\n/** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */\nconst FILL_OPACITY = 0.12;\n/** How long the first-vertex tick is, in screen pixels, at most. */\nconst TICK_PX = 8;\n\n/** The regions of one batched path. */\ninterface Batch {\n key: string;\n role: OverlayRole;\n dim: boolean;\n /** Item positions, ascending. */\n indices: number[];\n /** The outlines, concatenated. */\n d: string;\n}\n\n/**\n * A selectable set of closed regions inside an `ImageStage`.\n *\n * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default).\n * Rings are wound alike before they are batched, so overlapping regions never cut a hole in\n * each other.\n * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and\n * `structure`), hover 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every\n * outline has a halo. A region has no ring: its outline at 2.5 px is the mark.\n * - **Labels** at the centre of a region, only where regions are at least 24 screen px apart,\n * at most 200 at a time. The hovered and selected regions always carry theirs.\n * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of\n * an outline picks that region, else the smallest region containing the point. `onHoverChange`\n * and `onItemPress` here, and `useStageHitTest` for an app that arbitrates between layers.\n *\n * The SVG carries `data-hovered` (the hovered id).\n */\nexport function AreaSet({\n items,\n role = \"feature\",\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n labels = true,\n firstVertexTick = false,\n halo = true,\n selectionStroke = overlayRole(\"selection\"),\n layerId,\n priority = STAGE_HIT_PRIORITY.area,\n label = \"Areas\",\n}: AreaSetProps) {\n const stage = useStage();\n const px = useScreenPx();\n const unit = px(1);\n\n const index = useMemo(() => buildAreaIndex(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: AreaId) => 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<AreaId | null>(null);\n const hoverId = hoveredId !== undefined ? hoveredId : ownHover;\n\n useStageHitLayer({\n layerId,\n priority,\n pick: (point, radius) => {\n const hit = nearestArea(index, point, radius);\n return hit ? { id: hit.id, dist: hit.inside ? 0 : hit.distance } : null;\n },\n onHover: (id) => {\n setOwnHover(id);\n onHoverChange?.(id);\n },\n onPress: onItemPress ? (id, event) => onItemPress(id, event) : undefined,\n });\n\n // Regions 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: Batch = { key: \"selected\", role: \"selection\", dim: false, indices: [], d: \"\" };\n items.forEach((item, i) => {\n if (selectedSet.has(item.id)) {\n picked.indices.push(i);\n picked.d += areaPath(item.points);\n return;\n }\n const itemRole = item.role ?? role;\n const dim = isDimmed(item.id);\n const key = `${dim ? 1 : 0}|${itemRole}`;\n let batch = normal.get(key);\n if (!batch) {\n batch = { key, role: itemRole, dim, indices: [], d: \"\" };\n normal.set(key, batch);\n }\n batch.indices.push(i);\n batch.d += areaPath(item.points);\n });\n return { normal: [...normal.values()], picked: picked.indices.length > 0 ? picked : null };\n }, [items, role, selectedSet, isDimmed]);\n\n // The tick is a line a few screen pixels long, so it is the one thing here that follows\n // the zoom: regenerated per zoom step, in O(regions).\n const ticks = useMemo(() => {\n if (!firstVertexTick) return [];\n const batches = groups.picked ? [...groups.normal, groups.picked] : groups.normal;\n return batches.map((batch) => {\n let d = \"\";\n for (const i of batch.indices) d += tickPath(items[i]!.points, TICK_PX * unit);\n return { batch, d };\n });\n }, [firstVertexTick, groups, items, unit]);\n\n const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : undefined;\n const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;\n const hoverRole = hoverItem?.role ?? role;\n\n // Labels sit at the centre of a region; the layout is the shared level-of-detail rule.\n const anchors = useMemo(() => {\n const xy = new Float64Array(items.length * 2);\n const labelled: number[] = [];\n items.forEach((item, i) => {\n const c = areaCentre(item.points);\n xy[2 * i] = c?.x ?? Number.NaN;\n xy[2 * i + 1] = c?.y ?? Number.NaN;\n if (item.label) labelled.push(i);\n });\n return { xy, labelled };\n }, [items]);\n const forced = useMemo(() => {\n const list: number[] = [];\n if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);\n for (const id of selectedSet) {\n const i = positionOf.get(id);\n if (i !== undefined && items[i]!.label) list.push(i);\n }\n return list;\n }, [hoverItem, selectedSet, positionOf, items]);\n const shownLabels = useLabelIndices({ enabled: labels, xy: anchors.xy, labelled: anchors.labelled, forced });\n\n const widthOf = (itemRole: OverlayRole, state: \"default\" | \"hover\" | \"selected\"): number => {\n const thin = itemRole === \"model\" || itemRole === \"structure\";\n return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== \"selected\" ? 0.5 : 0));\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 role=\"img\"\n aria-label={`${label}: ${items.length} ${items.length === 1 ? \"area\" : \"areas\"}, ${selectedSet.size} selected`}\n data-hovered={hoverId ?? undefined}\n >\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {groups.normal.map((batch) => (\n <g key={batch.key} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && <path d={batch.d} stroke={HALO} strokeWidth={widthOf(batch.role, \"default\") + px(2)} opacity={0.6} />}\n <path\n data-batch={batch.key}\n d={batch.d}\n fill={overlayRole(batch.role)}\n fillOpacity={FILL_OPACITY}\n stroke={overlayRole(batch.role)}\n strokeWidth={widthOf(batch.role, \"default\")}\n />\n </g>\n ))}\n {groups.picked && (\n <>\n {halo && <path d={groups.picked.d} stroke={HALO} strokeWidth={widthOf(\"selection\", \"selected\") + px(2)} />}\n <path\n data-selected-areas=\"\"\n d={groups.picked.d}\n fill={selectionStroke}\n fillOpacity={FILL_OPACITY}\n stroke={selectionStroke}\n strokeWidth={widthOf(\"selection\", \"selected\")}\n />\n </>\n )}\n {hoverItem && (\n <>\n {halo && (\n <path d={areaPath(hoverItem.points)} stroke={HALO} strokeWidth={widthOf(hoverRole, hoverSelected ? \"selected\" : \"hover\") + px(2)} />\n )}\n <path\n data-hovered-area=\"\"\n d={areaPath(hoverItem.points)}\n stroke={hoverSelected ? selectionStroke : overlayRole(hoverRole)}\n strokeWidth={widthOf(hoverRole, hoverSelected ? \"selected\" : \"hover\")}\n />\n </>\n )}\n {ticks.map(({ batch, d }) => (\n <g key={`tick|${batch.key}`} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && <path d={d} stroke={HALO} strokeWidth={px(OVERLAY_STATE_WIDTH.selected + 2)} opacity={0.6} />}\n <path\n data-ticks={batch.key}\n d={d}\n stroke={batch === groups.picked ? selectionStroke : overlayRole(batch.role)}\n strokeWidth={px(OVERLAY_STATE_WIDTH.selected)}\n />\n </g>\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 <text key={items[i]!.id} x={anchors.xy[2 * i]} y={anchors.xy[2 * i + 1]} fill={LABEL} textAnchor=\"middle\" dominantBaseline=\"central\">\n {items[i]!.label}\n </text>\n ))}\n </g>\n )}\n </svg>\n );\n}\n\n/**\n * The first-vertex tick of a ring: a segment from vertex 0 towards the ring's centre, at most\n * `length` long and at most 45 % of the way there, so a small quad's tick stays inside it.\n */\nfunction tickPath(points: ArrayLike<number>, length: number): string {\n const c = areaCentre(points);\n if (c === null || points.length < 4) return \"\";\n const x = points[0]!;\n const y = points[1]!;\n const dist = Math.hypot(c.x - x, c.y - y);\n if (!(dist > 0)) return \"\";\n const k = Math.min(length, 0.45 * dist) / dist;\n return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1000) / 1000} ${Math.round((y + (c.y - y) * k) * 1000) / 1000}`;\n}\n","/**\n * The edges of a detected lattice: which nodes are neighbours.\n *\n * A calibration detector returns its corners with integer lattice indices `(i, j)` and gaps\n * where a corner was not found. The edges are not data: node `(i, j)` is joined to\n * `(i + 1, j)` and to `(i, j + 1)` when both exist. This module computes them in O(n) with a\n * hash of the indices. It imports neither React nor the DOM.\n */\n\n/** What `latticeEdges` reads from each node. */\nexport interface LatticeNode {\n /** The lattice index along the first axis. A non-integer index is not part of the lattice. */\n i: number;\n /** The lattice index along the second axis. A non-integer index is not part of the lattice. */\n j: number;\n}\n\n/** The lattice axis an edge runs along: `\"i\"` joins `(i, j)` to `(i + 1, j)`, `\"j\"` joins `(i, j)` to `(i, j + 1)`. */\nexport type LatticeAxis = \"i\" | \"j\";\n\n/** An edge between two neighbouring nodes. */\nexport interface LatticeEdge {\n /** Position in the node array of the end with the lower index along `axis`. */\n a: number;\n /** Position in the node array of the end with the higher index along `axis`. */\n b: number;\n /** The axis it runs along. */\n axis: LatticeAxis;\n}\n\n/** Indices past this magnitude are not hashed (the key must stay an exact integer). */\nconst LIMIT = 2 ** 25;\n\nfunction key(i: number, j: number): number {\n return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);\n}\n\n/**\n * The edges of a lattice: every pair of nodes whose indices differ by one along exactly one\n * axis.\n *\n * @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an\n * integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the\n * first one is the lattice's node there.\n * @returns The edges, ordered by the position of `a`, then `\"i\"` before `\"j\"`.\n */\nexport function latticeEdges(nodes: ArrayLike<LatticeNode>): LatticeEdge[] {\n const at = new Map<number, number>();\n const valid = (n: LatticeNode) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;\n for (let p = 0; p < nodes.length; p++) {\n const node = nodes[p]!;\n if (!valid(node)) continue;\n const k = key(node.i, node.j);\n if (!at.has(k)) at.set(k, p);\n }\n const edges: LatticeEdge[] = [];\n for (let p = 0; p < nodes.length; p++) {\n const node = nodes[p]!;\n if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;\n if (node.i + 1 < LIMIT) {\n const q = at.get(key(node.i + 1, node.j));\n if (q !== undefined) edges.push({ a: p, b: q, axis: \"i\" });\n }\n if (node.j + 1 < LIMIT) {\n const q = at.get(key(node.i, node.j + 1));\n if (q !== undefined) edges.push({ a: p, b: q, axis: \"j\" });\n }\n }\n return edges;\n}\n","/**\n * A detected lattice over the image: the corners of a calibration board with the row and\n * column edges between neighbours, and optional `(i, j)` labels.\n *\n * Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of\n * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1\n * and 4). Edges are not picked: a person points at a corner.\n */\n\nimport { useMemo } from \"react\";\n\nimport { latticeEdges, type LatticeAxis } from \"./gridEdges\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\nimport { PointSet, type PointSetItem } from \"./PointSet\";\nimport type { MarkerShape } from \"./markerShapes\";\nimport type { PointId } from \"./pointIndex\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { StagePointerEvent } from \"./stage/hitContext\";\nimport { STAGE_HIT_PRIORITY } from \"./stage/hitTest\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox } from \"./stage/view\";\n\n/** One node of a `GridLayer`: a point with its lattice index. */\nexport interface GridNode extends PointSetItem {\n /** The lattice index along the first axis. */\n i: number;\n /** The lattice index along the second axis. */\n j: number;\n}\n\n/** How the edges along one lattice axis are drawn. */\nexport interface GridEdgeStyle {\n /** The overlay role of the edges. Defaults to `\"structure\"`: they are context. */\n role?: OverlayRole | undefined;\n /** Draw them dashed (4 3 screen px), so the two axes differ by more than colour. */\n dashed?: boolean | undefined;\n /** Draw them at all. Defaults to `true`. */\n visible?: boolean | undefined;\n}\n\n/** Props of `GridLayer`. */\nexport interface GridLayerProps {\n /** The nodes, in image coordinates, with their lattice indices. Gaps are allowed. */\n nodes: readonly GridNode[];\n /**\n * How edges are drawn, by axis: `i` joins `(i, j)` to `(i + 1, j)` (the rows, when `i`\n * counts columns), `j` joins `(i, j)` to `(i, j + 1)`. Both are solid `structure` by default.\n */\n edges?: { i?: GridEdgeStyle | undefined; j?: GridEdgeStyle | undefined } | undefined;\n /** The marker kind of a node that names none. Defaults to `\"plus\"`: a corner. */\n kind?: string | undefined;\n /** More marker kinds, or replacements for built-in ones, by name; see `PointSet`. */\n markers?: Readonly<Record<string, MarkerShape>> | undefined;\n /**\n * Label every node without a `label` of its own with its lattice index, `i,j`, where the\n * zoom leaves room (nodes at least 24 screen px apart). Off by default.\n */\n indexLabels?: boolean | undefined;\n /** Show the nodes' labels where the zoom leaves room for them. On by default. */\n labels?: boolean | undefined;\n /** The hovered node id, when the app controls hover. */\n hoveredId?: PointId | null | undefined;\n /** Called when the node under the pointer changes. `null` when it leaves every node. */\n onHoverChange?: ((id: PointId | null) => void) | undefined;\n /** The selected node ids, drawn at 2.5 px in the selection colour with a ring. */\n selectedIds?: Iterable<PointId> | undefined;\n /**\n * Node ids drawn at 35 % opacity, as a set or a predicate. An edge is dimmed when both its\n * nodes are. Pass a stable value: a new one re-batches the layer.\n */\n dimmed?: Iterable<PointId> | ((id: PointId) => boolean) | undefined;\n /** A press landed on a node; see `PointSet`. Setting it makes the layer claim presses on its nodes. */\n onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | 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 nodes and rings. Defaults to the overlay `selection` role. */\n selectionStroke?: string | undefined;\n /** The id hit-tests report for the nodes. 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 \"Grid\". */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n\n/** A style with its defaults filled in. */\nfunction edgeStyle(style: GridEdgeStyle | undefined): { role: OverlayRole; dashed: boolean; visible: boolean } {\n return { role: style?.role ?? \"structure\", dashed: style?.dashed ?? false, visible: style?.visible ?? true };\n}\n\n/** One batched path of edges. */\ninterface EdgeBatch {\n key: string;\n axis: LatticeAxis;\n dim: boolean;\n d: string;\n}\n\n/**\n * A detected lattice inside an `ImageStage`.\n *\n * - **Nodes** are a `PointSet`: `plus` markers by default, picked through the point index at\n * point priority, with `onHoverChange`, `onItemPress`, selection (with ring) and dimming.\n * - **Edges** join `(i, j)` to `(i + 1, j)` and to `(i, j + 1)` where both nodes exist\n * (`latticeEdges`), in one path per axis and dimming, below the nodes. They are `structure`\n * role by default, 1 screen px with a halo; `edges` restyles each axis.\n * - **Labels** are the nodes' own `label`s, or with `indexLabels` their `i,j`, only where nodes\n * are at least 24 screen px apart.\n *\n * The edges' SVG carries `data-edges`; the nodes' is the `PointSet`'s.\n */\nexport function GridLayer({\n nodes,\n edges,\n kind = \"plus\",\n markers,\n indexLabels = false,\n labels = true,\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n halo = true,\n selectionStroke,\n layerId,\n priority = STAGE_HIT_PRIORITY.point,\n label = \"Grid\",\n}: GridLayerProps) {\n const stage = useStage();\n const px = useScreenPx();\n\n const styles = { i: edgeStyle(edges?.i), j: edgeStyle(edges?.j) };\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\n const batches = useMemo(() => {\n const map = new Map<string, EdgeBatch>();\n for (const edge of latticeEdges(nodes)) {\n const a = nodes[edge.a]!;\n const b = nodes[edge.b]!;\n if (!Number.isFinite(a.x + a.y + b.x + b.y)) continue;\n const dim = isDimmed(a.id) && isDimmed(b.id);\n const k = `${edge.axis}|${dim ? 1 : 0}`;\n let batch = map.get(k);\n if (!batch) {\n batch = { key: k, axis: edge.axis, dim, d: \"\" };\n map.set(k, batch);\n }\n batch.d += `M${a.x} ${a.y}L${b.x} ${b.y}`;\n }\n return [...map.values()];\n }, [nodes, isDimmed]);\n\n // Without `indexLabels` the nodes go through as they are, so the PointSet's index is not rebuilt.\n const items = useMemo<readonly PointSetItem[]>(\n () => (indexLabels ? nodes.map((node) => (node.label ? node : { ...node, label: `${node.i},${node.j}` })) : nodes),\n [nodes, indexLabels],\n );\n\n return (\n <>\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n data-edges=\"\"\n aria-hidden\n >\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {batches\n .filter((batch) => styles[batch.axis].visible)\n .map((batch) => {\n const style = styles[batch.axis];\n const thin = style.role === \"model\" || style.role === \"structure\";\n const width = px(OVERLAY_STATE_WIDTH.default - (thin ? 0.5 : 0));\n const dash = style.dashed ? `${px(4)} ${px(3)}` : undefined;\n return (\n <g key={batch.key} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && <path d={batch.d} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}\n <path data-edge-batch={batch.key} d={batch.d} stroke={overlayRole(style.role)} strokeWidth={width} strokeDasharray={dash} />\n </g>\n );\n })}\n </g>\n </svg>\n <PointSet\n items={items}\n kind={kind}\n markers={markers}\n hoveredId={hoveredId}\n onHoverChange={onHoverChange}\n selectedIds={selectedIds}\n dimmed={dimmed}\n onItemPress={onItemPress}\n labels={labels}\n halo={halo}\n selectionStroke={selectionStroke}\n layerId={layerId}\n priority={priority}\n label={label}\n />\n </>\n );\n}\n","/**\n * Scalar field to pixels: the colourising step of `HeatmapLayer`, pure so the cases that bite\n * (NaN holes, a flat field, a value outside the range) are tested without a canvas.\n */\n\nimport type { ValuePlane } from \"../api/mapValues\";\n\n/**\n * A sequential colour map: a position in `[0, 1]` to an `[r, g, b]` colour, each channel\n * 0 to 255. `@vitavision/charts`' `colormapRgb(name, t)` is one: `(t) => colormapRgb(\"viridis\", t)`.\n */\nexport type Colormap = (t: number) => readonly [number, number, number];\n\n/** A range of values mapped onto the colour map: `low` to its start, `high` to its end. */\nexport interface ValueRange {\n /** The value drawn in the map's first colour. */\n low: number;\n /** The value drawn in the map's last colour. */\n high: number;\n}\n\n/** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */\nconst STEPS = 256;\n\n/**\n * The extent of a plane's finite values.\n *\n * @param plane - The plane.\n * @param channel - Which of its channels. Defaults to the first.\n * @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.\n */\nexport function planeRange(plane: ValuePlane, channel = 0): ValueRange | null {\n if (!(channel >= 0 && channel < plane.channels)) return null;\n const size = plane.width * plane.height;\n const offset = channel * size;\n let low = Infinity;\n let high = -Infinity;\n for (let k = 0; k < size; k++) {\n const v = plane.values[offset + k]!;\n if (!Number.isFinite(v)) continue;\n if (v < low) low = v;\n if (v > high) high = v;\n }\n return low <= high ? { low, high } : null;\n}\n\n/**\n * Colour a plane through a colour map.\n *\n * Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered\n * pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range\n * (`high <= low`) draws every pixel in the map's first colour.\n *\n * @param plane - The plane.\n * @param colormap - The colour map; sampled at 256 positions.\n * @param range - What the map spans. Defaults to the extent of the channel's finite values.\n * @param channel - Which channel to draw. Defaults to the first.\n * @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.\n */\nexport function rasterizePlane(plane: ValuePlane, colormap: Colormap, range?: ValueRange, channel = 0): Uint8ClampedArray {\n const size = plane.width * plane.height;\n const out = new Uint8ClampedArray(size * 4);\n if (!(channel >= 0 && channel < plane.channels)) return out;\n const { low, high } = range ?? planeRange(plane, channel) ?? { low: 0, high: 0 };\n const lut = new Uint8ClampedArray(STEPS * 3);\n for (let s = 0; s < STEPS; s++) {\n const [r, g, b] = colormap(s / (STEPS - 1));\n lut[3 * s] = r;\n lut[3 * s + 1] = g;\n lut[3 * s + 2] = b;\n }\n const scale = high > low ? (STEPS - 1) / (high - low) : 0;\n const offset = channel * size;\n for (let k = 0; k < size; k++) {\n const v = plane.values[offset + k]!;\n if (!Number.isFinite(v)) continue;\n const s = Math.min(STEPS - 1, Math.max(0, Math.round((v - low) * scale)));\n out[4 * k] = lut[3 * s]!;\n out[4 * k + 1] = lut[3 * s + 1]!;\n out[4 * k + 2] = lut[3 * s + 2]!;\n out[4 * k + 3] = 255;\n }\n return out;\n}\n","/**\n * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.\n *\n * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an\n * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage\n * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel\n * map costs one element. It takes no pointer events; to read the numbers under the pointer, use\n * `valueAt` on the plane.\n */\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\nimport type { ValuePlane } from \"../api/mapValues\";\nimport { rasterizePlane, type Colormap, type ValueRange } from \"./heatmapRaster\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { PIXEL_CENTRE, type Rect } from \"./stage/view\";\n\n/** What every `HeatmapLayer` takes. */\nexport interface HeatmapLayerBaseProps {\n /** How opaque the heatmap is, 0 to 1. Defaults to `1`. */\n opacity?: number | undefined;\n /** Draw it. Defaults to `true`. While `false` nothing is rasterised. */\n visible?: boolean | undefined;\n /**\n * Where the raster is placed, in image coordinates: `x` and `y` the top-left edge of its\n * first pixel's footprint (`-0.5, -0.5` is the image's own top-left corner), `width` and `height`\n * the extent it is stretched over. Defaults to the whole image, so a raster of any\n * resolution covers it 1:1 in position.\n */\n rect?: Rect | undefined;\n /** The zoom (CSS pixels per heatmap pixel) from which heatmap pixels are drawn as blocks. Defaults to 4. */\n pixelatedAbove?: number | undefined;\n /** A description for assistive technology. Defaults to `\"\"`: decorative, as the legend carries the meaning. */\n alt?: string | undefined;\n /** Called once the raster is on screen (and again for each new one). */\n onReady?: (() => void) | undefined;\n /** Called when the raster could not be made: a canvas that could not be allocated, or an `rgba` buffer too short for its size. */\n onError?: (() => void) | undefined;\n /** Merged onto the image with `cn`. */\n className?: string | undefined;\n}\n\n/** A heatmap from pixels that are already coloured. */\nexport interface HeatmapRgbaProps extends HeatmapLayerBaseProps {\n /** Row-major RGBA, `width · height · 4` bytes. A `Uint8Array` is read in place, not copied. */\n rgba: Uint8ClampedArray | Uint8Array;\n /** The raster's width in pixels. */\n width: number;\n /** The raster's height in pixels. */\n height: number;\n /** Not used with `rgba`. */\n plane?: undefined;\n /** Not used with `rgba`. */\n colormap?: undefined;\n /** Not used with `rgba`. */\n range?: undefined;\n /** Not used with `rgba`. */\n channel?: undefined;\n}\n\n/** A heatmap from a scalar field and a colour map. */\nexport interface HeatmapPlaneProps extends HeatmapLayerBaseProps {\n /** The field, as decoded by `decodePlane`. */\n plane: ValuePlane;\n /**\n * The colour map. `NaN` pixels stay transparent. Pass a stable function: a new one\n * re-rasterises the heatmap. `@vitavision/charts`' `(t) => colormapRgb(\"viridis\", t)` is one.\n */\n colormap: Colormap;\n /** What the map spans. Defaults to the extent of the channel's finite values. */\n range?: ValueRange | undefined;\n /** Which channel of the plane to draw. Defaults to the first. */\n channel?: number | undefined;\n /** Not used with `plane`. */\n rgba?: undefined;\n /** Not used with `plane`. */\n width?: undefined;\n /** Not used with `plane`. */\n height?: undefined;\n}\n\n/** Props of `HeatmapLayer`: pre-coloured `rgba` pixels, or a `plane` with a `colormap`. */\nexport type HeatmapLayerProps = HeatmapRgbaProps | HeatmapPlaneProps;\n\n/** A raster on screen and the object URL it came from. */\ninterface Raster {\n url: string;\n width: number;\n height: number;\n}\n\n/**\n * A heatmap inside an `ImageStage`: a scalar field coloured through a colour map, or an RGBA\n * buffer, placed over the image (default) or any rectangle of it.\n *\n * - **Rasterised in an effect**, once per change of its data, into an offscreen canvas and an\n * object URL that is revoked when replaced and on unmount. Server rendering draws nothing.\n * - **Pixelated** from 4 CSS pixels per heatmap pixel, like `ImageLayer`, so the cells of a\n * coarse map are not smoothed into a blur.\n * - **Stacking:** it is drawn where it is placed among the stage's children. Before the\n * overlays it sits under them; the image layer goes before it.\n * - **Input:** none. It takes no pointer events, so presses reach the layers above and the stage.\n *\n * The image carries `data-heatmap`, `data-pixelated` while pixelated, and `data-ready`.\n */\nexport function HeatmapLayer(props: HeatmapLayerProps) {\n const { opacity = 1, visible = true, rect, pixelatedAbove = 4, alt = \"\", onReady, onError, className } = props;\n const stage = useStage();\n const [raster, setRaster] = useState<Raster | null>(null);\n const [ready, setReady] = useState(false);\n const urlRef = useRef<string | null>(null);\n const callbacksRef = useRef({ onReady, onError });\n useEffect(() => {\n callbacksRef.current = { onReady, onError };\n });\n\n // The inputs that change what is drawn, spelled out so the effect re-runs on exactly those.\n const { rgba, width, height, plane, colormap, channel } = props;\n const rangeLow = props.range?.low;\n const rangeHigh = props.range?.high;\n\n useEffect(() => {\n if (!visible) return;\n let cancelled = false;\n const range = rangeLow === undefined || rangeHigh === undefined ? undefined : { low: rangeLow, high: rangeHigh };\n const source = rgba ? wrapRgba(rgba, width, height) : plane && colormap ? colourPlane(plane, colormap, range, channel) : null;\n const canvas = document.createElement(\"canvas\");\n const context = source ? ((canvas.width = source.width), (canvas.height = source.height), canvas.getContext(\"2d\")) : null;\n if (!source || !context) {\n callbacksRef.current.onError?.();\n return;\n }\n const { width: w, height: h } = source;\n context.putImageData(new ImageData(source.pixels, w, h), 0, 0);\n canvas.toBlob((blob) => {\n if (cancelled) return;\n if (!blob) {\n callbacksRef.current.onError?.();\n return;\n }\n const previous = urlRef.current;\n const url = URL.createObjectURL(blob);\n urlRef.current = url;\n setReady(false);\n setRaster({ url, width: w, height: h });\n // The old image is replaced in this commit; the browser has already decoded it.\n if (previous) URL.revokeObjectURL(previous);\n });\n return () => {\n cancelled = true;\n };\n }, [visible, rgba, width, height, plane, colormap, rangeLow, rangeHigh, channel]);\n\n useEffect(\n () => () => {\n if (urlRef.current) URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n },\n [],\n );\n\n if (!visible || raster === null) return null;\n const box = rect ?? { x: -PIXEL_CENTRE, y: -PIXEL_CENTRE, width: stage.image.width, height: stage.image.height };\n const pixelated = (stage.view.scale * box.width) / raster.width >= pixelatedAbove;\n return (\n <img\n src={raster.url}\n alt={alt}\n draggable={false}\n data-heatmap=\"\"\n data-ready={ready ? \"\" : undefined}\n data-pixelated={pixelated ? \"\" : undefined}\n onLoad={() => {\n setReady(true);\n callbacksRef.current.onReady?.();\n }}\n className={cn(\"pointer-events-none absolute max-w-none select-none\", className)}\n style={{\n left: box.x + PIXEL_CENTRE,\n top: box.y + PIXEL_CENTRE,\n width: box.width,\n height: box.height,\n opacity,\n pointerEvents: \"none\",\n imageRendering: pixelated ? \"pixelated\" : undefined,\n }}\n />\n );\n}\n\n/** Pixels to draw, and their size. */\ninterface Pixels {\n pixels: Uint8ClampedArray<ArrayBuffer>;\n width: number;\n height: number;\n}\n\n/** The first `width · height · 4` bytes of an RGBA buffer, read in place; `null` if it is too short or empty. */\nfunction wrapRgba(rgba: Uint8ClampedArray | Uint8Array, width: number, height: number): Pixels | null {\n const length = width * height * 4;\n if (!(length > 0) || rgba.length < length) return null;\n return { pixels: new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, length), width, height };\n}\n\n/** A plane through a colour map; `null` for an empty plane. */\nfunction colourPlane(plane: ValuePlane, colormap: Colormap, range: ValueRange | undefined, channel: number | undefined): Pixels | null {\n if (!(plane.width > 0 && plane.height > 0)) return null;\n const pixels = rasterizePlane(plane, colormap, range, channel) as Uint8ClampedArray<ArrayBuffer>;\n return { pixels, width: plane.width, height: plane.height };\n}\n","/**\n * The arithmetic of editing a rotated rectangle or ellipse: eight handles, a rotation handle\n * and an interior.\n *\n * A shape is its centre, its size and a rotation, so a resize can be done in the shape's own\n * frame (where its sides are axis-aligned) and the opposite edge stays put whatever the\n * rotation. Kept pure, so the cases that bite are tested without a pointer:\n * - a handle dragged across the shape, or to a point far away;\n * - a shape collapsed below the minimum size;\n * - a rotation about the centre and not about a corner.\n *\n * Everything is in the stage's image coordinates. **Rotation is in radians, positive\n * clockwise on screen** (image `y` points down), zero when the shape's width runs along `x`.\n * A degrees-clockwise value, such as Konva's `rotation`, is `degrees * Math.PI / 180`.\n */\n\nimport type { Point } from \"./measureGeometry\";\nimport type { RoiHandle } from \"./roiEdit\";\n\n/** A rotated rectangle, or the ellipse inscribed in one. */\nexport interface RotatedShape {\n /** Centre x, in image coordinates. */\n cx: number;\n /** Centre y, in image coordinates. */\n cy: number;\n /** Extent along the shape's own x axis: a rectangle's width, an ellipse's full axis `2·rx`. */\n width: number;\n /** Extent along the shape's own y axis: a rectangle's height, an ellipse's full axis `2·ry`. */\n height: number;\n /** Radians, clockwise on screen: the turn from the image's x axis to the shape's own. */\n rotation: number;\n}\n\n/**\n * A point of image space in the shape's own frame: origin at its centre, axes along its sides.\n *\n * @param shape - The shape.\n * @param p - A point in image coordinates.\n * @returns The point relative to the shape.\n */\nexport function toShapeFrame(shape: RotatedShape, p: Point): Point {\n const c = Math.cos(shape.rotation);\n const s = Math.sin(shape.rotation);\n const dx = p.x - shape.cx;\n const dy = p.y - shape.cy;\n return { x: c * dx + s * dy, y: -s * dx + c * dy };\n}\n\n/**\n * A point of the shape's own frame in image space; the inverse of `toShapeFrame`.\n *\n * @param shape - The shape.\n * @param p - A point relative to the shape.\n * @returns The point in image coordinates.\n */\nexport function fromShapeFrame(shape: RotatedShape, p: Point): Point {\n const c = Math.cos(shape.rotation);\n const s = Math.sin(shape.rotation);\n return { x: shape.cx + c * p.x - s * p.y, y: shape.cy + s * p.x + c * p.y };\n}\n\n/** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */\nfunction handleDirection(handle: RoiHandle): Point {\n return { x: handle.includes(\"e\") ? 1 : handle.includes(\"w\") ? -1 : 0, y: handle.includes(\"s\") ? 1 : handle.includes(\"n\") ? -1 : 0 };\n}\n\n/**\n * Where a handle sits: a corner or the middle of a side, turned with the shape.\n *\n * @param shape - The shape.\n * @param handle - The handle, by compass direction in the shape's own frame.\n * @returns The handle's centre, in image coordinates.\n */\nexport function shapeHandlePoint(shape: RotatedShape, handle: RoiHandle): Point {\n const d = handleDirection(handle);\n return fromShapeFrame(shape, { x: (d.x * shape.width) / 2, y: (d.y * shape.height) / 2 });\n}\n\n/**\n * Where the rotation handle sits: beyond the middle of the top side, along the shape's own\n * up direction.\n *\n * @param shape - The shape.\n * @param distance - How far past the top side, in image pixels. For a screen-constant handle,\n * pass `useScreenPx()(css)`.\n * @returns The handle's centre, in image coordinates.\n */\nexport function rotationHandlePoint(shape: RotatedShape, distance: number): Point {\n return fromShapeFrame(shape, { x: 0, y: -shape.height / 2 - distance });\n}\n\n/**\n * Drag a handle to `to`.\n *\n * The dragged side or corner follows the pointer in the shape's own frame and the opposite\n * side or corner stays where it is in the image, which is what makes a handle feel attached.\n * The shape does not flip when dragged through the opposite side: it stops at `minSize`.\n *\n * @param shape - The shape before the drag.\n * @param handle - The handle being dragged.\n * @param to - The pointer, in image coordinates.\n * @param minSize - The smallest extent on either axis, in image pixels.\n * @returns The resized shape: the same rotation, and the opposite side or corner unmoved.\n */\nexport function resizeShape(shape: RotatedShape, handle: RoiHandle, to: Point, minSize: number): RotatedShape {\n const d = handleDirection(handle);\n const u = toShapeFrame(shape, to);\n let width = shape.width;\n let height = shape.height;\n let x = 0;\n let y = 0;\n if (d.x !== 0) {\n // The fixed side is at `-d.x · width / 2`; the new extent runs from it to the pointer.\n width = Math.max(minSize, d.x * u.x + shape.width / 2);\n x = -d.x * (shape.width / 2) + (d.x * width) / 2;\n }\n if (d.y !== 0) {\n height = Math.max(minSize, d.y * u.y + shape.height / 2);\n y = -d.y * (shape.height / 2) + (d.y * height) / 2;\n }\n const centre = fromShapeFrame(shape, { x, y });\n return { cx: centre.x, cy: centre.y, width, height, rotation: shape.rotation };\n}\n\n/**\n * Turn the shape about its centre so that its rotation handle points at `to`.\n *\n * @param shape - The shape before the drag.\n * @param to - The pointer, in image coordinates.\n * @param snap - Round the rotation to a multiple of this many radians (Shift while dragging\n * rounds to 15°). Defaults to no rounding.\n * @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.\n */\nexport function rotateShape(shape: RotatedShape, to: Point, snap = 0): RotatedShape {\n // The handle sits along the shape's own up direction, which is at angle `rotation - π/2`.\n let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;\n if (snap > 0) rotation = Math.round(rotation / snap) * snap;\n return { ...shape, rotation: normalizeAngle(rotation) };\n}\n\n/**\n * Move the shape.\n *\n * @param shape - The shape.\n * @param dx - Horizontal shift, in image pixels.\n * @param dy - Vertical shift, in image pixels.\n * @returns The moved shape.\n */\nexport function moveShape(shape: RotatedShape, dx: number, dy: number): RotatedShape {\n return { ...shape, cx: shape.cx + dx, cy: shape.cy + dy };\n}\n\n/**\n * An angle as the equivalent one in `(-π, π]`.\n *\n * @param angle - Radians.\n * @returns The angle in `(-π, π]`.\n */\nexport function normalizeAngle(angle: number): number {\n const turn = 2 * Math.PI;\n let a = angle % turn;\n if (a > Math.PI) a -= turn;\n else if (a <= -Math.PI) a += turn;\n return a;\n}\n\n/**\n * The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize\n * cursors to the handle's direction on screen.\n *\n * @param handle - The handle.\n * @param rotation - The shape's rotation, in radians.\n * @returns A CSS `cursor` value.\n */\nexport function shapeHandleCursor(handle: RoiHandle, rotation: number): string {\n const d = handleDirection(handle);\n const angle = Math.atan2(d.y, d.x) + rotation;\n const half = ((angle % Math.PI) + Math.PI) % Math.PI;\n return [\"ew-resize\", \"nwse-resize\", \"ns-resize\", \"nesw-resize\"][Math.round(half / (Math.PI / 4)) % 4]!;\n}\n\n/**\n * The shape for a rectangle given as an origin corner, a size and a rotation about that\n * corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.\n *\n * @param corner - The corner the rotation is about, in image coordinates.\n * @param width - Extent along the rotated x axis.\n * @param height - Extent along the rotated y axis.\n * @param rotation - Radians, clockwise on screen.\n * @returns The same rectangle as a `RotatedShape`.\n */\nexport function shapeFromCorner(corner: Point, width: number, height: number, rotation: number): RotatedShape {\n const c = Math.cos(rotation);\n const s = Math.sin(rotation);\n return {\n cx: corner.x + (c * width - s * height) / 2,\n cy: corner.y + (s * width + c * height) / 2,\n width,\n height,\n rotation,\n };\n}\n\n/**\n * The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;\n * the inverse of `shapeFromCorner`.\n *\n * @param shape - The shape.\n * @returns The corner, in image coordinates.\n */\nexport function shapeCorner(shape: RotatedShape): Point {\n return fromShapeFrame(shape, { x: -shape.width / 2, y: -shape.height / 2 });\n}\n\n/**\n * Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).\n *\n * @param a - A shape, or `null`.\n * @param b - A shape, or `null`.\n * @param epsilon - The tolerance. Defaults to 1e-6.\n * @returns `true` for two equal shapes, or two `null`s.\n */\nexport function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilon = 1e-6): boolean {\n if (a === null || b === null) return a === b;\n return (\n Math.abs(a.cx - b.cx) < epsilon &&\n Math.abs(a.cy - b.cy) < epsilon &&\n Math.abs(a.width - b.width) < epsilon &&\n Math.abs(a.height - b.height) < epsilon &&\n Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon\n );\n}\n","/**\n * A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own\n * frame, and turned from a rotation handle, on the image.\n *\n * The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which\n * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;\n * this is the gestures, the handles and the keyboard.\n */\n\nimport { useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport { overlayRole } from \"./overlayRole\";\nimport { ROI_HANDLES, type RoiHandle } from \"./roiEdit\";\nimport {\n fromShapeFrame,\n moveShape,\n resizeShape,\n rotateShape,\n rotationHandlePoint,\n shapeHandleCursor,\n shapeHandlePoint,\n type RotatedShape,\n} from \"./shapeEdit\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox } from \"./stage/view\";\n\n/** Handle square side, in screen pixels. */\nconst HANDLE_PX = 9;\n/** Rotation handle radius, and its distance past the top side, in screen pixels. */\nconst ROTATE_RADIUS_PX = 5;\nconst ROTATE_OFFSET_PX = 24;\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;\n/** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */\nconst SNAP = Math.PI / 12;\nconst KEY_TURN = Math.PI / 180;\nconst HALO = overlayRole(\"halo\");\n\n/** Props of `ShapeEditor`. */\nexport interface ShapeEditorProps {\n /** `\"rect\"` draws a rotated rectangle, `\"ellipse\"` the ellipse inscribed in it. */\n kind: \"rect\" | \"ellipse\";\n /**\n * The shape in image coordinates, or `null` for none. `rotation` is in **radians, clockwise\n * on screen**, so a value in degrees (Konva's, say) is `degrees * Math.PI / 180`. An\n * ellipse's `width` and `height` are its full axes, `2 · radiusX` and `2 · radiusY`.\n */\n value: RotatedShape | null;\n /** Called with the shape as it changes: on every move of a drag, and on each key nudge. */\n onValueChange: (value: RotatedShape) => void;\n /** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */\n onCommit?: ((value: RotatedShape) => void) | undefined;\n /** Show handles and accept moves, resizes and rotations. Defaults to `true`. */\n editable?: boolean | undefined;\n /** Show the rotation handle and accept `[` / `]`. Defaults to `true`; off for a shape that must stay level. */\n rotatable?: boolean | undefined;\n /** The smallest extent on either axis, in image pixels. Defaults to 5. */\n minSize?: number | undefined;\n /** The shape's accessible name. Defaults to \"Shape\". */\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: RotatedShape; moved: boolean }\n | { kind: \"resize\"; handle: RoiHandle; start: RotatedShape; moved: boolean }\n | { kind: \"rotate\"; start: RotatedShape; moved: boolean };\n\n/**\n * An editable rotated rectangle or ellipse inside an `ImageStage`.\n *\n * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the\n * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at\n * `minSize` rather than flipping. The interior moves it.\n * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to\n * round to 15°.\n * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),\n * with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`\n * turn it by 1° (15° with Shift).\n * - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an\n * ellipse also shows its bounding box, where the handles are.\n * - **Panning.** A press with the hand tool, or with space held, still pans.\n *\n * It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does\n * not keep the shape inside the image.\n *\n * The SVG carries `data-editable`; the outline carries `data-shape`.\n */\nexport function ShapeEditor({\n kind,\n value,\n onValueChange,\n onCommit,\n editable = true,\n rotatable = true,\n minSize = 5,\n label = \"Shape\",\n stroke = overlayRole(\"selection\"),\n}: ShapeEditorProps) {\n const stage = useStage();\n const px = useScreenPx();\n const dragRef = useRef<Drag | null>(null);\n const lastRef = useRef<RotatedShape | null>(null);\n\n const report = (next: RotatedShape) => {\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\") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));\n else if (drag.kind === \"resize\") report(resizeShape(drag.start, drag.handle, p, minSize));\n else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));\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.moved && lastRef.current) onCommit?.(lastRef.current);\n };\n\n const onKeyDown = (event: KeyboardEvent<SVGElement>) => {\n if (!editable || value === null) return;\n const turn = rotatable && (event.key === \"[\" || event.key === \"]\");\n if (turn) {\n event.preventDefault();\n event.stopPropagation();\n const angle = (event.key === \"]\" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);\n const next = { ...value, rotation: value.rotation + angle };\n onValueChange(next);\n onCommit?.(next);\n return;\n }\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 // Alt grows from the top-left corner, along the shape's own axes, as `RectRoiEditor` does.\n const next = event.altKey\n ? resizeShape(value, \"se\", fromShapeFrame(value, { x: value.width / 2 + d.x, y: value.height / 2 + d.y }), minSize)\n : moveShape(value, d.x, d.y);\n onValueChange(next);\n onCommit?.(next);\n };\n\n const stem = value ? { from: shapeHandlePoint(value, \"n\"), to: rotationHandlePoint(value, px(ROTATE_OFFSET_PX)) } : null;\n const handleSize = px(HANDLE_PX);\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 >\n {value && <Outline kind={kind} shape={value} fill=\"none\" stroke={HALO} strokeWidth={px(STROKE_PX + 2 * HALO_PX)} />}\n {value && <Outline kind={kind} shape={value} data-shape={kind} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(STROKE_PX)} />}\n {kind === \"ellipse\" && value && (\n <rect\n x={value.cx - value.width / 2}\n y={value.cy - value.height / 2}\n width={value.width}\n height={value.height}\n transform={turned(value)}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={px(1)}\n strokeDasharray={`${px(4)} ${px(3)}`}\n opacity={0.6}\n />\n )}\n {editable && value && (\n <Outline\n kind={kind}\n shape={value}\n fill=\"transparent\"\n role=\"button\"\n tabIndex={0}\n aria-label={`${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt((value.rotation * 180) / Math.PI)}°`}\n aria-roledescription={kind === \"rect\" ? \"rotated rectangle\" : \"ellipse\"}\n className=\"pointer-events-auto cursor-move outline-none focus-visible:stroke-signal\"\n onPointerDown={(event) =>\n begin(event, { kind: \"move\", from: stage.toImage({ x: event.clientX, y: event.clientY }), start: value, moved: false })\n }\n onPointerMove={onMove}\n onPointerUp={onEnd}\n onLostPointerCapture={onEnd}\n onKeyDown={onKeyDown}\n onDoubleClick={(event) => event.stopPropagation()}\n />\n )}\n {editable && value && rotatable && stem && (\n <>\n <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={HALO} strokeWidth={px(1 + 2 * HALO_PX)} />\n <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={stroke} strokeWidth={px(1)} />\n <circle\n data-handle=\"rotate\"\n cx={stem.to.x}\n cy={stem.to.y}\n r={px(ROTATE_RADIUS_PX)}\n fill={stroke}\n stroke={HALO}\n strokeWidth={px(1)}\n className=\"pointer-events-auto\"\n style={{ cursor: \"grab\" }}\n onPointerDown={(event) => begin(event, { kind: \"rotate\", start: value, moved: false })}\n onPointerMove={onMove}\n onPointerUp={onEnd}\n onLostPointerCapture={onEnd}\n onDoubleClick={(event) => event.stopPropagation()}\n />\n </>\n )}\n {editable &&\n value &&\n ROI_HANDLES.map((handle) => {\n const centre = shapeHandlePoint(value, handle);\n return (\n <rect\n key={handle}\n data-handle={handle}\n x={centre.x - handleSize / 2}\n y={centre.y - handleSize / 2}\n width={handleSize}\n height={handleSize}\n fill={stroke}\n stroke={HALO}\n strokeWidth={px(1)}\n className=\"pointer-events-auto\"\n style={{ cursor: shapeHandleCursor(handle, value.rotation) }}\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\n/** What the outline element takes: any SVG attribute, and `data-*`. */\ntype OutlineProps = Omit<SVGProps<SVGElement>, \"ref\"> & Record<`data-${string}`, string>;\n\n/** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */\nfunction Outline({ kind, shape, ...rest }: OutlineProps & { kind: \"rect\" | \"ellipse\"; shape: RotatedShape }) {\n const transform = turned(shape);\n return kind === \"rect\" ? (\n <rect x={shape.cx - shape.width / 2} y={shape.cy - shape.height / 2} width={shape.width} height={shape.height} transform={transform} {...rest} />\n ) : (\n <ellipse cx={shape.cx} cy={shape.cy} rx={shape.width / 2} ry={shape.height / 2} transform={transform} {...rest} />\n );\n}\n\n/** The SVG transform that turns a shape drawn level about its centre. */\nfunction turned(shape: RotatedShape): string {\n return `rotate(${(shape.rotation * 180) / Math.PI} ${shape.cx} ${shape.cy})`;\n}\n\nfunction fmt(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(1);\n}\n","/**\n * What an annotation tool shows while a shape is being drawn: a dashed preview of the\n * point, line, polyline, polygon, rectangle or ellipse so far, and the rubber band of a\n * multi-select.\n *\n * Both draw from state the app's tool keeps; neither takes input. The tool decides what a\n * press means (`StageSurface` and `useStageHitTest`); these only make it visible.\n */\n\nimport { overlayRole, type OverlayRole } from \"./overlayRole\";\nimport type { Point } from \"./measureGeometry\";\nimport { rectFromCorners } from \"./roiEdit\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox, type Rect } from \"./stage/view\";\n\n/**\n * The shape being drawn.\n * - `point`: a position.\n * - `line`: a segment from `from` to `to`.\n * - `polyline` and `polygon`: the vertices placed so far, flat `[x0, y0, x1, y1, …]`, and\n * the pointer as `cursor`, which the next vertex would land on.\n * - `rect` and `ellipse`: two opposite corners of the axis-aligned box (the drag's start and\n * the pointer).\n */\nexport type DraftShapeSpec =\n | { kind: \"point\"; x: number; y: number }\n | { kind: \"line\"; from: Point; to: Point }\n | { kind: \"polyline\"; points: ArrayLike<number>; cursor?: Point | undefined }\n | { kind: \"polygon\"; points: ArrayLike<number>; cursor?: Point | undefined }\n | { kind: \"rect\"; from: Point; to: Point }\n | { kind: \"ellipse\"; from: Point; to: Point };\n\n/** Props of `DraftShape`. */\nexport interface DraftShapeProps {\n /** The shape so far, or `null` when nothing is being drawn. */\n shape: DraftShapeSpec | null;\n /** The overlay role it is drawn in. Defaults to `\"selection\"`, the accent. */\n role?: OverlayRole | undefined;\n /** Draw the dark band under the outline. On by default. */\n halo?: boolean | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n/** Dash, gap, outline width and vertex dot size, in screen pixels. */\nconst DASH = 6;\nconst GAP = 4;\nconst STROKE_PX = 1.5;\nconst VERTEX_PX = 6;\n\n/**\n * A dashed preview of a shape being drawn, inside an `ImageStage`.\n *\n * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by\n * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline\n * or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also\n * shows, fainter, the segment that would close it. It takes no pointer events and is hidden\n * from assistive technology: it is transient feedback for a gesture.\n *\n * The SVG carries `data-draft` (the shape's kind).\n */\nexport function DraftShape({ shape, role = \"selection\", halo = true }: DraftShapeProps) {\n const stage = useStage();\n const px = useScreenPx();\n const colour = overlayRole(role);\n const dash = `${px(DASH)} ${px(GAP)}`;\n const width = px(STROKE_PX);\n const parts = shape ? draftParts(shape, px(1)) : null;\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 aria-hidden\n data-draft={shape?.kind}\n >\n {parts && (\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {parts.outline && halo && <path d={parts.outline} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}\n {parts.outline && parts.region && <path d={parts.outline} fill={colour} fillOpacity={0.12} stroke=\"none\" />}\n {parts.outline && <path data-draft-outline=\"\" d={parts.outline} stroke={colour} strokeWidth={width} strokeDasharray={dash} />}\n {parts.closing && <path data-draft-closing=\"\" d={parts.closing} stroke={colour} strokeWidth={px(1)} strokeDasharray={dash} opacity={0.5} />}\n {parts.vertices && <path data-draft-vertices=\"\" d={parts.vertices} stroke={colour} strokeWidth={px(VERTEX_PX)} />}\n </g>\n )}\n </svg>\n );\n}\n\n/** A shape as the path data of its outline, and what goes with it. */\ninterface DraftParts {\n /** The outline. `null` before a polyline has a vertex. */\n outline: string | null;\n /** Whether the outline encloses a region, which takes the fill. */\n region: boolean;\n /** The segment that would close a polygon, from the pointer to the first vertex. */\n closing: string | null;\n /** The placed vertices, as zero-length segments drawn with round caps. */\n vertices: string | null;\n}\n\n/** An ellipse with the given centre and radii as two arcs. */\nfunction ellipsePath(cx: number, cy: number, rx: number, ry: number): string {\n return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;\n}\n\nfunction draftParts(shape: DraftShapeSpec, unit: number): DraftParts {\n switch (shape.kind) {\n case \"point\":\n return { outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit), region: false, closing: null, vertices: `M${shape.x} ${shape.y}h0` };\n case \"line\":\n return { outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`, region: false, closing: null, vertices: null };\n case \"rect\":\n case \"ellipse\": {\n const box = rectFromCorners(shape.from, shape.to);\n const outline =\n shape.kind === \"rect\"\n ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z`\n : ellipsePath(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2);\n return { outline, region: true, closing: null, vertices: null };\n }\n case \"polyline\":\n case \"polygon\": {\n const n = Math.floor(shape.points.length / 2);\n if (n === 0) return { outline: null, region: false, closing: null, vertices: null };\n let outline = \"\";\n let vertices = \"\";\n for (let i = 0; i < n; i++) {\n outline += `${i === 0 ? \"M\" : \"L\"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;\n vertices += `M${shape.points[2 * i]} ${shape.points[2 * i + 1]}h0`;\n }\n if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;\n const polygon = shape.kind === \"polygon\";\n return {\n outline,\n region: polygon && n + (shape.cursor ? 1 : 0) >= 3,\n closing: polygon && shape.cursor ? `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}` : null,\n vertices,\n };\n }\n }\n}\n\n/** Props of `MarqueeRect`. */\nexport interface MarqueeRectProps {\n /** The band in image coordinates, or `null` when no band is being dragged. */\n rect: Rect | null;\n /** CSS colour of the band. Defaults to the overlay `selection` role. */\n stroke?: string | undefined;\n}\n\n/**\n * The rubber band of a multi-select, inside an `ImageStage`: the 12 % fill and a 1 screen px\n * outline in the selection colour, the same as `PolylineSet`'s own band. Feed it the box\n * between the press and the pointer from `StageSurface`, and the box to `pointsInRect`,\n * `polylinesInRect` or `areasInRect` at the release. It takes no pointer events.\n *\n * The SVG carries `data-marquee`.\n */\nexport function MarqueeRect({ rect, stroke = overlayRole(\"selection\") }: MarqueeRectProps) {\n const stage = useStage();\n const px = useScreenPx();\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n aria-hidden\n data-marquee={rect ? \"\" : undefined}\n >\n {rect && (\n <rect x={rect.x} y={rect.y} width={rect.width} height={rect.height} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(1)} />\n )}\n </svg>\n );\n}\n","/**\n * Moving a manual shape: a press on a selected item becomes image-space displacements, with the\n * click-slop handling every selection UI needs (a press that barely moves is a click, not a\n * drag).\n *\n * The layers resolve what is under the pointer (`onItemPress`); this turns the press that\n * follows into a move. The app keeps the item's geometry, shows the displaced copy while the\n * drag is in flight, and commits it at the end:\n *\n * <AreaSet items={items} selectedIds={selected}\n * onItemPress={(id, event) => {\n * if (!selected.has(id)) return select(id);\n * startMove(event, {\n * onMove: setOffset, // preview: draw the item shifted\n * onEnd: (delta, moved) => moved ? commit(id, delta) : select(id),\n * onCancel: () => setOffset(null),\n * });\n * }} />\n */\n\nimport { useCallback } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport type { StagePointerEvent } from \"./stage/hitContext\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useStageDrag } from \"./stage/StageSurface\";\n\n/** What a shape drag does as the pointer moves and when it ends. Displacements are total, from the press. */\nexport interface ShapeDragHandlers {\n /**\n * Each move of the pointer once it has left the click slop: how far it is from where the\n * press landed, in image pixels. Draw the shape shifted by it.\n */\n onMove?: ((delta: Point, event: PointerEvent) => void) | undefined;\n /**\n * The release. `moved` is whether the pointer ever left the click slop; when it did not,\n * `delta` is `{ x: 0, y: 0 }` and the press was a click. Commit the shape shifted by `delta`.\n */\n onEnd?: ((delta: Point, moved: boolean, event: PointerEvent) => void) | undefined;\n /** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag: drop the preview. */\n onCancel?: (() => void) | undefined;\n}\n\n/** Options of the function `useShapeDrag` returns. */\nexport interface ShapeDragOptions {\n /** How far the pointer may travel before the press is a drag, in screen pixels. Defaults to 3. */\n slop?: number | undefined;\n}\n\n/** The default click slop, in screen pixels (the stage's own). */\nconst DEFAULT_SLOP = 3;\n\n/**\n * Start moving a shape from a press, inside an `ImageStage`.\n *\n * Returns `start(event, handlers, options?)`. Call it from `onItemPress` of a layer with the\n * press event: the press is claimed, so the stage does not pan, and the pointer is followed on\n * `window` until it is released, whether or not it leaves the canvas. A touch tap reaches\n * `onItemPress` on release, so there is nothing to follow: it ends at once as a click\n * (`moved` false). Move a shape on touch with `ShapeEditor`'s handles or the app's own mode.\n *\n * @returns `start`.\n */\nexport function useShapeDrag(): (event: StagePointerEvent, handlers: ShapeDragHandlers, options?: ShapeDragOptions) => void {\n const { toImage } = useStage();\n const startDrag = useStageDrag();\n return useCallback(\n (event, handlers, options) => {\n if (event.type !== \"pointerdown\") {\n handlers.onEnd?.({ x: 0, y: 0 }, false, event.nativeEvent);\n return;\n }\n const slop = options?.slop ?? DEFAULT_SLOP;\n const from = { x: event.clientX, y: event.clientY };\n // Where the press landed, in image pixels: displacements are measured from it.\n const press = toImage(from);\n const displacement = (point: Point): Point => ({ x: point.x - press.x, y: point.y - press.y });\n let moved = false;\n startDrag(event, {\n onMove: (point, e) => {\n if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= slop) return;\n moved = true;\n handlers.onMove?.(displacement(point), e);\n },\n onEnd: (point, e) => handlers.onEnd?.(moved ? displacement(point) : { x: 0, y: 0 }, moved, e),\n onCancel: handlers.onCancel,\n });\n },\n [toImage, startDrag],\n );\n}\n\n/**\n * Move flat points by a displacement.\n *\n * @param points - `[x0, y0, x1, y1, …]`.\n * @param delta - The displacement, in the points' units.\n * @returns A new array, `points` shifted.\n */\nexport function translatePoints(points: ArrayLike<number>, delta: Point): number[] {\n const out = new Array<number>(points.length);\n for (let i = 0; i < points.length; i++) out[i] = points[i]! + (i % 2 === 0 ? delta.x : delta.y);\n return out;\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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AAG,MAAK;GAAO,QAAO;GAAgB,aAAa,MAAM,YAAY,GAAG;EAAI,CAAA;CACxI,CAAA,CAEP,EAAA,CAAA;AAEN"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["clamp","CLICK_SLOP","clamp","STROKE_PX","HALO","fmt","HALO","MAX_CELLS","HALO","LABEL","batchPath","HALO","HALO","HALO","STROKE_PX","HALO","ellipsePath"],"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/touchWatch.ts","../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/labelLod.ts","../src/components/PointSet.tsx","../src/components/areaIndex.ts","../src/components/areaBatching.ts","../src/components/AreaSet.tsx","../src/components/ellipseIndex.ts","../src/components/EllipseSet.tsx","../src/components/gridEdges.ts","../src/components/GridLayer.tsx","../src/components/heatmapRaster.ts","../src/components/HeatmapLayer.tsx","../src/components/shapeEdit.ts","../src/components/stage/useCoarsePointer.ts","../src/components/ShapeEditor.tsx","../src/components/DraftShape.tsx","../src/components/useShapeDrag.ts","../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/** How `fitScale` and `fitView` treat the margin and a small image. */\nexport interface FitOptions {\n /**\n * A margin on each side of the fitted image, in CSS pixels. Defaults to 0: the image fills\n * the box edge to edge. A margin that leaves no room (the box is smaller than twice the\n * padding) is ignored.\n */\n padding?: number | undefined;\n /**\n * Whether fit may magnify a small image past 1:1. On by default; `false` caps the fit scale\n * at 1, so a small image opens at its own size, centred.\n */\n upscale?: boolean | undefined;\n}\n\n/**\n * The scale at which the whole image is just visible inside `box`.\n *\n * @param box - The viewport, in CSS pixels.\n * @param image - The image, in image pixels.\n * @param options - A margin and an upscale cap; the defaults fill the box edge to edge.\n * @returns CSS pixels per image pixel; `1` for a degenerate box or image.\n */\nexport function fitScale(box: Box, image: Box, options: FitOptions = {}): number {\n if (!(box.width > 0) || !(box.height > 0) || !(image.width > 0) || !(image.height > 0)) return 1;\n const pad = Math.max(0, options.padding ?? 0);\n const room = box.width > 2 * pad && box.height > 2 * pad ? pad : 0;\n const scale = Math.min((box.width - 2 * room) / image.width, (box.height - 2 * room) / image.height);\n return options.upscale === false ? Math.min(1, scale) : scale;\n}\n\n/**\n * Fit, centred: the view a viewer opens at and the one `0` returns to.\n *\n * @param box - The viewport, in CSS pixels.\n * @param image - The image, in image pixels.\n * @param options - A margin and an upscale cap; see `FitOptions`.\n * @returns The view.\n */\nexport function fitView(box: Box, image: Box, options: FitOptions = {}): StageView {\n const scale = fitScale(box, image, options);\n return centred(scale, box, image);\n}\n\n/**\n * The whole image visible at 1:1 if it fits, otherwise fit — a sane opening view.\n *\n * @param box - The viewport, in CSS pixels.\n * @param image - The image, in image pixels.\n * @param options - Only `padding` matters here (the image must fit inside the margin to open\n * at 1:1, and \"otherwise fit\" is the padded fit); it never magnifies, so `upscale` is moot.\n * @returns The view.\n */\nexport function initialView(box: Box, image: Box, options: FitOptions = {}): StageView {\n return centred(Math.min(1, fitScale(box, image, { padding: options.padding })), 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, image and `FitOptions`. */\nexport function isFit(view: StageView, box: Box, image: Box, options: FitOptions = {}): boolean {\n const fit = fitView(box, image, options);\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/**\n * An image coordinate held to the image's extent, `[-0.5, w - 0.5] x [-0.5, h - 0.5]` in the\n * pixel-centre convention: the point on the frame's edge nearest to `p`.\n */\nexport function clampToImage(p: Point, image: Box): Point {\n return {\n x: Math.min(image.width - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.x)),\n y: Math.min(image.height - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.y)),\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 /**\n * How far the image may be panned. `\"cover\"` (the default): an axis the image overflows\n * keeps the viewport covered, and an axis it does not fill is centred. `\"center\"`: any\n * image point may be brought to the viewport's centre and no further, on both axes and at\n * every scale — so a zoom about the pointer keeps the pointer's pixel under it while the\n * image is still smaller than the viewport, and an edge or corner can be worked on in the\n * middle of the screen.\n */\n panBounds?: \"cover\" | \"center\" | undefined;\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 * With the default `panBounds: \"cover\"`, an axis where the scaled image is smaller than the\n * viewport is centred rather than left where a drag put it — free-floating pixels in a grey\n * field is a way to be lost with no visible handle to get back — and an axis where it is\n * larger is held so the viewport stays covered. With `\"center\"`, each axis only keeps some\n * image point at or past the viewport's centre.\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 const axis = options.panBounds === \"center\" ? centreAxis : clampAxis;\n return {\n scale,\n tx: axis(view.tx, box.width, image.width * scale),\n ty: axis(view.ty, box.height, image.height * scale),\n };\n}\n\n/** `\"center\"` bounds: the content's far edge may come to the centre, and its near edge too. */\nfunction centreAxis(t: number, boxLength: number, contentLength: number): number {\n return clamp(t, boxLength / 2 - contentLength, boxLength / 2);\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 fit: FitOptions = {},\n): StageView {\n if (!(from.width > 0) || !(from.height > 0)) return clampView(fitView(to, image, fit), to, image, options);\n if (isFit(view, from, image, fit)) return fitView(to, image, fit);\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\n/** The pointer's tolerance for hover and presses, in screen pixels: a mouse or pen. */\nexport const POINTER_RADIUS_PX = 6;\n/** The pointer's tolerance for a touch, in screen pixels: a fingertip is fatter. */\nexport const TOUCH_RADIUS_PX = 12;\n\n/**\n * The hit-test tolerance for a pointer, in screen pixels.\n *\n * @param pointerType - `PointerEvent.pointerType`.\n * @returns 12 for `\"touch\"`, 6 otherwise.\n */\nexport function hitRadiusPx(pointerType: string): number {\n return pointerType === \"touch\" ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX;\n}\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, hitRadiusPx, 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 FitOptions,\n type Rect,\n type StageView,\n} from \"./view\";\n\nconst WHEEL_SENSITIVITY = 0.0015;\n/**\n * How long after the last view change the stage box keeps `will-change: transform`.\n *\n * The hint keeps a pan on the compositor (without it every overlay path is repainted each\n * frame: 130 ms against 17 ms with 4,000 corners in view under software raster), but Chromium\n * then keeps the layer at the raster scale it had when the hint was applied, so the stage\n * would stay blurry after a zoom. Measured in `willChange.browser.test.ts`: always on, the\n * edge of a zoomed image ramps over 6 px and a 1 px line smears to 10; cleared once the view\n * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.\n */\nconst MOVING_SETTLE_MS = 150;\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/** 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/** Why a view was reported through `ImageStage`'s `onView`. */\nexport interface StageViewChange {\n /**\n * What moved the view:\n * - `\"gesture\"`: a wheel zoom, a drag or touch pan, a pinch, a double-click.\n * - `\"key\"`: a keyboard shortcut or pan key.\n * - `\"command\"`: a call to the handle or the context (`fit`, `zoomTo`, `frame`, `setView`),\n * which includes the toolbar's buttons.\n * - `\"measure\"`: the opening view, and a resize re-anchoring the view.\n */\n cause: \"gesture\" | \"key\" | \"command\" | \"measure\";\n /** The measured viewport, in CSS pixels, at the moment of the change. */\n box: Box;\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 /**\n * Called with every view change: gestures, keys, toolbar, and viewport resizes. The second\n * argument says why and carries the measured viewport; a one-argument callback ignores it.\n * A `null` `view` that the stage has already measured is re-opened and reported again, with\n * cause `\"measure\"`.\n */\n onView: (view: StageView, change: StageViewChange) => 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 /**\n * A press on the background that was not a pan — how a layer hears \"deselect\". `point` is\n * where it landed, in image coordinates (the pixel-centre convention, unclamped).\n */\n onBackgroundClick?: (event: ReactPointerEvent<HTMLDivElement>, point: Point) => 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 * (inside the `fit` margin) 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 /**\n * The margin and upscale cap of every fit: `initialView=\"fit\"`, the handle's and the\n * context's `fit()`, the `0` key, the double-click toggle, the toolbar's Fit button, and\n * `isFit` / `data-fit`. Defaults to filling the viewport edge to edge, upscaling freely.\n * Each field is read by value, so an inline object does not re-fit the view.\n */\n fit?: FitOptions | 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 * The transformed box (`[data-stage]`) carries `will-change: transform` and `data-moving` while\n * the view changes and for 150 ms after, so a pan stays on the compositor and the layer\n * re-rasterises sharp once the view settles.\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 fit: fitOptions,\n ref,\n}: ImageStageProps) {\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const boxRef = 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 fitOpts = useMemo<FitOptions>(\n () => ({ padding: fitOptions?.padding, upscale: fitOptions?.upscale }),\n [fitOptions?.padding, fitOptions?.upscale],\n );\n const effective = useMemo(\n () => view ?? (box.width > 0 ? openingView(opening, box, image, fitOpts) : UNMEASURED_VIEW),\n [view, box, image, opening, fitOpts],\n );\n\n const latestRef = useRef({\n view,\n effective: UNMEASURED_VIEW,\n box,\n image,\n clamp,\n onView,\n opening,\n fitOpts,\n });\n useLayoutEffect(() => {\n latestRef.current = {\n view,\n effective,\n box,\n image,\n clamp,\n onView,\n opening,\n fitOpts,\n };\n });\n /** Whether the opening view of the current `null` view has been reported. */\n const openedRef = useRef(false);\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<{\n distance: number;\n centre: Point;\n view: StageView;\n } | 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 // `will-change: transform` (and `data-moving`) on the transformed box while the view moves, set\n // on the element itself so a pan costs no React render; see `MOVING_SETTLE_MS`.\n useEffect(() => {\n const element = boxRef.current;\n if (!element) return;\n element.style.willChange = \"transform\";\n element.dataset[\"moving\"] = \"\";\n const timer = setTimeout(() => {\n element.style.willChange = \"\";\n delete element.dataset[\"moving\"];\n }, MOVING_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [effective.scale, effective.tx, effective.ty]);\n\n /** Report a view with its cause and the viewport it was made for (the measured one by default). */\n const emit = useCallback((next: StageView, cause: StageViewChange[\"cause\"], box?: Box) => {\n const { box: b, onView: report } = latestRef.current;\n report(next, { cause, box: box ?? b });\n }, []);\n\n const commit = useCallback(\n (next: StageView, cause: StageViewChange[\"cause\"] = \"command\") => {\n const { box: b, image: i, clamp: c } = latestRef.current;\n emit(b.width > 0 ? clampView(next, b, i, c) : next, cause);\n },\n [emit],\n );\n\n // A `null` view the stage has already measured: `measure` only fires when the size changes,\n // so without this the opening view was drawn but never reported, and the pane stayed on a\n // view the app did not hold. Once per null period; a non-null view re-arms it.\n useEffect(() => {\n if (view !== null) {\n openedRef.current = false;\n return;\n }\n if (box.width > 0 && !openedRef.current) {\n openedRef.current = true;\n emit(openingView(opening, box, image, fitOpts), \"measure\");\n }\n }, [view, box, image, opening, fitOpts, emit]);\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(\n (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, opening: o, fitOpts: f } = latestRef.current;\n if (v === null) {\n openedRef.current = true;\n emit(openingView(o, next, i, f), \"measure\", next);\n }\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)) emit(clampView(v, next, i, c), \"measure\", next);\n else emit(preserveCenter(v, current, next, i, c, f), \"measure\", next);\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 { effective: v, box: b, image: i, clamp: c } = latestRef.current;\n if (!(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 = {\n x: event.clientX - origin.x,\n y: event.clientY - origin.y,\n };\n emit(clampView(zoomAbout(v, scale, anchor), b, i, c), \"gesture\");\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 [emit],\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: held, effective: v, box: b } = latestRef.current;\n // Unmeasured and uncontrolled: there is no view to convert with yet.\n if (!element || (held === null && !(b.width > 0))) 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: held, effective: v, box: b } = latestRef.current;\n // Unmeasured and uncontrolled: there is no view to convert with yet.\n if (!element || (held === null && !(b.width > 0))) 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 fitBy = useCallback(\n (cause: StageViewChange[\"cause\"]) => {\n const { box: b, image: i, view: v, fitOpts: f } = latestRef.current;\n if (!(b.width > 0)) return;\n if (v !== null && !isFit(v, b, i, f)) previousRef.current = v;\n emit(fitView(b, i, f), cause);\n },\n [emit],\n );\n const fit = useCallback(() => fitBy(\"command\"), [fitBy]);\n\n const zoomBy = useCallback(\n (cause: StageViewChange[\"cause\"], scale: number, anchor?: Point) => {\n const { effective: v, box: b, image: i, clamp: c } = latestRef.current;\n const element = viewportRef.current;\n if (!(b.width > 0) || !element) return;\n const origin = viewportOrigin(element);\n const local = anchor ? { x: anchor.x - origin.x, y: anchor.y - origin.y } : { x: b.width / 2, y: b.height / 2 };\n const [min, max] = scaleRange(b, i, c);\n emit(clampView(zoomAbout(v, Math.min(max, Math.max(min, scale)), local), b, i, c), cause);\n },\n [emit],\n );\n const zoomTo = useCallback((scale: number, anchor?: Point) => zoomBy(\"command\", scale, anchor), [zoomBy]);\n\n const frame = useCallback(\n (rect: Rect, pad?: number) => {\n const { box: b, image: i } = latestRef.current;\n if (!(b.width > 0)) return;\n emit(frameRect(b, i, rect, pad), \"command\");\n },\n [emit],\n );\n\n useImperativeHandle(ref, () => ({ frame, fit, zoomTo }), [frame, fit, zoomTo]);\n\n const atFit = box.width > 0 && isFit(effective, box, image, fitOpts);\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 [effective, commit, image, box, clientToImage, imageToClient, frame, fit, zoomTo, atFit, panning, panMode],\n );\n\n /** The pointer's tolerance for hover and presses in image pixels: a fingertip is fatter. */\n const hitRadius = (event: { pointerType: string }) => imageLengthFor(effective, hitRadiusPx(event.pointerType));\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 }, \"gesture\");\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) {\n onBackgroundClick?.(event, clientToImage({ x: event.clientX, y: event.clientY }));\n }\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 \"gesture\",\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 }, \"gesture\");\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, clientToImage({ x: event.clientX, y: event.clientY }));\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 emit(clampView(restore, box, image, clamp), \"gesture\");\n } else {\n zoomBy(\"gesture\", 1, { x: event.clientX, y: event.clientY });\n }\n return;\n }\n previousRef.current = effective;\n emit(fitView(box, image, fitOpts), \"gesture\");\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 zoomBy(\"key\", Math.min(max, effective.scale * 1.5));\n break;\n case \"-\":\n case \"_\":\n zoomBy(\"key\", Math.max(min, effective.scale / 1.5));\n break;\n case \"0\":\n fitBy(\"key\");\n break;\n case \"1\":\n zoomBy(\"key\", 1);\n break;\n case \"ArrowLeft\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx + nudge }, \"key\");\n break;\n case \"ArrowRight\":\n if (!panKeys) return;\n commit({ ...effective, tx: effective.tx - nudge }, \"key\");\n break;\n case \"ArrowUp\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty + nudge }, \"key\");\n break;\n case \"ArrowDown\":\n if (!panKeys) return;\n commit({ ...effective, ty: effective.ty - nudge }, \"key\");\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 ref={boxRef}\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, fit: FitOptions): StageView {\n return opening === \"fit\" ? fitView(box, image, fit) : initialView(box, image, fit);\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, {\n x: event.clientX - origin.x,\n y: event.clientY - origin.y,\n });\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 * Watching a touch without claiming it.\n *\n * A layer that claims a touch (`stopPropagation` plus pointer capture) takes it from the stage,\n * so a second finger can no longer pinch and a drag can no longer pan. A layer that only wants\n * to know whether the touch was a tap leaves the press alone and follows its pointer on\n * `window`, where the moves and the release arrive whoever captured the pointer.\n */\n\nimport { TAP_SLOP, isTap } from \"./gesture\";\n\n/** What a watched touch reports. */\nexport interface TouchWatch {\n /** The finger has left the tap slop, and moved again. Not called for a finger that stays put. */\n onMove?: ((event: PointerEvent) => void) | undefined;\n /**\n * The finger lifted. `moved` is whether it ever left the tap slop; `tap` whether it was a\n * tap (it stayed put and was quick).\n */\n onEnd: (event: PointerEvent, moved: boolean, tap: boolean) => void;\n /** The browser took the touch (`pointercancel`), a second finger landed, or the watch was cancelled. */\n onCancel?: (() => void) | undefined;\n}\n\n/** The press a watch begins from. */\nexport interface TouchOrigin {\n /** `PointerEvent.pointerId`. */\n pointerId: number;\n /** Client x of the press. */\n clientX: number;\n /** Client y of the press. */\n clientY: number;\n /** `PointerEvent.timeStamp` of the press. */\n timeStamp: number;\n}\n\n/**\n * Follow one touch on `window` until it lifts. A second touch landing, or `pointercancel`,\n * cancels the watch and leaves the touches to the stage.\n *\n * @param origin - The `pointerdown` of the touch.\n * @param watch - What to report.\n * @returns A function that cancels the watch (calling `onCancel`); a no-op once it has ended.\n */\nexport function watchTouch(origin: TouchOrigin, watch: TouchWatch): () => void {\n const id = origin.pointerId;\n let moved = false;\n let done = false;\n const travel = (e: PointerEvent) => Math.hypot(e.clientX - origin.clientX, e.clientY - origin.clientY);\n\n const stop = () => {\n done = true;\n window.removeEventListener(\"pointermove\", move);\n window.removeEventListener(\"pointerup\", up);\n window.removeEventListener(\"pointercancel\", cancelEvent);\n window.removeEventListener(\"pointerdown\", other);\n };\n const cancel = () => {\n if (done) return;\n stop();\n watch.onCancel?.();\n };\n function move(e: PointerEvent) {\n if (e.pointerId !== id) return;\n if (!moved && travel(e) > TAP_SLOP) moved = true;\n if (moved) watch.onMove?.(e);\n }\n function up(e: PointerEvent) {\n if (e.pointerId !== id) return;\n stop();\n if (!moved && travel(e) > TAP_SLOP) moved = true;\n watch.onEnd(e, moved, isTap(moved ? Infinity : travel(e), e.timeStamp - origin.timeStamp));\n }\n function cancelEvent(e: PointerEvent) {\n if (e.pointerId === id) cancel();\n }\n function other(e: PointerEvent) {\n if (e.pointerId !== id && e.pointerType === \"touch\") cancel();\n }\n window.addEventListener(\"pointermove\", move);\n window.addEventListener(\"pointerup\", up);\n window.addEventListener(\"pointercancel\", cancelEvent);\n window.addEventListener(\"pointerdown\", other);\n return cancel;\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 { cn } from \"@vitavision/ui\";\nimport type { Point } from \"../measureGeometry\";\nimport { useStage } from \"./ImageStage\";\nimport { hitRadiusPx } from \"./gesture\";\nimport { watchTouch } from \"./touchWatch\";\nimport { clampToImage, imageViewBox, toImage } 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 * Claim a touch that starts this gesture, as a mouse press is claimed: the stage neither\n * pans nor pinches from it. Without it a touch is only watched (see `StageSurface`), so\n * return `true` for a gesture a finger must own, such as moving a selected shape. Ignored for\n * a mouse or pen.\n */\n claimsTouch?: boolean | 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 /** Where, in client coordinates, for anchoring a tooltip or a menu. */\n client: Point;\n /** The press is a touch: act on its release (see `StageSurface`), and expect a fingertip's tolerance. */\n touch: boolean;\n /** The hit-test tolerance for this pointer, in screen pixels: 12 for a touch, 6 otherwise. Pass it to `useStageHitTest`. */\n radius: number;\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 * **For a touch, act in `onEnd` when `moved` is `false` (a tap), not here.** The press may\n * become a pan or the first finger of a pinch, so nothing should happen until the finger\n * lifts. Return `claimsTouch: true` for a gesture the finger must own.\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 mouse is over the image while no drag is in flight, for hover feedback. Not called for a touch. */\n onHover?: ((point: Point) => void) | undefined;\n /**\n * A double click or double tap on the surface. When given, the surface handles it and the\n * stage's double-click-to-fit does not run; leave it out to keep the fit.\n */\n onDoubleClick?: ((point: Point) => void) | undefined;\n /**\n * How far the surface reaches. `\"image\"` (the default) is the image rectangle: a press in\n * the margin around the image goes to the stage, which pans. `\"viewport\"` covers everything\n * visible, margin included, so a drawing tool can place a point on the image's border by\n * pressing just outside it; every point the surface then reports (the press, a drag's moves\n * and release, hover, double-click) is clamped to the image's extent, `[-0.5, w - 0.5]` by\n * `[-0.5, h - 0.5]`. `StagePress.client` stays the raw pointer position.\n */\n extent?: \"image\" | \"viewport\" | 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 * **Mouse and pen.** Only the left button comes here. The press is claimed and followed on\n * `window`, so the stage does not pan from it.\n *\n * **Touch.** A touch is only *watched* unless its `StageDrag` sets `claimsTouch`: the surface\n * neither stops the press nor captures the pointer, so the stage still pans (one-finger mode)\n * and a second finger still pinches. The drag then sees:\n * - `onMove`, only once the finger has left the tap slop;\n * - `onEnd(point, event, moved)` on release, with `moved` `false` for a tap;\n * - `onCancel` on `pointercancel`, or when a second finger lands (a pinch).\n *\n * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.\n *\n * With `extent=\"viewport\"` the surface also takes presses in the margin around the image, and\n * clamps every reported point to the image.\n *\n * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.\n */\nexport function StageSurface({ onPress, cursor, onHover, onDoubleClick, extent = \"image\" }: StageSurfaceProps) {\n const stage = useStage();\n const start = useStageDrag();\n const [dragging, setDragging] = useState(false);\n const watchRef = useRef<(() => void) | null>(null);\n\n // A touch still being watched when the surface goes away is cancelled, not left listening.\n useEffect(() => () => watchRef.current?.(), []);\n\n const viewport = extent === \"viewport\";\n // The image point under a client position; held to the image only for a viewport-wide surface.\n const pointAt = (client: Point): Point => {\n const p = stage.toImage(client);\n return viewport ? clampToImage(p, stage.image) : p;\n };\n // The visible area in image coordinates, from the view and the measured box, so it follows\n // pan, zoom and resize; the image rectangle until the viewport has been measured.\n const target = (() => {\n const { image, view, box } = stage;\n if (!viewport || !(box.width > 0)) return { x: -0.5, y: -0.5, width: image.width, height: image.height };\n const a = toImage(view, { x: 0, y: 0 });\n const b = toImage(view, { x: box.width, y: box.height });\n return { x: a.x, y: a.y, width: b.x - a.x, height: b.y - a.y };\n })();\n\n const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {\n const touch = event.pointerType === \"touch\";\n if (stage.panMode || (!touch && event.button !== 0)) return;\n // A second finger turns the first one's gesture into a pinch; the watch cancels itself on it.\n if (touch && watchRef.current) return;\n const client = { x: event.clientX, y: event.clientY };\n const drag = onPress({\n point: pointAt(client),\n client,\n touch,\n radius: hitRadiusPx(event.pointerType),\n shiftKey: event.shiftKey,\n altKey: event.altKey,\n metaKey: event.metaKey || event.ctrlKey,\n });\n if (!drag) return; // Declined: the stage pans.\n const finish = () => setDragging(false);\n setDragging(true);\n if (touch && !drag.claimsTouch) {\n // Watched, not claimed: the press goes on to the stage.\n const release = () => {\n watchRef.current = null;\n finish();\n };\n watchRef.current = watchTouch(event, {\n onMove: (e) => drag.onMove?.(pointAt({ x: e.clientX, y: e.clientY }), e),\n onEnd: (e, moved) => {\n release();\n drag.onEnd?.(pointAt({ x: e.clientX, y: e.clientY }), e, moved);\n },\n onCancel: () => {\n release();\n drag.onCancel?.();\n },\n });\n return;\n }\n start(event, {\n onMove: drag.onMove && ((point, e) => drag.onMove?.(viewport ? clampToImage(point, stage.image) : point, e)),\n onEnd: (point, e, moved) => {\n finish();\n drag.onEnd?.(viewport ? clampToImage(point, stage.image) : point, e, moved);\n },\n onCancel: () => {\n finish();\n drag.onCancel?.();\n },\n });\n };\n\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className={cn(\"pointer-events-none absolute inset-0 h-full w-full\", viewport && \"overflow-visible\")}\n data-dragging={dragging ? \"\" : undefined}\n aria-hidden\n >\n <rect\n data-stage-surface=\"\"\n x={target.x}\n y={target.y}\n width={target.width}\n height={target.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 && event.pointerType !== \"touch\") onHover?.(pointAt({ x: event.clientX, y: event.clientY }));\n }}\n onDoubleClick={(event) => {\n if (!onDoubleClick) return;\n event.stopPropagation();\n onDoubleClick(pointAt({ 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\n/** The point of segment ab nearest to `p`. Shared with `areaIndex.ts`. */\nexport function 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). Shared with `areaIndex.ts`. */\nexport function 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\";\nimport type { Rect } from \"./stage/view\";\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 * The area, in image coordinates, every vertex is kept inside: a drag, a keyboard nudge and\n * an inserted vertex are clamped to it. Defaults to the pixel centres,\n * `{ x: 0, y: 0, width: w - 1, height: h - 1 }`. Pass `{ x: -0.5, y: -0.5, width: w, height: h }`\n * for polygons in the area convention, which may lie exactly on the image border.\n */\n bounds?: Rect | undefined;\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)\", bounds }: 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 const area = bounds ?? { x: 0, y: 0, width: stage.image.width - 1, height: stage.image.height - 1 };\n return {\n x: Math.max(area.x, Math.min(area.x + area.width, point.x)),\n y: Math.max(area.y, Math.min(area.y + area.height, 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 { PIXEL_CENTRE, 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, in the stage's centre convention. Defaults to\n * `{ x: -0.5, y: -0.5, width, height }` of the image: its full extent, so a region that\n * fills it outlines the image edges.\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: -PIXEL_CENTRE, y: -PIXEL_CENTRE, 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 { useEffect, useMemo, useRef, 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 { watchTouch } from \"./stage/touchWatch\";\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 /**\n * Whether the layer takes presses and hover. Defaults to `true` when any of `onItemPress`,\n * `onSelect`, `onHover`, `onHoverChange` or `marquee` is given. When `false` the layer\n * renders no press target at all: a press on a line falls through to whatever is below (a\n * draw tool's `StageSurface`, say), while `useStageHitTest` still finds the lines. Set it\n * `false` while a tool other than selection is active.\n *\n * A touch on an interactive layer is not claimed: the stage still pans and pinches, and the\n * line is selected when the finger lifts after a tap.\n */\n interactive?: 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 * - **Tools.** Without a handler (or with `interactive={false}`) the layer takes no presses\n * and only answers `useStageHitTest`, so a draw tool's surface below receives them.\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 interactive,\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 watchRef = useRef<(() => void) | null>(null);\n // A touch still being watched when the layer goes away is cancelled, not left listening.\n useEffect(() => () => watchRef.current?.(), []);\n const takesPresses =\n interactive ??\n (onItemPress !== undefined || onSelect !== undefined || onHover !== undefined || onHoverChange !== undefined || marquee);\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 const touch = event.pointerType === \"touch\";\n if (stage.panMode || (!touch && event.button !== 0)) return;\n if (touch && watchRef.current) return; // a second finger: the watch cancels itself, the stage pinches\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 if (touch && !marquee) {\n // Not claimed: the press may become a pan or a pinch, so the line is selected on the tap.\n const additive = event.metaKey || event.ctrlKey;\n watchRef.current = watchTouch(event, {\n onEnd: (_e, _moved, tap) => {\n watchRef.current = null;\n if (!tap) return;\n onItemPress?.(id, event);\n onSelect?.([id], additive ? \"toggle\" : \"replace\");\n },\n onCancel: () => {\n watchRef.current = null;\n },\n });\n return;\n }\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 {takesPresses && 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 {takesPresses && (\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 && event.pointerType !== \"touch\") setHover(pickAt(event));\n }}\n onPointerLeave={() => setHover(null)}\n />\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 * @param angle2 - The item's second angle in radians, `undefined` when it has none. Most\n * shapes ignore it; a glyph with two axes (a corner's two edge directions) reads it.\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, angle2?: 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 * Which labels a layer draws: the level-of-detail rule of the overlay grammar\n * (`docs/visual-language.md` §5), shared by `PointSet`, `AreaSet` and `GridLayer`.\n *\n * Labels are 11 px mono. They are shown only where their anchors are at least 24 screen\n * pixels apart (so a zoomed-out scene shows none and a zoomed-in one shows all), at most 200 at\n * a time, and only inside the viewport. The hovered and selected items always carry theirs.\n */\n\nimport { useMemo } from \"react\";\n\nimport { thinPoints } from \"./pointIndex\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport type { Rect } from \"./stage/view\";\n\n/** Labels need this much room between anchors, in screen pixels (overlay grammar §5). */\nexport const LABEL_SPACING = 24;\n/** The most label elements drawn at once. */\nexport const MAX_LABELS = 200;\n/** The most hovered-or-selected labels forced on regardless of spacing. */\nexport const MAX_FORCED_LABELS = 50;\n\n/** The image-space rectangle on screen, or `null` before the viewport is measured. */\nexport function 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 * Choose the labels to draw.\n *\n * @param spaced - Anchors that are far enough apart, in priority order (`thinPoints`).\n * @param forced - Anchors that always carry a label: the hovered and the selected.\n * @param inView - Whether an anchor is inside the viewport.\n * @returns The anchor indices to label: the forced ones first (at most 50), then the spaced\n * ones, 200 in all.\n */\nexport function pickLabelIndices(spaced: readonly number[], forced: readonly number[], inView: (index: number) => boolean): number[] {\n const shown = new Set<number>();\n for (const i of forced) {\n if (shown.size >= MAX_FORCED_LABELS) break;\n if (i >= 0 && 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}\n\n/** What `useLabelIndices` reads. */\nexport interface LabelAnchors {\n /** Whether labels are shown at all. */\n enabled: boolean;\n /** Flat `[x0, y0, x1, y1, …]` anchors, in image coordinates. */\n xy: ArrayLike<number>;\n /** The anchors that have a label, in priority order. Pass a stable array. */\n labelled: readonly number[];\n /** The anchors that must carry theirs (hovered, selected) and have one. Pass a stable array. */\n forced: readonly number[];\n}\n\n/**\n * The anchors to label at the stage's current zoom and viewport. The spacing depends on the\n * zoom only, so panning does not reshuffle which anchors carry a label.\n *\n * @param anchors - See `LabelAnchors`.\n * @returns Anchor indices.\n */\nexport function useLabelIndices({ enabled, xy, labelled, forced }: LabelAnchors): number[] {\n const stage = useStage();\n const unit = useScreenPx()(1);\n const spacing = LABEL_SPACING * unit;\n const spaced = useMemo(\n () => (enabled && labelled.length > 0 ? thinPoints(xy, spacing, labelled) : []),\n [enabled, labelled, xy, spacing],\n );\n return useMemo(() => {\n if (!enabled || (spaced.length === 0 && forced.length === 0)) return [];\n const view = visibleRect(stage.view, stage.box);\n const inView = (i: number) => {\n if (view === null) return true;\n const x = xy[2 * i]!;\n const y = xy[2 * i + 1]!;\n return x >= view.x && x <= view.x + view.width && y >= view.y && y <= view.y + view.height;\n };\n return pickLabelIndices(spaced, forced, inView);\n }, [enabled, spaced, forced, xy, stage.view, stage.box]);\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, colour, 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 { useLabelIndices, visibleRect } from \"./labelLod\";\nimport { buildPointIndexFrom, nearestPoint, 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 /**\n * CSS colour of its mark (`#hex`, `var(--x)`, `color-mix(…)`; used as given). Overrides the\n * role; selection still paints in `selectionStroke`. Points sharing a colour share a batch.\n */\n color?: string | undefined;\n /** Its orientation in radians, clockwise from +x; read by `directed`. */\n angle?: number | undefined;\n /** A second angle in radians, for a glyph with two axes. `MarkerShape.path` gets `undefined` without it. */\n angle2?: 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/** 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 /** The custom colour, when the items of this batch have one. */\n color: string | undefined;\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\", color: undefined, 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 color = item.color || undefined;\n const key = `${dim ? 1 : 0}|${role}|${kindName}${color ? `|${color}` : \"\"}`;\n let batch = normal.get(key);\n if (!batch) {\n batch = { key, shape, role, color, 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 forced = useMemo(() => {\n const list: number[] = [];\n if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);\n for (const id of selectedSet) {\n const i = positionOf.get(id);\n if (i !== undefined && items[i]!.label) list.push(i);\n }\n return list;\n }, [hoverItem, selectedSet, positionOf, items]);\n const shownLabels = useLabelIndices({ enabled: labels, xy: index.xy, labelled, forced });\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={batch.color ?? 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, hoverItem.angle2)}\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, hoverItem.angle2)}\n stroke={hoverSelected ? selectionStroke : (hoverItem?.color || 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, item.angle2);\n }\n batch.cache = { key, d };\n return d;\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","/**\n * A spatial index over many closed polygons: which one is under the pointer, and which ones a\n * rubber band touched.\n *\n * The same uniform grid as `polylineIndex.ts` and `pointIndex.ts` (CSR layout, built once per\n * change of the items), but over each polygon's bounding box: a query looks at the polygons\n * whose box is near the pointer and runs the exact tests (even-odd containment, distance to\n * the outline) on those few only. It imports neither React nor the DOM.\n *\n * Polygons are flat `[x0, y0, x1, y1, …]` rings in image coordinates, implicitly closed. A\n * ring with fewer than three vertices has no interior: it is still pickable along its outline\n * (a two-vertex ring is a segment, a one-vertex ring a point), but never \"inside\".\n */\n\nimport type { Point } from \"./measureGeometry\";\nimport { closestOnSegment, segmentTouchesRect } from \"./polylineIndex\";\nimport type { Rect } from \"./stage/view\";\n\n/** An area's identity. */\nexport type AreaId = string | number;\n\n/** One closed polygon. */\nexport interface Area {\n /** Its identity, unique in the set. */\n id: AreaId;\n /** `[x0, y0, x1, y1, …]` in image coordinates; the last vertex joins the first. */\n points: ArrayLike<number>;\n}\n\n/**\n * An index built by `buildAreaIndex`. Treat it as opaque and query it with `nearestArea` and\n * `areasInRect`; its layout may change.\n */\nexport interface AreaIndex {\n /** The areas, in the order given. */\n readonly items: readonly Area[];\n /** Per area, `[minX, minY, maxX, maxY]`; `NaN`s for an area with no finite vertex. */\n readonly bounds: Float64Array;\n /** Per area, its unsigned area (shoelace), used to prefer the smaller of nested areas. */\n readonly size: Float64Array;\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 `entries[starts[c] .. starts[c + 1]]`. */\n readonly starts: Uint32Array;\n /** Area indices by cell. */\n readonly entries: Uint32Array;\n}\n\n/** The area `nearestArea` picked. */\nexport interface AreaHit {\n /** Its id. */\n id: AreaId;\n /** Its position in the array the index was built from. */\n index: number;\n /** Whether the query is inside the polygon (even-odd rule). */\n inside: boolean;\n /** The distance from the query to the polygon's outline, in image pixels. */\n distance: number;\n}\n\n/** The most grid cells an index allocates, and the most area-to-cell entries. */\nconst MAX_CELLS = 4_000_000;\nconst MAX_ENTRIES = 8_000_000;\n\nfunction vertexCount(points: ArrayLike<number>): number {\n return Math.floor(points.length / 2);\n}\n\n/**\n * Whether `(x, y)` is inside the polygon, by the even-odd rule.\n *\n * @param points - Flat ring, implicitly closed.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns `false` for a ring with fewer than three vertices. A point exactly on the outline\n * may be either; `nearestArea` treats the outline separately.\n */\nexport function pointInPolygon(points: ArrayLike<number>, x: number, y: number): boolean {\n const n = vertexCount(points);\n if (n < 3) return false;\n let inside = false;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const xi = points[2 * i]!;\n const yi = points[2 * i + 1]!;\n const xj = points[2 * j]!;\n const yj = points[2 * j + 1]!;\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;\n }\n return inside;\n}\n\n/**\n * The distance from `(x, y)` to the outline of a polygon (its closing edge included).\n *\n * @param points - Flat ring, implicitly closed.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns The distance; `Infinity` for an empty ring.\n */\nexport function distanceToOutline(points: ArrayLike<number>, x: number, y: number): number {\n const n = vertexCount(points);\n if (n === 0) return Infinity;\n const p = { x, y };\n let best = Infinity;\n const edges = n === 1 ? 1 : n === 2 ? 1 : n;\n for (let i = 0; i < edges; i++) {\n const j = n === 1 ? 0 : (i + 1) % n;\n const q = closestOnSegment(p, points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!);\n const d = Math.hypot(q.x - x, q.y - y);\n if (d < best) best = d;\n }\n return best;\n}\n\n/**\n * The unsigned area of a polygon (shoelace).\n *\n * @param points - Flat ring, implicitly closed.\n * @returns The area; `0` for fewer than three vertices.\n */\nexport function polygonArea(points: ArrayLike<number>): number {\n const n = vertexCount(points);\n if (n < 3) return 0;\n let sum = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n sum += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;\n }\n return Math.abs(sum) / 2;\n}\n\n/**\n * A polygon as an SVG path (`M … L … Z`) from its first vertex, wound the same way whatever the\n * input's winding.\n * A batched path of overlapping polygons filled with the nonzero rule would otherwise cut a\n * hole where a clockwise ring overlaps an anticlockwise one.\n *\n * @param points - Flat ring.\n * @returns Path data; `\"\"` with no vertices.\n */\nexport function areaPath(points: ArrayLike<number>): string {\n const n = vertexCount(points);\n if (n === 0) return \"\";\n let signed = 0;\n for (let i = 0, j = n - 1; i < n; j = i++) signed += points[2 * j]! * points[2 * i + 1]! - points[2 * i]! * points[2 * j + 1]!;\n const reversed = signed < 0;\n const at = (k: number) => (reversed ? (n - k) % n : k); // still starts at vertex 0\n let d = `M${points[2 * at(0)]} ${points[2 * at(0) + 1]}`;\n if (n === 1) return `${d}h0`;\n for (let k = 1; k < n; k++) d += `L${points[2 * at(k)]} ${points[2 * at(k) + 1]}`;\n return `${d}Z`;\n}\n\n/**\n * The centre a label is drawn at: the mean of the vertices.\n *\n * @param points - Flat ring.\n * @returns The mean, or `null` for an empty ring.\n */\nexport function areaCentre(points: ArrayLike<number>): Point | null {\n const n = vertexCount(points);\n if (n === 0) return null;\n let sx = 0;\n let sy = 0;\n for (let i = 0; i < n; i++) {\n sx += points[2 * i]!;\n sy += points[2 * i + 1]!;\n }\n return { x: sx / n, y: sy / n };\n}\n\n/**\n * Index a set of polygons.\n *\n * @param items - The polygons.\n * @param cell - The grid cell side in image pixels. Defaults to the median of the polygons'\n * larger bounding-box sides, within `[8, 256]`, doubled if the grid would be huge.\n * @returns The index.\n */\nexport function buildAreaIndex(items: readonly Area[], cell?: number): AreaIndex {\n const count = items.length;\n const bounds = new Float64Array(count * 4).fill(Number.NaN);\n const size = new Float64Array(count);\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n const sides: number[] = [];\n items.forEach((item, a) => {\n const p = item.points;\n let x0 = Infinity;\n let y0 = Infinity;\n let x1 = -Infinity;\n let y1 = -Infinity;\n for (let i = 0; i + 1 < p.length; i += 2) {\n const x = p[i]!;\n const y = p[i + 1]!;\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n }\n if (!(x1 >= x0)) return;\n bounds[4 * a] = x0;\n bounds[4 * a + 1] = y0;\n bounds[4 * a + 2] = x1;\n bounds[4 * a + 3] = y1;\n size[a] = polygonArea(p);\n minX = Math.min(minX, x0);\n minY = Math.min(minY, y0);\n maxX = Math.max(maxX, x1);\n maxY = Math.max(maxY, y1);\n sides.push(Math.max(x1 - x0, y1 - y0));\n });\n if (sides.length === 0) {\n return { items, bounds, size, cell: 1, x0: 0, y0: 0, cols: 1, rows: 1, starts: new Uint32Array(2), entries: new Uint32Array(0) };\n }\n sides.sort((a, b) => a - b);\n let side = cell ?? Math.min(256, Math.max(8, sides[sides.length >> 1]!));\n const width = maxX - minX;\n const height = maxY - minY;\n const cellsAt = (s: number) => (Math.floor(width / s) + 1) * (Math.floor(height / s) + 1);\n const entriesAt = (s: number) => {\n let total = 0;\n for (let a = 0; a < count; a++) {\n if (Number.isNaN(bounds[4 * a]!)) continue;\n total += (Math.floor((bounds[4 * a + 2]! - bounds[4 * a]!) / s) + 1) * (Math.floor((bounds[4 * a + 3]! - bounds[4 * a + 1]!) / s) + 1);\n }\n return total;\n };\n // A pathological extent (one far outlier, a tiny `cell`) must not allocate a huge grid.\n while (cellsAt(side) > MAX_CELLS || entriesAt(side) > MAX_ENTRIES) side *= 2;\n const cols = Math.floor(width / side) + 1;\n const rows = Math.floor(height / side) + 1;\n const cellX = (x: number) => Math.min(cols - 1, Math.max(0, Math.floor((x - minX) / side)));\n const cellY = (y: number) => Math.min(rows - 1, Math.max(0, Math.floor((y - minY) / side)));\n\n // Two passes (count, then fill) into a CSR layout: no per-cell arrays.\n const starts = new Uint32Array(cols * rows + 1);\n const visit = (fn: (c: number, a: number) => void) => {\n for (let a = 0; a < count; a++) {\n if (Number.isNaN(bounds[4 * a]!)) continue;\n const cx0 = cellX(bounds[4 * a]!);\n const cx1 = cellX(bounds[4 * a + 2]!);\n const cy0 = cellY(bounds[4 * a + 1]!);\n const cy1 = cellY(bounds[4 * a + 3]!);\n for (let cy = cy0; cy <= cy1; cy++) for (let cx = cx0; cx <= cx1; cx++) fn(cy * cols + cx, a);\n }\n };\n visit((c) => starts[c + 1]!++);\n for (let c = 0; c < cols * rows; c++) starts[c + 1]! += starts[c]!;\n const fill = starts.slice(0, cols * rows);\n const entries = new Uint32Array(starts[cols * rows]!);\n visit((c, a) => {\n entries[fill[c]!++] = a;\n });\n return { items, bounds, size, cell: side, x0: minX, y0: minY, cols, rows, starts, entries };\n}\n\n/**\n * The indices of the areas whose bounding box meets `[left, right] × [top, bottom]`, ascending.\n * The first, cheap stage of every query; `ellipseIndex` reuses it over ellipse bounding boxes.\n */\nexport function areaCandidates(index: AreaIndex, left: number, top: number, right: number, bottom: number): number[] {\n const { cell, x0, y0, cols, rows, starts, entries, bounds } = index;\n if (entries.length === 0) return [];\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 seen = new Set<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 a = entries[k]!;\n if (seen.has(a)) continue;\n if (bounds[4 * a]! <= right && bounds[4 * a + 2]! >= left && bounds[4 * a + 1]! <= bottom && bounds[4 * a + 3]! >= top) seen.add(a);\n }\n }\n }\n return [...seen].sort((a, b) => a - b);\n}\n\n/**\n * The area under a point: one whose outline passes within `radius`, or else one that contains it.\n *\n * An outline is the more precise gesture, so it wins: among areas whose outline is within\n * `radius` the nearest is picked, and only without one the containing area. Ties (equal\n * distance, or several containing areas) go to the smaller area, so a quad drawn inside a\n * region is picked rather than the region, then to the earlier one. The result does not depend\n * on cell order.\n *\n * @param index - The index.\n * @param p - The query, in image coordinates.\n * @param radius - How far from an outline the query still picks it, in image pixels.\n * @returns The area, or `null`.\n */\nexport function nearestArea(index: AreaIndex, p: Point, radius: number): AreaHit | null {\n if (!(radius >= 0)) return null;\n const { items, size } = index;\n let edge: AreaHit | null = null;\n let inner: AreaHit | null = null;\n for (const a of areaCandidates(index, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {\n const points = items[a]!.points;\n const distance = distanceToOutline(points, p.x, p.y);\n const inside = pointInPolygon(points, p.x, p.y);\n const hit: AreaHit = { id: items[a]!.id, index: a, inside, distance };\n if (distance <= radius) {\n if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;\n } else if (inside && (inner === null || size[a]! < size[inner.index]!)) {\n inner = hit;\n }\n }\n return edge ?? inner;\n}\n\n/**\n * The areas any part of which is inside `rect`: a vertex, an edge crossing it, or the whole\n * rectangle lying inside the polygon.\n *\n * @param index - The index.\n * @param rect - The band, in image coordinates. A negative extent is read as the box between\n * its corners.\n * @returns Their ids, in the order the areas were given.\n */\nexport function areasInRect(index: AreaIndex, rect: Rect): AreaId[] {\n const box = {\n x: Math.min(rect.x, rect.x + rect.width),\n y: Math.min(rect.y, rect.y + rect.height),\n width: Math.abs(rect.width),\n height: Math.abs(rect.height),\n };\n const out: AreaId[] = [];\n for (const a of areaCandidates(index, box.x, box.y, box.x + box.width, box.y + box.height)) {\n if (polygonTouchesRect(index.items[a]!.points, box)) out.push(index.items[a]!.id);\n }\n return out;\n}\n\nfunction polygonTouchesRect(points: ArrayLike<number>, rect: Rect): boolean {\n const n = vertexCount(points);\n const right = rect.x + rect.width;\n const bottom = rect.y + rect.height;\n for (let i = 0; i < n; i++) {\n const x = points[2 * i]!;\n const y = points[2 * i + 1]!;\n if (x >= rect.x && x <= right && y >= rect.y && y <= bottom) return true;\n }\n const edges = n < 2 ? 0 : n === 2 ? 1 : n;\n for (let i = 0; i < edges; i++) {\n const j = (i + 1) % n;\n if (segmentTouchesRect(points[2 * i]!, points[2 * i + 1]!, points[2 * j]!, points[2 * j + 1]!, rect)) return true;\n }\n return pointInPolygon(points, rect.x, rect.y);\n}\n","/**\n * How `AreaSet` groups its regions into batched paths: by appearance (state, role, colours),\n * either one batch per appearance or consecutive runs in item order. Pure, so the keys are\n * unit-tested without a DOM (ADR-0004 rule 1).\n */\n\nimport { areaPath, type Area, type AreaId } from \"./areaIndex\";\nimport type { OverlayRole } from \"./overlayRole\";\n\n/** An item as batching sees it: a region and its appearance overrides. */\nexport interface BatchableArea extends Area {\n role?: OverlayRole | undefined;\n stroke?: string | undefined;\n fill?: string | undefined;\n}\n\n/** The regions of one batched path. */\nexport interface AreaBatch {\n /** The appearance key; several runs of one appearance share it under `paintOrder: \"items\"`. */\n key: string;\n /** A unique key for rendering (the appearance key, plus the run number for runs). */\n id: string;\n role: OverlayRole;\n /** The outline colour when the item or the layer set one; `undefined` paints the role. */\n stroke: string | undefined;\n /** The fill colour when an item set one; `undefined` paints the outline colour. */\n fill: string | undefined;\n dim: boolean;\n /** Item positions, ascending. */\n indices: number[];\n /** The outlines, concatenated (without the selected items under `selectionFill: \"item\"`). */\n d: string;\n /** Each item's own ring, aligned with `indices`, when fills are drawn apart from outlines. */\n fills: string[] | null;\n}\n\n/** What decides the batches. */\nexport interface AreaBatchOptions {\n /** The role of an item that names none. */\n role: OverlayRole;\n /** The layer's outline colour. */\n stroke: string | undefined;\n /** `\"items\"` makes batches consecutive runs in item order. */\n paintOrder: \"appearance\" | \"items\";\n /** `\"evenodd\"` gives every item its own fill path. */\n fillRule: \"nonzero\" | \"evenodd\";\n /** `\"item\"` keeps a selected item in its own batch, fill included. */\n selectionFill: \"selection\" | \"item\";\n selected: ReadonlySet<AreaId>;\n isDimmed: (id: AreaId) => boolean;\n}\n\n/**\n * The appearance key of an item. Without a custom colour it is `dim|role`, as before colours\n * existed; a custom colour appends the outline and fill it was given.\n *\n * @param dim - Whether the item is dimmed.\n * @param role - The item's role.\n * @param stroke - The outline colour, if any.\n * @param fill - The fill colour, if any.\n * @returns The key.\n */\nexport function areaBatchKey(dim: boolean, role: OverlayRole, stroke: string | undefined, fill: string | undefined): string {\n const base = `${dim ? 1 : 0}|${role}`;\n return stroke || fill ? `${base}|${stroke ?? \"\"}|${fill ?? \"\"}` : base;\n}\n\n/**\n * Groups items into batches. Selected items go to `picked` (drawn on top in the selection\n * colour), unless `selectionFill` is `\"item\"`: then they stay in their batch for the fill and\n * `picked` carries only their outlines.\n *\n * @param items - The regions.\n * @param options - What decides the grouping.\n * @returns The appearance batches in paint order, and the selected overlay.\n */\nexport function batchAreas(items: readonly BatchableArea[], options: AreaBatchOptions): { normal: AreaBatch[]; picked: AreaBatch | null } {\n const { role, stroke, paintOrder, fillRule, selectionFill, selected, isDimmed } = options;\n const keepSelected = selectionFill === \"item\";\n // Fills apart from outlines: needed per item for even-odd, and to leave selected outlines out.\n const separate = fillRule === \"evenodd\" || keepSelected;\n const byKey = new Map<string, AreaBatch>();\n const runs: AreaBatch[] = [];\n const picked: AreaBatch = { key: \"selected\", id: \"selected\", role: \"selection\", stroke: undefined, fill: undefined, dim: false, indices: [], d: \"\", fills: fillRule === \"evenodd\" && !keepSelected ? [] : null };\n\n items.forEach((item, i) => {\n const isSelected = selected.has(item.id);\n if (isSelected) {\n const d = areaPath(item.points);\n picked.indices.push(i);\n picked.d += d;\n picked.fills?.push(d);\n if (!keepSelected) return;\n }\n const itemRole = item.role ?? role;\n const itemStroke = item.stroke ?? stroke;\n const dim = isDimmed(item.id);\n const key = areaBatchKey(dim, itemRole, itemStroke, item.fill);\n let batch = paintOrder === \"items\" ? runs[runs.length - 1] : byKey.get(key);\n if (!batch || batch.key !== key) {\n batch = { key, id: paintOrder === \"items\" ? `${key}#${runs.length}` : key, role: itemRole, stroke: itemStroke, fill: item.fill, dim, indices: [], d: \"\", fills: separate ? [] : null };\n byKey.set(key, batch);\n runs.push(batch);\n }\n const d = areaPath(item.points);\n batch.indices.push(i);\n batch.fills?.push(d);\n if (!(isSelected && keepSelected)) batch.d += d;\n });\n return { normal: runs, picked: picked.indices.length > 0 ? picked : null };\n}\n","/**\n * Many closed regions over the image, hoverable and selectable: marker quads, drawn polygons,\n * region annotations, defect outlines.\n *\n * Drawn as a handful of batched paths, one per (state, role, colours), each outline with its 12 % fill\n * in one element (ADR-0004 rule 1); the pointer is resolved by `nearestArea` through the\n * stage's hit registry, never by the DOM (rule 2); strokes and labels are sized in screen\n * pixels (rule 4). A scene of 5,000 quads is a dozen DOM nodes plus at most 200 labels.\n */\n\nimport { useMemo, useState } from \"react\";\n\nimport { batchAreas, type AreaBatch } from \"./areaBatching\";\nimport { areaCentre, areaPath, buildAreaIndex, nearestArea, type Area, type AreaId } from \"./areaIndex\";\nimport { useLabelIndices } from \"./labelLod\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\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 } from \"./stage/view\";\n\n/** One region of an `AreaSet`. */\nexport interface AreaSetItem extends Area {\n /** The overlay role it is painted in. Defaults to the layer's `role`. */\n role?: OverlayRole | undefined;\n /** Text drawn at its centre (the mean of its vertices), when the zoom leaves room. */\n label?: string | undefined;\n /**\n * CSS colour of its outline (`#hex`, `var(--x)`, `color-mix(…)`; used as given). Overrides\n * the role and the layer's `stroke`. Items sharing a colour share a batch.\n */\n stroke?: string | undefined;\n /** CSS colour of its fill. Defaults to its outline colour. */\n fill?: string | undefined;\n}\n\n/** Props of `AreaSet`. */\nexport interface AreaSetProps {\n /** The regions, as closed rings in image coordinates. */\n items: readonly AreaSetItem[];\n /** The role of an item that names none. Defaults to `\"feature\"`: they are detected regions. */\n role?: OverlayRole | undefined;\n /** The hovered id, when the app controls hover (a list beside the stage hovers regions too). */\n hoveredId?: AreaId | null | undefined;\n /** Called when the region under the pointer changes. `null` when it leaves every region. */\n onHoverChange?: ((id: AreaId | null) => void) | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour. */\n selectedIds?: Iterable<AreaId> | 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<AreaId> | ((id: AreaId) => boolean) | undefined;\n /**\n * A press landed on a region. Setting it makes the layer claim presses inside its regions,\n * so the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for\n * a touch tap), so `useShapeDrag` 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: AreaId, 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 /**\n * Tick the first vertex: a short line from vertex 0 towards the centre, so the orientation\n * of a marker quad reads (the overlay grammar's \"corner 0 ticked\"). Off by default.\n */\n firstVertexTick?: boolean | undefined;\n /** CSS colour of every outline that names none of its own, in place of its role's. */\n stroke?: string | undefined;\n /** The fill's alpha, 0 to 1. Defaults to 0.12. */\n fillOpacity?: number | undefined;\n /**\n * How a self-overlapping ring is filled. `\"nonzero\"` (the default) fills everything a ring\n * encloses; `\"evenodd\"` leaves the doubly-wound part of a self-intersecting ring open, as\n * a rasteriser would. With `\"evenodd\"` every region's fill is its own path (even-odd across\n * a batched path would cut a hole where two regions overlap); outlines stay batched.\n */\n fillRule?: \"nonzero\" | \"evenodd\" | undefined;\n /**\n * The paint order. `\"appearance\"` (the default) draws one batch per appearance, in order of\n * first appearance. `\"items\"` draws consecutive runs in item order, so a later region\n * covers an earlier one of another appearance (a subtract region over an add region); more\n * runs mean more paths, so use it when the order matters.\n */\n paintOrder?: \"appearance\" | \"items\" | undefined;\n /**\n * What a selected region looks like. `\"selection\"` (the default) paints it in the\n * selection colour, fill and outline. `\"item\"` keeps its own fill (and its place in the\n * paint order) and restyles only the outline.\n */\n selectionFill?: \"selection\" | \"item\" | undefined;\n /** Draw the dark band under every outline. On by default; off for a fast, flat layer. */\n halo?: boolean | undefined;\n /** CSS colour of selected regions. 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.area`. */\n priority?: number | undefined;\n /** The layer's accessible name. Defaults to \"Areas\". */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\nconst LABEL = overlayRole(\"label\");\n/** The fill of a region under its outline (overlay grammar: outline plus 12 % fill). */\nconst FILL_OPACITY = 0.12;\n/** How long the first-vertex tick is, in screen pixels, at most. */\nconst TICK_PX = 8;\n\n/**\n * A selectable set of closed regions inside an `ImageStage`.\n *\n * - **Rendering**: an outline and its 12 % fill, in the item's role (`feature` by default) or its own\n * `stroke` / `fill` colours (`fillOpacity`, `fillRule`, `paintOrder` and `selectionFill` tune the fill).\n * Rings are wound alike before they are batched, so overlapping regions never cut a hole in\n * each other.\n * - **States**, from visual-language §5: default 1.5 screen px (1 for `model` and\n * `structure`), hover 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every\n * outline has a halo. A region has no ring: its outline at 2.5 px is the mark.\n * - **Labels** at the centre of a region, only where regions are at least 24 screen px apart,\n * at most 200 at a time. The hovered and selected regions always carry theirs.\n * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of\n * an outline picks that region, else the smallest region containing the point. `onHoverChange`\n * and `onItemPress` here, and `useStageHitTest` for an app that arbitrates between layers.\n *\n * The SVG carries `data-hovered` (the hovered id).\n */\nexport function AreaSet({\n items,\n role = \"feature\",\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n labels = true,\n firstVertexTick = false,\n stroke,\n fillOpacity = FILL_OPACITY,\n fillRule = \"nonzero\",\n paintOrder = \"appearance\",\n selectionFill = \"selection\",\n halo = true,\n selectionStroke = overlayRole(\"selection\"),\n layerId,\n priority = STAGE_HIT_PRIORITY.area,\n label = \"Areas\",\n}: AreaSetProps) {\n const stage = useStage();\n const px = useScreenPx();\n const unit = px(1);\n\n const index = useMemo(() => buildAreaIndex(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: AreaId) => 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<AreaId | null>(null);\n const hoverId = hoveredId !== undefined ? hoveredId : ownHover;\n\n useStageHitLayer({\n layerId,\n priority,\n pick: (point, radius) => {\n const hit = nearestArea(index, point, radius);\n return hit ? { id: hit.id, dist: hit.inside ? 0 : hit.distance } : null;\n },\n onHover: (id) => {\n setOwnHover(id);\n onHoverChange?.(id);\n },\n onPress: onItemPress ? (id, event) => onItemPress(id, event) : undefined,\n });\n\n // Regions 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 () => batchAreas(items, { role, stroke, paintOrder, fillRule, selectionFill, selected: selectedSet, isDimmed }),\n [items, role, stroke, paintOrder, fillRule, selectionFill, selectedSet, isDimmed],\n );\n const keepFill = selectionFill === \"item\";\n const evenOdd = fillRule === \"evenodd\";\n const separate = evenOdd || keepFill;\n\n // The tick is a line a few screen pixels long, so it is the one thing here that follows\n // the zoom: regenerated per zoom step, in O(regions).\n const ticks = useMemo(() => {\n if (!firstVertexTick) return [];\n const batches = groups.picked ? [...groups.normal, groups.picked] : groups.normal;\n return batches.map((batch) => {\n let d = \"\";\n for (const i of batch.indices) {\n // A selected item keeping its fill is ticked in the selection batch only.\n if (keepFill && batch !== groups.picked && selectedSet.has(items[i]!.id)) continue;\n d += tickPath(items[i]!.points, TICK_PX * unit);\n }\n return { batch, d };\n });\n }, [firstVertexTick, groups, items, unit, keepFill, selectedSet]);\n\n const hoverItem = hoverId !== null ? items[positionOf.get(hoverId) ?? -1] : undefined;\n const hoverSelected = hoverItem ? selectedSet.has(hoverItem.id) : false;\n const hoverRole = hoverItem?.role ?? role;\n const hoverStroke = hoverItem ? (hoverItem.stroke ?? stroke ?? overlayRole(hoverRole)) : undefined;\n\n // Labels sit at the centre of a region; the layout is the shared level-of-detail rule.\n const anchors = useMemo(() => {\n const xy = new Float64Array(items.length * 2);\n const labelled: number[] = [];\n items.forEach((item, i) => {\n const c = areaCentre(item.points);\n xy[2 * i] = c?.x ?? Number.NaN;\n xy[2 * i + 1] = c?.y ?? Number.NaN;\n if (item.label) labelled.push(i);\n });\n return { xy, labelled };\n }, [items]);\n const forced = useMemo(() => {\n const list: number[] = [];\n if (hoverItem?.label) list.push(positionOf.get(hoverItem.id)!);\n for (const id of selectedSet) {\n const i = positionOf.get(id);\n if (i !== undefined && items[i]!.label) list.push(i);\n }\n return list;\n }, [hoverItem, selectedSet, positionOf, items]);\n const shownLabels = useLabelIndices({ enabled: labels, xy: anchors.xy, labelled: anchors.labelled, forced });\n\n const widthOf = (itemRole: OverlayRole, state: \"default\" | \"hover\" | \"selected\"): number => {\n const thin = itemRole === \"model\" || itemRole === \"structure\";\n return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== \"selected\" ? 0.5 : 0));\n };\n\n const strokeOf = (batch: AreaBatch) => batch.stroke ?? overlayRole(batch.role);\n\n /** Each region's fill as its own even-odd path, or all of them as one path. */\n const fillPaths = (batch: AreaBatch, colour: string, tag: string) =>\n evenOdd ? (\n batch.fills!.map((d, k) => <path key={batch.indices[k]} data-fill={tag} d={d} fill={colour} fillOpacity={fillOpacity} fillRule=\"evenodd\" />)\n ) : (\n <path data-fill={tag} d={batch.fills!.join(\"\")} fill={colour} fillOpacity={fillOpacity} />\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 role=\"img\"\n aria-label={`${label}: ${items.length} ${items.length === 1 ? \"area\" : \"areas\"}, ${selectedSet.size} selected`}\n data-hovered={hoverId ?? undefined}\n >\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {groups.normal.map((batch) => (\n <g key={batch.id} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && (!separate || batch.d !== \"\") && <path d={batch.d} stroke={HALO} strokeWidth={widthOf(batch.role, \"default\") + px(2)} opacity={0.6} />}\n {separate && fillPaths(batch, batch.fill ?? strokeOf(batch), batch.key)}\n {(!separate || batch.d !== \"\") && (\n <path\n data-batch={batch.key}\n d={batch.d}\n fill={separate ? undefined : (batch.fill ?? strokeOf(batch))}\n fillOpacity={separate ? undefined : fillOpacity}\n stroke={strokeOf(batch)}\n strokeWidth={widthOf(batch.role, \"default\")}\n />\n )}\n </g>\n ))}\n {groups.picked && (\n <>\n {halo && <path d={groups.picked.d} stroke={HALO} strokeWidth={widthOf(\"selection\", \"selected\") + px(2)} />}\n {evenOdd && !keepFill && fillPaths(groups.picked, selectionStroke, \"selected\")}\n <path\n data-selected-areas=\"\"\n d={groups.picked.d}\n fill={evenOdd || keepFill ? undefined : selectionStroke}\n fillOpacity={evenOdd || keepFill ? undefined : fillOpacity}\n stroke={selectionStroke}\n strokeWidth={widthOf(\"selection\", \"selected\")}\n />\n </>\n )}\n {hoverItem && (\n <>\n {halo && (\n <path d={areaPath(hoverItem.points)} stroke={HALO} strokeWidth={widthOf(hoverRole, hoverSelected ? \"selected\" : \"hover\") + px(2)} />\n )}\n <path\n data-hovered-area=\"\"\n d={areaPath(hoverItem.points)}\n stroke={hoverSelected ? selectionStroke : hoverStroke}\n strokeWidth={widthOf(hoverRole, hoverSelected ? \"selected\" : \"hover\")}\n />\n </>\n )}\n {ticks.map(({ batch, d }) => (\n <g key={`tick|${batch.id}`} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && <path d={d} stroke={HALO} strokeWidth={px(OVERLAY_STATE_WIDTH.selected + 2)} opacity={0.6} />}\n <path\n data-ticks={batch.key}\n d={d}\n stroke={batch === groups.picked ? selectionStroke : strokeOf(batch)}\n strokeWidth={px(OVERLAY_STATE_WIDTH.selected)}\n />\n </g>\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 <text key={items[i]!.id} x={anchors.xy[2 * i]} y={anchors.xy[2 * i + 1]} fill={LABEL} textAnchor=\"middle\" dominantBaseline=\"central\">\n {items[i]!.label}\n </text>\n ))}\n </g>\n )}\n </svg>\n );\n}\n\n/**\n * The first-vertex tick of a ring: a segment from vertex 0 towards the ring's centre, at most\n * `length` long and at most 45 % of the way there, so a small quad's tick stays inside it.\n */\nfunction tickPath(points: ArrayLike<number>, length: number): string {\n const c = areaCentre(points);\n if (c === null || points.length < 4) return \"\";\n const x = points[0]!;\n const y = points[1]!;\n const dist = Math.hypot(c.x - x, c.y - y);\n if (!(dist > 0)) return \"\";\n const k = Math.min(length, 0.45 * dist) / dist;\n return `M${x} ${y}L${Math.round((x + (c.x - x) * k) * 1000) / 1000} ${Math.round((y + (c.y - y) * k) * 1000) / 1000}`;\n}\n","/**\n * A spatial index over many ellipses: which one is under the pointer, and which ones a\n * rubber band touched.\n *\n * The grid is `areaIndex.ts`'s (CSR layout over bounding boxes, built once per change of the\n * items); a query runs the exact tests on the few ellipses whose box is near the pointer. The\n * exact tests are in the ellipse's own frame: containment is one quadratic form, and the\n * distance to the outline is the true Euclidean distance (a few Newton steps on the\n * parametrisation), not a scaled approximation, so a thin ellipse is picked as precisely as a\n * round one. It imports neither React nor the DOM.\n *\n * An ellipse with a non-finite value or a semi-axis not above zero is skipped: it has no\n * outline to draw or to pick.\n */\n\nimport { areaCandidates, buildAreaIndex, type AreaIndex } from \"./areaIndex\";\nimport type { Point } from \"./measureGeometry\";\nimport type { Rect } from \"./stage/view\";\n\n/** An ellipse's identity. */\nexport type EllipseId = string | number;\n\n/** One ellipse. */\nexport interface Ellipse {\n /** Its identity, unique in the set. */\n id: EllipseId;\n /** Centre x, image pixels. */\n x: number;\n /** Centre y, image pixels. */\n y: number;\n /** Semi-axis along the rotated x axis, image pixels. */\n rx: number;\n /** Semi-axis along the rotated y axis, image pixels. */\n ry: number;\n /** Rotation of the `rx` axis, radians clockwise on screen (y points down). Defaults to 0. */\n angle?: number | undefined;\n}\n\n/**\n * An index built by `buildEllipseIndex`. Treat it as opaque and query it with `nearestEllipse`\n * and `ellipsesInRect`; its layout may change.\n */\nexport interface EllipseIndex {\n /** The ellipses, in the order given. */\n readonly items: readonly Ellipse[];\n /** The grid over their bounding boxes (an `AreaIndex` of boxes, one per ellipse). */\n readonly grid: AreaIndex;\n /** Per ellipse, its area `π·rx·ry`, used to prefer the smaller of nested ellipses; `NaN` for a degenerate one. */\n readonly size: Float64Array;\n}\n\n/** The ellipse `nearestEllipse` picked. */\nexport interface EllipseHit {\n /** Its id. */\n id: EllipseId;\n /** Its position in the array the index was built from. */\n index: number;\n /** Whether the query is inside the ellipse. */\n inside: boolean;\n /** The distance from the query to the ellipse's outline, in image pixels (also when inside). */\n distance: number;\n}\n\nfunction usable(e: Ellipse): boolean {\n return e.rx > 0 && e.ry > 0 && Number.isFinite(e.x + e.y + e.rx + e.ry + (e.angle ?? 0));\n}\n\n/**\n * The axis-aligned bounding box of an ellipse.\n *\n * @param e - The ellipse.\n * @returns `[minX, minY, maxX, maxY]`, or `null` for a degenerate ellipse.\n */\nexport function ellipseBounds(e: Ellipse): [number, number, number, number] | null {\n if (!usable(e)) return null;\n const c = Math.cos(e.angle ?? 0);\n const s = Math.sin(e.angle ?? 0);\n const hx = Math.hypot(e.rx * c, e.ry * s);\n const hy = Math.hypot(e.rx * s, e.ry * c);\n return [e.x - hx, e.y - hy, e.x + hx, e.y + hy];\n}\n\n/** The query in the ellipse's frame: translated to its centre and rotated by `-angle`. */\nfunction toFrame(e: Ellipse, x: number, y: number): Point {\n const c = Math.cos(e.angle ?? 0);\n const s = Math.sin(e.angle ?? 0);\n const dx = x - e.x;\n const dy = y - e.y;\n return { x: c * dx + s * dy, y: -s * dx + c * dy };\n}\n\n/**\n * Whether `(x, y)` is inside the ellipse (its outline counts as inside).\n *\n * @param e - The ellipse.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns `false` for a degenerate ellipse.\n */\nexport function pointInEllipse(e: Ellipse, x: number, y: number): boolean {\n if (!usable(e)) return false;\n const p = toFrame(e, x, y);\n return (p.x / e.rx) ** 2 + (p.y / e.ry) ** 2 <= 1;\n}\n\n/** Newton steps on the ellipse's parametrisation; enough to converge from the start below. */\nconst NEWTON_STEPS = 12;\n\n/**\n * The Euclidean distance from `(x, y)` to the outline of an ellipse.\n *\n * The query is folded into the first quadrant of the ellipse's frame and the nearest outline\n * point found by Newton's method on the parameter `θ` of `(a·cos θ, b·sin θ)`, started from the\n * better of a coarse scan so a thin ellipse and a query near its centre both converge.\n *\n * @param e - The ellipse.\n * @param x - The query's x.\n * @param y - The query's y.\n * @returns The distance; `Infinity` for a degenerate ellipse.\n */\nexport function distanceToEllipse(e: Ellipse, x: number, y: number): number {\n if (!usable(e)) return Infinity;\n const p = toFrame(e, x, y);\n const px = Math.abs(p.x);\n const py = Math.abs(p.y);\n const a = e.rx;\n const b = e.ry;\n const squared = (t: number) => (a * Math.cos(t) - px) ** 2 + (b * Math.sin(t) - py) ** 2;\n // The squared distance can have two local minima in the quadrant (a query near the centre of\n // a thin ellipse), so start from the best of a coarse scan, then polish.\n let t = 0;\n let best = Infinity;\n const SCAN = 16;\n for (let k = 0; k <= SCAN; k++) {\n const candidate = (k / SCAN) * (Math.PI / 2);\n const value = squared(candidate);\n if (value < best) {\n best = value;\n t = candidate;\n }\n }\n for (let i = 0; i < NEWTON_STEPS; i++) {\n const c = Math.cos(t);\n const s = Math.sin(t);\n // f(θ) = d/dθ of half the squared distance; f' by differentiating again.\n const f = (b * b - a * a) * s * c + a * px * s - b * py * c;\n const df = (b * b - a * a) * (c * c - s * s) + a * px * c + b * py * s;\n if (!(Math.abs(df) > 1e-12)) break;\n const next = Math.min(Math.PI / 2, Math.max(0, t - f / df));\n if (squared(next) > squared(t)) break; // a step that does not descend is noise\n t = next;\n }\n return Math.sqrt(squared(t));\n}\n\n/**\n * An ellipse as an SVG path: two arcs, exactly, so it stays round at any zoom.\n *\n * @param cx - Centre x, image pixels.\n * @param cy - Centre y, image pixels.\n * @param rx - Semi-axis along the rotated x axis, image pixels.\n * @param ry - Semi-axis along the rotated y axis, image pixels.\n * @param angle - Rotation of the `rx` axis, radians clockwise on screen.\n * @returns Path data, or `\"\"` for a degenerate ellipse (a non-finite value, or a radius not above zero).\n */\nexport function ellipsePath(cx: number, cy: number, rx: number, ry: number, angle = 0): string {\n if (!(rx > 0) || !(ry > 0) || !Number.isFinite(cx + cy + rx + ry + angle)) return \"\";\n const dx = rx * Math.cos(angle);\n const dy = rx * Math.sin(angle);\n const degrees = round((angle * 180) / Math.PI);\n const arc = `A${round(rx)} ${round(ry)} ${degrees} 1 0`;\n return `M${round(cx + dx)} ${round(cy + dy)}${arc} ${round(cx - dx)} ${round(cy - dy)}${arc} ${round(cx + dx)} ${round(cy + dy)}`;\n}\n\n/** Round to 1/1000 of an image pixel. */\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n\n/**\n * Index a set of ellipses.\n *\n * @param items - The ellipses.\n * @param cell - The grid cell side in image pixels; see `buildAreaIndex` for the default.\n * @returns The index.\n */\nexport function buildEllipseIndex(items: readonly Ellipse[], cell?: number): EllipseIndex {\n const size = new Float64Array(items.length).fill(Number.NaN);\n const boxes = items.map((item, i) => {\n const box = ellipseBounds(item);\n if (box === null) return { id: i, points: [] as number[] };\n size[i] = Math.PI * item.rx * item.ry;\n const [x0, y0, x1, y1] = box;\n return { id: i, points: [x0, y0, x1, y0, x1, y1, x0, y1] };\n });\n return { items, grid: buildAreaIndex(boxes, cell), size };\n}\n\n/**\n * The ellipse under a point: one whose outline passes within `radius`, or else one that\n * contains it.\n *\n * An outline is the more precise gesture, so it wins: among ellipses whose outline is within\n * `radius` the nearest is picked, and only without one the containing ellipse. Ties (equal\n * distance, or several containing ellipses) go to the smaller ellipse, so a ring drawn inside\n * another is picked rather than the outer one, then to the earlier one.\n *\n * @param index - The index.\n * @param p - The query, in image coordinates.\n * @param radius - How far from an outline the query still picks it, in image pixels.\n * @returns The ellipse, or `null`.\n */\nexport function nearestEllipse(index: EllipseIndex, p: Point, radius: number): EllipseHit | null {\n if (!(radius >= 0)) return null;\n const { items, size } = index;\n let edge: EllipseHit | null = null;\n let inner: EllipseHit | null = null;\n for (const a of areaCandidates(index.grid, p.x - radius, p.y - radius, p.x + radius, p.y + radius)) {\n const e = items[a]!;\n const distance = distanceToEllipse(e, p.x, p.y);\n const hit: EllipseHit = { id: e.id, index: a, inside: pointInEllipse(e, p.x, p.y), distance };\n if (distance <= radius) {\n if (edge === null || distance < edge.distance || (distance === edge.distance && size[a]! < size[edge.index]!)) edge = hit;\n } else if (hit.inside && (inner === null || size[a]! < size[inner.index]!)) {\n inner = hit;\n }\n }\n return edge ?? inner;\n}\n\n/**\n * The ellipses any part of which is inside `rect`: the rectangle meets the outline, or lies\n * inside the ellipse, or contains it.\n *\n * @param index - The index.\n * @param rect - The band, in image coordinates. A negative extent is read as the box between\n * its corners.\n * @returns Their ids, in the order the ellipses were given.\n */\nexport function ellipsesInRect(index: EllipseIndex, rect: Rect): EllipseId[] {\n const x0 = Math.min(rect.x, rect.x + rect.width);\n const y0 = Math.min(rect.y, rect.y + rect.height);\n const x1 = Math.max(rect.x, rect.x + rect.width);\n const y1 = Math.max(rect.y, rect.y + rect.height);\n const out: EllipseId[] = [];\n for (const a of areaCandidates(index.grid, x0, y0, x1, y1)) {\n const e = index.items[a]!;\n if (rectMeetsEllipse(e, x0, y0, x1, y1)) out.push(e.id);\n }\n return out;\n}\n\n/** Whether the filled ellipse and the rectangle share a point (both convex). */\nfunction rectMeetsEllipse(e: Ellipse, x0: number, y0: number, x1: number, y1: number): boolean {\n // The rectangle contains the ellipse (its centre is inside), the ellipse contains a corner,\n // or an edge crosses the ellipse with both end points outside it: the three ways two convex\n // shapes meet.\n if (e.x >= x0 && e.x <= x1 && e.y >= y0 && e.y <= y1) return true;\n const corners: Point[] = [\n { x: x0, y: y0 },\n { x: x1, y: y0 },\n { x: x1, y: y1 },\n { x: x0, y: y1 },\n ];\n if (corners.some((c) => pointInEllipse(e, c.x, c.y))) return true;\n // Minimise the ellipse's quadratic form along each edge, in the ellipse's frame.\n for (let k = 0; k < 4; k++) {\n const a = toFrame(e, corners[k]!.x, corners[k]!.y);\n const b = toFrame(e, corners[(k + 1) % 4]!.x, corners[(k + 1) % 4]!.y);\n const ux = (b.x - a.x) / e.rx;\n const uy = (b.y - a.y) / e.ry;\n const vx = a.x / e.rx;\n const vy = a.y / e.ry;\n const len2 = ux * ux + uy * uy;\n const t = len2 > 0 ? Math.min(1, Math.max(0, -(ux * vx + uy * vy) / len2)) : 0;\n if ((vx + t * ux) ** 2 + (vy + t * uy) ** 2 <= 1) return true;\n }\n return false;\n}\n","/**\n * Many ellipses over the image whose size is data, hoverable and selectable: fitted ring\n * edges, edge-bit dots, drawn ellipse annotations.\n *\n * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a\n * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by\n * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).\n * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the\n * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.\n */\n\nimport { useMemo, useState } from \"react\";\n\nimport { buildEllipseIndex, ellipsePath, nearestEllipse, type Ellipse, type EllipseId, type EllipseIndex } from \"./ellipseIndex\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\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 } from \"./stage/view\";\n\n/** One ellipse of an `EllipseSet`. */\nexport interface EllipseSetItem extends Ellipse {\n /** The overlay role it is painted in. Defaults to the layer's `role`. */\n role?: OverlayRole | undefined;\n /** Draw it dashed (4 3 screen px), so two kinds differ by more than colour. */\n dashed?: boolean | undefined;\n /** Opacity in [0, 1], rounded to a tenth so ellipses still share paths. Defaults to 1. */\n opacity?: number | undefined;\n}\n\n/** Props of `EllipseSet`. */\nexport interface EllipseSetProps {\n /** The ellipses, in image coordinates. */\n items: readonly EllipseSetItem[];\n /** The role of an item that names none. Defaults to `\"feature\"`. */\n role?: OverlayRole | undefined;\n /** The hovered id, when the app controls hover: its ellipses are drawn at 2 px. */\n hoveredId?: EllipseId | null | undefined;\n /** Called when the ellipse under the pointer changes. `null` when it leaves every ellipse. Not called when `pickable` is off. */\n onHoverChange?: ((id: EllipseId | null) => void) | undefined;\n /** The selected ids, drawn at 2.5 px in the selection colour. */\n selectedIds?: Iterable<EllipseId> | undefined;\n /** Ids drawn at 35 % opacity, as a set or a predicate. Pass a stable value: a new one re-batches the layer. */\n dimmed?: Iterable<EllipseId> | ((id: EllipseId) => boolean) | undefined;\n /**\n * A press landed on an ellipse. Setting it makes the layer claim presses on its ellipses,\n * so the stage does not pan from them. The event is the `pointerdown` (the `pointerup` for\n * a touch tap), so `useShapeDrag` 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: EllipseId, event: StagePointerEvent) => void) | undefined;\n /**\n * Whether the layer takes part in the stage's hit-test. On by default. Turn it off for a\n * decorative layer (the ring outlines under a `PointSet` of centres), so it neither\n * hovers, nor claims presses, nor answers `useStageHitTest`.\n */\n pickable?: boolean | 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.area`. */\n priority?: number | undefined;\n /** Draw the dark band under every stroke. On by default. */\n halo?: boolean | undefined;\n /**\n * The smallest semi-axis, in screen pixels: a dot whose data size would vanish at the fitted\n * zoom is still drawn this large. Omit for none.\n */\n minRadius?: number | undefined;\n /** CSS colour of selected ellipses. Defaults to the overlay `selection` role. */\n selectionStroke?: string | undefined;\n /** Name the layer as an image for assistive technology. Without it the layer is decorative (`aria-hidden`). */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n\n/** The outline of an item, its semi-axes raised to `floor` image pixels. */\nfunction outlineOf(item: EllipseSetItem, floor: number): string {\n return ellipsePath(item.x, item.y, Math.max(item.rx, floor), Math.max(item.ry, floor), item.angle ?? 0);\n}\n\n/** The concatenated outlines of the items at `indices`. */\nfunction batchPath(items: readonly EllipseSetItem[], indices: readonly number[], floor: number): string {\n let d = \"\";\n for (const i of indices) d += outlineOf(items[i]!, floor);\n return d;\n}\n\n/**\n * The layer's entry in the stage's hit registry: a component, not a hook call in\n * `EllipseSet`, so `pickable={false}` really unregisters it. Renders nothing.\n */\nfunction EllipseHits({\n index,\n layerId,\n priority,\n onHover,\n onPress,\n}: {\n index: EllipseIndex;\n layerId: string | undefined;\n priority: number;\n onHover: (id: EllipseId | null) => void;\n onPress: ((id: EllipseId, event: StagePointerEvent) => void) | undefined;\n}) {\n useStageHitLayer({\n layerId,\n priority,\n pick: (point, radius) => {\n const hit = nearestEllipse(index, point, radius);\n return hit ? { id: hit.id, dist: hit.inside ? 0 : hit.distance } : null;\n },\n onHover,\n onPress: onPress ? (id, event) => onPress(id, event) : undefined,\n });\n return null;\n}\n\n/** The ellipses of one batched path. */\ninterface Batch {\n key: string;\n role: OverlayRole;\n dashed: boolean;\n opacity: number;\n dim: boolean;\n /** Item positions, ascending. */\n indices: number[];\n}\n\n/**\n * A batched set of ellipses inside an `ImageStage`.\n *\n * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;\n * the stroke is a screen constant.\n * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover\n * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.\n * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.\n * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of\n * an outline picks that ellipse, else the smallest ellipse containing the point.\n * `onHoverChange` and `onItemPress` here, and `useStageHitTest` for an app that arbitrates\n * between layers. `pickable={false}` turns it off.\n *\n * The SVG carries `data-ellipses` (the count) and `data-hovered` (the hovered id).\n */\nexport function EllipseSet({\n items,\n role = \"feature\",\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n pickable = true,\n layerId,\n priority = STAGE_HIT_PRIORITY.area,\n halo = true,\n minRadius,\n selectionStroke = overlayRole(\"selection\"),\n label,\n}: EllipseSetProps) {\n const stage = useStage();\n const px = useScreenPx();\n const unit = px(1);\n\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: EllipseId) => set.has(id);\n }, [dimmed]);\n\n const index = useMemo(() => (pickable ? buildEllipseIndex(items) : null), [items, pickable]);\n const [ownHover, setOwnHover] = useState<EllipseId | null>(null);\n const hoverId = hoveredId !== undefined ? hoveredId : pickable ? ownHover : null;\n\n const batches = useMemo(() => {\n const normal = new Map<string, Batch>();\n const picked: Batch = { key: \"selected\", role: \"selection\", dashed: false, opacity: 1, dim: false, indices: [] };\n items.forEach((item, i) => {\n if (selectedSet.has(item.id)) {\n picked.indices.push(i);\n return;\n }\n const itemRole = item.role ?? role;\n const dashed = item.dashed ?? false;\n const opacity = Math.round(Math.min(1, Math.max(0, item.opacity ?? 1)) * 10) / 10;\n const dim = isDimmed(item.id);\n const key = `${dim ? 1 : 0}|${itemRole}|${dashed ? \"dashed\" : \"solid\"}|${opacity}`;\n let batch = normal.get(key);\n if (!batch) {\n batch = { key, role: itemRole, dashed, opacity, dim, indices: [] };\n normal.set(key, batch);\n }\n batch.indices.push(i);\n });\n return { normal: [...normal.values()], picked: picked.indices.length > 0 ? picked : null };\n }, [items, role, selectedSet, isDimmed]);\n\n // Outlines depend on the zoom only through the screen-pixel floor.\n const floor = minRadius !== undefined ? minRadius * unit : 0;\n const normalPaths = useMemo(\n () => batches.normal.map((batch) => ({ batch, d: batchPath(items, batch.indices, floor) })),\n [batches, items, floor],\n );\n const pickedPath = useMemo(() => (batches.picked ? batchPath(items, batches.picked.indices, floor) : \"\"), [batches, items, floor]);\n\n const hoverPositions: number[] = [];\n if (hoverId !== null) {\n items.forEach((item, i) => {\n if (item.id === hoverId) hoverPositions.push(i);\n });\n }\n const hoverSelected = hoverId !== null && selectedSet.has(hoverId);\n\n const widthOf = (itemRole: OverlayRole, state: \"default\" | \"hover\" | \"selected\"): number => {\n const thin = itemRole === \"model\" || itemRole === \"structure\";\n return px(OVERLAY_STATE_WIDTH[state] - (thin && state !== \"selected\" ? 0.5 : 0));\n };\n const dash = `${px(4)} ${px(3)}`;\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 {...(label !== undefined ? { role: \"img\", \"aria-label\": label } : { \"aria-hidden\": true })}\n data-ellipses={items.length}\n data-hovered={hoverId ?? undefined}\n >\n {index && (\n <EllipseHits\n index={index}\n layerId={layerId}\n priority={priority}\n onHover={(id) => {\n setOwnHover(id);\n onHoverChange?.(id);\n }}\n onPress={onItemPress}\n />\n )}\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {normalPaths.map(({ batch, d }) => (\n <g key={batch.key} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && (\n <path\n d={d}\n stroke={HALO}\n strokeWidth={widthOf(batch.role, \"default\") + px(2)}\n strokeDasharray={batch.dashed ? dash : undefined}\n opacity={0.6 * batch.opacity}\n />\n )}\n <path\n data-batch={batch.key}\n d={d}\n stroke={overlayRole(batch.role)}\n strokeWidth={widthOf(batch.role, \"default\")}\n strokeDasharray={batch.dashed ? dash : undefined}\n opacity={batch.opacity}\n />\n </g>\n ))}\n {batches.picked && (\n <>\n {halo && <path d={pickedPath} stroke={HALO} strokeWidth={widthOf(\"selection\", \"selected\") + px(2)} />}\n <path data-selected-ellipses=\"\" d={pickedPath} stroke={selectionStroke} strokeWidth={widthOf(\"selection\", \"selected\")} />\n </>\n )}\n {hoverPositions.map((position) => {\n const item = items[position]!;\n const itemRole = item.role ?? role;\n const state = hoverSelected ? \"selected\" : \"hover\";\n return (\n <g key={position}>\n {halo && <path d={outlineOf(item, floor)} stroke={HALO} strokeWidth={widthOf(itemRole, state) + px(2)} />}\n <path\n data-hovered-ellipse=\"\"\n d={outlineOf(item, floor)}\n stroke={hoverSelected ? selectionStroke : overlayRole(itemRole)}\n strokeWidth={widthOf(itemRole, state)}\n />\n </g>\n );\n })}\n </g>\n </svg>\n );\n}\n","/**\n * The edges of a detected lattice: which nodes are neighbours.\n *\n * A calibration detector returns its corners with integer lattice indices `(i, j)` and gaps\n * where a corner was not found. The edges are not data: node `(i, j)` is joined to\n * `(i + 1, j)` and to `(i, j + 1)` when both exist. This module computes them in O(n) with a\n * hash of the indices. It imports neither React nor the DOM.\n */\n\n/** What `latticeEdges` reads from each node. */\nexport interface LatticeNode {\n /** The lattice index along the first axis. A non-integer index is not part of the lattice. */\n i: number;\n /** The lattice index along the second axis. A non-integer index is not part of the lattice. */\n j: number;\n}\n\n/** The lattice axis an edge runs along: `\"i\"` joins `(i, j)` to `(i + 1, j)`, `\"j\"` joins `(i, j)` to `(i, j + 1)`. */\nexport type LatticeAxis = \"i\" | \"j\";\n\n/** An edge between two neighbouring nodes. */\nexport interface LatticeEdge {\n /** Position in the node array of the end with the lower index along `axis`. */\n a: number;\n /** Position in the node array of the end with the higher index along `axis`. */\n b: number;\n /** The axis it runs along. */\n axis: LatticeAxis;\n}\n\n/** Indices past this magnitude are not hashed (the key must stay an exact integer). */\nconst LIMIT = 2 ** 25;\n\nfunction key(i: number, j: number): number {\n return (i + LIMIT) * (2 * LIMIT) + (j + LIMIT);\n}\n\n/**\n * The edges of a lattice: every pair of nodes whose indices differ by one along exactly one\n * axis.\n *\n * @param nodes - The nodes, in any order, with gaps allowed. A node whose index is not an\n * integer of magnitude below 2²⁵ takes no edges, and when two nodes share an index the\n * first one is the lattice's node there.\n * @returns The edges, ordered by the position of `a`, then `\"i\"` before `\"j\"`.\n */\nexport function latticeEdges(nodes: ArrayLike<LatticeNode>): LatticeEdge[] {\n const at = new Map<number, number>();\n const valid = (n: LatticeNode) => Number.isInteger(n.i) && Number.isInteger(n.j) && Math.abs(n.i) < LIMIT && Math.abs(n.j) < LIMIT;\n for (let p = 0; p < nodes.length; p++) {\n const node = nodes[p]!;\n if (!valid(node)) continue;\n const k = key(node.i, node.j);\n if (!at.has(k)) at.set(k, p);\n }\n const edges: LatticeEdge[] = [];\n for (let p = 0; p < nodes.length; p++) {\n const node = nodes[p]!;\n if (!valid(node) || at.get(key(node.i, node.j)) !== p) continue;\n if (node.i + 1 < LIMIT) {\n const q = at.get(key(node.i + 1, node.j));\n if (q !== undefined) edges.push({ a: p, b: q, axis: \"i\" });\n }\n if (node.j + 1 < LIMIT) {\n const q = at.get(key(node.i, node.j + 1));\n if (q !== undefined) edges.push({ a: p, b: q, axis: \"j\" });\n }\n }\n return edges;\n}\n","/**\n * A detected lattice over the image: the corners of a calibration board with the row and\n * column edges between neighbours, and optional `(i, j)` labels.\n *\n * Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of\n * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1\n * and 4). Edges are not picked: a person points at a corner.\n */\n\nimport { useMemo } from \"react\";\n\nimport { latticeEdges, type LatticeAxis } from \"./gridEdges\";\nimport { overlayRole, OVERLAY_STATE_OPACITY, OVERLAY_STATE_WIDTH, type OverlayRole } from \"./overlayRole\";\nimport { PointSet, type PointSetItem } from \"./PointSet\";\nimport type { MarkerShape } from \"./markerShapes\";\nimport type { PointId } from \"./pointIndex\";\nimport { useStage } from \"./stage/ImageStage\";\nimport type { StagePointerEvent } from \"./stage/hitContext\";\nimport { STAGE_HIT_PRIORITY } from \"./stage/hitTest\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox } from \"./stage/view\";\n\n/** One node of a `GridLayer`: a point with its lattice index. */\nexport interface GridNode extends PointSetItem {\n /** The lattice index along the first axis. */\n i: number;\n /** The lattice index along the second axis. */\n j: number;\n}\n\n/** How the edges along one lattice axis are drawn. */\nexport interface GridEdgeStyle {\n /** The overlay role of the edges. Defaults to `\"structure\"`: they are context. */\n role?: OverlayRole | undefined;\n /** Draw them dashed (4 3 screen px), so the two axes differ by more than colour. */\n dashed?: boolean | undefined;\n /** Draw them at all. Defaults to `true`. */\n visible?: boolean | undefined;\n}\n\n/** Props of `GridLayer`. */\nexport interface GridLayerProps {\n /** The nodes, in image coordinates, with their lattice indices. Gaps are allowed. */\n nodes: readonly GridNode[];\n /**\n * How edges are drawn, by axis: `i` joins `(i, j)` to `(i + 1, j)` (the rows, when `i`\n * counts columns), `j` joins `(i, j)` to `(i, j + 1)`. Both are solid `structure` by default.\n */\n edges?: { i?: GridEdgeStyle | undefined; j?: GridEdgeStyle | undefined } | undefined;\n /** The marker kind of a node that names none. Defaults to `\"plus\"`: a corner. */\n kind?: string | undefined;\n /** More marker kinds, or replacements for built-in ones, by name; see `PointSet`. */\n markers?: Readonly<Record<string, MarkerShape>> | undefined;\n /**\n * Label every node without a `label` of its own with its lattice index, `i,j`, where the\n * zoom leaves room (nodes at least 24 screen px apart). Off by default.\n */\n indexLabels?: boolean | undefined;\n /** Show the nodes' labels where the zoom leaves room for them. On by default. */\n labels?: boolean | undefined;\n /** The hovered node id, when the app controls hover. */\n hoveredId?: PointId | null | undefined;\n /** Called when the node under the pointer changes. `null` when it leaves every node. */\n onHoverChange?: ((id: PointId | null) => void) | undefined;\n /** The selected node ids, drawn at 2.5 px in the selection colour with a ring. */\n selectedIds?: Iterable<PointId> | undefined;\n /**\n * Node ids drawn at 35 % opacity, as a set or a predicate. An edge is dimmed when both its\n * nodes are. Pass a stable value: a new one re-batches the layer.\n */\n dimmed?: Iterable<PointId> | ((id: PointId) => boolean) | undefined;\n /** A press landed on a node; see `PointSet`. Setting it makes the layer claim presses on its nodes. */\n onItemPress?: ((id: PointId, event: StagePointerEvent) => void) | 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 nodes and rings. Defaults to the overlay `selection` role. */\n selectionStroke?: string | undefined;\n /** The id hit-tests report for the nodes. 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 \"Grid\". */\n label?: string | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n\n/** A style with its defaults filled in. */\nfunction edgeStyle(style: GridEdgeStyle | undefined): { role: OverlayRole; dashed: boolean; visible: boolean } {\n return { role: style?.role ?? \"structure\", dashed: style?.dashed ?? false, visible: style?.visible ?? true };\n}\n\n/** One batched path of edges. */\ninterface EdgeBatch {\n key: string;\n axis: LatticeAxis;\n dim: boolean;\n d: string;\n}\n\n/**\n * A detected lattice inside an `ImageStage`.\n *\n * - **Nodes** are a `PointSet`: `plus` markers by default, picked through the point index at\n * point priority, with `onHoverChange`, `onItemPress`, selection (with ring) and dimming.\n * - **Edges** join `(i, j)` to `(i + 1, j)` and to `(i, j + 1)` where both nodes exist\n * (`latticeEdges`), in one path per axis and dimming, below the nodes. They are `structure`\n * role by default, 1 screen px with a halo; `edges` restyles each axis.\n * - **Labels** are the nodes' own `label`s, or with `indexLabels` their `i,j`, only where nodes\n * are at least 24 screen px apart.\n *\n * The edges' SVG carries `data-edges`; the nodes' is the `PointSet`'s.\n */\nexport function GridLayer({\n nodes,\n edges,\n kind = \"plus\",\n markers,\n indexLabels = false,\n labels = true,\n hoveredId,\n onHoverChange,\n selectedIds,\n dimmed,\n onItemPress,\n halo = true,\n selectionStroke,\n layerId,\n priority = STAGE_HIT_PRIORITY.point,\n label = \"Grid\",\n}: GridLayerProps) {\n const stage = useStage();\n const px = useScreenPx();\n\n const styles = { i: edgeStyle(edges?.i), j: edgeStyle(edges?.j) };\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\n const batches = useMemo(() => {\n const map = new Map<string, EdgeBatch>();\n for (const edge of latticeEdges(nodes)) {\n const a = nodes[edge.a]!;\n const b = nodes[edge.b]!;\n if (!Number.isFinite(a.x + a.y + b.x + b.y)) continue;\n const dim = isDimmed(a.id) && isDimmed(b.id);\n const k = `${edge.axis}|${dim ? 1 : 0}`;\n let batch = map.get(k);\n if (!batch) {\n batch = { key: k, axis: edge.axis, dim, d: \"\" };\n map.set(k, batch);\n }\n batch.d += `M${a.x} ${a.y}L${b.x} ${b.y}`;\n }\n return [...map.values()];\n }, [nodes, isDimmed]);\n\n // Without `indexLabels` the nodes go through as they are, so the PointSet's index is not rebuilt.\n const items = useMemo<readonly PointSetItem[]>(\n () => (indexLabels ? nodes.map((node) => (node.label ? node : { ...node, label: `${node.i},${node.j}` })) : nodes),\n [nodes, indexLabels],\n );\n\n return (\n <>\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n data-edges=\"\"\n aria-hidden\n >\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {batches\n .filter((batch) => styles[batch.axis].visible)\n .map((batch) => {\n const style = styles[batch.axis];\n const thin = style.role === \"model\" || style.role === \"structure\";\n const width = px(OVERLAY_STATE_WIDTH.default - (thin ? 0.5 : 0));\n const dash = style.dashed ? `${px(4)} ${px(3)}` : undefined;\n return (\n <g key={batch.key} opacity={batch.dim ? OVERLAY_STATE_OPACITY.dimmed : undefined}>\n {halo && <path d={batch.d} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}\n <path data-edge-batch={batch.key} d={batch.d} stroke={overlayRole(style.role)} strokeWidth={width} strokeDasharray={dash} />\n </g>\n );\n })}\n </g>\n </svg>\n <PointSet\n items={items}\n kind={kind}\n markers={markers}\n hoveredId={hoveredId}\n onHoverChange={onHoverChange}\n selectedIds={selectedIds}\n dimmed={dimmed}\n onItemPress={onItemPress}\n labels={labels}\n halo={halo}\n selectionStroke={selectionStroke}\n layerId={layerId}\n priority={priority}\n label={label}\n />\n </>\n );\n}\n","/**\n * Scalar field to pixels: the colourising step of `HeatmapLayer`, pure so the cases that bite\n * (NaN holes, a flat field, a value outside the range) are tested without a canvas.\n */\n\nimport type { ValuePlane } from \"../api/mapValues\";\n\n/**\n * A sequential colour map: a position in `[0, 1]` to an `[r, g, b]` colour, each channel\n * 0 to 255. `@vitavision/charts`' `colormapRgb(name, t)` is one: `(t) => colormapRgb(\"viridis\", t)`.\n */\nexport type Colormap = (t: number) => readonly [number, number, number];\n\n/** A range of values mapped onto the colour map: `low` to its start, `high` to its end. */\nexport interface ValueRange {\n /** The value drawn in the map's first colour. */\n low: number;\n /** The value drawn in the map's last colour. */\n high: number;\n}\n\n/** How many steps the colour map is sampled at: one per 8-bit level, so no pixel is off by a visible amount. */\nconst STEPS = 256;\n\n/**\n * The extent of a plane's finite values.\n *\n * @param plane - The plane.\n * @param channel - Which of its channels. Defaults to the first.\n * @returns `{ low, high }`, or `null` when the channel is missing or has no finite value.\n */\nexport function planeRange(plane: ValuePlane, channel = 0): ValueRange | null {\n if (!(channel >= 0 && channel < plane.channels)) return null;\n const size = plane.width * plane.height;\n const offset = channel * size;\n let low = Infinity;\n let high = -Infinity;\n for (let k = 0; k < size; k++) {\n const v = plane.values[offset + k]!;\n if (!Number.isFinite(v)) continue;\n if (v < low) low = v;\n if (v > high) high = v;\n }\n return low <= high ? { low, high } : null;\n}\n\n/**\n * Colour a plane through a colour map.\n *\n * Opaque where the value is finite; transparent where it is `NaN` or infinite (an uncovered\n * pixel, as in `valueAt`). Values outside `range` take the map's end colours. A flat range\n * (`high <= low`) draws every pixel in the map's first colour.\n *\n * @param plane - The plane.\n * @param colormap - The colour map; sampled at 256 positions.\n * @param range - What the map spans. Defaults to the extent of the channel's finite values.\n * @param channel - Which channel to draw. Defaults to the first.\n * @returns `width · height` RGBA pixels, row-major; all transparent for a missing channel.\n */\nexport function rasterizePlane(plane: ValuePlane, colormap: Colormap, range?: ValueRange, channel = 0): Uint8ClampedArray {\n const size = plane.width * plane.height;\n const out = new Uint8ClampedArray(size * 4);\n if (!(channel >= 0 && channel < plane.channels)) return out;\n const { low, high } = range ?? planeRange(plane, channel) ?? { low: 0, high: 0 };\n const lut = new Uint8ClampedArray(STEPS * 3);\n for (let s = 0; s < STEPS; s++) {\n const [r, g, b] = colormap(s / (STEPS - 1));\n lut[3 * s] = r;\n lut[3 * s + 1] = g;\n lut[3 * s + 2] = b;\n }\n const scale = high > low ? (STEPS - 1) / (high - low) : 0;\n const offset = channel * size;\n for (let k = 0; k < size; k++) {\n const v = plane.values[offset + k]!;\n if (!Number.isFinite(v)) continue;\n const s = Math.min(STEPS - 1, Math.max(0, Math.round((v - low) * scale)));\n out[4 * k] = lut[3 * s]!;\n out[4 * k + 1] = lut[3 * s + 1]!;\n out[4 * k + 2] = lut[3 * s + 2]!;\n out[4 * k + 3] = 255;\n }\n return out;\n}\n","/**\n * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.\n *\n * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an\n * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage\n * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel\n * map costs one element. It takes no pointer events; to read the numbers under the pointer, use\n * `valueAt` on the plane.\n */\n\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { cn } from \"@vitavision/ui\";\nimport type { ValuePlane } from \"../api/mapValues\";\nimport { rasterizePlane, type Colormap, type ValueRange } from \"./heatmapRaster\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { PIXEL_CENTRE, type Rect } from \"./stage/view\";\n\n/** What every `HeatmapLayer` takes. */\nexport interface HeatmapLayerBaseProps {\n /** How opaque the heatmap is, 0 to 1. Defaults to `1`. */\n opacity?: number | undefined;\n /** Draw it. Defaults to `true`. While `false` nothing is rasterised. */\n visible?: boolean | undefined;\n /**\n * Where the raster is placed, in image coordinates: `x` and `y` the top-left edge of its\n * first pixel's footprint (`-0.5, -0.5` is the image's own top-left corner), `width` and `height`\n * the extent it is stretched over. Defaults to the whole image, so a raster of any\n * resolution covers it 1:1 in position.\n */\n rect?: Rect | undefined;\n /** The zoom (CSS pixels per heatmap pixel) from which heatmap pixels are drawn as blocks. Defaults to 4. */\n pixelatedAbove?: number | undefined;\n /** A description for assistive technology. Defaults to `\"\"`: decorative, as the legend carries the meaning. */\n alt?: string | undefined;\n /** Called once the raster is on screen (and again for each new one). */\n onReady?: (() => void) | undefined;\n /** Called when the raster could not be made: a canvas that could not be allocated, or an `rgba` buffer too short for its size. */\n onError?: (() => void) | undefined;\n /** Merged onto the image with `cn`. */\n className?: string | undefined;\n}\n\n/** A heatmap from pixels that are already coloured. */\nexport interface HeatmapRgbaProps extends HeatmapLayerBaseProps {\n /** Row-major RGBA, `width · height · 4` bytes. A `Uint8Array` is read in place, not copied. */\n rgba: Uint8ClampedArray | Uint8Array;\n /** The raster's width in pixels. */\n width: number;\n /** The raster's height in pixels. */\n height: number;\n /** Not used with `rgba`. */\n plane?: undefined;\n /** Not used with `rgba`. */\n colormap?: undefined;\n /** Not used with `rgba`. */\n range?: undefined;\n /** Not used with `rgba`. */\n channel?: undefined;\n}\n\n/** A heatmap from a scalar field and a colour map. */\nexport interface HeatmapPlaneProps extends HeatmapLayerBaseProps {\n /** The field, as decoded by `decodePlane`. */\n plane: ValuePlane;\n /**\n * The colour map. `NaN` pixels stay transparent. Pass a stable function: a new one\n * re-rasterises the heatmap. `@vitavision/charts`' `(t) => colormapRgb(\"viridis\", t)` is one.\n */\n colormap: Colormap;\n /** What the map spans. Defaults to the extent of the channel's finite values. */\n range?: ValueRange | undefined;\n /** Which channel of the plane to draw. Defaults to the first. */\n channel?: number | undefined;\n /** Not used with `plane`. */\n rgba?: undefined;\n /** Not used with `plane`. */\n width?: undefined;\n /** Not used with `plane`. */\n height?: undefined;\n}\n\n/** Props of `HeatmapLayer`: pre-coloured `rgba` pixels, or a `plane` with a `colormap`. */\nexport type HeatmapLayerProps = HeatmapRgbaProps | HeatmapPlaneProps;\n\n/** A raster on screen and the object URL it came from. */\ninterface Raster {\n url: string;\n width: number;\n height: number;\n}\n\n/**\n * A heatmap inside an `ImageStage`: a scalar field coloured through a colour map, or an RGBA\n * buffer, placed over the image (default) or any rectangle of it.\n *\n * - **Rasterised in an effect**, once per change of its data, into an offscreen canvas and an\n * object URL that is revoked when replaced and on unmount. Server rendering draws nothing.\n * - **Pixelated** from 4 CSS pixels per heatmap pixel, like `ImageLayer`, so the cells of a\n * coarse map are not smoothed into a blur.\n * - **Stacking:** it is drawn where it is placed among the stage's children. Before the\n * overlays it sits under them; the image layer goes before it.\n * - **Input:** none. It takes no pointer events, so presses reach the layers above and the stage.\n *\n * The image carries `data-heatmap`, `data-pixelated` while pixelated, and `data-ready`.\n */\nexport function HeatmapLayer(props: HeatmapLayerProps) {\n const { opacity = 1, visible = true, rect, pixelatedAbove = 4, alt = \"\", onReady, onError, className } = props;\n const stage = useStage();\n const [raster, setRaster] = useState<Raster | null>(null);\n const [ready, setReady] = useState(false);\n const urlRef = useRef<string | null>(null);\n const callbacksRef = useRef({ onReady, onError });\n useEffect(() => {\n callbacksRef.current = { onReady, onError };\n });\n\n // The inputs that change what is drawn, spelled out so the effect re-runs on exactly those.\n const { rgba, width, height, plane, colormap, channel } = props;\n const rangeLow = props.range?.low;\n const rangeHigh = props.range?.high;\n\n useEffect(() => {\n if (!visible) return;\n let cancelled = false;\n const range = rangeLow === undefined || rangeHigh === undefined ? undefined : { low: rangeLow, high: rangeHigh };\n const source = rgba ? wrapRgba(rgba, width, height) : plane && colormap ? colourPlane(plane, colormap, range, channel) : null;\n const canvas = document.createElement(\"canvas\");\n const context = source ? ((canvas.width = source.width), (canvas.height = source.height), canvas.getContext(\"2d\")) : null;\n if (!source || !context) {\n callbacksRef.current.onError?.();\n return;\n }\n const { width: w, height: h } = source;\n context.putImageData(new ImageData(source.pixels, w, h), 0, 0);\n canvas.toBlob((blob) => {\n if (cancelled) return;\n if (!blob) {\n callbacksRef.current.onError?.();\n return;\n }\n const previous = urlRef.current;\n const url = URL.createObjectURL(blob);\n urlRef.current = url;\n setReady(false);\n setRaster({ url, width: w, height: h });\n // The old image is replaced in this commit; the browser has already decoded it.\n if (previous) URL.revokeObjectURL(previous);\n });\n return () => {\n cancelled = true;\n };\n }, [visible, rgba, width, height, plane, colormap, rangeLow, rangeHigh, channel]);\n\n useEffect(\n () => () => {\n if (urlRef.current) URL.revokeObjectURL(urlRef.current);\n urlRef.current = null;\n },\n [],\n );\n\n if (!visible || raster === null) return null;\n const box = rect ?? { x: -PIXEL_CENTRE, y: -PIXEL_CENTRE, width: stage.image.width, height: stage.image.height };\n const pixelated = (stage.view.scale * box.width) / raster.width >= pixelatedAbove;\n return (\n <img\n src={raster.url}\n alt={alt}\n draggable={false}\n data-heatmap=\"\"\n data-ready={ready ? \"\" : undefined}\n data-pixelated={pixelated ? \"\" : undefined}\n onLoad={() => {\n setReady(true);\n callbacksRef.current.onReady?.();\n }}\n className={cn(\"pointer-events-none absolute max-w-none select-none\", className)}\n style={{\n left: box.x + PIXEL_CENTRE,\n top: box.y + PIXEL_CENTRE,\n width: box.width,\n height: box.height,\n opacity,\n pointerEvents: \"none\",\n imageRendering: pixelated ? \"pixelated\" : undefined,\n }}\n />\n );\n}\n\n/** Pixels to draw, and their size. */\ninterface Pixels {\n pixels: Uint8ClampedArray<ArrayBuffer>;\n width: number;\n height: number;\n}\n\n/** The first `width · height · 4` bytes of an RGBA buffer, read in place; `null` if it is too short or empty. */\nfunction wrapRgba(rgba: Uint8ClampedArray | Uint8Array, width: number, height: number): Pixels | null {\n const length = width * height * 4;\n if (!(length > 0) || rgba.length < length) return null;\n return { pixels: new Uint8ClampedArray(rgba.buffer as ArrayBuffer, rgba.byteOffset, length), width, height };\n}\n\n/** A plane through a colour map; `null` for an empty plane. */\nfunction colourPlane(plane: ValuePlane, colormap: Colormap, range: ValueRange | undefined, channel: number | undefined): Pixels | null {\n if (!(plane.width > 0 && plane.height > 0)) return null;\n const pixels = rasterizePlane(plane, colormap, range, channel) as Uint8ClampedArray<ArrayBuffer>;\n return { pixels, width: plane.width, height: plane.height };\n}\n","/**\n * The arithmetic of editing a rotated rectangle or ellipse: eight handles, a rotation handle\n * and an interior.\n *\n * A shape is its centre, its size and a rotation, so a resize can be done in the shape's own\n * frame (where its sides are axis-aligned) and the opposite edge stays put whatever the\n * rotation. Kept pure, so the cases that bite are tested without a pointer:\n * - a handle dragged across the shape, or to a point far away;\n * - a shape collapsed below the minimum size;\n * - a rotation about the centre and not about a corner.\n *\n * Everything is in the stage's image coordinates. **Rotation is in radians, positive\n * clockwise on screen** (image `y` points down), zero when the shape's width runs along `x`.\n * A degrees-clockwise value, such as Konva's `rotation`, is `degrees * Math.PI / 180`.\n */\n\nimport type { Point } from \"./measureGeometry\";\nimport { ROI_HANDLES, type RoiHandle } from \"./roiEdit\";\n\n/** Handle square side, in screen pixels. */\nexport const SHAPE_HANDLE_PX = 9;\n/** Rotation handle radius, and its distance past the top side, in screen pixels. */\nexport const SHAPE_ROTATE_RADIUS_PX = 5;\nexport const SHAPE_ROTATE_OFFSET_PX = 24;\n\n/** A rotated rectangle, or the ellipse inscribed in one. */\nexport interface RotatedShape {\n /** Centre x, in image coordinates. */\n cx: number;\n /** Centre y, in image coordinates. */\n cy: number;\n /** Extent along the shape's own x axis: a rectangle's width, an ellipse's full axis `2·rx`. */\n width: number;\n /** Extent along the shape's own y axis: a rectangle's height, an ellipse's full axis `2·ry`. */\n height: number;\n /** Radians, clockwise on screen: the turn from the image's x axis to the shape's own. */\n rotation: number;\n}\n\n/**\n * A point of image space in the shape's own frame: origin at its centre, axes along its sides.\n *\n * @param shape - The shape.\n * @param p - A point in image coordinates.\n * @returns The point relative to the shape.\n */\nexport function toShapeFrame(shape: RotatedShape, p: Point): Point {\n const c = Math.cos(shape.rotation);\n const s = Math.sin(shape.rotation);\n const dx = p.x - shape.cx;\n const dy = p.y - shape.cy;\n return { x: c * dx + s * dy, y: -s * dx + c * dy };\n}\n\n/**\n * A point of the shape's own frame in image space; the inverse of `toShapeFrame`.\n *\n * @param shape - The shape.\n * @param p - A point relative to the shape.\n * @returns The point in image coordinates.\n */\nexport function fromShapeFrame(shape: RotatedShape, p: Point): Point {\n const c = Math.cos(shape.rotation);\n const s = Math.sin(shape.rotation);\n return { x: shape.cx + c * p.x - s * p.y, y: shape.cy + s * p.x + c * p.y };\n}\n\n/** The sign of a handle along the shape's own x and y axes: `e` and `s` are `+1`. */\nfunction handleDirection(handle: RoiHandle): Point {\n return { x: handle.includes(\"e\") ? 1 : handle.includes(\"w\") ? -1 : 0, y: handle.includes(\"s\") ? 1 : handle.includes(\"n\") ? -1 : 0 };\n}\n\n/**\n * Where a handle sits: a corner or the middle of a side, turned with the shape.\n *\n * @param shape - The shape.\n * @param handle - The handle, by compass direction in the shape's own frame.\n * @returns The handle's centre, in image coordinates.\n */\nexport function shapeHandlePoint(shape: RotatedShape, handle: RoiHandle): Point {\n const d = handleDirection(handle);\n return fromShapeFrame(shape, { x: (d.x * shape.width) / 2, y: (d.y * shape.height) / 2 });\n}\n\n/**\n * Where the rotation handle sits: beyond the middle of the top side, along the shape's own\n * up direction.\n *\n * @param shape - The shape.\n * @param distance - How far past the top side, in image pixels. For a screen-constant handle,\n * pass `useScreenPx()(css)`.\n * @returns The handle's centre, in image coordinates.\n */\nexport function rotationHandlePoint(shape: RotatedShape, distance: number): Point {\n return fromShapeFrame(shape, { x: 0, y: -shape.height / 2 - distance });\n}\n\n/**\n * Drag a handle to `to`.\n *\n * The dragged side or corner follows the pointer in the shape's own frame and the opposite\n * side or corner stays where it is in the image, which is what makes a handle feel attached.\n * The shape does not flip when dragged through the opposite side: it stops at `minSize`.\n *\n * @param shape - The shape before the drag.\n * @param handle - The handle being dragged.\n * @param to - The pointer, in image coordinates.\n * @param minSize - The smallest extent on either axis, in image pixels.\n * @returns The resized shape: the same rotation, and the opposite side or corner unmoved.\n */\nexport function resizeShape(shape: RotatedShape, handle: RoiHandle, to: Point, minSize: number): RotatedShape {\n const d = handleDirection(handle);\n const u = toShapeFrame(shape, to);\n let width = shape.width;\n let height = shape.height;\n let x = 0;\n let y = 0;\n if (d.x !== 0) {\n // The fixed side is at `-d.x · width / 2`; the new extent runs from it to the pointer.\n width = Math.max(minSize, d.x * u.x + shape.width / 2);\n x = -d.x * (shape.width / 2) + (d.x * width) / 2;\n }\n if (d.y !== 0) {\n height = Math.max(minSize, d.y * u.y + shape.height / 2);\n y = -d.y * (shape.height / 2) + (d.y * height) / 2;\n }\n const centre = fromShapeFrame(shape, { x, y });\n return { cx: centre.x, cy: centre.y, width, height, rotation: shape.rotation };\n}\n\n/**\n * Turn the shape about its centre so that its rotation handle points at `to`.\n *\n * @param shape - The shape before the drag.\n * @param to - The pointer, in image coordinates.\n * @param snap - Round the rotation to a multiple of this many radians (Shift while dragging\n * rounds to 15°). Defaults to no rounding.\n * @returns The rotated shape: the same centre and size, `rotation` in `(-π, π]`.\n */\nexport function rotateShape(shape: RotatedShape, to: Point, snap = 0): RotatedShape {\n // The handle sits along the shape's own up direction, which is at angle `rotation - π/2`.\n let rotation = Math.atan2(to.y - shape.cy, to.x - shape.cx) + Math.PI / 2;\n if (snap > 0) rotation = Math.round(rotation / snap) * snap;\n return { ...shape, rotation: normalizeAngle(rotation) };\n}\n\n/**\n * Move the shape.\n *\n * @param shape - The shape.\n * @param dx - Horizontal shift, in image pixels.\n * @param dy - Vertical shift, in image pixels.\n * @returns The moved shape.\n */\nexport function moveShape(shape: RotatedShape, dx: number, dy: number): RotatedShape {\n return { ...shape, cx: shape.cx + dx, cy: shape.cy + dy };\n}\n\n/**\n * An angle as the equivalent one in `(-π, π]`.\n *\n * @param angle - Radians.\n * @returns The angle in `(-π, π]`.\n */\nexport function normalizeAngle(angle: number): number {\n const turn = 2 * Math.PI;\n let a = angle % turn;\n if (a > Math.PI) a -= turn;\n else if (a <= -Math.PI) a += turn;\n return a;\n}\n\n/**\n * The resize cursor for a handle of a rotated shape: the nearest of the four CSS resize\n * cursors to the handle's direction on screen.\n *\n * @param handle - The handle.\n * @param rotation - The shape's rotation, in radians.\n * @returns A CSS `cursor` value.\n */\nexport function shapeHandleCursor(handle: RoiHandle, rotation: number): string {\n const d = handleDirection(handle);\n const angle = Math.atan2(d.y, d.x) + rotation;\n const half = ((angle % Math.PI) + Math.PI) % Math.PI;\n return [\"ew-resize\", \"nwse-resize\", \"ns-resize\", \"nesw-resize\"][Math.round(half / (Math.PI / 4)) % 4]!;\n}\n\n/**\n * The shape for a rectangle given as an origin corner, a size and a rotation about that\n * corner: Konva's `Rect` (`x`, `y`, `width`, `height`, `rotation` in degrees), for one.\n *\n * @param corner - The corner the rotation is about, in image coordinates.\n * @param width - Extent along the rotated x axis.\n * @param height - Extent along the rotated y axis.\n * @param rotation - Radians, clockwise on screen.\n * @returns The same rectangle as a `RotatedShape`.\n */\nexport function shapeFromCorner(corner: Point, width: number, height: number, rotation: number): RotatedShape {\n const c = Math.cos(rotation);\n const s = Math.sin(rotation);\n return {\n cx: corner.x + (c * width - s * height) / 2,\n cy: corner.y + (s * width + c * height) / 2,\n width,\n height,\n rotation,\n };\n}\n\n/**\n * The top-left corner of a shape in its own frame, the origin Konva rotates a `Rect` about;\n * the inverse of `shapeFromCorner`.\n *\n * @param shape - The shape.\n * @returns The corner, in image coordinates.\n */\nexport function shapeCorner(shape: RotatedShape): Point {\n return fromShapeFrame(shape, { x: -shape.width / 2, y: -shape.height / 2 });\n}\n\n/**\n * Whether two shapes are the same, to within `epsilon` on every field (rotations compared modulo a turn).\n *\n * @param a - A shape, or `null`.\n * @param b - A shape, or `null`.\n * @param epsilon - The tolerance. Defaults to 1e-6.\n * @returns `true` for two equal shapes, or two `null`s.\n */\nexport function sameShape(a: RotatedShape | null, b: RotatedShape | null, epsilon = 1e-6): boolean {\n if (a === null || b === null) return a === b;\n return (\n Math.abs(a.cx - b.cx) < epsilon &&\n Math.abs(a.cy - b.cy) < epsilon &&\n Math.abs(a.width - b.width) < epsilon &&\n Math.abs(a.height - b.height) < epsilon &&\n Math.abs(normalizeAngle(a.rotation - b.rotation)) < epsilon\n );\n}\n\n/** What a press on an editable shape does. */\nexport type ShapePress = { kind: \"resize\"; handle: RoiHandle } | { kind: \"rotate\" } | { kind: \"move\" };\n\n/**\n * How far a point is outside a shape, in image pixels; zero inside it. For an ellipse this is\n * a first-order estimate, which is exact on the axes and good to a few percent elsewhere.\n */\nfunction distanceOutside(shape: RotatedShape, kind: \"rect\" | \"ellipse\", p: Point): number {\n const u = toShapeFrame(shape, p);\n const a = Math.max(shape.width / 2, 1e-9);\n const b = Math.max(shape.height / 2, 1e-9);\n if (kind === \"rect\") return Math.hypot(Math.max(Math.abs(u.x) - a, 0), Math.max(Math.abs(u.y) - b, 0));\n const f = (u.x / a) ** 2 + (u.y / b) ** 2;\n if (f <= 1) return 0;\n const g = Math.hypot(u.x / (a * a), u.y / (b * b));\n return (f - Math.sqrt(f)) / g;\n}\n\n/**\n * What a press on an editable shape means, decided once for the whole editor so that a small\n * shape's interior never steals a press meant for its handle.\n *\n * In order:\n * 1. The nearest handle (the eight, and the rotation handle when `rotatable`) whose screen\n * distance from the press is within `radius` plus the handle's half size: resize or rotate.\n * 2. Inside the shape, or within `radius` screen pixels of its outline: move.\n * 3. Otherwise `null`: the press is declined and belongs to whatever is below.\n *\n * @param shape - The shape.\n * @param kind - `\"rect\"` or `\"ellipse\"` (the outline differs).\n * @param scale - The view scale: screen pixels per image pixel.\n * @param point - The press, in image coordinates.\n * @param radius - The pointer's tolerance in screen pixels: 12 for a touch, 6 for a mouse.\n * @param rotatable - Whether the rotation handle exists. Defaults to `true`.\n * @returns The decision, or `null`.\n */\nexport function shapePress(\n shape: RotatedShape,\n kind: \"rect\" | \"ellipse\",\n scale: number,\n point: Point,\n radius: number,\n rotatable = true,\n): ShapePress | null {\n const best: { press: ShapePress | null; distance: number } = { press: null, distance: Infinity };\n const consider = (candidate: ShapePress, at: Point, half: number) => {\n const d = Math.hypot(at.x - point.x, at.y - point.y) * scale;\n if (d <= radius + half && d < best.distance) {\n best.press = candidate;\n best.distance = d;\n }\n };\n for (const handle of ROI_HANDLES) consider({ kind: \"resize\", handle }, shapeHandlePoint(shape, handle), SHAPE_HANDLE_PX / 2);\n if (rotatable) {\n consider({ kind: \"rotate\" }, rotationHandlePoint(shape, SHAPE_ROTATE_OFFSET_PX / scale), SHAPE_ROTATE_RADIUS_PX);\n }\n if (best.press) return best.press;\n return distanceOutside(shape, kind, point) * scale <= radius ? { kind: \"move\" } : null;\n}\n","/**\n * Whether the device's primary pointer is coarse (a finger), for sizing a press target that\n * must exist before any pointer event says which pointer is coming.\n */\n\nimport { useSyncExternalStore } from \"react\";\n\nconst QUERY = \"(pointer: coarse)\";\n\nfunction mediaList(): MediaQueryList | null {\n return typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" ? window.matchMedia(QUERY) : null;\n}\n\nfunction subscribe(onChange: () => void): () => void {\n const list = mediaList();\n list?.addEventListener(\"change\", onChange);\n return () => list?.removeEventListener(\"change\", onChange);\n}\n\nconst snapshot = () => mediaList()?.matches ?? false;\n\n/**\n * Whether `(pointer: coarse)` matches: the primary pointer is a finger. `false` on the server\n * and wherever `matchMedia` is missing.\n *\n * @returns `true` on a touch-first device.\n */\nexport function useCoarsePointer(): boolean {\n return useSyncExternalStore(subscribe, snapshot, () => false);\n}\n","/**\n * A rotated rectangle or ellipse as an object: moved, resized from eight handles in its own\n * frame, and turned from a rotation handle, on the image.\n *\n * The axis-aligned `RectRoiEditor` cannot hold a rotated bounding box or an ellipse fit, which\n * is what an annotation tool and a detector's fitted marker are. The arithmetic is `shapeEdit.ts`;\n * this is the gestures, the handles and the keyboard.\n */\n\nimport { useEffect, useRef, type KeyboardEvent, type PointerEvent, type SVGProps } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport { overlayRole } from \"./overlayRole\";\nimport { ROI_HANDLES, type RoiHandle } from \"./roiEdit\";\nimport {\n fromShapeFrame,\n moveShape,\n resizeShape,\n rotateShape,\n rotationHandlePoint,\n shapeHandleCursor,\n shapeHandlePoint,\n shapePress,\n SHAPE_HANDLE_PX,\n SHAPE_ROTATE_OFFSET_PX,\n SHAPE_ROTATE_RADIUS_PX,\n type RotatedShape,\n} from \"./shapeEdit\";\nimport { POINTER_RADIUS_PX, TOUCH_RADIUS_PX, hitRadiusPx } from \"./stage/gesture\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useCoarsePointer } from \"./stage/useCoarsePointer\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox } from \"./stage/view\";\n\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;\n/** Shift while rotating rounds to this step, and `[` / `]` turn by 1° (15° with Shift). */\nconst SNAP = Math.PI / 12;\nconst KEY_TURN = Math.PI / 180;\nconst HALO = overlayRole(\"halo\");\n\n/** Props of `ShapeEditor`. */\nexport interface ShapeEditorProps {\n /** `\"rect\"` draws a rotated rectangle, `\"ellipse\"` the ellipse inscribed in it. */\n kind: \"rect\" | \"ellipse\";\n /**\n * The shape in image coordinates, or `null` for none. `rotation` is in **radians, clockwise\n * on screen**, so a value in degrees (Konva's, say) is `degrees * Math.PI / 180`. An\n * ellipse's `width` and `height` are its full axes, `2 · radiusX` and `2 · radiusY`.\n */\n value: RotatedShape | null;\n /** Called with the shape as it changes: on every move of a drag, and on each key nudge. */\n onValueChange: (value: RotatedShape) => void;\n /** Called once a gesture ends (a drag released, a nudge made): the moment to save or re-run. */\n onCommit?: ((value: RotatedShape) => void) | undefined;\n /** Show handles and accept moves, resizes and rotations. Defaults to `true`. */\n editable?: boolean | undefined;\n /** Show the rotation handle and accept `[` / `]`. Defaults to `true`; off for a shape that must stay level. */\n rotatable?: boolean | undefined;\n /** The smallest extent on either axis, in image pixels. Defaults to 5. */\n minSize?: number | undefined;\n /** The shape's accessible name. Defaults to \"Shape\". */\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 }\n | { kind: \"resize\"; handle: RoiHandle }\n | { kind: \"rotate\" }\n) & { start: RotatedShape; moved: boolean; pointerId: number };\n\n/**\n * An editable rotated rectangle or ellipse inside an `ImageStage`.\n *\n * - **Handles.** Eight handles resize the shape in its own frame: the dragged side follows the\n * pointer and the opposite side stays where it is, whatever the rotation. A shape stops at\n * `minSize` rather than flipping. The interior moves it, and so does the band along its\n * outline (the pointer's tolerance: 6 px for a mouse, 12 px for a finger), which is how a thin\n * or rotated shape is grabbed. The band is as wide as the device's primary pointer needs\n * (`(pointer: coarse)`), so on a touch laptop whose primary pointer is fine, a touch 6 to\n * 12 px outside the outline reaches the layers below instead of the editor.\n * - **Press order.** One decision serves every part of the editor: the nearest handle first,\n * then the interior or outline band (move), then nothing. A small shape's interior does not\n * steal a press meant for a handle, and a press that hits none of them is not claimed, so\n * it reaches whatever is below, or the stage.\n * - **Touch.** A press that grabs the shape is claimed; a second finger landing during an edit\n * cancels it (the shape reverts, nothing is committed) and is left to the stage.\n * - **Rotation.** The handle past the top side turns the shape about its centre; hold Shift to\n * round to 15°.\n * - **Keyboard.** The shape is focusable: arrow keys move it by one image pixel (ten with Shift),\n * with Alt they grow or shrink it along its own axes from its top-left corner, and `[` / `]`\n * turn it by 1° (15° with Shift).\n * - **Rendering.** Handles and the outline are a constant size on screen at every zoom; an\n * ellipse also shows its bounding box, where the handles are.\n * - **Panning.** A press with the hand tool, or with space held, still pans.\n *\n * It does not draw a new shape (`DraftShape` previews one while the app's tool does), and does\n * not keep the shape inside the image.\n *\n * The SVG carries `data-editable`; the outline carries `data-shape`.\n */\nexport function ShapeEditor({\n kind,\n value,\n onValueChange,\n onCommit,\n editable = true,\n rotatable = true,\n minSize = 5,\n label = \"Shape\",\n stroke = overlayRole(\"selection\"),\n}: ShapeEditorProps) {\n const stage = useStage();\n const px = useScreenPx();\n const coarse = useCoarsePointer();\n const dragRef = useRef<Drag | null>(null);\n const lastRef = useRef<RotatedShape | null>(null);\n const stopWatchRef = useRef<(() => void) | null>(null);\n\n const report = (next: RotatedShape) => {\n lastRef.current = next;\n onValueChange(next);\n };\n\n /** Abandon an edit in flight: the shape reverts and nothing is committed. */\n const cancelEdit = () => {\n const drag = dragRef.current;\n dragRef.current = null;\n stopWatchRef.current?.();\n stopWatchRef.current = null;\n if (drag && lastRef.current) onValueChange(drag.start);\n lastRef.current = null;\n };\n\n // An edit still in flight when the editor goes away is cancelled, not left listening.\n useEffect(() => () => stopWatchRef.current?.(), []);\n\n /**\n * The one press decision for the whole editor: every target (the interior, the outline\n * band, a handle) comes here, and the nearest handle wins over the interior. A declined\n * press is not claimed and bubbles to the stage.\n */\n const press = (event: PointerEvent<SVGElement>) => {\n if (!value || stage.panMode) return;\n const touch = event.pointerType === \"touch\";\n if (!touch && event.button !== 0) return;\n // A second finger while an edit is in flight cancels it (a pinch, not an edit), unclaimed.\n if (dragRef.current) {\n if (touch && dragRef.current.pointerId !== event.pointerId) cancelEdit();\n return;\n }\n const at = stage.toImage({ x: event.clientX, y: event.clientY });\n const decision = shapePress(value, kind, stage.view.scale, at, hitRadiusPx(event.pointerType), rotatable);\n if (!decision) return;\n event.stopPropagation();\n event.preventDefault();\n try {\n event.currentTarget.setPointerCapture(event.pointerId);\n } catch {\n // The pointer ended before this handler ran; the edit still follows the events the editor receives.\n }\n const base = { start: value, moved: false, pointerId: event.pointerId };\n dragRef.current =\n decision.kind === \"move\"\n ? { ...base, kind: \"move\", from: at }\n : decision.kind === \"resize\"\n ? { ...base, kind: \"resize\", handle: decision.handle }\n : { ...base, kind: \"rotate\" };\n lastRef.current = null;\n if (touch) {\n const id = event.pointerId;\n const other = (e: globalThis.PointerEvent) => {\n if (e.pointerId !== id && e.pointerType === \"touch\") cancelEdit();\n };\n window.addEventListener(\"pointerdown\", other);\n stopWatchRef.current = () => window.removeEventListener(\"pointerdown\", other);\n }\n };\n\n const onMove = (event: PointerEvent<SVGElement>) => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n event.stopPropagation();\n const p = stage.toImage({ x: event.clientX, y: event.clientY });\n drag.moved = true;\n if (drag.kind === \"move\") report(moveShape(drag.start, p.x - drag.from.x, p.y - drag.from.y));\n else if (drag.kind === \"resize\") report(resizeShape(drag.start, drag.handle, p, minSize));\n else report(rotateShape(drag.start, p, event.shiftKey ? SNAP : 0));\n };\n\n const onEnd = (event: PointerEvent<SVGElement>) => {\n const drag = dragRef.current;\n if (!drag || drag.pointerId !== event.pointerId) return;\n event.stopPropagation();\n dragRef.current = null;\n stopWatchRef.current?.();\n stopWatchRef.current = null;\n if (drag.moved && lastRef.current) onCommit?.(lastRef.current);\n };\n\n /** The handlers every target of the editor shares. */\n const gesture = {\n onPointerDown: press,\n onPointerMove: onMove,\n onPointerUp: onEnd,\n onPointerCancel: (event: PointerEvent<SVGElement>) => {\n if (dragRef.current?.pointerId === event.pointerId) cancelEdit();\n },\n onLostPointerCapture: onEnd,\n onDoubleClick: (event: { stopPropagation: () => void }) => event.stopPropagation(),\n };\n\n const onKeyDown = (event: KeyboardEvent<SVGElement>) => {\n if (!editable || value === null) return;\n const turn = rotatable && (event.key === \"[\" || event.key === \"]\");\n if (turn) {\n event.preventDefault();\n event.stopPropagation();\n const angle = (event.key === \"]\" ? 1 : -1) * (event.shiftKey ? SNAP : KEY_TURN);\n const next = { ...value, rotation: value.rotation + angle };\n onValueChange(next);\n onCommit?.(next);\n return;\n }\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 // Alt grows from the top-left corner, along the shape's own axes, as `RectRoiEditor` does.\n const next = event.altKey\n ? resizeShape(value, \"se\", fromShapeFrame(value, { x: value.width / 2 + d.x, y: value.height / 2 + d.y }), minSize)\n : moveShape(value, d.x, d.y);\n onValueChange(next);\n onCommit?.(next);\n };\n\n const stem = value ? { from: shapeHandlePoint(value, \"n\"), to: rotationHandlePoint(value, px(SHAPE_ROTATE_OFFSET_PX)) } : null;\n const handleSize = px(SHAPE_HANDLE_PX);\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 >\n {value && <Outline kind={kind} shape={value} fill=\"none\" stroke={HALO} strokeWidth={px(STROKE_PX + 2 * HALO_PX)} />}\n {value && <Outline kind={kind} shape={value} data-shape={kind} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(STROKE_PX)} />}\n {kind === \"ellipse\" && value && (\n <rect\n x={value.cx - value.width / 2}\n y={value.cy - value.height / 2}\n width={value.width}\n height={value.height}\n transform={turned(value)}\n fill=\"none\"\n stroke={stroke}\n strokeWidth={px(1)}\n strokeDasharray={`${px(4)} ${px(3)}`}\n opacity={0.6}\n />\n )}\n {editable && value && (\n // The outline band: a wide transparent stroke, so a press a few pixels outside the\n // outline still reaches the editor. Sized for the device's primary pointer (a finger's\n // 12 px on a touch-first device, a mouse's 6 px otherwise) so a mouse press just\n // outside the outline reaches the layers below. `press` decides with the event's own pointer.\n <Outline\n kind={kind}\n shape={value}\n data-shape-band=\"\"\n fill=\"none\"\n stroke=\"transparent\"\n strokeWidth={px(2 * (coarse ? TOUCH_RADIUS_PX : POINTER_RADIUS_PX))}\n strokeLinejoin=\"round\"\n aria-hidden\n className=\"pointer-events-auto cursor-move\"\n style={{ pointerEvents: \"stroke\" }}\n {...gesture}\n />\n )}\n {editable && value && (\n <Outline\n kind={kind}\n shape={value}\n fill=\"transparent\"\n role=\"button\"\n tabIndex={0}\n aria-label={`${label}: centre ${fmt(value.cx)}, ${fmt(value.cy)}, ${fmt(value.width)} × ${fmt(value.height)} px, rotated ${fmt((value.rotation * 180) / Math.PI)}°`}\n aria-roledescription={kind === \"rect\" ? \"rotated rectangle\" : \"ellipse\"}\n className=\"pointer-events-auto cursor-move outline-none focus-visible:stroke-signal\"\n strokeWidth={px(2)}\n {...gesture}\n onKeyDown={onKeyDown}\n />\n )}\n {editable && value && rotatable && stem && (\n <>\n <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={HALO} strokeWidth={px(1 + 2 * HALO_PX)} />\n <line x1={stem.from.x} y1={stem.from.y} x2={stem.to.x} y2={stem.to.y} stroke={stroke} strokeWidth={px(1)} />\n <circle\n data-handle=\"rotate\"\n cx={stem.to.x}\n cy={stem.to.y}\n r={px(SHAPE_ROTATE_RADIUS_PX)}\n fill={stroke}\n stroke={HALO}\n strokeWidth={px(1)}\n className=\"pointer-events-auto\"\n style={{ cursor: \"grab\" }}\n {...gesture}\n />\n </>\n )}\n {editable &&\n value &&\n ROI_HANDLES.map((handle) => {\n const centre = shapeHandlePoint(value, handle);\n return (\n <rect\n key={handle}\n data-handle={handle}\n x={centre.x - handleSize / 2}\n y={centre.y - handleSize / 2}\n width={handleSize}\n height={handleSize}\n fill={stroke}\n stroke={HALO}\n strokeWidth={px(1)}\n className=\"pointer-events-auto\"\n style={{ cursor: shapeHandleCursor(handle, value.rotation) }}\n {...gesture}\n />\n );\n })}\n </svg>\n );\n}\n\n/** What the outline element takes: any SVG attribute, and `data-*`. */\ntype OutlineProps = Omit<SVGProps<SVGElement>, \"ref\"> & Record<`data-${string}`, string>;\n\n/** The shape drawn level about its centre and turned by its rotation: a rectangle, or the ellipse inscribed in it. */\nfunction Outline({ kind, shape, ...rest }: OutlineProps & { kind: \"rect\" | \"ellipse\"; shape: RotatedShape }) {\n const transform = turned(shape);\n return kind === \"rect\" ? (\n <rect x={shape.cx - shape.width / 2} y={shape.cy - shape.height / 2} width={shape.width} height={shape.height} transform={transform} {...rest} />\n ) : (\n <ellipse cx={shape.cx} cy={shape.cy} rx={shape.width / 2} ry={shape.height / 2} transform={transform} {...rest} />\n );\n}\n\n/** The SVG transform that turns a shape drawn level about its centre. */\nfunction turned(shape: RotatedShape): string {\n return `rotate(${(shape.rotation * 180) / Math.PI} ${shape.cx} ${shape.cy})`;\n}\n\nfunction fmt(value: number): string {\n return Number.isInteger(value) ? String(value) : value.toFixed(1);\n}\n","/**\n * What an annotation tool shows while a shape is being drawn: a dashed preview of the\n * point, line, polyline, polygon, rectangle or ellipse so far, and the rubber band of a\n * multi-select.\n *\n * Both draw from state the app's tool keeps; neither takes input. The tool decides what a\n * press means (`StageSurface` and `useStageHitTest`); these only make it visible.\n */\n\nimport { overlayRole, type OverlayRole } from \"./overlayRole\";\nimport type { Point } from \"./measureGeometry\";\nimport { rectFromCorners } from \"./roiEdit\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useScreenPx } from \"./stage/useScreenPx\";\nimport { imageViewBox, type Rect } from \"./stage/view\";\n\n/**\n * The shape being drawn.\n * - `point`: a position.\n * - `line`: a segment from `from` to `to`.\n * - `polyline` and `polygon`: the vertices placed so far, flat `[x0, y0, x1, y1, …]`, and\n * the pointer as `cursor`, which the next vertex would land on. A polygon with `closing`\n * set has the pointer on its first vertex: a click there closes it, so the first vertex is\n * highlighted and the closing edge drawn solid.\n * - `stroke`: a brush trail, the flat `points` swept by a round brush of `width` image pixels\n * (never thinner than 1 screen pixel), as a translucent filled band without dashes.\n * - `brush`: a brush footprint cursor, a circle of `diameter` image pixels centred on `x`, `y`.\n * - `rect` and `ellipse`: two opposite corners of the axis-aligned box (the drag's start and\n * the pointer).\n */\nexport type DraftShapeSpec =\n | { kind: \"point\"; x: number; y: number }\n | { kind: \"line\"; from: Point; to: Point }\n | { kind: \"polyline\"; points: ArrayLike<number>; cursor?: Point | undefined }\n | { kind: \"polygon\"; points: ArrayLike<number>; cursor?: Point | undefined; closing?: boolean | undefined }\n | { kind: \"stroke\"; points: ArrayLike<number>; width: number }\n | { kind: \"brush\"; x: number; y: number; diameter: number }\n | { kind: \"rect\"; from: Point; to: Point }\n | { kind: \"ellipse\"; from: Point; to: Point };\n\n/** Props of `DraftShape`. */\nexport interface DraftShapeProps {\n /** The shape so far, or `null` when nothing is being drawn. */\n shape: DraftShapeSpec | null;\n /** The overlay role it is drawn in. Defaults to `\"selection\"`, the accent. */\n role?: OverlayRole | undefined;\n /** A CSS colour that overrides `role`, for example `\"var(--defect)\"` for an eraser. */\n stroke?: string | undefined;\n /** Draw the dark band under the outline. On by default. */\n halo?: boolean | undefined;\n}\n\nconst HALO = overlayRole(\"halo\");\n/** Dash, gap, outline width and vertex dot size, in screen pixels. */\nconst DASH = 6;\nconst GAP = 4;\nconst STROKE_PX = 1.5;\nconst VERTEX_PX = 6;\n\n/**\n * A dashed preview of a shape being drawn, inside an `ImageStage`.\n *\n * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by\n * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline\n * or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also\n * shows, fainter, the segment that would close it; with `closing` the first vertex gets a\n * ring and that segment turns solid and full strength: \"click here to close\". A `stroke`\n * (brush trail) is a translucent band of its own width with round caps and joins and no\n * dashes, and a `brush` is a footprint ring: a dark ring under a light one, so it reads on\n * any image. `points` may be a typed-array view that changes identity every move: the draft\n * is rebuilt in one O(n) pass per render, with no per-vertex elements. It takes no pointer events and is hidden\n * from assistive technology: it is transient feedback for a gesture.\n *\n * The SVG carries `data-draft` (the shape's kind).\n */\nexport function DraftShape({ shape, role = \"selection\", stroke, halo = true }: DraftShapeProps) {\n const stage = useStage();\n const px = useScreenPx();\n const colour = stroke ?? overlayRole(role);\n const dash = `${px(DASH)} ${px(GAP)}`;\n const width = px(STROKE_PX);\n const parts = shape ? draftParts(shape, px(1)) : null;\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 aria-hidden\n data-draft={shape?.kind}\n >\n {parts && (\n <g fill=\"none\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n {parts.outline && halo && <path d={parts.outline} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}\n {parts.outline && parts.region && <path d={parts.outline} fill={colour} fillOpacity={0.12} stroke=\"none\" />}\n {parts.outline && <path data-draft-outline=\"\" d={parts.outline} stroke={colour} strokeWidth={width} strokeDasharray={dash} />}\n {parts.trail && <path data-draft-stroke=\"\" d={parts.trail.d} stroke={colour} strokeWidth={Math.max(parts.trail.width, px(1))} opacity={0.4} />}\n {parts.footprint && halo && <path d={parts.footprint} stroke={HALO} strokeWidth={px(3.5)} opacity={0.6} />}\n {parts.footprint && <path data-draft-brush=\"\" d={parts.footprint} stroke={colour} strokeWidth={px(1.5)} />}\n {parts.closing && <path data-draft-closing=\"\" d={parts.closing} stroke={colour} strokeWidth={parts.armed ? width : px(1)} strokeDasharray={parts.armed ? undefined : dash} opacity={parts.armed ? 1 : 0.5} />}\n {parts.first && <path data-draft-first=\"\" d={parts.first} stroke={colour} strokeWidth={width} fill={colour} fillOpacity={0.35} />}\n {parts.vertices && <path data-draft-vertices=\"\" d={parts.vertices} stroke={colour} strokeWidth={px(VERTEX_PX)} />}\n </g>\n )}\n </svg>\n );\n}\n\n/** A shape as the path data of its outline, and what goes with it. */\ninterface DraftParts {\n /** The outline. `null` before a polyline has a vertex. */\n outline: string | null;\n /** Whether the outline encloses a region, which takes the fill. */\n region: boolean;\n /** The segment that would close a polygon, from the pointer to the first vertex. */\n closing: string | null;\n /** The placed vertices, as zero-length segments drawn with round caps. */\n vertices: string | null;\n /** Whether the closing segment is the live \"click to close\" cue: solid, full strength. */\n armed: boolean;\n /** The ring around the first vertex while the pointer is on it. */\n first: string | null;\n /** A brush trail: its path and the width in image pixels. */\n trail: { d: string; width: number } | null;\n /** A brush footprint circle. */\n footprint: string | null;\n}\n\nconst NONE: DraftParts = { outline: null, region: false, closing: null, vertices: null, armed: false, first: null, trail: null, footprint: null };\n\n/** An ellipse with the given centre and radii as two arcs. */\nfunction ellipsePath(cx: number, cy: number, rx: number, ry: number): string {\n return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;\n}\n\nfunction draftParts(shape: DraftShapeSpec, unit: number): DraftParts {\n switch (shape.kind) {\n case \"point\":\n return { ...NONE, outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit), vertices: `M${shape.x} ${shape.y}h0` };\n case \"line\":\n return { ...NONE, outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}` };\n case \"rect\":\n case \"ellipse\": {\n const box = rectFromCorners(shape.from, shape.to);\n const outline =\n shape.kind === \"rect\"\n ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z`\n : ellipsePath(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2);\n return { ...NONE, outline, region: true };\n }\n case \"brush\":\n return { ...NONE, footprint: ellipsePath(shape.x, shape.y, Math.max(shape.diameter, 2 * unit) / 2, Math.max(shape.diameter, 2 * unit) / 2) };\n case \"stroke\": {\n const n = Math.floor(shape.points.length / 2);\n if (n === 0) return NONE;\n let d = \"\";\n for (let i = 0; i < n; i++) d += `${i === 0 ? \"M\" : \"L\"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;\n // A single point is a zero-length segment: the round caps make it a dot.\n return { ...NONE, trail: { d: n === 1 ? `${d}h0` : d, width: shape.width } };\n }\n case \"polyline\":\n case \"polygon\": {\n const n = Math.floor(shape.points.length / 2);\n if (n === 0) return NONE;\n let outline = \"\";\n let vertices = \"\";\n for (let i = 0; i < n; i++) {\n outline += `${i === 0 ? \"M\" : \"L\"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;\n vertices += `M${shape.points[2 * i]} ${shape.points[2 * i + 1]}h0`;\n }\n if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;\n const polygon = shape.kind === \"polygon\";\n const armed = polygon && shape.closing === true && n >= 2;\n let closing: string | null = null;\n if (armed) closing = `M${shape.points[2 * n - 2]} ${shape.points[2 * n - 1]}L${shape.points[0]} ${shape.points[1]}`;\n else if (polygon && shape.cursor) closing = `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}`;\n return {\n ...NONE,\n outline,\n region: polygon && n + (shape.cursor ? 1 : 0) >= 3,\n closing,\n vertices,\n armed,\n first: armed ? ellipsePath(shape.points[0]!, shape.points[1]!, 5 * unit, 5 * unit) : null,\n };\n }\n }\n}\n\n/** Props of `MarqueeRect`. */\nexport interface MarqueeRectProps {\n /** The band in image coordinates, or `null` when no band is being dragged. */\n rect: Rect | null;\n /** CSS colour of the band. Defaults to the overlay `selection` role. */\n stroke?: string | undefined;\n}\n\n/**\n * The rubber band of a multi-select, inside an `ImageStage`: the 12 % fill and a 1 screen px\n * outline in the selection colour, the same as `PolylineSet`'s own band. Feed it the box\n * between the press and the pointer from `StageSurface`, and the box to `pointsInRect`,\n * `polylinesInRect` or `areasInRect` at the release. It takes no pointer events.\n *\n * The SVG carries `data-marquee`.\n */\nexport function MarqueeRect({ rect, stroke = overlayRole(\"selection\") }: MarqueeRectProps) {\n const stage = useStage();\n const px = useScreenPx();\n return (\n <svg\n viewBox={imageViewBox(stage.image)}\n className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n aria-hidden\n data-marquee={rect ? \"\" : undefined}\n >\n {rect && (\n <rect x={rect.x} y={rect.y} width={rect.width} height={rect.height} fill={stroke} fillOpacity={0.12} stroke={stroke} strokeWidth={px(1)} />\n )}\n </svg>\n );\n}\n","/**\n * Moving a manual shape: a press on a selected item becomes image-space displacements, with the\n * click-slop handling every selection UI needs (a press that barely moves is a click, not a\n * drag).\n *\n * The layers resolve what is under the pointer (`onItemPress`); this turns the press that\n * follows into a move. The app keeps the item's geometry, shows the displaced copy while the\n * drag is in flight, and commits it at the end:\n *\n * <AreaSet items={items} selectedIds={selected}\n * onItemPress={(id, event) => {\n * if (!selected.has(id)) return select(id);\n * startMove(event, {\n * onMove: setOffset, // preview: draw the item shifted\n * onEnd: (delta, moved) => moved ? commit(id, delta) : select(id),\n * onCancel: () => setOffset(null),\n * });\n * }} />\n */\n\nimport { useCallback } from \"react\";\n\nimport type { Point } from \"./measureGeometry\";\nimport type { StagePointerEvent } from \"./stage/hitContext\";\nimport { useStage } from \"./stage/ImageStage\";\nimport { useStageDrag } from \"./stage/StageSurface\";\n\n/** What a shape drag does as the pointer moves and when it ends. Displacements are total, from the press. */\nexport interface ShapeDragHandlers {\n /**\n * Each move of the pointer once it has left the click slop: how far it is from where the\n * press landed, in image pixels. Draw the shape shifted by it.\n */\n onMove?: ((delta: Point, event: PointerEvent) => void) | undefined;\n /**\n * The release. `moved` is whether the pointer ever left the click slop; when it did not,\n * `delta` is `{ x: 0, y: 0 }` and the press was a click. Commit the shape shifted by `delta`.\n */\n onEnd?: ((delta: Point, moved: boolean, event: PointerEvent) => void) | undefined;\n /** The drag was interrupted (`pointercancel`) or the component unmounted mid-drag: drop the preview. */\n onCancel?: (() => void) | undefined;\n}\n\n/** Options of the function `useShapeDrag` returns. */\nexport interface ShapeDragOptions {\n /** How far the pointer may travel before the press is a drag, in screen pixels. Defaults to 3. */\n slop?: number | undefined;\n}\n\n/** The default click slop, in screen pixels (the stage's own). */\nconst DEFAULT_SLOP = 3;\n\n/**\n * Start moving a shape from a press, inside an `ImageStage`.\n *\n * Returns `start(event, handlers, options?)`. Call it from `onItemPress` of a layer with the\n * press event: the press is claimed, so the stage does not pan, and the pointer is followed on\n * `window` until it is released, whether or not it leaves the canvas. A touch tap reaches\n * `onItemPress` on release, so there is nothing to follow: it ends at once as a click\n * (`moved` false). Move a shape on touch with `ShapeEditor`'s handles or the app's own mode.\n *\n * @returns `start`.\n */\nexport function useShapeDrag(): (event: StagePointerEvent, handlers: ShapeDragHandlers, options?: ShapeDragOptions) => void {\n const { toImage } = useStage();\n const startDrag = useStageDrag();\n return useCallback(\n (event, handlers, options) => {\n if (event.type !== \"pointerdown\") {\n handlers.onEnd?.({ x: 0, y: 0 }, false, event.nativeEvent);\n return;\n }\n const slop = options?.slop ?? DEFAULT_SLOP;\n const from = { x: event.clientX, y: event.clientY };\n // Where the press landed, in image pixels: displacements are measured from it.\n const press = toImage(from);\n const displacement = (point: Point): Point => ({ x: point.x - press.x, y: point.y - press.y });\n let moved = false;\n startDrag(event, {\n onMove: (point, e) => {\n if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) <= slop) return;\n moved = true;\n handlers.onMove?.(displacement(point), e);\n },\n onEnd: (point, e) => handlers.onEnd?.(moved ? displacement(point) : { x: 0, y: 0 }, moved, e),\n onCancel: handlers.onCancel,\n });\n },\n [toImage, startDrag],\n );\n}\n\n/**\n * Move flat points by a displacement.\n *\n * @param points - `[x0, y0, x1, y1, …]`.\n * @param delta - The displacement, in the points' units.\n * @returns A new array, `points` shifted.\n */\nexport function translatePoints(points: ArrayLike<number>, delta: Point): number[] {\n const out = new Array<number>(points.length);\n for (let i = 0; i < points.length; i++) out[i] = points[i]! + (i % 2 === 0 ? delta.x : delta.y);\n return out;\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 { DraftShape } from \"./DraftShape\";\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/**\n * Render and edit a binary raster mask within the enclosing ImageStage. While editing, a\n * `DraftShape` brush footprint (a circle of the brush's diameter) follows the mouse or pen\n * pointer, and the keyboard brush while the layer has keyboard focus.\n */\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 // Where the pointer hovers (or paints); the footprint follows it. Not set for touch.\n const [hover, setHover] = 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 if (event.pointerType !== \"touch\") setHover(point);\n apply(point, point);\n }\n\n function move(event: PointerEvent<HTMLCanvasElement>) {\n if (!lastRef.current) {\n if (editable && !stage.panMode && event.pointerType !== \"touch\") {\n setHover(stage.toImage({ x: event.clientX, y: event.clientY }));\n setBrush(null);\n }\n return;\n }\n event.stopPropagation();\n const point = stage.toImage({ x: event.clientX, y: event.clientY });\n if (event.pointerType !== \"touch\") setHover(point);\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 if (event.pointerType === \"touch\") setHover(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 setHover(null);\n } else if (event.key === \"Enter\") {\n event.preventDefault();\n event.stopPropagation();\n const at = cursor();\n draftRef.current = mask;\n setBrush(at);\n setHover(null);\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)} onPointerLeave={() => { if (!lastRef.current) setHover(null); }} />\n {(hover ?? brush) && editable && <DraftShape shape={{ kind: \"brush\", x: (hover ?? brush)!.x, y: (hover ?? brush)!.y, diameter: 2 * Math.max(0.75, brushRadius) }} stroke=\"var(--signal)\" />}\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;;;;;;;;;AAyBvB,SAAgB,SAAS,KAAU,OAAY,UAAsB,CAAC,GAAW;CAC/E,IAAI,EAAE,IAAI,QAAQ,MAAM,EAAE,IAAI,SAAS,MAAM,EAAE,MAAM,QAAQ,MAAM,EAAE,MAAM,SAAS,IAAI,OAAO;CAC/F,MAAM,MAAM,KAAK,IAAI,GAAG,QAAQ,WAAW,CAA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