@crux-diagram/react 0.0.0-stage → 0.1.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 (98) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +50 -2
  4. package/dist/cjs/DrawingEditor.d.ts +34 -0
  5. package/dist/cjs/DrawingEditor.js +289 -0
  6. package/dist/cjs/DrawingViewer.d.ts +14 -0
  7. package/dist/cjs/DrawingViewer.js +14 -0
  8. package/dist/cjs/JointDisplayBar.d.ts +8 -0
  9. package/dist/cjs/JointDisplayBar.js +22 -0
  10. package/dist/cjs/NameEditor.d.ts +15 -0
  11. package/dist/cjs/NameEditor.js +36 -0
  12. package/dist/cjs/Toolbar.d.ts +8 -0
  13. package/dist/cjs/Toolbar.js +34 -0
  14. package/dist/cjs/VersionHistory.d.ts +33 -0
  15. package/dist/cjs/VersionHistory.js +49 -0
  16. package/dist/cjs/a11y.d.ts +12 -0
  17. package/dist/cjs/a11y.js +53 -0
  18. package/dist/cjs/config.d.ts +50 -0
  19. package/dist/cjs/config.js +39 -0
  20. package/dist/cjs/controls.d.ts +12 -0
  21. package/dist/cjs/controls.js +15 -0
  22. package/dist/cjs/editor-context.d.ts +45 -0
  23. package/dist/cjs/editor-context.js +101 -0
  24. package/dist/cjs/export/export-image.d.ts +29 -0
  25. package/dist/cjs/export/export-image.js +94 -0
  26. package/dist/cjs/hooks.d.ts +6 -0
  27. package/dist/cjs/hooks.js +10 -0
  28. package/dist/cjs/index.d.ts +9 -0
  29. package/dist/cjs/index.js +21 -0
  30. package/dist/cjs/interaction/gestures.d.ts +133 -0
  31. package/dist/cjs/interaction/gestures.js +353 -0
  32. package/dist/cjs/interaction/joints.d.ts +41 -0
  33. package/dist/cjs/interaction/joints.js +104 -0
  34. package/dist/cjs/interaction/keyboard.d.ts +51 -0
  35. package/dist/cjs/interaction/keyboard.js +116 -0
  36. package/dist/cjs/interaction/palette.d.ts +19 -0
  37. package/dist/cjs/interaction/palette.js +64 -0
  38. package/dist/cjs/interaction/viewport.d.ts +14 -0
  39. package/dist/cjs/interaction/viewport.js +23 -0
  40. package/dist/cjs/labels.d.ts +39 -0
  41. package/dist/cjs/labels.js +49 -0
  42. package/dist/cjs/package.json +1 -0
  43. package/dist/cjs/render/DrawingStage.d.ts +27 -0
  44. package/dist/cjs/render/DrawingStage.js +77 -0
  45. package/dist/cjs/render/fonts.d.ts +7 -0
  46. package/dist/cjs/render/fonts.js +50 -0
  47. package/dist/cjs/render/scene.d.ts +75 -0
  48. package/dist/cjs/render/scene.js +92 -0
  49. package/dist/cjs/store.d.ts +90 -0
  50. package/dist/cjs/store.js +159 -0
  51. package/dist/esm/DrawingEditor.d.ts +34 -0
  52. package/dist/esm/DrawingEditor.js +285 -0
  53. package/dist/esm/DrawingViewer.d.ts +14 -0
  54. package/dist/esm/DrawingViewer.js +11 -0
  55. package/dist/esm/JointDisplayBar.d.ts +8 -0
  56. package/dist/esm/JointDisplayBar.js +19 -0
  57. package/dist/esm/NameEditor.d.ts +15 -0
  58. package/dist/esm/NameEditor.js +32 -0
  59. package/dist/esm/Toolbar.d.ts +8 -0
  60. package/dist/esm/Toolbar.js +31 -0
  61. package/dist/esm/VersionHistory.d.ts +33 -0
  62. package/dist/esm/VersionHistory.js +45 -0
  63. package/dist/esm/a11y.d.ts +12 -0
  64. package/dist/esm/a11y.js +47 -0
  65. package/dist/esm/config.d.ts +50 -0
  66. package/dist/esm/config.js +35 -0
  67. package/dist/esm/controls.d.ts +12 -0
  68. package/dist/esm/controls.js +11 -0
  69. package/dist/esm/editor-context.d.ts +45 -0
  70. package/dist/esm/editor-context.js +95 -0
  71. package/dist/esm/export/export-image.d.ts +29 -0
  72. package/dist/esm/export/export-image.js +86 -0
  73. package/dist/esm/hooks.d.ts +6 -0
  74. package/dist/esm/hooks.js +7 -0
  75. package/dist/esm/index.d.ts +9 -0
  76. package/dist/esm/index.js +9 -0
  77. package/dist/esm/interaction/gestures.d.ts +133 -0
  78. package/dist/esm/interaction/gestures.js +338 -0
  79. package/dist/esm/interaction/joints.d.ts +41 -0
  80. package/dist/esm/interaction/joints.js +95 -0
  81. package/dist/esm/interaction/keyboard.d.ts +51 -0
  82. package/dist/esm/interaction/keyboard.js +109 -0
  83. package/dist/esm/interaction/palette.d.ts +19 -0
  84. package/dist/esm/interaction/palette.js +59 -0
  85. package/dist/esm/interaction/viewport.d.ts +14 -0
  86. package/dist/esm/interaction/viewport.js +19 -0
  87. package/dist/esm/labels.d.ts +39 -0
  88. package/dist/esm/labels.js +45 -0
  89. package/dist/esm/package.json +1 -0
  90. package/dist/esm/render/DrawingStage.d.ts +27 -0
  91. package/dist/esm/render/DrawingStage.js +74 -0
  92. package/dist/esm/render/fonts.d.ts +7 -0
  93. package/dist/esm/render/fonts.js +45 -0
  94. package/dist/esm/render/scene.d.ts +75 -0
  95. package/dist/esm/render/scene.js +86 -0
  96. package/dist/esm/store.d.ts +90 -0
  97. package/dist/esm/store.js +156 -0
  98. package/package.json +80 -4
