@vitavision/stage2d 0.11.0 → 0.13.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.
Files changed (41) hide show
  1. package/README.md +3 -6
  2. package/dist/index.d.ts +806 -74
  3. package/dist/index.js +6669 -4568
  4. package/dist/index.js.map +1 -1
  5. package/package.json +2 -2
  6. package/src/components/AreaSet.tsx +87 -56
  7. package/src/components/ContourEditor.tsx +297 -39
  8. package/src/components/DatumEditor.tsx +261 -0
  9. package/src/components/DraftShape.tsx +56 -11
  10. package/src/components/EllipseSet.tsx +3 -3
  11. package/src/components/GridLayer.tsx +1 -2
  12. package/src/components/HeatmapLayer.tsx +1 -1
  13. package/src/components/MaskEditor.tsx +22 -9
  14. package/src/components/MeasureOverlay.tsx +320 -89
  15. package/src/components/PointSet.tsx +18 -10
  16. package/src/components/PolylineSet.tsx +81 -17
  17. package/src/components/RectRoiEditor.tsx +193 -88
  18. package/src/components/ShapeEditor.tsx +14 -4
  19. package/src/components/areaBatching.ts +111 -0
  20. package/src/components/contourArc.ts +268 -0
  21. package/src/components/datumEdit.ts +149 -0
  22. package/src/components/labelLod.ts +2 -3
  23. package/src/components/markerShapes.ts +1 -2
  24. package/src/components/measureGeometry.ts +34 -1
  25. package/src/components/measureHit.ts +371 -0
  26. package/src/components/overlayRole.ts +1 -1
  27. package/src/components/pointIndex.ts +2 -3
  28. package/src/components/polylineIndex.ts +3 -3
  29. package/src/components/shapeEdit.ts +38 -5
  30. package/src/components/stage/CompareLayer.tsx +228 -0
  31. package/src/components/stage/ImageLayer.tsx +56 -15
  32. package/src/components/stage/ImageStage.tsx +231 -128
  33. package/src/components/stage/StageSurface.tsx +44 -18
  34. package/src/components/stage/StageToolbar.tsx +26 -8
  35. package/src/components/stage/compareStyle.ts +155 -0
  36. package/src/components/stage/gesture.ts +5 -0
  37. package/src/components/stage/hitTest.ts +19 -0
  38. package/src/components/stage/useStageHitTest.ts +11 -0
  39. package/src/components/stage/view.ts +33 -6
  40. package/src/components/useShapeDrag.ts +2 -4
  41. package/src/index.ts +34 -2
@@ -19,11 +19,12 @@
19
19
  import { useCallback, useEffect, useRef, useState } from "react";
20
20
  import type { PointerEvent as ReactPointerEvent } from "react";
21
21
 
22
+ import { cn } from "@vitavision/ui";
22
23
  import type { Point } from "../measureGeometry";
23
24
  import { useStage } from "./ImageStage";
24
- import { hitRadiusPx } from "./gesture";
25
+ import { CLICK_SLOP, hitRadiusPx } from "./gesture";
25
26
  import { watchTouch } from "./touchWatch";
26
- import { imageViewBox } from "./view";
27
+ import { clampToImage, imageViewBox, toImage } from "./view";
27
28
 
28
29
  /** What a drag does as the pointer moves and when it is released, in image coordinates. */
29
30
  export interface StageDrag {
@@ -45,9 +46,6 @@ export interface StageDrag {
45
46
  claimsTouch?: boolean | undefined;
46
47
  }
47
48
 
48
- /** How far a press may travel and still be a click, in screen pixels. */
49
- const CLICK_SLOP = 3;
50
-
51
49
  /**
52
50
  * Start a drag from a press on any element inside an `ImageStage`.
53
51
  *
@@ -137,6 +135,15 @@ export interface StageSurfaceProps {
137
135
  * stage's double-click-to-fit does not run; leave it out to keep the fit.
138
136
  */
139
137
  onDoubleClick?: ((point: Point) => void) | undefined;
138
+ /**
139
+ * How far the surface reaches. `"image"` (the default) is the image rectangle: a press in
140
+ * the margin around the image goes to the stage, which pans. `"viewport"` covers everything
141
+ * visible, margin included, so a drawing tool can place a point on the image's border by
142
+ * pressing just outside it; every point the surface then reports (the press, a drag's moves
143
+ * and release, hover, double-click) is clamped to the image's extent, `[-0.5, w - 0.5]` by
144
+ * `[-0.5, h - 0.5]`. `StagePress.client` stays the raw pointer position.
145
+ */
146
+ extent?: "image" | "viewport" | undefined;
140
147
  }
