@vitavision/stage2d 0.6.1 → 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/README.md CHANGED
@@ -22,6 +22,14 @@ deprecated predecessor, still exported unchanged.
22
22
  (`decodePlane`, `valueAt`, `valuesAt`, `fractionOf`, `fetchPlane`) — it never draws;
23
23
  colour range and colormap stay the caller's decision.
24
24
 
25
+ **Annotation layers** — `ContourEditor` edits ordered source-image pixel-center
26
+ vertices; `MaskEditor` paints or erases a row-major binary mask with a bounded
27
+ source-pixel brush. Both are controlled layers for `ImageStage`: the caller owns
28
+ the geometry, undo history, persistence, and approval policy. `onCommit` marks
29
+ the end of a gesture. The contour supports arrow-key nudging, Insert for a
30
+ midpoint, and Delete; the mask supports arrow-key brush movement and Enter.
31
+ Raster masks use `Uint8Array` values 0/1 with exactly `width × height` entries.
32
+
25
33
  **Measurement overlay** — `MeasureOverlay` is a pure-props SVG layer meant to sit inside
26
34
  `ImageStage`'s transformed stack, drawing `point`, `segment`, `circle`, `arc`, `caliper`
27
35
  and `dimension` primitives given in **source-image pixel coordinates**, each with an
package/dist/index.d.ts CHANGED
@@ -708,5 +708,51 @@ interface MeasureOverlayProps {
708
708
  */
709
709
  export declare function MeasureOverlay({ nativeWidth, nativeHeight, primitives, strokeScale, className }: MeasureOverlayProps): import("react").JSX.Element;
710
710
  //#endregion
711
- export type { ArcPrimitive, Box, CaliperPrimitive, CirclePrimitive, ClampOptions, DimensionGeometry, DimensionPrimitive, ImageStageProps, MeasureOverlayProps, MeasurePrimitive, Point, PointPrimitive, Rect, SegmentPrimitive, StageButtonProps, StageContext, StageReadoutProps, StageToolbarDividerProps, StageToolbarProps, StageView, ValuePlane, View, ZoomPanCanvasProps };
711
+ //#region src/components/ContourEditor.d.ts
712
+ /** An ordered, closed contour drawn in source-image pixel-center coordinates. */
713
+ interface ContourEditorProps {
714
+ /** Ordered vertices; the final vertex connects back to the first. */
715
+ points: Point[];
716
+ /** Receives a complete replacement point list after each edit. */
717
+ onChange: (points: Point[]) => void;
718
+ /** Called at the end of a pointer or keyboard edit; useful for history snapshots. */
719
+ onCommit?: () => void;
720
+ /** Show draggable, keyboard-editable vertices. */
721
+ editable?: boolean;
722
+ /** Accessible name for the contour and its vertices. */
723
+ label?: string;
724
+ /** CSS stroke color. */
725
+ stroke?: string;
726
+ }
727
+ /** Return the index of the closest segment, with the last vertex joined to the first. */
728
+ export declare function nearestContourSegment(points: Point[], point: Point): number;
729
+ /** Edit contour vertices over an ImageStage using its shared source-image transform. */
730
+ export declare function ContourEditor({ points, onChange, onCommit, editable, label, stroke }: ContourEditorProps): import("react").JSX.Element;
731
+ //#endregion
732
+ //#region src/components/MaskEditor.d.ts
733
+ /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
734
+ export declare function paintMask(mask: Uint8Array, width: number, height: number, from: Point, to: Point, radius: number, value: 0 | 1): Uint8Array;
735
+ /** Binary mask values are 0 or 1, in row-major source-image coordinates. */
736
+ interface MaskEditorProps {
737
+ /** Exactly image width × image height bytes. */
738
+ mask: Uint8Array;
739
+ /** Receives a fresh array after each brush movement. */
740
+ onChange: (mask: Uint8Array) => void;
741
+ /** Called once when a pointer stroke or keyboard paint finishes. */
742
+ onCommit?: () => void;
743
+ /** Allow brush interaction; otherwise render only. */
744
+ editable?: boolean;
745
+ /** Source-image pixels, independent of zoom. */
746
+ brushRadius?: number;
747
+ /** Paint or erase. */
748
+ mode?: "paint" | "erase";
749
+ /** Accessible name for the brush control. */
750
+ label?: string;
751
+ /** RGBA overlay color. */
752
+ color?: readonly [number, number, number, number];
753
+ }
754
+ /** Render and edit a binary raster mask within the enclosing ImageStage. */
755
+ export declare function MaskEditor({ mask, onChange, onCommit, editable, brushRadius, mode, label, color }: MaskEditorProps): import("react").JSX.Element;
756
+ //#endregion
757
+ export type { ArcPrimitive, Box, CaliperPrimitive, CirclePrimitive, ClampOptions, ContourEditorProps, DimensionGeometry, DimensionPrimitive, ImageStageProps, MaskEditorProps, MeasureOverlayProps, MeasurePrimitive, Point, PointPrimitive, Rect, SegmentPrimitive, StageButtonProps, StageContext, StageReadoutProps, StageToolbarDividerProps, StageToolbarProps, StageView, ValuePlane, View, ZoomPanCanvasProps };
712
758
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1554,6 +1554,362 @@ function Label({ x, y, text, colour, size }) {
1554
1554
  });