@@ -0,0 +1,95 @@
1
+ // The joint tool and the name editor, as store operations (REA-020, REA-021, REA-025;
2
+ // Flutter JT-1 to JT-4, NM-1, NM-2, DL-3).
3
+ import { addJoint, normalizeJointName, pickAnchor, renameJoint, setJointDisplay } from '@crux-diagram/core';
4
+ import { labelAt } from './gestures.js';
5
+ /** Hit radius of an anchor, in screen pixels (JT-2). */
6
+ export const ANCHOR_HIT_RADIUS = 22;
7
+ /** Anchors whose distance differs by less than this, in screen pixels, are tied: the topmost shape wins (JT-4). */
8
+ export const ANCHOR_TIE_TOLERANCE = 2;
9
+ /** Radius of an anchor dot, in screen pixels (JT-1). */
10
+ export const ANCHOR_VISUAL_RADIUS = 5;
11
+ /**
12
+ * A tap with the joint tool at canvas `point`. A free anchor gets a new joint, shown as a
13
+ * preview until its name is confirmed so that creating and naming is one history entry
14
+ * (DL-3); an anchor with a joint selects it, showing hidden joints again (REA-025); empty
15
+ * canvas clears the joint selection.
16
+ */
17
+ export function jointToolTap(editor, point, { scale, namePrefix, nameMaxLength, labels }) {
18
+ const labeled = labels && labelAt(labels, point);
19
+ if (labeled)
20
+ return editor.selectJoint(labeled);
21
+ const document = editor.getDocument();
22
+ const hit = pickAnchor(document.shapes, point, {
23
+ radius: ANCHOR_HIT_RADIUS / scale,
24
+ tieTolerance: ANCHOR_TIE_TOLERANCE / scale,
25
+ });
26
+ if (!hit)
27
+ return editor.selectJoint(null);
28
+ const existing = document.joints.find((j) => j.shapeId === hit.shapeId && j.anchorId === hit.anchorId);
29
+ if (existing) {
30
+ if (!document.jointDisplay.visible)
31
+ editor.commit(setJointDisplay(document, { visible: true }));
32
+ return editor.selectJoint(existing.id);
33
+ }
34
+ const next = addJoint(document, { ...hit, namePrefix, maxNameLength: nameMaxLength });
35
+ const created = next.joints[next.joints.length - 1];
36
+ editor.preview(next);
37
+ editor.selectJoint(created.id);
38
+ editor.setNaming({ jointId: created.id, isNew: true });
39
+ }
40
+ /** Opens the name editor for an existing joint (NM-2). */
41
+ export function beginRename(editor, jointId) {
42
+ editor.setNaming({ jointId, isNew: false });
43
+ }
44
+ /**
45
+ * Confirms the name editor with `raw`, trimmed and cut to `nameMaxLength` (NM-1). A new joint
46
+ * is committed with its name; an empty name cancels it. An existing joint is renamed, or
47
+ * keeps its name when `raw` is empty.
48
+ */
49
+ export function confirmNaming(editor, raw, nameMaxLength) {
50
+ const { naming, preview } = editor.getState();
51
+ if (!naming)
52
+ return;
53
+ const name = normalizeJointName(raw, nameMaxLength);
54
+ if (naming.isNew) {
55
+ if (!name || !preview)
56
+ return cancelNaming(editor);
57
+ editor.setNaming(null);
58
+ editor.commit(renameJoint(preview, naming.jointId, name, nameMaxLength));
59
+ return;
60
+ }
61
+ editor.setNaming(null);
62
+ if (name)
63
+ editor.commit(renameJoint(editor.getDocument(), naming.jointId, name, nameMaxLength));
64
+ }
65
+ /** Closes the name editor without a change; a joint that was being created is dropped. */
66
+ export function cancelNaming(editor) {
67
+ const { naming } = editor.getState();
68
+ if (!naming)
69
+ return;
70
+ editor.setNaming(null);
71
+ if (naming.isNew) {
72
+ editor.preview(null);
73
+ editor.selectJoint(null);
74
+ }
75
+ }
76
+ /** Sets the joint label size as one history entry; the size already active adds none (JS-4). */
77
+ export function setJointLabelSize(editor, labelSize) {
78
+ const document = editor.getDocument();
79
+ const next = setJointDisplay(document, { labelSize });
80
+ if (next !== document)
81
+ editor.commit(next);
82
+ }
83
+ /**
84
+ * Shows or hides every joint as one history entry (JV-6). Hiding clears the joint
85
+ * selection and keeps the shape selection (JV-3); the joints stay in the document (JV-5).
86
+ */
87
+ export function setJointsVisible(editor, visible) {
88
+ const document = editor.getDocument();
89
+ const next = setJointDisplay(document, { visible });
90
+ if (next === document)
91
+ return;
92
+ if (!visible)
93
+ editor.selectJoint(null);
94
+ editor.commit(next);
95
+ }
@@ -0,0 +1,51 @@
1
+ import { type DrawingDocument, type Group } from '@crux-diagram/core';
2
+ import type { EditorStore } from '../store.js';
3
+ /** Arrow-key move, in canvas units; `Shift` uses the large step (REA-015). */
4
+ export declare const NUDGE_STEP = 1;
5
+ export declare const NUDGE_STEP_LARGE = 10;
6
+ export type EditorCommand = {
7
+ readonly type: 'delete';
8
+ } | {
9
+ readonly type: 'undo';
10
+ } | {
11
+ readonly type: 'redo';
12
+ } | {
13
+ readonly type: 'duplicate';
14
+ } | {
15
+ readonly type: 'rotate90';
16
+ } | {
17
+ readonly type: 'front';
18
+ } | {
19
+ readonly type: 'back';
20
+ } | {
21
+ readonly type: 'group';
22
+ } | {
23
+ readonly type: 'ungroup';
24
+ } | {
25
+ readonly type: 'nudge';
26
+ readonly dx: number;
27
+ readonly dy: number;
28
+ };
29
+ /** The modifier and key fields of a `KeyboardEvent`. */
30
+ export interface KeyInput {
31
+ readonly key: string;
32
+ readonly ctrlKey: boolean;
33
+ readonly metaKey: boolean;
34
+ readonly shiftKey: boolean;
35
+ readonly altKey: boolean;
36
+ }
37
+ /** The command bound to a key press, or `null` when the key is not a shortcut. */
38
+ export declare function commandForKey(event: KeyInput): EditorCommand | null;
39
+ /** Whether key presses on `target` belong to a text field rather than to the editor. */
40
+ export declare function isTextEntry(target: EventTarget | null): boolean;
41
+ /** The group whose shapes are exactly `selection`, if any (a selected group, MS-6). */
42
+ export declare function wholeGroup(document: DrawingDocument, selection: readonly string[]): Group | undefined;
43
+ /**
44
+ * Runs `command` on the committed document. Each change is one history entry: delete
45
+ * removes the selected shapes with their joints (REC-071) and clears the selection;
46
+ * duplicate copies them as FR-20 does and selects the copies; nudge moves them without
47
+ * grid snapping, every center kept inside the canvas (FR-10); rotate90 turns a single
48
+ * shape a quarter turn clockwise (FR-17, REA-013; it has no key and serves the toolbar).
49
+ * Without a selection, or when nothing would change, it does nothing.
50
+ */
51
+ export declare function runCommand(editor: EditorStore, command: EditorCommand): void;
@@ -0,0 +1,109 @@
1
+ // Editor keyboard shortcuts (REA-014, REA-015, REA-018). Flutter has none; these follow
2
+ // the REA-018 assumption: they act only while the editor has the focus and never while
3
+ // a text field has it.
4
+ import { bringToFront, duplicateShapes, groupShapes, moveShape, removeJoint, removeShape, rotateShape, sendToBack, ungroup } from '@crux-diagram/core';
5
+ /** Arrow-key move, in canvas units; `Shift` uses the large step (REA-015). */
6
+ export const NUDGE_STEP = 1;
7
+ export const NUDGE_STEP_LARGE = 10;
8
+ const ARROWS = {
9
+ ArrowLeft: [-1, 0],
10
+ ArrowRight: [1, 0],
11
+ ArrowUp: [0, -1],
12
+ ArrowDown: [0, 1],
13
+ };
14
+ /** The command bound to a key press, or `null` when the key is not a shortcut. */
15
+ export function commandForKey(event) {
16
+ if (event.altKey)
17
+ return null;
18
+ const command = event.ctrlKey || event.metaKey;
19
+ const key = event.key.toLowerCase();
20
+ if (command) {
21
+ if (key === 'z')
22
+ return { type: event.shiftKey ? 'redo' : 'undo' };
23
+ if (key === 'd' && !event.shiftKey)
24
+ return { type: 'duplicate' };
25
+ return null;
26
+ }
27
+ if (event.key === 'Delete' || event.key === 'Backspace')
28
+ return { type: 'delete' };
29
+ const arrow = ARROWS[event.key];
30
+ if (!arrow)
31
+ return null;
32
+ const step = event.shiftKey ? NUDGE_STEP_LARGE : NUDGE_STEP;
33
+ return { type: 'nudge', dx: arrow[0] * step, dy: arrow[1] * step };
34
+ }
35
+ /** Whether key presses on `target` belong to a text field rather than to the editor. */
36
+ export function isTextEntry(target) {
37
+ if (!target || typeof target.tagName !== 'string')
38
+ return false;
39
+ const element = target;
40
+ const tag = element.tagName.toLowerCase();
41
+ return tag === 'input' || tag === 'textarea' || tag === 'select' || element.isContentEditable === true || element.getAttribute('contenteditable') === 'true';
42
+ }
43
+ /** The group whose shapes are exactly `selection`, if any (a selected group, MS-6). */
44
+ export function wholeGroup(document, selection) {
45
+ return document.groups.find((g) => g.shapeIds.length === selection.length && g.shapeIds.every((id) => selection.includes(id)));
46
+ }
47
+ /**
48
+ * Runs `command` on the committed document. Each change is one history entry: delete
49
+ * removes the selected shapes with their joints (REC-071) and clears the selection;
50
+ * duplicate copies them as FR-20 does and selects the copies; nudge moves them without
51
+ * grid snapping, every center kept inside the canvas (FR-10); rotate90 turns a single
52
+ * shape a quarter turn clockwise (FR-17, REA-013; it has no key and serves the toolbar).
53
+ * Without a selection, or when nothing would change, it does nothing.
54
+ */
55
+ export function runCommand(editor, command) {
56
+ if (command.type === 'undo')
57
+ return editor.undo();
58
+ if (command.type === 'redo')
59
+ return editor.redo();
60
+ const { document, selection, selectedJoint } = editor.getState();
61
+ // A selected joint is deleted on its own, as one entry (DL-1); it never coexists with shapes.
62
+ if (command.type === 'delete' && selectedJoint)
63
+ return editor.commit(removeJoint(document, selectedJoint));
64
+ if (selection.length === 0)
65
+ return;
66
+ switch (command.type) {
67
+ case 'delete':
68
+ editor.commit(removeShape(document, selection), []);
69
+ return;
70
+ case 'duplicate': {
71
+ const next = duplicateShapes(document, selection);
72
+ editor.commit(next, next.shapes.slice(-selection.length).map((s) => s.id));
73
+ return;
74
+ }
75
+ case 'rotate90':
76
+ // Only a single shape rotates; a multi-selection or a group does nothing (MS-5).
77
+ if (selection.length === 1)
78
+ editor.commit(rotateShape(document, selection[0], { by: Math.PI / 2 }));
79
+ return;
80
+ case 'front':
81
+ case 'back': {
82
+ // The order is a toolbar command (TB-3); it has no key. An unchanged order adds no entry.
83
+ const next = command.type === 'front' ? bringToFront(document, selection) : sendToBack(document, selection);
84
+ if (next !== document)
85
+ editor.commit(next);
86
+ return;
87
+ }
88
+ case 'group': {
89
+ // A toolbar command (MS-6); a selection that is already one whole group adds no entry.
90
+ if (selection.length < 2)
91
+ return;
92
+ const next = groupShapes(document, selection);
93
+ if (next !== document)
94
+ editor.commit(next);
95
+ return;
96
+ }
97
+ case 'ungroup': {
98
+ const group = wholeGroup(document, selection);
99
+ if (group)
100
+ editor.commit(ungroup(document, group.id));
101
+ return;
102
+ }
103
+ case 'nudge': {
104
+ const next = moveShape(document, selection, { dx: command.dx, dy: command.dy });
105
+ if (next !== document)
106
+ editor.commit(next);
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,19 @@
1
+ import { type Point, type ShapeType, type Size } from '@crux-diagram/core';
2
+ import type { ShapeStyle } from '../config.js';
3
+ import type { EditorStore } from '../store.js';
4
+ /** Size of a new shape, in canvas units (Flutter spec 01, section 4). */
5
+ export declare const DEFAULT_SHAPE_SIZES: Readonly<Record<ShapeType, Size>>;
6
+ export interface PaletteOptions {
7
+ /** The unsnapped visible center (PL-1). */
8
+ readonly center: Point;
9
+ /** Grid step, or `null` for none (FR-9). */
10
+ readonly gridSize: number | null;
11
+ readonly style: ShapeStyle;
12
+ }
13
+ /** Adds a default shape of `type` on top as one history entry and selects it (FR-4). */
14
+ export declare function addPaletteShape(editor: EditorStore, type: ShapeType, { center, gridSize, style }: PaletteOptions): void;
15
+ /**
16
+ * The canvas point under the center of the drawing area, with the current zoom and pan
17
+ * (PL-1); the canvas center while the area is not measured yet.
18
+ */
19
+ export declare function visibleCenterOf(editor: EditorStore): Point;
@@ -0,0 +1,59 @@
1
+ // Adding shapes from the toolbar palette (REA-053; Flutter FR-4, FR-5, FR-9, PL-1, PL-2).
2
+ import { addShape, applyZoom, clampZoom, fitViewport, generateId, snapPointToGrid, visibleCenter } from '@crux-diagram/core';
3
+ /** Size of a new shape, in canvas units (Flutter spec 01, section 4). */
4
+ export const DEFAULT_SHAPE_SIZES = {
5
+ square: { width: 160, height: 160 },
6
+ rectangle: { width: 240, height: 140 },
7
+ circle: { width: 160, height: 160 },
8
+ };
9
+ /** Distance of one cascade step, in canvas units (FR-5). */
10
+ const CASCADE_STEP = 20;
11
+ const inCanvas = (point, canvas) => point.x >= 0 && point.x <= canvas.width && point.y >= 0 && point.y <= canvas.height;
12
+ /**
13
+ * Where a new shape of `type` goes: `start` snapped to the grid, moved +20/+20 while a shape
14
+ * of the same type sits exactly there; when that would leave the canvas, −20/−20 from the
15
+ * start instead; when both are exhausted, the start (FR-5, PL-2).
16
+ */
17
+ function freeCenter(document, type, start) {
18
+ const taken = (p) => document.shapes.some((s) => s.type === type && s.center.x === p.x && s.center.y === p.y);
19
+ if (!taken(start))
20
+ return start;
21
+ for (const direction of [1, -1]) {
22
+ let candidate = start;
23
+ for (;;) {
24
+ candidate = { x: candidate.x + direction * CASCADE_STEP, y: candidate.y + direction * CASCADE_STEP };
25
+ if (!inCanvas(candidate, document.canvas))
26
+ break;
27
+ if (!taken(candidate))
28
+ return candidate;
29
+ }
30
+ }
31
+ return start;
32
+ }
33
+ /** Adds a default shape of `type` on top as one history entry and selects it (FR-4). */
34
+ export function addPaletteShape(editor, type, { center, gridSize, style }) {
35
+ const document = editor.getDocument();
36
+ const start = gridSize === null ? center : snapPointToGrid(center, gridSize);
37
+ const id = generateId('s');
38
+ const next = addShape(document, {
39
+ id,
40
+ type,
41
+ center: freeCenter(document, type, start),
42
+ size: DEFAULT_SHAPE_SIZES[type],
43
+ rotation: 0,
44
+ ...style,
45
+ });
46
+ editor.commit(next, [id]);
47
+ }
48
+ /**
49
+ * The canvas point under the center of the drawing area, with the current zoom and pan
50
+ * (PL-1); the canvas center while the area is not measured yet.
51
+ */
52
+ export function visibleCenterOf(editor) {
53
+ const { stageArea, view } = editor.getState();
54
+ const { canvas } = editor.getDocument();
55
+ if (!stageArea)
56
+ return { x: canvas.width / 2, y: canvas.height / 2 };
57
+ const viewport = applyZoom(clampZoom(view.zoom, canvas, stageArea), fitViewport(canvas, stageArea));
58
+ return visibleCenter(viewport, stageArea, canvas);
59
+ }
@@ -0,0 +1,14 @@
1
+ import { type Point, type Size, type Vector, type ViewportZoom } from '@crux-diagram/core';
2
+ export interface WheelInput {
3
+ readonly deltaY: number;
4
+ /** `WheelEvent.deltaMode`: 0 pixels, 1 lines. */
5
+ readonly deltaMode?: number;
6
+ /** True for a trackpad pinch, which browsers report as a wheel with `ctrlKey`. */
7
+ readonly ctrlKey: boolean;
8
+ /** The pointer, in screen coordinates of the drawing area. */
9
+ readonly focal: Point;
10
+ }
11
+ /** The view after `wheel`: zoomed around the pointer, between 1× and 4×, with the pan kept inside the canvas. */
12
+ export declare function wheelZoom(current: ViewportZoom, wheel: WheelInput, canvas: Size, area: Size): ViewportZoom;
13
+ /** `current` moved by the screen `delta`, with the pan kept inside the canvas. */
14
+ export declare function panBy(current: ViewportZoom, delta: Vector, canvas: Size, area: Size): ViewportZoom;
@@ -0,0 +1,19 @@
1
+ // Pure zoom and pan rules for the editor view (REA-016). The geometry (pinch, clamping)
2
+ // is core's `ViewportZoom`; this adds how a wheel event or a drag becomes a new view.
3
+ import { clampZoom, pinchZoom } from '@crux-diagram/core';
4
+ /** Zoom per wheel pixel for a mouse wheel: one 100 px notch is about 22 %. */
5
+ const WHEEL_SENSITIVITY = 0.002;
6
+ /** Zoom per wheel pixel for a trackpad pinch (`ctrlKey`), whose deltas are small. */
7
+ const PINCH_SENSITIVITY = 0.01;
8
+ /** Pixels per line when the browser reports the wheel delta in lines (`deltaMode` 1). */
9
+ const LINE_PIXELS = 33;
10
+ /** The view after `wheel`: zoomed around the pointer, between 1× and 4×, with the pan kept inside the canvas. */
11
+ export function wheelZoom(current, wheel, canvas, area) {
12
+ const pixels = wheel.deltaY * (wheel.deltaMode === 1 ? LINE_PIXELS : 1);
13
+ const scale = Math.exp(-pixels * (wheel.ctrlKey ? PINCH_SENSITIVITY : WHEEL_SENSITIVITY));
14
+ return clampZoom(pinchZoom(current, { startFocal: wheel.focal, focal: wheel.focal, scale }), canvas, area);
15
+ }
16
+ /** `current` moved by the screen `delta`, with the pan kept inside the canvas. */
17
+ export function panBy(current, delta, canvas, area) {
18
+ return clampZoom({ zoom: current.zoom, pan: { dx: current.pan.dx + delta.dx, dy: current.pan.dy + delta.dy } }, canvas, area);
19
+ }
@@ -0,0 +1,39 @@
1
+ export interface EditorLabels {
2
+ readonly fitToScreen: string;
3
+ readonly rename: string;
4
+ readonly delete: string;
5
+ readonly small: string;
6
+ readonly medium: string;
7
+ readonly large: string;
8
+ readonly hide: string;
9
+ readonly show: string;
10
+ readonly hideJoints: string;
11
+ readonly showJoints: string;
12
+ readonly square: string;
13
+ readonly rectangle: string;
14
+ readonly circle: string;
15
+ readonly joint: string;
16
+ readonly grid: string;
17
+ readonly undo: string;
18
+ readonly redo: string;
19
+ readonly select: string;
20
+ readonly rotate: string;
21
+ readonly duplicate: string;
22
+ readonly front: string;
23
+ readonly back: string;
24
+ readonly group: string;
25
+ readonly ungroup: string;
26
+ readonly showGrid: string;
27
+ readonly hideGrid: string;
28
+ readonly rotate90: string;
29
+ readonly bringToFront: string;
30
+ readonly sendToBack: string;
31
+ readonly selectMode: string;
32
+ readonly jointTool: string;
33
+ readonly createBar: string;
34
+ readonly selectionBar: string;
35
+ }
36
+ export type EditorLabelsInput = Partial<EditorLabels>;
37
+ export declare const DEFAULT_EDITOR_LABELS: EditorLabels;
38
+ /** The defaults with the given texts on top; a field given as `undefined` keeps its default. */
39
+ export declare function resolveEditorLabels(input?: EditorLabelsInput): EditorLabels;
@@ -0,0 +1,45 @@
1
+ // Texts of the ready-made controls (REA-053), like Flutter's `DrawingEditorLabels`: short
2
+ // visible texts with the longer ones as titles. English by default.
3
+ export const DEFAULT_EDITOR_LABELS = {
4
+ fitToScreen: 'Fit to screen',
5
+ rename: 'Rename',
6
+ delete: 'Delete',
7
+ small: 'Small',
8
+ medium: 'Medium',
9
+ large: 'Large',
10
+ hide: 'Hide',
11
+ show: 'Show',
12
+ hideJoints: 'Hide joints',
13
+ showJoints: 'Show joints',
14
+ square: 'Square',
15
+ rectangle: 'Rect',
16
+ circle: 'Circle',
17
+ joint: 'Joint',
18
+ grid: 'Grid',
19
+ undo: 'Undo',
20
+ redo: 'Redo',
21
+ select: 'Select',
22
+ rotate: 'Rotate',
23
+ duplicate: 'Copy',
24
+ front: 'Front',
25
+ back: 'Back',
26
+ group: 'Group',
27
+ ungroup: 'Ungroup',
28
+ showGrid: 'Show grid',
29
+ hideGrid: 'Hide grid',
30
+ rotate90: 'Rotate 90°',
31
+ bringToFront: 'Bring to front',
32
+ sendToBack: 'Send to back',
33
+ selectMode: 'Select several shapes',
34
+ jointTool: 'Add joints',
35
+ createBar: 'Create',
36
+ selectionBar: 'Selection',
37
+ };
38
+ /** The defaults with the given texts on top; a field given as `undefined` keeps its default. */
39
+ export function resolveEditorLabels(input) {
40
+ const labels = { ...DEFAULT_EDITOR_LABELS };
41
+ for (const [key, value] of Object.entries(input ?? {}))
42
+ if (typeof value === 'string')
43
+ labels[key] = value;
44
+ return labels;
45
+ }
@@ -0,0 +1 @@
1
+ {"type":"module","sideEffects":false}
@@ -0,0 +1,27 @@
1
+ import { type CanvasViewport, type DrawingDocument, type JointStyle, type Size, type ViewportZoom } from '@crux-diagram/core';
2
+ import type { KonvaEventObject } from 'konva/lib/Node';
3
+ import { type ReactNode } from 'react';
4
+ export interface DrawingStageProps {
5
+ readonly document: DrawingDocument;
6
+ readonly jointStyle?: JointStyle;
7
+ /** Whether the stage handles pointer events. */
8
+ readonly listening: boolean;
9
+ /** Zoom and pan on top of the fitted view (default: fitted); clamped so the canvas stays in view. */
10
+ readonly zoom?: ViewportZoom;
11
+ /** Called on a mouse wheel or trackpad pinch over the stage (REA-016). */
12
+ readonly onWheel?: (event: KonvaEventObject<WheelEvent>) => void;
13
+ /** Alternative description of the drawing for screen readers (REA-052); a summary by default. */
14
+ readonly alt?: string;
15
+ /** Ids of the selected shapes, announced in the shape list (REA-052). */
16
+ readonly selection?: readonly string[];
17
+ /** Called with the measured size of the drawing area whenever it changes. */
18
+ readonly onAreaChange?: (area: Size) => void;
19
+ /** Called when a pointer goes down anywhere on the stage (the editor's gestures). */
20
+ readonly onPointerDown?: (event: KonvaEventObject<PointerEvent>) => void;
21
+ /** HTML drawn over the stage, positioned with the viewport (the joint name editor). */
22
+ readonly overlay?: (viewport: CanvasViewport) => ReactNode;
23
+ /** Layer 4, drawn above the joints; a function receives the view scale (screen pixels per canvas unit). */
24
+ readonly children?: ReactNode | ((scale: number) => ReactNode);
25
+ }
26
+ /** Fills its parent and fits the canvas into it, centered, keeping the aspect ratio. */
27
+ export declare function DrawingStage({ document, jointStyle, listening, zoom, onWheel, onPointerDown, onAreaChange, alt, selection, overlay, children }: DrawingStageProps): import("react").JSX.Element;
@@ -0,0 +1,74 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The Konva stage shared by the viewer and the editor. Layers, bottom to top (spec 05
3
+ // section 4): (1) background, (2) shapes, (3) joints, (4) editing UI, given as children.
4
+ import { applyZoom, argbToCss, clampZoom, DEFAULT_JOINT_STYLE, FITTED_ZOOM, fitViewport, } from '@crux-diagram/core';
5
+ import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
6
+ import { Ellipse, Layer, Line, Rect, Stage, Text } from 'react-konva';
7
+ import { useFontsReady, useLabelMeasurer } from './fonts.js';
8
+ import { describeDrawing, DrawingList } from '../a11y.js';
9
+ import { jointGraphics, placeJoints, shapeNodeProps } from './scene.js';
10
+ /** Fills its parent and fits the canvas into it, centered, keeping the aspect ratio. */
11
+ export function DrawingStage({ document, jointStyle = DEFAULT_JOINT_STYLE, listening, zoom = FITTED_ZOOM, onWheel, onPointerDown, onAreaChange, alt, selection, overlay, children }) {
12
+ const container = useRef(null);
13
+ const area = useContainerSize(container);
14
+ const width = area?.width;
15
+ const height = area?.height;
16
+ useEffect(() => {
17
+ if (width !== undefined && height !== undefined)
18
+ onAreaChange?.({ width, height });
19
+ }, [width, height, onAreaChange]);
20
+ return (_jsxs("div", { ref: container, role: "group", "aria-label": alt ?? describeDrawing(document), style: { position: 'relative', width: '100%', height: '100%', overflow: 'hidden' }, children: [_jsx(DrawingList, { document: document, selection: selection }), area && area.width > 0 && area.height > 0 && (_jsx(FittedStage, { document: document, jointStyle: jointStyle, listening: listening, zoom: zoom, onWheel: onWheel, onPointerDown: onPointerDown, overlay: overlay, area: area, children: children }))] }));
21
+ }
22
+ function FittedStage({ document, jointStyle, listening, zoom, onWheel, onPointerDown, overlay, area, children, }) {
23
+ const viewport = applyZoom(clampZoom(zoom, document.canvas, area), fitViewport(document.canvas, area));
24
+ const clip = { x: 0, y: 0, width: document.canvas.width, height: document.canvas.height };
25
+ return (_jsxs(_Fragment, { children: [_jsx("div", { "aria-hidden": "true", children: _jsxs(Stage, { width: area.width, height: area.height, x: viewport.origin.x, y: viewport.origin.y, scaleX: viewport.scale, scaleY: viewport.scale, listening: listening, onPointerDown: onPointerDown, onWheel: onWheel, children: [_jsx(Layer, { name: "background", clip: clip, listening: false, children: _jsx(Rect, { name: "background-fill", width: clip.width, height: clip.height, fill: "#ffffff" }) }), _jsx(Layer, { name: "shapes", clip: clip, children: document.shapes.map((shape) => (_jsx(ShapeNode, { shape: shape }, shape.id))) }), _jsx(JointsLayer, { document: document, style: jointStyle, clip: clip }), typeof children === 'function' ? children(viewport.scale) : children] }) }), overlay?.(viewport)] }));
26
+ }
27
+ /** One shape; re-renders only when its data changes (REA-050). */
28
+ const ShapeNode = memo(function ShapeNode({ shape }) {
29
+ const { kind, ...props } = shapeNodeProps(shape);
30
+ return kind === 'ellipse' ? _jsx(Ellipse, { id: shape.id, ...props }) : _jsx(Rect, { id: shape.id, ...props });
31
+ });
32
+ function JointsLayer({ document, style, clip }) {
33
+ const fontsReady = useFontsReady();
34
+ const measurer = useLabelMeasurer();
35
+ const graphics = useMemo(() => {
36
+ if (!fontsReady)
37
+ return [];
38
+ const labelSize = document.jointDisplay.labelSize;
39
+ return placeJoints(document, style, measurer()).map((p) => ({
40
+ id: p.joint.id,
41
+ ...jointGraphics(p, style, labelSize),
42
+ }));
43
+ }, [document, style, fontsReady, measurer]);
44
+ const color = argbToCss(style.color);
45
+ return (_jsx(Layer, { name: "joints", clip: clip, children: graphics.map(({ id, line, head, text }) => [
46
+ line && (_jsx(Line, { name: "joint-line", points: line, stroke: color, strokeWidth: style.lineWidth, lineCap: "butt" }, `${id}-line`)),
47
+ head && _jsx(Line, { name: "joint-head", points: head, closed: true, fill: color }, `${id}-head`),
48
+ _jsx(Text, { id: id, name: "joint-label", ...text, align: "center", verticalAlign: "middle", wrap: "none" }, `${id}-label`),
49
+ ]) }));
50
+ }
51
+ /** The content size of `ref`, tracked with `ResizeObserver` (window resizes without it); `null` before mount. */
52
+ function useContainerSize(ref) {
53
+ const [size, setSize] = useState(null);
54
+ useLayoutEffect(() => {
55
+ const element = ref.current;
56
+ if (!element)
57
+ return;
58
+ const update = (width, height) => setSize((old) => (old && old.width === width && old.height === height ? old : { width, height }));
59
+ if (typeof ResizeObserver === 'undefined') {
60
+ // Without ResizeObserver, follow window resizes only.
61
+ const read = () => update(element.clientWidth, element.clientHeight);
62
+ read();
63
+ window.addEventListener('resize', read);
64
+ return () => window.removeEventListener('resize', read);
65
+ }
66
+ const observer = new ResizeObserver(([entry]) => {
67
+ if (entry)
68
+ update(entry.contentRect.width, entry.contentRect.height);
69
+ });
70
+ observer.observe(element);
71
+ return () => observer.disconnect();
72
+ }, [ref]);
73
+ return size;
74
+ }
@@ -0,0 +1,7 @@
1
+ import { type TextMeasurer } from '@crux-diagram/core';
2
+ /** Resolves when `document.fonts` has settled, also when loading fails; at once without a font set (REA-032). */
3
+ export declare function whenFontsReady(): Promise<void>;
4
+ /** Whether `document.fonts` has settled; labels are measured only after it has (REA-032). */
5
+ export declare function useFontsReady(): boolean;
6
+ /** One measurer per component, created on first use in the browser with the label font. */
7
+ export declare function useLabelMeasurer(): () => TextMeasurer;
@@ -0,0 +1,45 @@
1
+ // Font readiness and the label measurer (REA-030, REA-032). Client only: nothing here
2
+ // runs at import time.
3
+ import { CanvasTextMeasurer } from '@crux-diagram/core';
4
+ import { useEffect, useState } from 'react';
5
+ import { LABEL_FONT_FAMILY } from './scene.js';
6
+ function fontSet() {
7
+ return globalThis.document?.fonts;
8
+ }
9
+ /** Resolves when `document.fonts` has settled, also when loading fails; at once without a font set (REA-032). */
10
+ export async function whenFontsReady() {
11
+ const fonts = fontSet();
12
+ if (!fonts || fonts.status === 'loaded')
13
+ return;
14
+ await fonts.ready.catch(() => undefined);
15
+ }
16
+ /** Whether `document.fonts` has settled; labels are measured only after it has (REA-032). */
17
+ export function useFontsReady() {
18
+ const [ready, setReady] = useState(() => {
19
+ const fonts = fontSet();
20
+ return !fonts || fonts.status === 'loaded';
21
+ });
22
+ useEffect(() => {
23
+ if (ready)
24
+ return;
25
+ let live = true;
26
+ // A failed load still measures, with whatever font the browser falls back to.
27
+ const settle = () => {
28
+ if (live)
29
+ setReady(true);
30
+ };
31
+ void fontSet()?.ready.then(settle, settle);
32
+ return () => {
33
+ live = false;
34
+ };
35
+ }, [ready]);
36
+ return ready;
37
+ }
38
+ /** One measurer per component, created on first use in the browser with the label font. */
39
+ export function useLabelMeasurer() {
40
+ const [get] = useState(() => {
41
+ let measurer;
42
+ return () => (measurer ??= new CanvasTextMeasurer({ fontFamily: LABEL_FONT_FAMILY }));
43
+ });
44
+ return get;
45
+ }