141
148
 
142
149
  /**
@@ -156,9 +163,12 @@ export interface StageSurfaceProps {
156
163
  *
157
164
  * A touch gesture that sets `claimsTouch: true` is claimed like a mouse press.
158
165
  *
166
+ * With `extent="viewport"` the surface also takes presses in the margin around the image, and
167
+ * clamps every reported point to the image.
168
+ *
159
169
  * The surface draws nothing. It carries `data-dragging` while a gesture it started is in flight.
160
170
  */
161
- export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageSurfaceProps) {
171
+ export function StageSurface({ onPress, cursor, onHover, onDoubleClick, extent = "image" }: StageSurfaceProps) {
162
172
  const stage = useStage();
163
173
  const start = useStageDrag();
164
174
  const [dragging, setDragging] = useState(false);
@@ -167,6 +177,22 @@ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageS
167
177
  // A touch still being watched when the surface goes away is cancelled, not left listening.
168
178
  useEffect(() => () => watchRef.current?.(), []);
169
179
 
180
+ const viewport = extent === "viewport";
181
+ // The image point under a client position; held to the image only for a viewport-wide surface.
182
+ const pointAt = (client: Point): Point => {
183
+ const p = stage.toImage(client);
184
+ return viewport ? clampToImage(p, stage.image) : p;
185
+ };
186
+ // The visible area in image coordinates, from the view and the measured box, so it follows
187
+ // pan, zoom and resize; the image rectangle until the viewport has been measured.
188
+ const target = (() => {
189
+ const { image, view, box } = stage;
190
+ if (!viewport || !(box.width > 0)) return { x: -0.5, y: -0.5, width: image.width, height: image.height };
191
+ const a = toImage(view, { x: 0, y: 0 });
192
+ const b = toImage(view, { x: box.width, y: box.height });
193
+ return { x: a.x, y: a.y, width: b.x - a.x, height: b.y - a.y };
194
+ })();
195
+
170
196
  const onPointerDown = (event: ReactPointerEvent<SVGRectElement>) => {
171
197
  const touch = event.pointerType === "touch";
172
198
  if (stage.panMode || (!touch && event.button !== 0)) return;
@@ -174,7 +200,7 @@ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageS
174
200
  if (touch && watchRef.current) return;
175
201
  const client = { x: event.clientX, y: event.clientY };
176
202
  const drag = onPress({
177
- point: stage.toImage(client),
203
+ point: pointAt(client),
178
204
  client,
179
205
  touch,
180
206
  radius: hitRadiusPx(event.pointerType),
@@ -192,10 +218,10 @@ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageS
192
218
  finish();
193
219
  };
194
220
  watchRef.current = watchTouch(event, {
195
- onMove: (e) => drag.onMove?.(stage.toImage({ x: e.clientX, y: e.clientY }), e),
221
+ onMove: (e) => drag.onMove?.(pointAt({ x: e.clientX, y: e.clientY }), e),
196
222
  onEnd: (e, moved) => {
197
223
  release();
198
- drag.onEnd?.(stage.toImage({ x: e.clientX, y: e.clientY }), e, moved);
224
+ drag.onEnd?.(pointAt({ x: e.clientX, y: e.clientY }), e, moved);
199
225
  },
200
226
  onCancel: () => {
201
227
  release();
@@ -205,10 +231,10 @@ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageS
205
231
  return;
206
232
  }
207
233
  start(event, {
208
- onMove: drag.onMove,
234
+ onMove: drag.onMove && ((point, e) => drag.onMove?.(viewport ? clampToImage(point, stage.image) : point, e)),
209
235
  onEnd: (point, e, moved) => {
210
236
  finish();
211
- drag.onEnd?.(point, e, moved);
237
+ drag.onEnd?.(viewport ? clampToImage(point, stage.image) : point, e, moved);
212
238
  },
213
239
  onCancel: () => {
214
240
  finish();
@@ -220,27 +246,27 @@ export function StageSurface({ onPress, cursor, onHover, onDoubleClick }: StageS
220
246
  return (
221
247
  <svg
222
248
  viewBox={imageViewBox(stage.image)}
223
- className="pointer-events-none absolute inset-0 h-full w-full"
249
+ className={cn("pointer-events-none absolute inset-0 h-full w-full", viewport && "overflow-visible")}
224
250
  data-dragging={dragging ? "" : undefined}
225
251
  aria-hidden
226
252
  >
227
253
  <rect
228
254
  data-stage-surface=""
229
- x={-0.5}
230
- y={-0.5}
231
- width={stage.image.width}
232
- height={stage.image.height}
255
+ x={target.x}
256
+ y={target.y}
257
+ width={target.width}
258
+ height={target.height}
233
259
  fill="transparent"
234
260
  className="pointer-events-auto"
235
261
  style={{ cursor: stage.panMode ? undefined : cursor }}
236
262
  onPointerDown={onPointerDown}
237
263
  onPointerMove={(event) => {
238
- if (!dragging && event.pointerType !== "touch") onHover?.(stage.toImage({ x: event.clientX, y: event.clientY }));
264
+ if (!dragging && event.pointerType !== "touch") onHover?.(pointAt({ x: event.clientX, y: event.clientY }));
239
265
  }}
240
266
  onDoubleClick={(event) => {
241
267
  if (!onDoubleClick) return;
242
268
  event.stopPropagation();
243
- onDoubleClick(stage.toImage({ x: event.clientX, y: event.clientY }));
269
+ onDoubleClick(pointAt({ x: event.clientX, y: event.clientY }));
244
270
  }}
245
271
  />
246
272
  </svg>
@@ -229,8 +229,16 @@ export function StageButton({ label, pressed, hint, shortcut, className, childre
229
229
  export interface StageLayer {
230
230
  /** Its identity, passed back to `onVisibleChange`. */
231
231
  id: string;
232
- /** Its name in the menu. */
233
- label: string;
232
+ /**
233
+ * Its name in the menu: text, or richer content such as a name and a count. It names the
234
+ * menu item for assistive technology, so keep its text meaningful.
235
+ */
236
+ label: ReactNode;
237
+ /**
238
+ * A CSS colour shown as a small dot before the label, matching the layer's colour on the
239
+ * canvas. Decorative (`aria-hidden`), so the label must name the layer on its own.
240
+ */
241
+ swatch?: string | undefined;
234
242
  /** Whether it is shown. */
235
243
  visible: boolean;
236
244
  /** Shown but not switchable, e.g. a layer that has nothing to draw yet. */
@@ -245,17 +253,19 @@ export interface StageLayersMenuProps {
245
253
  layers: readonly StageLayer[];
246
254
  /** Called with a layer's id and its new visibility. */
247
255
  onVisibleChange: (id: string, visible: boolean) => void;
248
- /** The trigger's accessible name and the menu's heading. Defaults to "Layers". */
256
+ /** The trigger's accessible name and tooltip. Defaults to "Layers". */
249
257
  label?: string | undefined;
258
+ /** The heading over the menu's items. Defaults to `label`. */
259
+ heading?: ReactNode;
250
260
  }
251
261
 
252
262
  /**
253
263
  * A `StageButton`-shaped trigger opening a menu of layer toggles, for `StageToolbar`'s
254
- * children. Each layer is a `menuitemcheckbox`; toggling one keeps the menu open for the
255
- * next. The trigger shows as pressed while any layer is hidden, so a canvas missing a layer
256
- * says so before the menu is opened.
264
+ * children. Each layer is a `menuitemcheckbox`, with its `swatch` as a dot before its label;
265
+ * toggling one keeps the menu open for the next. The trigger shows as pressed while any layer
266
+ * is hidden, so a canvas missing a layer says so before the menu is opened.
257
267
  */
258
- export function StageLayersMenu({ layers, onVisibleChange, label = "Layers" }: StageLayersMenuProps) {
268
+ export function StageLayersMenu({ layers, onVisibleChange, label = "Layers", heading = label }: StageLayersMenuProps) {
259
269
  const hidden = layers.some((layer) => !layer.visible && !layer.disabled);
260
270
  return (
261
271
  <DropdownMenu
@@ -266,7 +276,7 @@ export function StageLayersMenu({ layers, onVisibleChange, label = "Layers" }: S
266
276
  </StageButton>
267
277
  }
268
278
  >
269
- <MenuLabel>{label}</MenuLabel>
279
+ <MenuLabel>{heading}</MenuLabel>
270
280
  {layers.map((layer) => (
271
281
  <MenuCheckboxItem
272
282
  key={layer.id}
@@ -275,6 +285,14 @@ export function StageLayersMenu({ layers, onVisibleChange, label = "Layers" }: S
275
285
  disabled={layer.disabled}
276
286
  shortcut={layer.shortcut}
277
287
  >
288
+ {layer.swatch !== undefined && (
289
+ <span
290
+ data-swatch=""
291
+ aria-hidden
292
+ className="mr-2 inline-block size-2 rounded-full align-middle ring-1 ring-line"
293
+ style={{ backgroundColor: layer.swatch }}
294
+ />
295
+ )}
278
296
  {layer.label}
279
297
  </MenuCheckboxItem>
280
298
  ))}
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The arithmetic of `CompareLayer`: how image B is masked, clipped or blended over image A
3
+ * for each mode, and how the wipe's split moves. Pure CSS values, no canvas, so a comparison
4
+ * of two large frames costs the browser's compositor and nothing else.
5
+ */
6
+
7
+ import type { CSSProperties } from "react";
8
+
9
+ /** How two images are compared. */
10
+ export type CompareMode = "checker" | "wipe" | "difference";
11
+
12
+ /** Which way the wipe's divider runs: `vertical` splits left from right, `horizontal` top from bottom. */
13
+ export type CompareOrientation = "vertical" | "horizontal";
14
+
15
+ /** The styles of one comparison: the wrapper of both images, and image B. */
16
+ export interface CompareStyles {
17
+ /** On the element holding both images. */
18
+ wrapper: CSSProperties;
19
+ /** On image B, drawn over image A. */
20
+ b: CSSProperties;
21
+ }
22
+
23
+ /**
24
+ * A split as a fraction in `[0, 1]`.
25
+ *
26
+ * @param split - Any number.
27
+ * @returns It clamped to `[0, 1]`; `0.5` for a non-finite value.
28
+ */
29
+ export function clampSplit(split: number): number {
30
+ if (!Number.isFinite(split)) return 0.5;
31
+ return Math.min(1, Math.max(0, split));
32
+ }
33
+
34
+ /**
35
+ * The styles that compare B with A.
36
+ *
37
+ * - `checker`: B is masked by a checkerboard of `cell`-pixel squares (a repeating conic
38
+ * gradient), so A shows through every other square, starting with A at the top-left.
39
+ * - `wipe`: B is clipped to the far side of the divider, so A shows before `split` (left of it,
40
+ * or above it) and B after.
41
+ * - `difference`: B is blended over A with `mix-blend-mode: difference`, isolated so nothing
42
+ * behind the layer joins the blend, then brightened by `gain`. The difference is per
43
+ * channel, of the sRGB-encoded values the browser composites, not of linear light.
44
+ *
45
+ * @param mode - The comparison.
46
+ * @param options - `split` (0..1), `orientation`, `cell` (image pixels) and `gain`.
47
+ * @returns The wrapper's and B's styles.
48
+ */
49
+ export function compareStyles(
50
+ mode: CompareMode,
51
+ options: { split: number; orientation: CompareOrientation; cell: number; gain: number },
52
+ ): CompareStyles {
53
+ if (mode === "checker") {
54
+ const size = 2 * Math.max(1, options.cell);
55
+ const mask = "conic-gradient(black 0 25%, transparent 0 50%, black 0 75%, transparent 0)";
56
+ return {
57
+ wrapper: {},
58
+ b: {
59
+ maskImage: mask,
60
+ WebkitMaskImage: mask,
61
+ maskSize: `${size}px ${size}px`,
62
+ WebkitMaskSize: `${size}px ${size}px`,
63
+ maskRepeat: "repeat",
64
+ WebkitMaskRepeat: "repeat",
65
+ maskPosition: "0 0",
66
+ WebkitMaskPosition: "0 0",
67
+ },
68
+ };
69
+ }
70
+ if (mode === "wipe") return { wrapper: {}, b: { clipPath: wipeClip(options.split, options.orientation) } };
71
+ return {
72
+ wrapper: { isolation: "isolate", filter: options.gain === 1 ? undefined : `brightness(${Math.max(0, options.gain)})` },
73
+ b: { mixBlendMode: "difference" },
74
+ };
75
+ }
76
+
77
+ /**
78
+ * The clip that leaves B on the far side of the divider.
79
+ *
80
+ * @param split - Where the divider is, as a fraction of the width (vertical) or height (horizontal).
81
+ * @param orientation - Which way the divider runs.
82
+ * @returns A CSS `clip-path`.
83
+ */
84
+ export function wipeClip(split: number, orientation: CompareOrientation): string {
85
+ const at = `${round(clampSplit(split) * 100)}%`;
86
+ return orientation === "vertical" ? `inset(0 0 0 ${at})` : `inset(${at} 0 0 0)`;
87
+ }
88
+
89
+ /**
90
+ * What a key does to the split: the arrows move it 1 % (10 % with Shift), Page Up / Page Down
91
+ * 10 %, Home and End to either edge. Right always moves it right and Left left; on a vertical
92
+ * divider Up raises the value (the slider convention), on a horizontal one Up and Down move it
93
+ * up and down.
94
+ *
95
+ * @param split - The split now.
96
+ * @param key - `KeyboardEvent.key`.
97
+ * @param shift - Whether Shift is held.
98
+ * @param orientation - Which way the divider runs.
99
+ * @returns The new split, clamped; `null` for a key that does nothing.
100
+ */
101
+ export function splitForKey(split: number, key: string, shift: boolean, orientation: CompareOrientation): number | null {
102
+ const step = shift ? 0.1 : 0.01;
103
+ const vertical = orientation === "vertical";
104
+ switch (key) {
105
+ case "ArrowRight":
106
+ return clampSplit(split + step);
107
+ case "ArrowLeft":
108
+ return clampSplit(split - step);
109
+ case "ArrowUp":
110
+ return clampSplit(split + (vertical ? step : -step));
111
+ case "ArrowDown":
112
+ return clampSplit(split + (vertical ? -step : step));
113
+ case "PageUp":
114
+ return clampSplit(split + 0.1);
115
+ case "PageDown":
116
+ return clampSplit(split - 0.1);
117
+ case "Home":
118
+ return 0;
119
+ case "End":
120
+ return 1;
121
+ default:
122
+ return null;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * The divider's value as text, for a screen reader: how much of A shows, e.g. `"40 % A"`.
128
+ *
129
+ * @param split - The split.
130
+ * @param labelA - Image A's name.
131
+ * @returns The text.
132
+ */
133
+ export function splitText(split: number, labelA: string): string {
134
+ return `${Math.round(clampSplit(split) * 100)} % ${labelA}`;
135
+ }
136
+
137
+ /**
138
+ * Where along the divider its knob sits: the middle of the part of the divider on screen, so the
139
+ * knob stays in view however the image is zoomed and panned.
140
+ *
141
+ * @param visible - The visible span along the divider, in image pixels (`[start, end]`), or `null` before the viewport is measured.
142
+ * @param length - The image's extent along the divider.
143
+ * @returns The knob's position along the divider, in image pixels.
144
+ */
145
+ export function knobPosition(visible: readonly [number, number] | null, length: number): number {
146
+ if (visible === null) return length / 2;
147
+ const start = Math.max(0, visible[0]);
148
+ const end = Math.min(length, visible[1]);
149
+ if (!(end >= start)) return Math.min(length, Math.max(0, (visible[0] + visible[1]) / 2));
150
+ return (start + end) / 2;
151
+ }
152
+
153
+ function round(value: number): number {
154
+ return Math.round(value * 1000) / 1000;
155
+ }
@@ -11,6 +11,11 @@ import { zoomAbout, type StageView } from "./view";
11
11
  /** A mouse button that can pan the stage. */
12
12
  export type StageMouseButton = "left" | "middle" | "right";
13
13
 
14
+ /**
15
+ * How far a press may travel and still be a click rather than a drag, in CSS pixels. A pan,
16
+ * a handle drag and a vertex drag all start only past it, so a jittery click edits nothing.
17
+ */
18
+ export const CLICK_SLOP = 3;
14
19
  /** How far a touch may travel and still be a tap, in CSS pixels. */
15
20
  export const TAP_SLOP = 3;
16
21
  /** The longest a touch may last and still be a tap, in milliseconds. */
@@ -64,6 +64,11 @@ export interface StageHitLayerSpec<E = unknown> {
64
64
  hover?: ((id: HitId | null) => void) | undefined;
65
65
  /** A press landed on an item. Return `false` to decline it. */
66
66
  press?: ((id: HitId, event: E) => boolean | void) | undefined;
67
+ /**
68
+ * A double-click landed on an item, at `point` (image coordinates). Return `false` to
69
+ * decline it.
70
+ */
71
+ doubleClick?: ((id: HitId, point: Point) => boolean | void) | undefined;
67
72
  }
68
73
 
69
74
  /** Options of a hit-test. */
@@ -131,6 +136,13 @@ export interface HitRegistry<E = unknown> {
131
136
  * @returns Whether a layer claimed it.
132
137
  */
133
138
  routePress: (point: Point, radius: number, event: E) => boolean;
139
+ /**
140
+ * Offer a double-click to the best item under `point` among layers that take double-clicks,
141
+ * then the next, until one claims it.
142
+ *
143
+ * @returns Whether a layer claimed it.
144
+ */
145
+ routeDoubleClick: (point: Point, radius: number) => boolean;
134
146
  }
135
147
 
136
148
  /** Make an empty registry. */
@@ -177,5 +189,12 @@ export function createHitRegistry<E = unknown>(): HitRegistry<E> {
177
189
  }
178
190
  return false;
179
191
  },
192
+ routeDoubleClick(point, radius) {
193
+ for (const { hit, layer } of answers(point, radius)) {
194
+ const doubleClick = layer.doubleClick;
195
+ if (doubleClick && doubleClick(hit.id, point) !== false) return true;
196
+ }
197
+ return false;
198
+ },
180
199
  };
181
200
  }
@@ -84,6 +84,12 @@ export interface StageHitLayerOptions {
84
84
  * decline one. For a touch tap this is the `pointerup`.
85
85
  */
86
86
  onPress?: ((id: HitId, event: StagePointerEvent) => boolean | void) | undefined;
87
+ /**
88
+ * A double-click landed on an item, at `point` in image coordinates, and nothing above it
89
+ * claimed it. The stage offers a double-click to its layers before its own double-click to
90
+ * fit, so a layer that handles one keeps the view where it is. Return `false` to decline it.
91
+ */
92
+ onDoubleClick?: ((id: HitId, point: Point) => boolean | void) | undefined;
87
93
  }
88
94
 
89
95
  /**
@@ -120,6 +126,11 @@ export function useStageHitLayer(options: StageHitLayerOptions): string {
120
126
  get press() {
121
127
  return latestRef.current.onPress === undefined ? undefined : (hit: HitId, event: StagePointerEvent) => latestRef.current.onPress?.(hit, event);
122
128
  },
129
+ get doubleClick() {
130
+ return latestRef.current.onDoubleClick === undefined
131
+ ? undefined
132
+ : (hit: HitId, point: Point) => latestRef.current.onDoubleClick?.(hit, point);
133
+ },
123
134
  };
124
135
  return registry.register(layer);
125
136
  }, [registry, id, priority]);
@@ -211,6 +211,17 @@ export function insideImage(p: Point, image: Box): boolean {
211
211
  );
212
212
  }
213
213
 
214
+ /**
215
+ * An image coordinate held to the image's extent, `[-0.5, w - 0.5] x [-0.5, h - 0.5]` in the
216
+ * pixel-centre convention: the point on the frame's edge nearest to `p`.
217
+ */
218
+ export function clampToImage(p: Point, image: Box): Point {
219
+ return {
220
+ x: Math.min(image.width - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.x)),
221
+ y: Math.min(image.height - PIXEL_CENTRE, Math.max(-PIXEL_CENTRE, p.y)),
222
+ };
223
+ }
224
+
214
225
  /** A length in image pixels that covers `css` screen pixels at this view. */
215
226
  export function imageLengthFor(view: StageView, css: number): number {
216
227
  return view.scale > 0 ? css / view.scale : css;
@@ -234,6 +245,15 @@ export function zoomAbout(view: StageView, scale: number, anchor: Point): StageV
234
245
 
235
246
  /** The scale range `clampView` and `scaleRange` allow. */
236
247
  export interface ClampOptions {
248
+ /**
249
+ * How far the image may be panned. `"cover"` (the default): an axis the image overflows
250
+ * keeps the viewport covered, and an axis it does not fill is centred. `"center"`: any
251
+ * image point may be brought to the viewport's centre and no further, on both axes and at
252
+ * every scale — so a zoom about the pointer keeps the pointer's pixel under it while the
253
+ * image is still smaller than the viewport, and an edge or corner can be worked on in the
254
+ * middle of the screen.
255
+ */
256
+ panBounds?: "cover" | "center" | undefined;
237
257
  /** Lowest scale, as a multiple of fit. Defaults to `MIN_SCALE_VS_FIT`. */
238
258
  minScaleVsFit?: number;
239
259
  /** Highest scale, in CSS pixels per image pixel. Defaults to `MAX_SCALE`. */
@@ -251,10 +271,11 @@ export function scaleRange(box: Box, image: Box, options: ClampOptions = {}): [n
251
271
  /**
252
272
  * Keep the view legal: scale inside its range, and the image never dragged off screen.
253
273
  *
254
- * An axis where the scaled image is smaller than the viewport is centred rather than left
255
- * where a drag put it — free-floating pixels in a grey field is a way to be lost with no
256
- * visible handle to get back. An axis where it is larger is held so the viewport stays
257
- * covered.
274
+ * With the default `panBounds: "cover"`, an axis where the scaled image is smaller than the
275
+ * viewport is centred rather than left where a drag put it — free-floating pixels in a grey
276
+ * field is a way to be lost with no visible handle to get back — and an axis where it is
277
+ * larger is held so the viewport stays covered. With `"center"`, each axis only keeps some
278
+ * image point at or past the viewport's centre.
258
279
  */
259
280
  export function clampView(
260
281
  view: StageView,
@@ -264,13 +285,19 @@ export function clampView(
264
285
  ): StageView {
265
286
  const [min, max] = scaleRange(box, image, options);
266
287
  const scale = clamp(view.scale, min, max);
288
+ const axis = options.panBounds === "center" ? centreAxis : clampAxis;
267
289
  return {
268
290
  scale,
269
- tx: clampAxis(view.tx, box.width, image.width * scale),
270
- ty: clampAxis(view.ty, box.height, image.height * scale),
291
+ tx: axis(view.tx, box.width, image.width * scale),
292
+ ty: axis(view.ty, box.height, image.height * scale),
271
293
  };
272
294
  }
273
295
 
296
+ /** `"center"` bounds: the content's far edge may come to the centre, and its near edge too. */
297
+ function centreAxis(t: number, boxLength: number, contentLength: number): number {
298
+ return clamp(t, boxLength / 2 - contentLength, boxLength / 2);
299
+ }
300
+
274
301
  function clampAxis(t: number, boxLength: number, contentLength: number): number {
275
302
  if (contentLength <= boxLength) return (boxLength - contentLength) / 2;
276
303
  return clamp(t, boxLength - contentLength, 0);
@@ -22,6 +22,7 @@ import { useCallback } from "react";
22
22
 
23
23
  import type { Point } from "./measureGeometry";
24
24
  import type { StagePointerEvent } from "./stage/hitContext";
25
+ import { CLICK_SLOP } from "./stage/gesture";
25
26
  import { useStage } from "./stage/ImageStage";
26
27
  import { useStageDrag } from "./stage/StageSurface";
27
28
 
@@ -47,9 +48,6 @@ export interface ShapeDragOptions {
47
48
  slop?: number | undefined;
48
49
  }
49
50
 
50
- /** The default click slop, in screen pixels (the stage's own). */
51
- const DEFAULT_SLOP = 3;
52
-
53
51
  /**
54
52
  * Start moving a shape from a press, inside an `ImageStage`.
55
53
  *
@@ -70,7 +68,7 @@ export function useShapeDrag(): (event: StagePointerEvent, handlers: ShapeDragHa
70
68
  handlers.onEnd?.({ x: 0, y: 0 }, false, event.nativeEvent);
71
69
  return;
72
70
  }
73
- const slop = options?.slop ?? DEFAULT_SLOP;
71
+ const slop = options?.slop ?? CLICK_SLOP;
74
72
  const from = { x: event.clientX, y: event.clientY };
75
73
  // Where the press landed, in image pixels: displacements are measured from it.
76
74
  const press = toImage(from);
package/src/index.ts CHANGED
@@ -9,6 +9,7 @@ export {
9
9
  type ImageStageProps,
10
10
  type StageContext,
11
11
  type StageHandle,
12
+ type StageViewChange,
12
13
  } from "./components/stage/ImageStage";
13
14
 
14
15
  export type { StageMouseButton } from "./components/stage/gesture";
@@ -28,7 +29,10 @@ export {
28
29
  type StageHitTestApi,
29
30
  } from "./components/stage/useStageHitTest";
30
31
 
31
- export { ImageLayer, type ImageLayerProps, type ImageTier } from "./components/stage/ImageLayer";
32
+ export { CompareLayer, type CompareLayerProps } from "./components/stage/CompareLayer";
33
+ export type { CompareMode, CompareOrientation } from "./components/stage/compareStyle";
34
+
35
+ export { ImageLayer, type ImageLayerBaseProps, type ImageLayerProps, type ImageTier } from "./components/stage/ImageLayer";
32
36
 
33
37
  export {
34
38
  StageSurface,
@@ -56,6 +60,7 @@ export {
56
60
  MAX_SCALE,
57
61
  MIN_SCALE_VS_FIT,
58
62
  PIXEL_CENTRE,
63
+ clampToImage,
59
64
  clampView,
60
65
  fitScale,
61
66
  fitView,
@@ -114,7 +119,9 @@ export {
114
119
  type PolylinePrimitive,
115
120
  type PrimitiveCommon,
116
121
  type SegmentPrimitive,
122
+ type SegmentsPrimitive,
117
123
  } from "./components/MeasureOverlay";
124
+ export { measurePrimitiveDistance, nearestMeasurePrimitive } from "./components/measureHit";
118
125
 
119
126
  export {
120
127
  OVERLAY_ROLES,
@@ -127,10 +134,20 @@ export {
127
134
  export { useScreenPx } from "./components/stage/useScreenPx";
128
135
 
129
136
  export { ContourEditor, nearestContourSegment, type ContourEditorProps } from "./components/ContourEditor";
130
- export { RectRoiEditor, type RectRoiEditorProps } from "./components/RectRoiEditor";
137
+ export {
138
+ arcLengths,
139
+ deformContour,
140
+ eraseArc,
141
+ normalAtArc,
142
+ pointAtArc,
143
+ projectToArc,
144
+ subPath,
145
+ } from "./components/contourArc";
146
+ export { RectRoiEditor, type RectRoiEditorHandle, type RectRoiEditorProps } from "./components/RectRoiEditor";
131
147
  export {
132
148
  PolylineSet,
133
149
  type PolylineSelectMode,
150
+ type PolylineSetHandle,
134
151
  type PolylineSetItem,
135
152
  type PolylineSetProps,
136
153
  } from "./components/PolylineSet";
@@ -224,9 +241,23 @@ export {
224
241
  shapeFromCorner,
225
242
  shapeHandleCursor,
226
243
  shapeHandlePoint,
244
+ snapAngle,
227
245
  toShapeFrame,
228
246
  type RotatedShape,
229
247
  } from "./components/shapeEdit";
248
+ export { DatumEditor, type DatumEditorProps } from "./components/DatumEditor";
249
+ export {
250
+ DATUM_ARM_PX,
251
+ DATUM_HANDLE_PX,
252
+ DATUM_RING_PX,
253
+ datumAxes,
254
+ datumPress,
255
+ moveDatum,
256
+ rotateDatum,
257
+ type Datum,
258
+ type DatumPressOptions,
259
+ type MoveDatumOptions,
260
+ } from "./components/datumEdit";
230
261
  export {
231
262
  DraftShape,
232
263
  MarqueeRect,
@@ -263,6 +294,7 @@ export {
263
294
  dimensionGeometry,
264
295
  polygonPath,
265
296
  rotatePoint,
297
+ segmentsPath,
266
298
  strokeWidthFor,
267
299
  type DimensionGeometry,
268
300
  type Point,