@vitavision/stage2d 0.12.0 → 0.13.2

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.
Files changed (43) hide show
  1. package/README.md +3 -6
  2. package/dist/index.d.ts +669 -57
  3. package/dist/index.js +5455 -3621
  4. package/dist/index.js.map +1 -1
  5. package/package.json +2 -2
  6. package/src/api/mapValues.ts +1 -4
  7. package/src/components/AreaSet.tsx +32 -9
  8. package/src/components/ContourEditor.tsx +325 -40
  9. package/src/components/DatumEditor.tsx +261 -0
  10. package/src/components/DraftShape.tsx +37 -5
  11. package/src/components/EllipseSet.tsx +3 -3
  12. package/src/components/GridLayer.tsx +8 -3
  13. package/src/components/HeatmapLayer.tsx +1 -1
  14. package/src/components/MaskEditor.tsx +57 -9
  15. package/src/components/MeasureOverlay.tsx +353 -92
  16. package/src/components/PointSet.tsx +23 -12
  17. package/src/components/PolylineSet.tsx +83 -27
  18. package/src/components/RectRoiEditor.tsx +189 -93
  19. package/src/components/ShapeEditor.tsx +25 -10
  20. package/src/components/areaBatching.ts +23 -3
  21. package/src/components/areaIndex.ts +2 -1
  22. package/src/components/contourArc.ts +268 -0
  23. package/src/components/datumEdit.ts +149 -0
  24. package/src/components/labelLod.ts +3 -7
  25. package/src/components/markerShapes.ts +2 -5
  26. package/src/components/measureGeometry.ts +46 -28
  27. package/src/components/measureHit.ts +383 -0
  28. package/src/components/overlayRole.ts +1 -1
  29. package/src/components/pointIndex.ts +14 -5
  30. package/src/components/polylineIndex.ts +3 -3
  31. package/src/components/shapeEdit.ts +38 -5
  32. package/src/components/stage/CompareLayer.tsx +231 -0
  33. package/src/components/stage/ImageLayer.tsx +56 -24
  34. package/src/components/stage/ImageStage.tsx +33 -38
  35. package/src/components/stage/StageSurface.tsx +34 -34
  36. package/src/components/stage/StageToolbar.tsx +35 -37
  37. package/src/components/stage/compareStyle.ts +155 -0
  38. package/src/components/stage/gesture.ts +5 -0
  39. package/src/components/stage/hitTest.ts +19 -0
  40. package/src/components/stage/useStageHitTest.ts +17 -12
  41. package/src/components/stage/view.ts +3 -15
  42. package/src/components/useShapeDrag.ts +2 -4
  43. package/src/index.ts +34 -65
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Two registered images of one size, compared in place: a checkerboard of the two, a wipe
3
+ * between them, or their difference.
4
+ *
5
+ * A stage layer like `ImageLayer`: both images are laid out at the stage's own pixel size, so
6
+ * they stay registered with each other and with every overlay at any zoom. All three modes are
7
+ * CSS on the second image (a mask, a clip, a blend), never a canvas, so nothing is read back or
8
+ * redrawn as the view moves.
9
+ */
10
+
11
+ import { useState, type KeyboardEvent, type PointerEvent } from "react";
12
+
13
+ import { cn } from "@vitavision/ui";
14
+ import { visibleRect } from "../labelLod";
15
+ import { overlayRole } from "../overlayRole";
16
+ import { clampSplit, compareStyles, knobPosition, splitForKey, splitText, type CompareMode, type CompareOrientation } from "./compareStyle";
17
+ import { useStage } from "./ImageStage";
18
+ import { useStageDrag } from "./StageSurface";
19
+ import { useScreenPx } from "./useScreenPx";
20
+ import { PIXEL_CENTRE } from "./view";
21
+
22
+ /** Props of `CompareLayer`. */
23
+ export interface CompareLayerProps {
24
+ /** Image A's URL: the reference. It is the stage's size. */
25
+ a: string;
26
+ /** Image B's URL: compared with A. The same size as A. */
27
+ b: string;
28
+ /**
29
+ * How they are compared.
30
+ * - `checker`: alternate squares of A and B, `cell` image pixels across, A at the top-left.
31
+ * - `wipe`: A before the divider and B after it; drag the divider, or focus it and use the keys.
32
+ * - `difference`: the per-channel difference of the two, brightened by `gain`. Identical pixels
33
+ * are black. It is computed on the sRGB-encoded values the browser composites, not on linear
34
+ * light, so treat it as a picture of where the images differ, not as a measurement.
35
+ */
36
+ mode: CompareMode;
37
+ /** The wipe's divider, as the fraction of the image before it (0 to 1), when the app controls it. */
38
+ split?: number | undefined;
39
+ /** The divider's starting place when the layer controls it. Defaults to 0.5. */
40
+ defaultSplit?: number | undefined;
41
+ /** Called as the divider is dragged or moved by a key, with the new fraction. */
42
+ onSplitChange?: ((split: number) => void) | undefined;
43
+ /** `vertical` (the default) puts A left of the divider; `horizontal` puts A above it. */
44
+ orientation?: CompareOrientation | undefined;
45
+ /** The checkerboard's square, in image pixels. Defaults to 32. */
46
+ cell?: number | undefined;
47
+ /** How much the difference is brightened: 1 shows it as it is, 4 makes a small one visible. Defaults to 1. */
48
+ gain?: number | undefined;
49
+ /** What the comparison shows, for assistive technology. */
50
+ alt: string;
51
+ /** The two images' names, for the divider's value and its tags. Defaults to `["A", "B"]`. */
52
+ labels?: readonly [string, string] | undefined;
53
+ /** The zoom (CSS pixels per image pixel) from which pixels are drawn as blocks. Defaults to 4. */
54
+ pixelatedAbove?: number | undefined;
55
+ /** Merged onto the layer's wrapper with `cn`. */
56
+ className?: string | undefined;
57
+ }
58
+
59
+ /** The divider's line, its knob's radius and the band that grabs it, in screen pixels. */
60
+ const LINE_PX = 1.5;
61
+ const KNOB_PX = 8;
62
+ const GRAB_PX = 12;
63
+ /** The tags' size and their distance from the knob's centre, in screen pixels. */
64
+ const TAG_PX = 11;
65
+ const TAG_GAP_PX = 14;
66
+
67
+ const HALO = overlayRole("halo");
68
+ const DIVIDER = overlayRole("label");
69
+
70
+ /**
71
+ * Two same-size images compared inside an `ImageStage`: as a checkerboard, a wipe or their
72
+ * difference (`mode`).
73
+ *
74
+ * - **Wipe.** The divider is a line one and a half screen pixels wide with a knob kept in the
75
+ * middle of the part of it on screen. Drag the line or the knob; the press is claimed, so the
76
+ * stage does not pan from it.
77
+ * - **Keyboard.** The knob is a slider (0 to 100, the share of A): arrow keys move it 1 % (10 %
78
+ * with Shift), Page Up and Page Down 10 %, Home and End to either edge. The keys do not reach
79
+ * the stage, so they do not pan it.
80
+ * - **Pixels.** Past `pixelatedAbove` both images are drawn as blocks, as `ImageLayer` does.
81
+ *
82
+ * The images are one picture to assistive technology (`role="img"`, named by `alt`); the knob is
83
+ * outside it, so it stays reachable. The wrapper carries `data-mode`, and `data-pixelated` while
84
+ * pixelated; the knob carries `data-dragging` during a drag.
85
+ */
86
+ export function CompareLayer({
87
+ a,
88
+ b,
89
+ mode,
90
+ split,
91
+ defaultSplit = 0.5,
92
+ onSplitChange,
93
+ orientation = "vertical",
94
+ cell = 32,
95
+ gain = 1,
96
+ alt,
97
+ labels = ["A", "B"],
98
+ pixelatedAbove = 4,
99
+ className,
100
+ }: CompareLayerProps) {
101
+ const stage = useStage();
102
+ const px = useScreenPx();
103
+ const startDrag = useStageDrag();
104
+ const [ownSplit, setOwnSplit] = useState(() => clampSplit(defaultSplit));
105
+ const [dragging, setDragging] = useState(false);
106
+ const current = clampSplit(split ?? ownSplit);
107
+
108
+ const change = (next: number) => {
109
+ const clamped = clampSplit(next);
110
+ setOwnSplit(clamped);
111
+ onSplitChange?.(clamped);
112
+ };
113
+
114
+ const styles = compareStyles(mode, { split: current, orientation, cell, gain });
115
+ const pixelated = stage.view.scale >= pixelatedAbove;
116
+ const image = { width: stage.image.width, height: stage.image.height };
117
+ const imgClass = "pointer-events-none absolute inset-0 h-full w-full select-none";
118
+ const rendering = pixelated ? ("pixelated" as const) : undefined;
119
+
120
+ // The divider is drawn in the layer's own CSS pixels (0 at the image's left edge, not at its
121
+ // first pixel's centre), the frame `clip-path` and `visibleRect` work in.
122
+ const vertical = orientation === "vertical";
123
+ const length = vertical ? image.height : image.width;
124
+ const extent = vertical ? image.width : image.height;
125
+ const at = current * extent;
126
+ const visible = visibleRect(stage.view, stage.box);
127
+ const along = knobPosition(
128
+ visible === null ? null : vertical ? [visible.y, visible.y + visible.height] : [visible.x, visible.x + visible.width],
129
+ length,
130
+ );
131
+ const knob = vertical ? { x: at, y: along } : { x: along, y: at };
132
+ const line = vertical ? { x1: at, y1: 0, x2: at, y2: image.height } : { x1: 0, y1: at, x2: image.width, y2: at };
133
+
134
+ const grab = (event: PointerEvent<SVGElement>) => {
135
+ if (stage.panMode) return;
136
+ if (event.pointerType !== "touch" && event.button !== 0) return;
137
+ setDragging(true);
138
+ const follow = (p: { x: number; y: number }) => change(((vertical ? p.x : p.y) + PIXEL_CENTRE) / extent);
139
+ startDrag(event, {
140
+ claimsTouch: true,
141
+ onMove: follow,
142
+ onEnd: () => setDragging(false),
143
+ onCancel: () => setDragging(false),
144
+ });
145
+ };
146
+
147
+ const onKeyDown = (event: KeyboardEvent<SVGElement>) => {
148
+ const next = splitForKey(current, event.key, event.shiftKey, orientation);
149
+ if (next === null) return;
150
+ event.preventDefault();
151
+ event.stopPropagation();
152
+ change(next);
153
+ };
154
+
155
+ return (
156
+ <div className={cn("pointer-events-none absolute inset-0", className)} data-mode={mode} data-pixelated={pixelated ? "" : undefined}>
157
+ <div role="img" aria-label={alt} className="absolute inset-0" style={styles.wrapper}>
158
+ <img src={a} alt="" draggable={false} data-image="a" className={imgClass} style={{ imageRendering: rendering }} />
159
+ <img src={b} alt="" draggable={false} data-image="b" className={imgClass} style={{ ...styles.b, imageRendering: rendering }} />
160
+ </div>
161
+ {mode === "wipe" && (
162
+ <svg viewBox={`0 0 ${image.width} ${image.height}`} className="absolute inset-0 h-full w-full overflow-visible" data-divider="">
163
+ <line {...line} stroke={HALO} strokeWidth={px(LINE_PX + 2)} />
164
+ <line {...line} stroke={DIVIDER} strokeWidth={px(LINE_PX)} />
165
+ <line
166
+ {...line}
167
+ data-divider-band=""
168
+ stroke="transparent"
169
+ strokeWidth={px(GRAB_PX)}
170
+ className="pointer-events-auto"
171
+ style={{ pointerEvents: "stroke", cursor: vertical ? "ew-resize" : "ns-resize" }}
172
+ aria-hidden
173
+ onPointerDown={grab}
174
+ />
175
+ <circle
176
+ cx={knob.x}
177
+ cy={knob.y}
178
+ r={px(KNOB_PX)}
179
+ fill={DIVIDER}
180
+ stroke={HALO}
181
+ strokeWidth={px(1.5)}
182
+ role="slider"
183
+ tabIndex={0}
184
+ aria-label={`Split between ${labels[0]} and ${labels[1]}`}
185
+ aria-orientation={vertical ? "horizontal" : "vertical"}
186
+ aria-valuemin={0}
187
+ aria-valuemax={100}
188
+ aria-valuenow={Math.round(current * 100)}
189
+ aria-valuetext={splitText(current, labels[0])}
190
+ data-dragging={dragging ? "" : undefined}
191
+ className="pointer-events-auto outline-none focus-visible:stroke-signal"
192
+ style={{ cursor: vertical ? "ew-resize" : "ns-resize" }}
193
+ onPointerDown={grab}
194
+ onKeyDown={onKeyDown}
195
+ />
196
+ {/* Which image is on which side, beside the knob. */}
197
+ <g
198
+ aria-hidden
199
+ fontSize={px(TAG_PX)}
200
+ className="font-mono select-none"
201
+ fill={DIVIDER}
202
+ stroke={HALO}
203
+ strokeWidth={px(3)}
204
+ strokeLinejoin="round"
205
+ paintOrder="stroke"
206
+ >
207
+ {vertical ? (
208
+ <>
209
+ <text data-tag="a" x={knob.x - px(TAG_GAP_PX)} y={knob.y} textAnchor="end" dominantBaseline="central">
210
+ {labels[0]}
211
+ </text>
212
+ <text data-tag="b" x={knob.x + px(TAG_GAP_PX)} y={knob.y} textAnchor="start" dominantBaseline="central">
213
+ {labels[1]}
214
+ </text>
215
+ </>
216
+ ) : (
217
+ <>
218
+ <text data-tag="a" x={knob.x} y={knob.y - px(TAG_GAP_PX)} textAnchor="middle" dominantBaseline="text-after-edge">
219
+ {labels[0]}
220
+ </text>
221
+ <text data-tag="b" x={knob.x} y={knob.y + px(TAG_GAP_PX)} textAnchor="middle" dominantBaseline="text-before-edge">
222
+ {labels[1]}
223
+ </text>
224
+ </>
225
+ )}
226
+ </g>
227
+ </svg>
228
+ )}
229
+ </div>
230
+ );
231
+ }
@@ -10,13 +10,14 @@
10
10
  * until it would be magnified — until the screen shows more pixels than it has. Past that