1555
1555
  }
1556
1556
  //#endregion
1557
- export { FULL_TIER_ZOOM, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MeasureOverlay, PIXEL_CENTRE, PlaneFormatError, RESET_VIEW, StageButton, StageReadout, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, caliperArrow, caliperCorners, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, nativeZoomFor, polygonPath, preserveCenter, rotatePoint, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useStage, valueAt, valuesAt, zoomAbout, zoomAt };
1557
+ //#region src/components/ContourEditor.tsx
1558
+ /** Reusable source-image contour overlay and vertex editor for ImageStage. */
1559
+ /** Return the index of the closest segment, with the last vertex joined to the first. */
1560
+ function nearestContourSegment(points, point) {
1561
+ let nearest = 0;
1562
+ let distance = Infinity;
1563
+ for (let i = 0; i < points.length; i++) {
1564
+ const a = points[i];
1565
+ const b = points[(i + 1) % points.length];
1566
+ if (!a || !b) continue;
1567
+ const dx = b.x - a.x;
1568
+ const dy = b.y - a.y;
1569
+ const t = Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / (dx * dx + dy * dy || 1)));
1570
+ const d = (point.x - a.x - t * dx) ** 2 + (point.y - a.y - t * dy) ** 2;
1571
+ if (d < distance) {
1572
+ distance = d;
1573
+ nearest = i;
1574
+ }
1575
+ }
1576
+ return nearest;
1577
+ }
1578
+ /** Edit contour vertices over an ImageStage using its shared source-image transform. */
1579
+ function ContourEditor({ points, onChange, onCommit, editable = false, label = "Contour", stroke = "var(--signal)" }) {
1580
+ const stage = useStage();
1581
+ const draggingRef = useRef(null);
1582
+ const movedRef = useRef(false);
1583
+ const [selected, setSelected] = useState(null);
1584
+ const line = points.map((point) => `${point.x},${point.y}`).join(" ");
1585
+ const radius = stage.imageLength(5);
1586
+ const hairline = stage.imageLength(1.5);
1587
+ function clamp(point) {
1588
+ return {
1589
+ x: Math.max(0, Math.min(stage.image.width - 1, point.x)),
1590
+ y: Math.max(0, Math.min(stage.image.height - 1, point.y))
1591
+ };
1592
+ }
1593
+ /** Replace one vertex; returns whether anything changed, so no-op edits add no history. */
1594
+ function move(index, point) {
1595
+ const current = points[index];
1596
+ const target = clamp(point);
1597
+ if (!current || current.x === target.x && current.y === target.y) return false;
1598
+ const next = [...points];
1599
+ next[index] = target;
1600
+ onChange(next);
1601
+ return true;
1602
+ }
1603
+ function pointerDown(event, index) {
1604
+ if (!editable || stage.panMode || event.button !== 0) return;
1605
+ event.stopPropagation();
1606
+ event.currentTarget.setPointerCapture(event.pointerId);
1607
+ draggingRef.current = index;
1608
+ movedRef.current = false;
1609
+ setSelected(index);
1610
+ }
1611
+ function pointerMove(event) {
1612
+ if (draggingRef.current === null) return;
1613
+ event.stopPropagation();
1614
+ if (move(draggingRef.current, stage.toImage({
1615
+ x: event.clientX,
1616
+ y: event.clientY
1617
+ }))) movedRef.current = true;
1618
+ }
1619
+ function pointerUp(event) {
1620
+ if (draggingRef.current === null) return;
1621
+ event.stopPropagation();
1622
+ draggingRef.current = null;
1623
+ if (movedRef.current) onCommit?.();
1624
+ }
1625
+ function keyDown(event, index) {
1626
+ if (!editable || stage.panMode) return;
1627
+ const delta = event.shiftKey ? .1 : 1;
1628
+ const p = points[index];
1629
+ if (!p) return;
1630
+ const shift = {
1631
+ ArrowLeft: {
1632
+ x: -delta,
1633
+ y: 0
1634
+ },
1635
+ ArrowRight: {
1636
+ x: delta,
1637
+ y: 0
1638
+ },
1639
+ ArrowUp: {
1640
+ x: 0,
1641
+ y: -delta
1642
+ },
1643
+ ArrowDown: {
1644
+ x: 0,
1645
+ y: delta
1646
+ }
1647
+ };
1648
+ if (shift[event.key]) {
1649
+ event.preventDefault();
1650
+ event.stopPropagation();
1651
+ if (move(index, {
1652
+ x: p.x + shift[event.key].x,
1653
+ y: p.y + shift[event.key].y
1654
+ })) onCommit?.();
1655
+ } else if ((event.key === "Delete" || event.key === "Backspace") && points.length > 3) {
1656
+ event.preventDefault();
1657
+ event.stopPropagation();
1658
+ onChange(points.filter((_, i) => i !== index));
1659
+ setSelected(null);
1660
+ onCommit?.();
1661
+ } else if (event.key === "Insert" && points.length >= 3) {
1662
+ event.preventDefault();
1663
+ event.stopPropagation();
1664
+ const next = points[(index + 1) % points.length];
1665
+ onChange([
1666
+ ...points.slice(0, index + 1),
1667
+ {
1668
+ x: (p.x + next.x) / 2,
1669
+ y: (p.y + next.y) / 2
1670
+ },
1671
+ ...points.slice(index + 1)
1672
+ ]);
1673
+ setSelected(index + 1);
1674
+ onCommit?.();
1675
+ }
1676
+ }
1677
+ return /* @__PURE__ */ jsxs("svg", {
1678
+ viewBox: imageViewBox(stage.image),
1679
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
1680
+ role: editable ? void 0 : "img",
1681
+ "aria-label": label,
1682
+ children: [
1683
+ /* @__PURE__ */ jsx("polygon", {
1684
+ points: line,
1685
+ fill: "none",
1686
+ stroke,
1687
+ strokeWidth: hairline
1688
+ }),
1689
+ editable && points.length >= 3 && /* @__PURE__ */ jsx("polygon", {
1690
+ points: line,
1691
+ fill: "none",
1692
+ stroke: "transparent",
1693
+ strokeWidth: stage.imageLength(12),
1694
+ className: "pointer-events-auto",
1695
+ onDoubleClick: (event) => {
1696
+ if (stage.panMode) return;
1697
+ event.stopPropagation();
1698
+ const point = clamp(stage.toImage({
1699
+ x: event.clientX,
1700
+ y: event.clientY
1701
+ }));
1702
+ const index = nearestContourSegment(points, point);
1703
+ onChange([
1704
+ ...points.slice(0, index + 1),
1705
+ point,
1706
+ ...points.slice(index + 1)
1707
+ ]);
1708
+ setSelected(index + 1);
1709
+ onCommit?.();
1710
+ }
1711
+ }),
1712
+ editable && points.map((point, index) => /* @__PURE__ */ jsx("circle", {
1713
+ cx: point.x,
1714
+ cy: point.y,
1715
+ r: selected === index ? radius * 1.3 : radius,
1716
+ fill: "var(--surface)",
1717
+ stroke,
1718
+ strokeWidth: hairline,
1719
+ className: "pointer-events-auto cursor-move",
1720
+ tabIndex: 0,
1721
+ role: "button",
1722
+ "aria-label": `${label} point ${index + 1}`,
1723
+ onPointerDown: (event) => pointerDown(event, index),
1724
+ onPointerMove: pointerMove,
1725
+ onPointerUp: pointerUp,
1726
+ onLostPointerCapture: pointerUp,
1727
+ onDoubleClick: (event) => {
1728
+ if (!stage.panMode) event.stopPropagation();
1729
+ },
1730
+ onKeyDown: (event) => keyDown(event, index),
1731
+ onFocus: () => setSelected(index)
1732
+ }, index))
1733
+ ]
1734
+ });
1735
+ }
1736
+ //#endregion
1737
+ //#region src/components/MaskEditor.tsx
1738
+ /** A source-pixel raster mask layer with a small paint/erase brush. */
1739
+ /** Paint a continuous round stroke into a copied binary mask. Pixel centers are integers. */
1740
+ function paintMask(mask, width, height, from, to, radius, value) {
1741
+ if (mask.length !== width * height) throw new RangeError("Mask dimensions do not match its pixel data.");
1742
+ if (![
1743
+ from.x,
1744
+ from.y,
1745
+ to.x,
1746
+ to.y,
1747
+ radius
1748
+ ].every(Number.isFinite) || radius < 0) throw new RangeError("Brush coordinates and radius must be finite and nonnegative.");
1749
+ const next = mask.slice();
1750
+ const clamp = (value, limit) => Math.max(0, Math.min(limit - 1, value));
1751
+ const start = {
1752
+ x: clamp(from.x, width),
1753
+ y: clamp(from.y, height)
1754
+ };
1755
+ const end = {
1756
+ x: clamp(to.x, width),
1757
+ y: clamp(to.y, height)
1758
+ };
1759
+ const steps = Math.max(1, Math.ceil(Math.hypot(end.x - start.x, end.y - start.y)));
1760
+ const r = Math.max(.75, radius);
1761
+ for (let step = 0; step <= steps; step++) {
1762
+ const x = start.x + (end.x - start.x) * step / steps;
1763
+ const y = start.y + (end.y - start.y) * step / steps;
1764
+ for (let row = Math.max(0, Math.ceil(y - r)); row <= Math.min(height - 1, Math.floor(y + r)); row++) for (let col = Math.max(0, Math.ceil(x - r)); col <= Math.min(width - 1, Math.floor(x + r)); col++) if ((col - x) ** 2 + (row - y) ** 2 <= r * r) next[row * width + col] = value;
1765
+ }
1766
+ return next;
1767
+ }
1768
+ /** Render and edit a binary raster mask within the enclosing ImageStage. */
1769
+ function MaskEditor({ mask, onChange, onCommit, editable = false, brushRadius = 3, mode = "paint", label = "Mask brush", color = [
1770
+ 0,
1771
+ 190,
1772
+ 220,
1773
+ 128
1774
+ ] }) {
1775
+ const stage = useStage();
1776
+ const canvasRef = useRef(null);
1777
+ const draftRef = useRef(mask);
1778
+ const lastRef = useRef(null);
1779
+ const cursorRef = useRef(null);
1780
+ const [brush, setBrush] = useState(null);
1781
+ function cursor() {
1782
+ return cursorRef.current ?? {
1783
+ x: Math.floor(stage.image.width / 2),
1784
+ y: Math.floor(stage.image.height / 2)
1785
+ };
1786
+ }
1787
+ useEffect(() => {
1788
+ if (mask.length !== stage.image.width * stage.image.height) throw new RangeError("Mask dimensions do not match ImageStage.");
1789
+ const context = canvasRef.current?.getContext("2d");
1790
+ if (!context) return;
1791
+ const pixels = context.createImageData(stage.image.width, stage.image.height);
1792
+ for (let i = 0; i < mask.length; i++) if (mask[i]) pixels.data.set(color, i * 4);
1793
+ context.putImageData(pixels, 0, 0);
1794
+ }, [
1795
+ mask,
1796
+ color,
1797
+ stage.image.width,
1798
+ stage.image.height
1799
+ ]);
1800
+ function apply(from, to) {
1801
+ const next = paintMask(draftRef.current, stage.image.width, stage.image.height, from, to, brushRadius, mode === "paint" ? 1 : 0);
1802
+ draftRef.current = next;
1803
+ onChange(next);
1804
+ }
1805
+ function down(event) {
1806
+ if (!editable || stage.panMode || event.button !== 0) return;
1807
+ event.stopPropagation();
1808
+ event.currentTarget.setPointerCapture(event.pointerId);
1809
+ const point = stage.toImage({
1810
+ x: event.clientX,
1811
+ y: event.clientY
1812
+ });
1813
+ draftRef.current = mask;
1814
+ lastRef.current = point;
1815
+ cursorRef.current = point;
1816
+ setBrush(null);
1817
+ apply(point, point);
1818
+ }
1819
+ function move(event) {
1820
+ if (!lastRef.current) return;
1821
+ event.stopPropagation();
1822
+ const point = stage.toImage({
1823
+ x: event.clientX,
1824
+ y: event.clientY
1825
+ });
1826
+ apply(lastRef.current, point);
1827
+ lastRef.current = point;
1828
+ cursorRef.current = point;
1829
+ }
1830
+ function up(event) {
1831
+ if (!lastRef.current) return;
1832
+ event.stopPropagation();
1833
+ lastRef.current = null;
1834
+ onCommit?.();
1835
+ }
1836
+ function keyDown(event) {
1837
+ if (!editable || stage.panMode) return;
1838
+ const delta = {
1839
+ ArrowLeft: {
1840
+ x: -1,
1841
+ y: 0
1842
+ },
1843
+ ArrowRight: {
1844
+ x: 1,
1845
+ y: 0
1846
+ },
1847
+ ArrowUp: {
1848
+ x: 0,
1849
+ y: -1
1850
+ },
1851
+ ArrowDown: {
1852
+ x: 0,
1853
+ y: 1
1854
+ }
1855
+ }[event.key];
1856
+ if (delta) {
1857
+ event.preventDefault();
1858
+ event.stopPropagation();
1859
+ const from = cursor();
1860
+ cursorRef.current = {
1861
+ x: Math.max(0, Math.min(stage.image.width - 1, from.x + delta.x)),
1862
+ y: Math.max(0, Math.min(stage.image.height - 1, from.y + delta.y))
1863
+ };
1864
+ setBrush(cursorRef.current);
1865
+ } else if (event.key === "Enter") {
1866
+ event.preventDefault();
1867
+ event.stopPropagation();
1868
+ const at = cursor();
1869
+ draftRef.current = mask;
1870
+ setBrush(at);
1871
+ apply(at, at);
1872
+ onCommit?.();
1873
+ }
1874
+ }
1875
+ function focus(event) {
1876
+ if (editable && event.currentTarget.matches(":focus-visible")) setBrush(cursor());
1877
+ }
1878
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("canvas", {
1879
+ ref: canvasRef,
1880
+ width: stage.image.width,
1881
+ height: stage.image.height,
1882
+ className: `absolute inset-0 h-full w-full ${editable ? "pointer-events-auto cursor-crosshair" : "pointer-events-none"}`,
1883
+ style: { imageRendering: "pixelated" },
1884
+ role: editable ? "button" : "img",
1885
+ tabIndex: editable ? 0 : void 0,
1886
+ "aria-label": label,
1887
+ "aria-description": editable ? "Arrow keys move the brush; Enter paints or erases." : void 0,
1888
+ onPointerDown: down,
1889
+ onPointerMove: move,
1890
+ onPointerUp: up,
1891
+ onLostPointerCapture: up,
1892
+ onDoubleClick: (event) => {
1893
+ if (editable && !stage.panMode) event.stopPropagation();
1894
+ },
1895
+ onKeyDown: keyDown,
1896
+ onFocus: focus,
1897
+ onBlur: () => setBrush(null)
1898
+ }), brush && /* @__PURE__ */ jsx("svg", {
1899
+ viewBox: imageViewBox(stage.image),
1900
+ className: "pointer-events-none absolute inset-0 h-full w-full overflow-visible",
1901
+ "aria-hidden": "true",
1902
+ children: /* @__PURE__ */ jsx("circle", {
1903
+ cx: brush.x,
1904
+ cy: brush.y,
1905
+ r: Math.max(.75, brushRadius),
1906
+ fill: "none",
1907
+ stroke: "var(--signal)",
1908
+ strokeWidth: stage.imageLength(1.5)
1909
+ })
1910
+ })] });
1911
+ }
1912
+ //#endregion
1913
+ export { ContourEditor, FULL_TIER_ZOOM, ImageStage, MAX_SCALE, MAX_ZOOM, MIN_SCALE_VS_FIT, MIN_ZOOM, MaskEditor, MeasureOverlay, PIXEL_CENTRE, PlaneFormatError, RESET_VIEW, StageButton, StageReadout, StageToolbar, StageToolbarDivider, ZoomPanCanvas, arcPath, arrowHeadPoints, caliperArrow, caliperCorners, clampView, contentUnder, crossSegments, decodePlane, dimensionGeometry, fetchPlane, fitScale, fitView, formatScale, fractionOf, frameRect, imageLengthFor, imageViewBox, initialView, insideImage, isFit, nativeZoomFor, nearestContourSegment, paintMask, polygonPath, preserveCenter, rotatePoint, scaleRange, steppedScale, strokeWidthFor, toImage, toScreen, useStage, valueAt, valuesAt, zoomAbout, zoomAt };
1558
1914
 
1559
1915
  //# sourceMappingURL=index.js.map