@vitavision/stage2d 0.6.0 → 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitavision/stage2d",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "The vitavision 2D image stage: view transform, zoom/pan, layered overlays, measurement.",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "repository": {
@@ -46,7 +46,7 @@
46
46
  "react-dom": "^19.2.0"
47
47
  },
48
48
  "dependencies": {
49
- "@vitavision/ui": "^0.6.0",
49
+ "@vitavision/ui": "^0.8.0",
50
50
  "lucide-react": "^1.48.0"
51
51
  },
52
52
  "devDependencies": {
@@ -0,0 +1,142 @@
1
+ /** Reusable source-image contour overlay and vertex editor for ImageStage. */
2
+
3
+ import { useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
4
+
5
+ import { imageViewBox } from "./stage/view";
6
+ import { useStage } from "./stage/ImageStage";
7
+ import type { Point } from "./measureGeometry";
8
+
9
+ /** An ordered, closed contour drawn in source-image pixel-center coordinates. */
10
+ export interface ContourEditorProps {
11
+ /** Ordered vertices; the final vertex connects back to the first. */
12
+ points: Point[];
13
+ /** Receives a complete replacement point list after each edit. */
14
+ onChange: (points: Point[]) => void;
15
+ /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */
16
+ onCommit?: () => void;
17
+ /** Show draggable, keyboard-editable vertices. */
18
+ editable?: boolean;
19
+ /** Accessible name for the contour and its vertices. */
20
+ label?: string;
21
+ /** CSS stroke color. */
22
+ stroke?: string;
23
+ }
24
+
25
+ /** Return the index of the closest segment, with the last vertex joined to the first. */
26
+ export function nearestContourSegment(points: Point[], point: Point): number {
27
+ let nearest = 0;
28
+ let distance = Infinity;
29
+ for (let i = 0; i < points.length; i++) {
30
+ const a = points[i];
31
+ const b = points[(i + 1) % points.length];
32
+ if (!a || !b) continue;
33
+ const dx = b.x - a.x;
34
+ const dy = b.y - a.y;
35
+ const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)));
36
+ const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;
37
+ if (d < distance) { distance = d; nearest = i; }
38
+ }
39
+ return nearest;
40
+ }
41
+
42
+ /** Edit contour vertices over an ImageStage using its shared source-image transform. */
43
+ export function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)" }: ContourEditorProps) {
44
+ const stage = useStage();
45
+ const draggingRef = useRef<number | null>(null);
46
+ const movedRef = useRef(false);
47
+ const [selected, setSelected] = useState<number | null>(null);
48
+ const line = points.map((point) => `${point.x},${point.y}`).join(" ");
49
+ const radius = stage.imageLength(5);
50
+ const hairline = stage.imageLength(1.5);
51
+
52
+ function clamp(point: Point): Point {
53
+ return {
54
+ x: Math.max(0, Math.min(stage.image.width - 1, point.x)),
55
+ y: Math.max(0, Math.min(stage.image.height - 1, point.y)),
56
+ };
57
+ }
58
+
59
+ /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */
60
+ function move(index: number, point: Point): boolean {
61
+ const current = points[index];
62
+ const target = clamp(point);
63
+ if (!current || (current.x === target.x && current.y === target.y)) return false;
64
+ const next = [...points];
65
+ next[index] = target;
66
+ onChange(next);
67
+ return true;
68
+ }
69
+
70
+ function pointerDown(event: PointerEvent<SVGCircleElement>, index: number) {
71
+ if (!editable || stage.panMode || event.button !== 0) return;
72
+ event.stopPropagation();
73
+ event.currentTarget.setPointerCapture(event.pointerId);
74
+ draggingRef.current = index;
75
+ movedRef.current = false;
76
+ setSelected(index);
77
+ }
78
+
79
+ function pointerMove(event: PointerEvent<SVGCircleElement>) {
80
+ if (draggingRef.current === null) return;
81
+ event.stopPropagation();
82
+ if (move(draggingRef.current, stage.toImage({ x: event.clientX, y: event.clientY }))) movedRef.current = true;
83
+ }
84
+
85
+ function pointerUp(event: PointerEvent<SVGCircleElement>) {
86
+ if (draggingRef.current === null) return;
87
+ event.stopPropagation();
88
+ draggingRef.current = null;
89
+ if (movedRef.current) onCommit?.();
90
+ }
91
+
92
+ function keyDown(event: KeyboardEvent<SVGCircleElement>, index: number) {
93
+ if (!editable || stage.panMode) return;
94
+ const delta = event.shiftKey ? 0.1 : 1;
95
+ const p = points[index];
96
+ if (!p) return;
97
+ const shift: Record<string, Point> = {
98
+ ArrowLeft: { x: -delta, y: 0 }, ArrowRight: { x: delta, y: 0 },
99
+ ArrowUp: { x: 0, y: -delta }, ArrowDown: { x: 0, y: delta },
100
+ };
101
+ if (shift[event.key]) {
102
+ event.preventDefault();
103
+ event.stopPropagation();
104
+ if (move(index, { x: p.x + shift[event.key]!.x, y: p.y + shift[event.key]!.y })) onCommit?.();
105
+ } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > 3) {
106
+ event.preventDefault();
107
+ event.stopPropagation();
108
+ onChange(points.filter((_, i) => i !== index));
109
+ setSelected(null);
110
+ onCommit?.();
111
+ } else if (event.key === "Insert" && points.length >= 3) {
112
+ event.preventDefault();
113
+ event.stopPropagation();
114
+ const next = points[(index + 1) % points.length]!;
115
+ onChange([...points.slice(0, index + 1), { x: (p.x + next.x) / 2, y: (p.y + next.y) / 2 }, ...points.slice(index + 1)]);
116
+ setSelected(index + 1);
117
+ onCommit?.();
118
+ }
119
+ }
120
+
121
+ return (
122
+ <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}>
123
+ <polygon points={line} fill="none" stroke={stroke} strokeWidth={hairline} />
124
+ {editable && points.length >= 3 && (
125
+ <polygon points={line} fill="none" stroke="transparent" strokeWidth={stage.imageLength(12)} className="pointer-events-auto" onDoubleClick={(event) => {
126
+ if (stage.panMode) return;
127
+ event.stopPropagation();
128
+ const point = clamp(stage.toImage({ x: event.clientX, y: event.clientY }));
129
+ const index = nearestContourSegment(points, point);
130
+ onChange([...points.slice(0, index + 1), point, ...points.slice(index + 1)]);
131
+ setSelected(index + 1);
132
+ onCommit?.();
133
+ }} />
134
+ )}
135
+ {editable && points.map((point, index) => (
136
+ // The contour API is an ordered point list without vertex IDs; indices are stable across drag edits.
137
+ // eslint-disable-next-line @eslint-react/no-array-index-key
138
+ <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)} />
139
+ ))}
140
+ </svg>
141
+ );
142
+ }
@@ -0,0 +1,154 @@
1
+ /** A source-pixel raster mask layer with a small paint/erase brush. */
2
+
3
+ import { useEffect, useRef, useState, type FocusEvent, type KeyboardEvent, type PointerEvent } from "react";
4
+
5
+ import { imageViewBox } from "./stage/view";
6
+ import { useStage } from "./stage/ImageStage";
7
+ import type { Point } from "./measureGeometry";
8
+
9
+ /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
10
+ export function paintMask(mask: Uint8Array, width: number, height: number, from: Point, to: Point, radius: number, value: 0 | 1): Uint8Array {
11
+ if (mask.length !== width * height) throw new RangeError("Mask dimensions do not match its pixel data.");
12
+ 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.");
13
+ const next = mask.slice();
14
+ const clamp = (value: number, limit: number) => Math.max(0, Math.min(limit - 1, value));
15
+ const start = { x: clamp(from.x, width), y: clamp(from.y, height) };
16
+ const end = { x: clamp(to.x, width), y: clamp(to.y, height) };
17
+ const steps = Math.max(1, Math.ceil(Math.hypot(end.x - start.x, end.y - start.y)));
18
+ // A click between four pixel centers must still affect the nearest pixels.
19
+ const r = Math.max(0.75, radius);
20
+ for (let step = 0; step <= steps; step++) {
21
+ const x = start.x + (end.x - start.x) * step / steps;
22
+ const y = start.y + (end.y - start.y) * step / steps;
23
+ for (let row = Math.max(0, Math.ceil(y - r)); row <= Math.min(height - 1, Math.floor(y + r)); row++) {
24
+ for (let col = Math.max(0, Math.ceil(x - r)); col <= Math.min(width - 1, Math.floor(x + r)); col++) {
25
+ if ((col - x) ** 2 + (row - y) ** 2 <= r * r) next[row * width + col] = value;
26
+ }
27
+ }
28
+ }
29
+ return next;
30
+ }
31
+
32
+ /** Binary mask values are 0 or 1, in row-major source-image coordinates. */
33
+ export interface MaskEditorProps {
34
+ /** Exactly image width × image height bytes. */
35
+ mask: Uint8Array;
36
+ /** Receives a fresh array after each brush movement. */
37
+ onChange: (mask: Uint8Array) => void;
38
+ /** Called once when a pointer stroke or keyboard paint finishes. */
39
+ onCommit?: () => void;
40
+ /** Allow brush interaction; otherwise render only. */
41
+ editable?: boolean;
42
+ /** Source-image pixels, independent of zoom. */
43
+ brushRadius?: number;
44
+ /** Paint or erase. */
45
+ mode?: "paint" | "erase";
46
+ /** Accessible name for the brush control. */
47
+ label?: string;
48
+ /** RGBA overlay color. */
49
+ color?: readonly [number, number, number, number];
50
+ }
51
+
52
+ /** Render and edit a binary raster mask within the enclosing ImageStage. */
53
+ export function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = "paint", label = "Mask brush", color = [0, 190, 220, 128] }: MaskEditorProps) {
54
+ const stage = useStage();
55
+ const canvasRef = useRef<HTMLCanvasElement>(null);
56
+ const draftRef = useRef(mask);
57
+ const lastRef = useRef<Point | null>(null);
58
+ // The keyboard brush; it starts at the image centre and follows the last pointer stroke.
59
+ const cursorRef = useRef<Point | null>(null);
60
+ // Where the keyboard brush is drawn, while the layer has keyboard focus.
61
+ const [brush, setBrush] = useState<Point | null>(null);
62
+
63
+ function cursor(): Point {
64
+ return cursorRef.current ?? { x: Math.floor(stage.image.width / 2), y: Math.floor(stage.image.height / 2) };
65
+ }
66
+
67
+ useEffect(() => {
68
+ if (mask.length !== stage.image.width * stage.image.height) throw new RangeError("Mask dimensions do not match ImageStage.");
69
+ const context = canvasRef.current?.getContext("2d");
70
+ if (!context) return;
71
+ const pixels = context.createImageData(stage.image.width, stage.image.height);
72
+ for (let i = 0; i < mask.length; i++) {
73
+ if (mask[i]) pixels.data.set(color, i * 4);
74
+ }
75
+ context.putImageData(pixels, 0, 0);
76
+ }, [mask, color, stage.image.width, stage.image.height]);
77
+
78
+ function apply(from: Point, to: Point) {
79
+ const next = paintMask(draftRef.current, stage.image.width, stage.image.height, from, to, brushRadius, mode === "paint" ? 1 : 0);
80
+ draftRef.current = next;
81
+ onChange(next);
82
+ }
83
+
84
+ function down(event: PointerEvent<HTMLCanvasElement>) {
85
+ if (!editable || stage.panMode || event.button !== 0) return;
86
+ event.stopPropagation();
87
+ event.currentTarget.setPointerCapture(event.pointerId);
88
+ const point = stage.toImage({ x: event.clientX, y: event.clientY });
89
+ // Each stroke starts from the mask the caller holds, so an edit it rejected is not carried forward.
90
+ draftRef.current = mask;
91
+ lastRef.current = point;
92
+ cursorRef.current = point;
93
+ setBrush(null);
94
+ apply(point, point);
95
+ }
96
+
97
+ function move(event: PointerEvent<HTMLCanvasElement>) {
98
+ if (!lastRef.current) return;
99
+ event.stopPropagation();
100
+ const point = stage.toImage({ x: event.clientX, y: event.clientY });
101
+ apply(lastRef.current, point);
102
+ lastRef.current = point;
103
+ cursorRef.current = point;
104
+ }
105
+
106
+ function up(event: PointerEvent<HTMLCanvasElement>) {
107
+ if (!lastRef.current) return;
108
+ event.stopPropagation();
109
+ lastRef.current = null;
110
+ onCommit?.();
111
+ }
112
+
113
+ function keyDown(event: KeyboardEvent<HTMLCanvasElement>) {
114
+ if (!editable || stage.panMode) return;
115
+ const shift: Record<string, Point> = {
116
+ ArrowLeft: { x: -1, y: 0 }, ArrowRight: { x: 1, y: 0 },
117
+ ArrowUp: { x: 0, y: -1 }, ArrowDown: { x: 0, y: 1 },
118
+ };
119
+ const delta = shift[event.key];
120
+ if (delta) {
121
+ event.preventDefault();
122
+ event.stopPropagation();
123
+ const from = cursor();
124
+ cursorRef.current = {
125
+ x: Math.max(0, Math.min(stage.image.width - 1, from.x + delta.x)),
126
+ y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y)),
127
+ };
128
+ setBrush(cursorRef.current);
129
+ } else if (event.key === "Enter") {
130
+ event.preventDefault();
131
+ event.stopPropagation();
132
+ const at = cursor();
133
+ draftRef.current = mask;
134
+ setBrush(at);
135
+ apply(at, at);
136
+ onCommit?.();
137
+ }
138
+ }
139
+
140
+ function focus(event: FocusEvent<HTMLCanvasElement>) {
141
+ if (editable && event.currentTarget.matches(":focus-visible")) setBrush(cursor());
142
+ }
143
+
144
+ return (
145
+ <>
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
+ )}
152
+ </>
153
+ );
154
+ }
@@ -247,7 +247,7 @@ export function ZoomPanCanvas({
247
247
  data-panning={grabbing ? "" : undefined}
248
248
  data-fit={view.zoom <= MIN_ZOOM ? "" : undefined}
249
249
  className={cn(
250
- "relative overflow-hidden rounded border border-line bg-canvas select-none",
250
+ "relative overflow-hidden rounded-control border border-line bg-canvas select-none",
251
251
  grabbing ? "cursor-grabbing" : "cursor-grab",
252
252
  className,
253
253
  )}
@@ -286,14 +286,14 @@ export function ZoomPanCanvas({
286
286
  {children}
287
287
  </div>
288
288
  {label && (
289
- <span className="pointer-events-none absolute bottom-1 left-1 rounded bg-black/60 px-1 font-mono text-[10px] text-white">
289
+ <span className="pointer-events-none absolute bottom-1 left-1 rounded-control bg-black/60 px-1 font-mono text-[10px] text-white">
290
290
  {label}
291
291
  </span>
292
292
  )}
293
293
  {fitLabel !== null && view.zoom > MIN_ZOOM && (
294
294
  <button
295
295
  type="button"
296
- className="absolute right-1 bottom-1 rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white hover:bg-black/80"
296
+ 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"
297
297
  // Stopping `pointerdown` is what makes the button work at all: without it the
298
298
  // press bubbles to the canvas, which calls `setPointerCapture` on itself and
299
299
  // takes the click with it, so the button rendered and did nothing.
@@ -496,7 +496,7 @@ export function ImageStage({
496
496
  data-panning={panning ? "" : undefined}
497
497
  data-pan-mode={panMode ? "" : undefined}
498
498
  className={cn(
499
- "relative h-full w-full overflow-hidden rounded border border-line bg-canvas select-none",
499
+ "relative h-full w-full overflow-hidden rounded-control border border-line bg-canvas select-none",
500
500
  "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-signal",
501
501
  panning ? "cursor-grabbing" : panMode ? "cursor-grab" : "cursor-default",
502
502
  className,
@@ -241,7 +241,7 @@ export function StageReadout({ cursor, extra, className }: StageReadoutProps) {
241
241
  return (
242
242
  <span
243
243
  className={cn(
244
- "rounded bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",
244
+ "rounded-control bg-black/60 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums",
245
245
  className,
246
246
  )}
247
247
  >
package/src/index.ts CHANGED
@@ -82,6 +82,9 @@ export {
82
82
  type SegmentPrimitive,
83
83
  } from "./components/MeasureOverlay";
84
84
 
85
+ export { ContourEditor, nearestContourSegment, type ContourEditorProps } from "./components/ContourEditor";
86
+ export { MaskEditor, paintMask, type MaskEditorProps } from "./components/MaskEditor";
87
+
85
88
  export {
86
89
  arcPath,
87
90
  arrowHeadPoints,