11
11
  * point the full image is requested, and it stays once loaded, so zooming back out does
12
12
  * not swap back. The preview stays underneath while the full image loads, so the frame
13
- * never goes blank.
13
+ * never goes blank. When the full image is costly to produce, the app can leave its URL
14
+ * out and supply it when `onFullNeeded` says the same rule has tripped.
14
15
  * - **Pixelated past a zoom.** Above about 4× the browser's smoothing paints detail the
15
16
  * sensor never recorded; on a metrology bench the sensor's own samples are what is worth
16
17
  * looking at.
17
18
  */
18
19
 
19
- import { useState } from "react";
20
+ import { useEffect, useRef, useState } from "react";
20
21
 
21
22
  import { cn } from "@vitavision/ui";
22
23
  import { useStage } from "./ImageStage";
@@ -29,16 +30,19 @@ export interface ImageTier {
29
30
  width: number;
30
31
  }
31
32
 
32
- /** Props of `ImageLayer`. */
33
- export interface ImageLayerProps {
34
- /** The full-resolution image's URL. */
35
- src: string;
36
- /** A smaller tier to show first; without one, `src` is shown from the start. */
37
- preview?: ImageTier | undefined;
33
+ /** What every `ImageLayer` takes, whichever tiers it is given. */
34
+ export interface ImageLayerBaseProps {
38
35
  /** The image's description, for assistive technology. `""` marks it decorative. */
39
36
  alt: string;
40
37
  /** The zoom (CSS pixels per image pixel) from which pixels are drawn as blocks. Defaults to 4. */
41
38
  pixelatedAbove?: number | undefined;
39
+ /**
40
+ * Called once per `preview.src` when the full image is first wanted: the stage would magnify
41
+ * the preview. An app whose full image is costly to make or fetch leaves `src` out and
42
+ * passes it from here; the full image is shown as soon as `src` arrives. Not called without
43
+ * a `preview`.
44
+ */
45
+ onFullNeeded?: (() => void) | undefined;
42
46
  /** Called when the full image has loaded. */
43
47
  onLoad?: (() => void) | undefined;
44
48
  /** Called when the full image fails to load. */
@@ -47,37 +51,64 @@ export interface ImageLayerProps {
47
51
  className?: string | undefined;
48
52
  }
49
53
 
54
+ /**
55
+ * Props of `ImageLayer`: the full image's `src`, a `preview` tier, or both. With a `preview`,
56
+ * `src` may be left out until `onFullNeeded` asks for it.
57
+ */
58
+ export type ImageLayerProps = ImageLayerBaseProps &
59
+ (
60
+ | {
61
+ /** The full-resolution image's URL. */
62
+ src: string;
63
+ /** A smaller tier to show first; without one, `src` is shown from the start. */
64
+ preview?: ImageTier | undefined;
65
+ }
66
+ | {
67
+ /** The full-resolution image's URL, once known. Until then the preview stands in. */
68
+ src?: string | undefined;
69
+ /** A smaller tier to show first. */
70
+ preview: ImageTier;
71
+ }
72
+ );
73
+
50
74
  /**
51
75
  * The photograph at its natural size inside an `ImageStage`, with an optional preview tier
52
76
  * and pixelated rendering past `pixelatedAbove`. It takes no pointer events, so presses reach
53
77
  * the stage and the layers above.
54
78
  *
79
+ * With a `preview`, the full image is wanted once the stage would magnify the preview, and
80
+ * `onFullNeeded` says so; `src` can be supplied then rather than up front.
81
+ *
55
82
  * Each image carries `data-tier` (`preview` or `full`); the full image carries `data-loaded`
56
- * once it has loaded, and both carry `data-pixelated` while pixelated.
83
+ * once it has loaded, the preview carries `data-wants-full` from the moment the full image is
84
+ * wanted until it has loaded, and both carry `data-pixelated` while pixelated.
57
85
  */
58
- export function ImageLayer({
59
- src,
60
- preview,
61
- alt,
62
- pixelatedAbove = 4,
63
- onLoad,
64
- onError,
65
- className,
66
- }: ImageLayerProps) {
86
+ export function ImageLayer({ src, preview, alt, pixelatedAbove = 4, onFullNeeded, onLoad, onError, className }: ImageLayerProps) {
67
87
  const stage = useStage();
68
88
  const scale = stage.view.scale;
69
89
  // The full image is wanted once the preview would be magnified on screen: its own pixels
70
90
  // per image pixel are `preview.width / image.width`. Not before the viewport is measured:
71
91
  // the placeholder view then is 1:1, which would fetch the full image on every open.
72
92
  const measured = stage.box.width > 0;
73
- const needsFull = preview === undefined || (measured && scale * stage.image.width > preview.width);
74
- // Requested once, kept: zooming back out should not drop the pixels already fetched.
75
- const [requested, setRequested] = useState<string | null>(needsFull ? src : null);
76
- if (needsFull && requested !== src) setRequested(src);
93
+ const previewSrc = preview?.src ?? null;
94
+ const magnified = preview !== undefined && measured && scale * stage.image.width > preview.width;
95
+ // Wanted once per preview, and kept: zooming back out should not drop the pixels already
96
+ // fetched.
97
+ const [wantedFor, setWantedFor] = useState<string | null>(magnified ? previewSrc : null);
98
+ if (magnified && wantedFor !== previewSrc) setWantedFor(previewSrc);
99
+ const wanted = previewSrc === null || wantedFor === previewSrc;
77
100
  const [loaded, setLoaded] = useState<string | null>(null);
78
101
 
79
- const showFull = requested === src;
80
- const fullReady = loaded === src;
102
+ // Told once per preview: the guard holds through a new `onFullNeeded` and a re-run effect.
103
+ const notifiedRef = useRef<string | null>(null);
104
+ useEffect(() => {
105
+ if (previewSrc === null || wantedFor !== previewSrc || notifiedRef.current === previewSrc) return;
106
+ notifiedRef.current = previewSrc;
107
+ onFullNeeded?.();
108
+ }, [previewSrc, wantedFor, onFullNeeded]);
109
+
110
+ const showFull = wanted && src !== undefined;
111
+ const fullReady = src !== undefined && loaded === src;
81
112
  const pixelated = scale >= pixelatedAbove;
82
113
  const shared = cn("pointer-events-none absolute inset-0 h-full w-full select-none", className);
83
114
  const rendering = pixelated ? ("pixelated" as const) : undefined;
@@ -91,6 +122,7 @@ export function ImageLayer({
91
122
  aria-hidden={showFull ? true : undefined}
92
123
  draggable={false}
93
124
  data-tier="preview"
125
+ data-wants-full={wanted ? "" : undefined}
94
126
  data-pixelated={pixelated ? "" : undefined}
95
127
  className={shared}
96
128
  style={{ imageRendering: rendering }}
@@ -25,28 +25,12 @@
25
25
  * with the image.
26
26
  */
27
27
 
28
- import {
29
- createContext,
30
- use,
31
- useCallback,
32
- useEffect,
33
- useImperativeHandle,
34
- useLayoutEffect,
35
- useMemo,
36
- useRef,
37
- useState,
38
- } from "react";
39
- import type {
40
- CSSProperties,
41
- KeyboardEvent as ReactKeyboardEvent,
42
- PointerEvent as ReactPointerEvent,
43
- ReactNode,
44
- Ref,
45
- } from "react";
28
+ import { createContext, use, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
29
+ import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode, Ref } from "react";
46
30
 
47
31
  import { cn } from "@vitavision/ui";
48
32
  import type { Point } from "../measureGeometry";
49
- import { centroid, hitRadiusPx, isTap, panButtonCodes, pinchView, type StageMouseButton } from "./gesture";
33
+ import { CLICK_SLOP, centroid, hitRadiusPx, isTap, panButtonCodes, pinchView, type StageMouseButton } from "./gesture";
50
34
  import { StageHitContext, type StagePointerEvent } from "./hitContext";
51
35
  import { createHitRegistry } from "./hitTest";
52
36
  import {
@@ -81,8 +65,6 @@ const WHEEL_SENSITIVITY = 0.0015;
81
65
  * has settled, both are as sharp as with no hint. Cleared, the layer re-rasterises.
82
66
  */
83
67
  const MOVING_SETTLE_MS = 150;
84
- /** How far a press may travel and still count as a click rather than a pan. */
85
- const CLICK_SLOP = 3;
86
68
  /** The view before the viewport has been measured — nothing is on screen yet. */
87
69
  const UNMEASURED_VIEW: StageView = { scale: 1, tx: 0, ty: 0 };
88
70
 
@@ -137,7 +119,10 @@ export interface StageContext {
137
119
  toViewport: (image: Point) => Point;
138
120
  /** The image-pixel length that covers `css` screen pixels — for screen-constant geometry. */
139
121
  imageLength: (css: number) => number;
140
- /** Put a rect (image coordinates) on screen with a margin. */
122
+ /**
123
+ * Put a rect (image coordinates) on screen with a margin: `pad` is a fraction of the rect's
124
+ * own width and height added on each side (default 0.15).
125
+ */
141
126
  frame: (rect: Rect, pad?: number) => void;
142
127
  /** Fit the whole image. */
143
128
  fit: () => void;
@@ -162,7 +147,10 @@ export interface StageContext {
162
147
  * measured. Layers inside the stage use `useStage` instead.
163
148
  */
164
149
  export interface StageHandle {
165
- /** Put a rect (image coordinates) on screen with a margin (CSS pixels, default 24). */
150
+ /**
151
+ * Put a rect (image coordinates) on screen with a margin: `pad` is a fraction of the rect's
152
+ * own width and height added on each side (default 0.15).
153
+ */
166
154
  frame: (rect: Rect, pad?: number) => void;
167
155
  /** Fit the whole image. */
168
156
  fit: () => void;
@@ -220,7 +208,8 @@ export interface ImageStageProps {
220
208
  panButton?: StageMouseButton | readonly StageMouseButton[] | undefined;
221
209
  /**
222
210
  * Whether a double-click toggles fit and the previous view. On by default; turn it off in
223
- * an app whose tools use double-click, such as closing a polygon.
211
+ * an app whose tools use double-click, such as closing a polygon. A double-click a layer
212
+ * takes through the hit-test (an editable `ContourEditor` inserting a vertex) never toggles.
224
213
  */
225
214
  doubleClickFit?: boolean | undefined;
226
215
  /**
@@ -246,6 +235,14 @@ export interface ImageStageProps {
246
235
  clamp?: ClampOptions;
247
236
  /** Keyboard zoom/pan shortcuts. On by default; the stage takes focus to receive them. */
248
237
  shortcuts?: boolean;
238
+ /**
239
+ * Whether the viewport is a tab stop (`tabIndex={0}`, `role="application"`). Defaults to
240
+ * `shortcuts`. Off, the viewport is a plain `role="group"` that takes no focus, for an app that
241
+ * owns the keyboard on an element around the stage and would otherwise have two nested tab
242
+ * stops. With `shortcuts` on and `focusable` off the keys still work while focus is on an
243
+ * element inside the stage, such as an editor's handle.
244
+ */
245
+ focusable?: boolean | undefined;
249
246
  /**
250
247
  * Whether the arrow keys pan. On by default, and worth turning off in an app where the
251
248
  * arrows have a better job — stepping through a list of findings, say. The zoom keys
@@ -283,6 +280,9 @@ export interface ImageStageProps {
283
280
  * State is exposed on the viewport as `data-fit` (the view is fit), `data-panning` (a drag
284
281
  * is in progress) and `data-pan-mode` (the hand tool is on or space is held), each present
285
282
  * or absent.
283
+ *
284
+ * The viewport is a `role="application"` tab stop named by `label`. With `focusable` off (the
285
+ * default when `shortcuts` is off) it is a `role="group"` and takes no focus.
286
286
  */
287
287
  export function ImageStage({
288
288
  image,
@@ -302,6 +302,7 @@ export function ImageStage({
302
302
  onBackgroundClick,
303
303
  clamp,
304
304
  shortcuts = true,
305
+ focusable = shortcuts,
305
306
  panKeys = true,
306
307
  label = "Image canvas",
307
308
  initialView: opening = "auto",
@@ -772,8 +773,12 @@ export function ImageStage({
772
773
  * Fit ↔ **the view you were just at**, which is the gesture a reader actually wants: a
773
774
  * double-click to see the whole part, another to go back to the corner they were working
774
775
  * in. Toggling against 1:1 instead (the predecessor's behaviour) throws that place away.
776
+ *
777
+ * A layer that registered for double-clicks hears one first (inserting a vertex on a
778
+ * contour, say); when it takes it, the view stays where it is.
775
779
  */
776
780
  const onDoubleClick = (event: ReactPointerEvent<HTMLDivElement>) => {
781
+ if (!panMode && hits.routeDoubleClick(clientToImage({ x: event.clientX, y: event.clientY }), hitRadius(event))) return;
777
782
  if (!doubleClickFit || !(box.width > 0)) return;
778
783
  if (atFit) {
779
784
  const restore = previousRef.current;
@@ -834,9 +839,9 @@ export function ImageStage({
834
839
  <StageHitContext value={hits}>
835
840
  <div
836
841
  ref={attachViewport}
837
- role="application"
842
+ role={focusable ? "application" : "group"}
838
843
  aria-label={label}
839
- tabIndex={0}
844
+ tabIndex={focusable ? 0 : undefined}
840
845
  style={style}
841
846
  data-fit={atFit ? "" : undefined}
842
847
  data-panning={panning ? "" : undefined}
@@ -939,18 +944,8 @@ function contentSize(element: HTMLElement): Box {
939
944
  const style = getComputedStyle(element);
940
945
  const px = (value: string) => Number.parseFloat(value) || 0;
941
946
  return {
942
- width:
943
- rect.width -
944
- px(style.borderLeftWidth) -
945
- px(style.borderRightWidth) -
946
- px(style.paddingLeft) -
947
- px(style.paddingRight),
948
- height:
949
- rect.height -
950
- px(style.borderTopWidth) -
951
- px(style.borderBottomWidth) -
952
- px(style.paddingTop) -
953
- px(style.paddingBottom),
947
+ width: rect.width - px(style.borderLeftWidth) - px(style.borderRightWidth) - px(style.paddingLeft) - px(style.paddingRight),
948
+ height: rect.height - px(style.borderTopWidth) - px(style.borderBottomWidth) - px(style.paddingTop) - px(style.paddingBottom),
954
949
  };
955
950
  }
956
951
 
@@ -22,7 +22,7 @@ import type { PointerEvent as ReactPointerEvent } from "react";
22
22
  import { cn } from "@vitavision/ui";
23
23
  import type { Point } from "../measureGeometry";
24
24
  import { useStage } from "./ImageStage";
25
- import { hitRadiusPx } from "./gesture";
25
+ import { CLICK_SLOP, hitRadiusPx } from "./gesture";
26
26
  import { watchTouch } from "./touchWatch";
27
27
  import { clampToImage, imageViewBox, toImage } from "./view";
28
28
 
@@ -46,9 +46,6 @@ export interface StageDrag {
46
46
  claimsTouch?: boolean | undefined;
47
47
  }
48
48
 
49
- /** How far a press may travel and still be a click, in screen pixels. */
50
- const CLICK_SLOP = 3;
51
-
52
49
  /**
53
50
  * Start a drag from a press on any element inside an `ImageStage`.
54
51
  *
@@ -67,37 +64,40 @@ export function useStageDrag(): (event: ReactPointerEvent<Element>, drag: StageD
67
64
  // A drag still in flight when the component unmounts is cancelled, not leaked.
68
65
  useEffect(() => () => cleanupRef.current?.(), []);
69
66
 
70
- return useCallback((event: ReactPointerEvent<Element>, drag: StageDrag) => {
71
- event.stopPropagation();
72
- event.preventDefault();
73
- cleanupRef.current?.();
74
- const from = { x: event.clientX, y: event.clientY };
75
- let moved = false;
76
- const at = (e: PointerEvent) => toImage({ x: e.clientX, y: e.clientY });
67
+ return useCallback(
68
+ (event: ReactPointerEvent<Element>, drag: StageDrag) => {
69
+ event.stopPropagation();
70
+ event.preventDefault();
71
+ cleanupRef.current?.();
72
+ const from = { x: event.clientX, y: event.clientY };
73
+ let moved = false;
74
+ const at = (e: PointerEvent) => toImage({ x: e.clientX, y: e.clientY });
77
75
 
78
- const move = (e: PointerEvent) => {
79
- if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP) moved = true;
80
- drag.onMove?.(at(e), e);
81
- };
82
- const up = (e: PointerEvent) => {
83
- stop();
84
- drag.onEnd?.(at(e), e, moved);
85
- };
86
- const cancel = () => {
87
- stop();
88
- drag.onCancel?.();
89
- };
90
- const stop = () => {
91
- window.removeEventListener("pointermove", move);
92
- window.removeEventListener("pointerup", up);
93
- window.removeEventListener("pointercancel", cancel);
94
- cleanupRef.current = null;
95
- };
96
- window.addEventListener("pointermove", move);
97
- window.addEventListener("pointerup", up);
98
- window.addEventListener("pointercancel", cancel);
99
- cleanupRef.current = cancel;
100
- }, [toImage]);
76
+ const move = (e: PointerEvent) => {
77
+ if (!moved && Math.hypot(e.clientX - from.x, e.clientY - from.y) > CLICK_SLOP) moved = true;
78
+ drag.onMove?.(at(e), e);
79
+ };
80
+ const up = (e: PointerEvent) => {
81
+ stop();
82
+ drag.onEnd?.(at(e), e, moved);
83
+ };
84
+ const cancel = () => {
85
+ stop();
86
+ drag.onCancel?.();
87
+ };
88
+ const stop = () => {
89
+ window.removeEventListener("pointermove", move);
90
+ window.removeEventListener("pointerup", up);
91
+ window.removeEventListener("pointercancel", cancel);
92
+ cleanupRef.current = null;
93
+ };
94
+ window.addEventListener("pointermove", move);
95
+ window.addEventListener("pointerup", up);
96
+ window.addEventListener("pointercancel", cancel);
97
+ cleanupRef.current = cancel;
98
+ },
99
+ [toImage],
100
+ );
101
101
  }
102
102
 
103
103
  /** A press on the surface, as the app's `onPress` sees it. */