@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,7 +19,12 @@ import { imageViewBox, type Rect } from "./stage/view";
19
19
  * - `point`: a position.
20
20
  * - `line`: a segment from `from` to `to`.
21
21
  * - `polyline` and `polygon`: the vertices placed so far, flat `[x0, y0, x1, y1, …]`, and
22
- * the pointer as `cursor`, which the next vertex would land on.
22
+ * the pointer as `cursor`, which the next vertex would land on. A polygon with `closing`
23
+ * set has the pointer on its first vertex: a click there closes it, so the first vertex is
24
+ * highlighted and the closing edge drawn solid.
25
+ * - `stroke`: a brush trail, the flat `points` swept by a round brush of `width` image pixels
26
+ * (never thinner than 1 screen pixel), as a translucent filled band without dashes.
27
+ * - `brush`: a brush footprint cursor, a circle of `diameter` image pixels centred on `x`, `y`.
23
28
  * - `rect` and `ellipse`: two opposite corners of the axis-aligned box (the drag's start and
24
29
  * the pointer).
25
30
  */
@@ -27,7 +32,9 @@ export type DraftShapeSpec =
27
32
  | { kind: "point"; x: number; y: number }
28
33
  | { kind: "line"; from: Point; to: Point }
29
34
  | { kind: "polyline"; points: ArrayLike<number>; cursor?: Point | undefined }
30
- | { kind: "polygon"; points: ArrayLike<number>; cursor?: Point | undefined }
35
+ | { kind: "polygon"; points: ArrayLike<number>; cursor?: Point | undefined; closing?: boolean | undefined }
36
+ | { kind: "stroke"; points: ArrayLike<number>; width: number }
37
+ | { kind: "brush"; x: number; y: number; diameter: number }
31
38
  | { kind: "rect"; from: Point; to: Point }
32
39
  | { kind: "ellipse"; from: Point; to: Point };
33
40
 
@@ -37,6 +44,8 @@ export interface DraftShapeProps {
37
44
  shape: DraftShapeSpec | null;
38
45
  /** The overlay role it is drawn in. Defaults to `"selection"`, the accent. */
39
46
  role?: OverlayRole | undefined;
47
+ /** A CSS colour that overrides `role`, for example `"var(--defect)"` for an eraser. */
48
+ stroke?: string | undefined;
40
49
  /** Draw the dark band under the outline. On by default. */
41
50
  halo?: boolean | undefined;
42
51
  }
@@ -54,15 +63,20 @@ const VERTEX_PX = 6;
54
63
  * The outline is 1.5 screen px, dashed 6 4 screen px, in the accent (`selection`) role by
55
64
  * default, with a halo; regions (`polygon`, `rect`, `ellipse`) carry the 12 % fill. A polyline
56
65
  * or polygon shows its placed vertices as dots and a segment on to the pointer; a polygon also
57
- * shows, fainter, the segment that would close it. It takes no pointer events and is hidden
66
+ * shows, fainter, the segment that would close it; with `closing` the first vertex gets a
67
+ * ring and that segment turns solid and full strength: "click here to close". A `stroke`
68
+ * (brush trail) is a translucent band of its own width with round caps and joins and no
69
+ * dashes, and a `brush` is a footprint ring: a dark ring under a light one, so it reads on
70
+ * any image. `points` may be a typed-array view that changes identity every move: the draft
71
+ * is rebuilt in one O(n) pass per render, with no per-vertex elements. It takes no pointer events and is hidden
58
72
  * from assistive technology: it is transient feedback for a gesture.
59
73
  *
60
74
  * The SVG carries `data-draft` (the shape's kind).
61
75
  */
62
- export function DraftShape({ shape, role = "selection", halo = true }: DraftShapeProps) {
76
+ export function DraftShape({ shape, role = "selection", stroke, halo = true }: DraftShapeProps) {
63
77
  const stage = useStage();
64
78
  const px = useScreenPx();
65
- const colour = overlayRole(role);
79
+ const colour = stroke ?? overlayRole(role);
66
80
  const dash = `${px(DASH)} ${px(GAP)}`;
67
81
  const width = px(STROKE_PX);
68
82
  const parts = shape ? draftParts(shape, px(1)) : null;
@@ -79,7 +93,11 @@ export function DraftShape({ shape, role = "selection", halo = true }: DraftShap
79
93
  {parts.outline && halo && <path d={parts.outline} stroke={HALO} strokeWidth={width + px(2)} opacity={0.6} />}
80
94
  {parts.outline && parts.region && <path d={parts.outline} fill={colour} fillOpacity={0.12} stroke="none" />}
81
95
  {parts.outline && <path data-draft-outline="" d={parts.outline} stroke={colour} strokeWidth={width} strokeDasharray={dash} />}
82
- {parts.closing && <path data-draft-closing="" d={parts.closing} stroke={colour} strokeWidth={px(1)} strokeDasharray={dash} opacity={0.5} />}
96
+ {parts.trail && <path data-draft-stroke="" d={parts.trail.d} stroke={colour} strokeWidth={Math.max(parts.trail.width, px(1))} opacity={0.4} />}
97
+ {parts.footprint && halo && <path d={parts.footprint} stroke={HALO} strokeWidth={px(3.5)} opacity={0.6} />}
98
+ {parts.footprint && <path data-draft-brush="" d={parts.footprint} stroke={colour} strokeWidth={px(1.5)} />}
99
+ {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} />}
100
+ {parts.first && <path data-draft-first="" d={parts.first} stroke={colour} strokeWidth={width} fill={colour} fillOpacity={0.35} />}
83
101
  {parts.vertices && <path data-draft-vertices="" d={parts.vertices} stroke={colour} strokeWidth={px(VERTEX_PX)} />}
84
102
  </g>
85
103
  )}
@@ -97,8 +115,18 @@ interface DraftParts {
97
115
  closing: string | null;
98
116
  /** The placed vertices, as zero-length segments drawn with round caps. */
99
117
  vertices: string | null;
118
+ /** Whether the closing segment is the live "click to close" cue: solid, full strength. */
119
+ armed: boolean;
120
+ /** The ring around the first vertex while the pointer is on it. */
121
+ first: string | null;
122
+ /** A brush trail: its path and the width in image pixels. */
123
+ trail: { d: string; width: number } | null;
124
+ /** A brush footprint circle. */
125
+ footprint: string | null;
100
126
  }
101
127
 
128
+ const NONE: DraftParts = { outline: null, region: false, closing: null, vertices: null, armed: false, first: null, trail: null, footprint: null };
129
+
102
130
  /** An ellipse with the given centre and radii as two arcs. */
103
131
  function ellipsePath(cx: number, cy: number, rx: number, ry: number): string {
104
132
  return `M${cx + rx} ${cy}a${rx} ${ry} 0 1 0 ${-2 * rx} 0a${rx} ${ry} 0 1 0 ${2 * rx} 0Z`;
@@ -107,9 +135,9 @@ function ellipsePath(cx: number, cy: number, rx: number, ry: number): string {
107
135
  function draftParts(shape: DraftShapeSpec, unit: number): DraftParts {
108
136
  switch (shape.kind) {
109
137
  case "point":
110
- return { outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit), region: false, closing: null, vertices: `M${shape.x} ${shape.y}h0` };
138
+ return { ...NONE, outline: ellipsePath(shape.x, shape.y, 8 * unit, 8 * unit), vertices: `M${shape.x} ${shape.y}h0` };
111
139
  case "line":
112
- return { outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}`, region: false, closing: null, vertices: null };
140
+ return { ...NONE, outline: `M${shape.from.x} ${shape.from.y}L${shape.to.x} ${shape.to.y}` };
113
141
  case "rect":
114
142
  case "ellipse": {
115
143
  const box = rectFromCorners(shape.from, shape.to);
@@ -117,12 +145,22 @@ function draftParts(shape: DraftShapeSpec, unit: number): DraftParts {
117
145
  shape.kind === "rect"
118
146
  ? `M${box.x} ${box.y}h${box.width}v${box.height}h${-box.width}Z`
119
147
  : ellipsePath(box.x + box.width / 2, box.y + box.height / 2, box.width / 2, box.height / 2);
120
- return { outline, region: true, closing: null, vertices: null };
148
+ return { ...NONE, outline, region: true };
149
+ }
150
+ case "brush":
151
+ return { ...NONE, footprint: ellipsePath(shape.x, shape.y, Math.max(shape.diameter, 2 * unit) / 2, Math.max(shape.diameter, 2 * unit) / 2) };
152
+ case "stroke": {
153
+ const n = Math.floor(shape.points.length / 2);
154
+ if (n === 0) return NONE;
155
+ let d = "";
156
+ for (let i = 0; i < n; i++) d += `${i === 0 ? "M" : "L"}${shape.points[2 * i]} ${shape.points[2 * i + 1]}`;
157
+ // A single point is a zero-length segment: the round caps make it a dot.
158
+ return { ...NONE, trail: { d: n === 1 ? `${d}h0` : d, width: shape.width } };
121
159
  }
122
160
  case "polyline":
123
161
  case "polygon": {
124
162
  const n = Math.floor(shape.points.length / 2);
125
- if (n === 0) return { outline: null, region: false, closing: null, vertices: null };
163
+ if (n === 0) return NONE;
126
164
  let outline = "";
127
165
  let vertices = "";
128
166
  for (let i = 0; i < n; i++) {
@@ -131,11 +169,18 @@ function draftParts(shape: DraftShapeSpec, unit: number): DraftParts {
131
169
  }
132
170
  if (shape.cursor) outline += `L${shape.cursor.x} ${shape.cursor.y}`;
133
171
  const polygon = shape.kind === "polygon";
172
+ const armed = polygon && shape.closing === true && n >= 2;
173
+ let closing: string | null = null;
174
+ if (armed) closing = `M${shape.points[2 * n - 2]} ${shape.points[2 * n - 1]}L${shape.points[0]} ${shape.points[1]}`;
175
+ else if (polygon && shape.cursor) closing = `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}`;
134
176
  return {
177
+ ...NONE,
135
178
  outline,
136
179
  region: polygon && n + (shape.cursor ? 1 : 0) >= 3,
137
- closing: polygon && shape.cursor ? `M${shape.cursor.x} ${shape.cursor.y}L${shape.points[0]} ${shape.points[1]}` : null,
180
+ closing,
138
181
  vertices,
182
+ armed,
183
+ first: armed ? ellipsePath(shape.points[0]!, shape.points[1]!, 5 * unit, 5 * unit) : null,
139
184
  };
140
185
  }
141
186
  }
@@ -4,9 +4,9 @@
4
4
  *
5
5
  * A `MarkerShape` is sized in screen pixels, so it cannot draw a ring whose radius is a
6
6
  * measurement. This layer draws exact ellipses (two arcs each) in image pixels, batched by
7
- * appearance into a handful of `<path>`s (ADR-0004 rule 1). Strokes stay screen-sized (rule 4).
7
+ * appearance into a handful of `<path>`s Strokes stay screen-sized.
8
8
  * The pointer is resolved by `nearestEllipse` through the stage's hit registry, never by the
9
- * DOM (rule 2); `pickable={false}` leaves a decorative layer out of it.
9
+ * DOM; `pickable={false}` leaves a decorative layer out of it.
10
10
  */
11
11
 
12
12
  import { useMemo, useState } from "react";
@@ -136,7 +136,7 @@ interface Batch {
136
136
  *
137
137
  * - **Geometry** is data: `rx`, `ry` and the centre are image pixels and scale with the image;
138
138
  * the stroke is a screen constant.
139
- * - **States** follow visual-language §5: 1.5 screen px (1 for `model` and `structure`), hover
139
+ * - **States**: 1.5 screen px (1 for `model` and `structure`), hover
140
140
  * 2, selected 2.5 in the selection colour, dimmed at 35 % opacity. Every stroke has a halo.
141
141
  * - **Batching** is by (role, dash, opacity, dimming): a thousand rings are a dozen elements.
142
142
  * - **Picking** goes through the stage's hit registry: a press within the pointer's tolerance of
@@ -3,8 +3,7 @@
3
3
  * column edges between neighbours, and optional `(i, j)` labels.
4
4
  *
5
5
  * Nodes are a `PointSet` (batched markers, the point index, hover and selection), so a grid of
6
- * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths (ADR-0004 rules 1
7
- * and 4). Edges are not picked: a person points at a corner.
6
+ * 20,000 corners is a dozen DOM nodes; the edges are two more batched paths. Edges are not picked: a person points at a corner.
8
7
  */
9
8
 
10
9
  import { useMemo } from "react";
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * A scalar field or a pre-coloured buffer, drawn as one image over (or under) the overlays.
3
3
  *
4
- * A heatmap is a raster, not vector geometry (ADR-0004 rule 5): it is rendered once into an
4
+ * A heatmap is a raster, not vector geometry : it is rendered once into an
5
5
  * offscreen canvas, handed to the browser as an object URL, and shown by an `<img>` the stage
6
6
  * positions and scales like the photograph. Nothing is drawn per pixel by React, so a 4-megapixel
7
7
  * map costs one element. It takes no pointer events; to read the numbers under the pointer, use
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { useEffect, useRef, useState, type FocusEvent, type KeyboardEvent, type PointerEvent } from "react";
4
4
 
5
- import { imageViewBox } from "./stage/view";
5
+ import { DraftShape } from "./DraftShape";
6
6
  import { useStage } from "./stage/ImageStage";
7
7
  import type { Point } from "./measureGeometry";
8
8
 
@@ -49,7 +49,11 @@ export interface MaskEditorProps {
49
49
  color?: readonly [number, number, number, number];
50
50
  }
51
51
 
52
- /** Render and edit a binary raster mask within the enclosing ImageStage. */
52
+ /**
53
+ * Render and edit a binary raster mask within the enclosing ImageStage. While editing, a
54
+ * `DraftShape` brush footprint (a circle of the brush's diameter) follows the mouse or pen
55
+ * pointer, and the keyboard brush while the layer has keyboard focus.
56
+ */
53
57
  export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = "paint", label = "Mask brush", color = [0, 190, 220, 128] }: MaskEditorProps) {
54
58
  const stage = useStage();
55
59
  const canvasRef = useRef<HTMLCanvasElement>(null);
@@ -59,6 +63,8 @@ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRa
59
63
  const cursorRef = useRef<Point | null>(null);
60
64
  // Where the keyboard brush is drawn, while the layer has keyboard focus.
61
65
  const [brush, setBrush] = useState<Point | null>(null);
66
+ // Where the pointer hovers (or paints); the footprint follows it. Not set for touch.
67
+ const [hover, setHover] = useState<Point | null>(null);
62
68
 
63
69
  function cursor(): Point {
64
70
  return cursorRef.current ?? { x: Math.floor(stage.image.width / 2), y: Math.floor(stage.image.height / 2) };
@@ -91,13 +97,21 @@ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRa
91
97
  lastRef.current = point;
92
98
  cursorRef.current = point;
93
99
  setBrush(null);
100
+ if (event.pointerType !== "touch") setHover(point);
94
101
  apply(point, point);
95
102
  }
96
103
 
97
104
  function move(event: PointerEvent<HTMLCanvasElement>) {
98
- if (!lastRef.current) return;
105
+ if (!lastRef.current) {
106
+ if (editable && !stage.panMode && event.pointerType !== "touch") {
107
+ setHover(stage.toImage({ x: event.clientX, y: event.clientY }));
108
+ setBrush(null);
109
+ }
110
+ return;
111
+ }
99
112
  event.stopPropagation();
100
113
  const point = stage.toImage({ x: event.clientX, y: event.clientY });
114
+ if (event.pointerType !== "touch") setHover(point);
101
115
  apply(lastRef.current, point);
102
116
  lastRef.current = point;
103
117
  cursorRef.current = point;
@@ -107,6 +121,7 @@ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRa
107
121
  if (!lastRef.current) return;
108
122
  event.stopPropagation();
109
123
  lastRef.current = null;
124
+ if (event.pointerType === "touch") setHover(null);
110
125
  onCommit?.();
111
126
  }
112
127
 
@@ -126,12 +141,14 @@ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRa
126
141
  y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y)),
127
142
  };
128
143
  setBrush(cursorRef.current);
144
+ setHover(null);
129
145
  } else if (event.key === "Enter") {
130
146
  event.preventDefault();
131
147
  event.stopPropagation();
132
148
  const at = cursor();
133
149
  draftRef.current = mask;
134
150
  setBrush(at);
151
+ setHover(null);
135
152
  apply(at, at);
136
153
  onCommit?.();
137
154
  }
@@ -143,12 +160,8 @@ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRa
143
160
 
144
161
  return (
145
162
  <>
146
- <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)} />
147
- {brush && (
148
- <svg viewBox={imageViewBox(stage.image)} className="pointer-events-none absolute inset-0 h-full w-full overflow-visible" aria-hidden="true">
149
- <circle cx={brush.x} cy={brush.y} r={Math.max(0.75, brushRadius)} fill="none" stroke="var(--signal)" strokeWidth={stage.imageLength(1.5)} />
150
- </svg>
151
- )}
163
+ <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); }} />
164
+ {(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)" />}
152
165
  </>
153
166
  );
154
167
  }