@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,92 @@
1
+ "use strict";
2
+ // Pure scene geometry for the Konva layers, shared by the viewer and the editor.
3
+ // Port of Flutter's shape_painting.dart and joint_painting.dart (REA-001, REA-023).
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.LABEL_FONT_FAMILY = void 0;
6
+ exports.shapeNodeProps = shapeNodeProps;
7
+ exports.placeJoints = placeJoints;
8
+ exports.jointGraphics = jointGraphics;
9
+ const core_1 = require("@crux-diagram/core");
10
+ /** Font family of joint labels, fixed in both implementations (REA-030, spec 02 section 12). */
11
+ exports.LABEL_FONT_FAMILY = 'Arial';
12
+ /** Konva props for `shape`. Paint with no alpha or no width is disabled, like Flutter. */
13
+ function shapeNodeProps(shape) {
14
+ const { width, height } = shape.size;
15
+ const base = {
16
+ x: shape.center.x,
17
+ y: shape.center.y,
18
+ width,
19
+ height,
20
+ rotation: (0, core_1.toDegrees)(shape.rotation),
21
+ fill: (0, core_1.argbToCss)(shape.fill),
22
+ stroke: (0, core_1.argbToCss)(shape.stroke),
23
+ strokeWidth: shape.strokeWidth,
24
+ fillEnabled: shape.fill >>> 24 > 0,
25
+ strokeEnabled: shape.strokeWidth > 0,
26
+ };
27
+ if (shape.type === 'circle')
28
+ return { ...base, kind: 'ellipse', radiusX: width / 2, radiusY: height / 2 };
29
+ return { ...base, kind: 'rect', offsetX: width / 2, offsetY: height / 2 };
30
+ }
31
+ /**
32
+ * Places every joint whose shape and anchor exist, measuring names at the document's
33
+ * label size. Hidden joints are not placed, so they are neither drawn nor exported.
34
+ */
35
+ function placeJoints(document, style, measurer) {
36
+ if (!document.jointDisplay.visible)
37
+ return [];
38
+ const fontSize = (0, core_1.labelFontSize)(style, document.jointDisplay.labelSize);
39
+ const shapes = new Map(document.shapes.map((shape) => [shape.id, shape]));
40
+ const placements = [];
41
+ for (const joint of document.joints) {
42
+ const shape = shapes.get(joint.shapeId);
43
+ const anchor = shape ? (0, core_1.anchorPositionOf)(shape, joint.anchorId) : null;
44
+ if (!anchor)
45
+ continue;
46
+ const textSize = measurer.measure(joint.name, fontSize, style.labelBold);
47
+ const width = textSize.width + 2 * style.labelPadding;
48
+ const height = textSize.height + 2 * style.labelPadding;
49
+ placements.push({
50
+ joint,
51
+ anchor,
52
+ textSize,
53
+ labelRect: {
54
+ left: anchor.x + joint.labelOffset.dx - width / 2,
55
+ top: anchor.y + joint.labelOffset.dy - height / 2,
56
+ width,
57
+ height,
58
+ },
59
+ });
60
+ }
61
+ return placements;
62
+ }
63
+ /**
64
+ * Leader arrow and label of `placement` (FMT-043, FMT-044). No arrow when the anchor is
65
+ * inside the label; no line when it would not reach past the arrowhead.
66
+ */
67
+ function jointGraphics(placement, style, labelSize) {
68
+ const { anchor, labelRect, textSize } = placement;
69
+ const text = {
70
+ text: placement.joint.name,
71
+ x: labelRect.left + style.labelPadding,
72
+ y: labelRect.top + style.labelPadding,
73
+ width: textSize.width,
74
+ height: textSize.height,
75
+ fontSize: (0, core_1.labelFontSize)(style, labelSize),
76
+ fontFamily: exports.LABEL_FONT_FAMILY,
77
+ fontStyle: style.labelBold ? 'bold' : 'normal',
78
+ fill: (0, core_1.argbToCss)(style.color),
79
+ };
80
+ const start = (0, core_1.leaderLineStart)(labelRect, anchor);
81
+ if (!start || (start.x === anchor.x && start.y === anchor.y))
82
+ return { line: null, head: null, text };
83
+ const size = (0, core_1.arrowheadSize)(style, labelSize);
84
+ const [tip, left, right] = (0, core_1.arrowheadPoints)({ from: start, tip: anchor, length: size.length, width: size.width });
85
+ const base = { x: (left.x + right.x) / 2, y: (left.y + right.y) / 2 };
86
+ const length = Math.hypot(anchor.x - start.x, anchor.y - start.y);
87
+ return {
88
+ line: length > size.length ? [start.x, start.y, base.x, base.y] : null,
89
+ head: [tip.x, tip.y, left.x, left.y, right.x, right.y],
90
+ text,
91
+ };
92
+ }
@@ -0,0 +1,90 @@
1
+ import { type DrawingDocument, type Point, type Size, type ViewportZoom } from '@crux-diagram/core';
2
+ /** View settings: never in history and never a document change (REA-017). */
3
+ export interface EditorView {
4
+ readonly showGrid: boolean;
5
+ /** Zoom and pan on top of the fitted view; the stage clamps it to the canvas (REA-016). */
6
+ readonly zoom: ViewportZoom;
7
+ }
8
+ /** The active tool: `select` moves and edits shapes, `joint` places and selects joints (REA-020). */
9
+ export type EditorTool = 'select' | 'joint';
10
+ /** The open joint name editor: for a joint being created (still a preview) or an existing one (REA-021). */
11
+ export interface JointNaming {
12
+ readonly jointId: string;
13
+ readonly isNew: boolean;
14
+ }
15
+ export interface EditorState {
16
+ /** The committed document, the one `onChange` receives. */
17
+ readonly document: DrawingDocument;
18
+ /** The document shown during a continuous gesture, or `null` (REA-003). */
19
+ readonly preview: DrawingDocument | null;
20
+ readonly view: EditorView;
21
+ /**
22
+ * Ids of the selected shapes in document z-order, always with whole groups (MS-6).
23
+ * Never in history: selecting adds no entry (REA-018).
24
+ */
25
+ readonly selection: readonly string[];
26
+ /** Whether taps toggle shapes and empty-canvas drags draw a selection rectangle (MS-1, MS-3). */
27
+ readonly selectionMode: boolean;
28
+ readonly tool: EditorTool;
29
+ /** The selected joint, never together with selected shapes. Not in history. */
30
+ readonly selectedJoint: string | null;
31
+ readonly naming: JointNaming | null;
32
+ /** Anchors highlighted while an anchor snap is active during a gesture (SN-3). Not in history. */
33
+ readonly snapHighlight: readonly Point[];
34
+ /** The measured size of the drawing area in screen pixels, or `null` before the first render; not in history. */
35
+ readonly stageArea: Size | null;
36
+ }
37
+ export interface EditorStoreOptions {
38
+ /** Maximum number of undo entries (default 100). */
39
+ readonly historyLimit?: number;
40
+ /** Initial grid visibility (default false). */
41
+ readonly showGrid?: boolean;
42
+ }
43
+ /**
44
+ * The editor's state with a snapshot history (spec 05 section 4). Only the committed
45
+ * document is recorded: a commit is one entry, previews and view changes are none.
46
+ */
47
+ export declare function createEditorStore(initial: DrawingDocument, options?: EditorStoreOptions): {
48
+ getState: () => EditorState;
49
+ getInitialState: () => EditorState;
50
+ subscribe: (listener: (state: EditorState, prevState: EditorState) => void) => () => void;
51
+ /** The committed document. */
52
+ getDocument: () => DrawingDocument;
53
+ /** Calls `listener` whenever the undo or redo stacks change (for `canUndo`/`canRedo` in the UI). */
54
+ subscribeHistory: (listener: () => void) => () => void;
55
+ canUndo: () => boolean;
56
+ canRedo: () => boolean;
57
+ /**
58
+ * Commits `document` as one entry and ends any gesture; the same instance adds none.
59
+ * With `selection`, the selection becomes those shapes (and their groups) in the same update.
60
+ */
61
+ commit(document: DrawingDocument, selection?: readonly string[]): void;
62
+ /** Shows `document` during a gesture without committing it; `null` cancels the gesture. */
63
+ preview(document: DrawingDocument | null, snapHighlight?: readonly Point[]): void;
64
+ undo(): void;
65
+ redo(): void;
66
+ /** Replaces the document and clears the history, adding no entry. */
67
+ reset(document: DrawingDocument): void;
68
+ /** Selects the shape with `id` and the rest of its group, or clears the selection with `null` (Flutter `select`). */
69
+ select(id: string | null): void;
70
+ /** Adds the shape with `id` and its group to the selection, or removes them when it is selected (MS-1, MS-6). */
71
+ toggleSelected(id: string): void;
72
+ /** Adds the shapes with `ids`, and their groups, to the selection (MS-3). */
73
+ selectAll(ids: readonly string[]): void;
74
+ /** Switches the tool: a view change, never a history entry. An open name editor closes. */
75
+ setTool(tool: EditorTool): void;
76
+ /** Selects the joint with `id` (and no shapes), or clears the joint selection with `null`. */
77
+ selectJoint(id: string | null): void;
78
+ /** Opens (or with `null` closes) the joint name editor. */
79
+ setNaming(naming: JointNaming | null): void;
80
+ /** Enters or leaves selection mode; leaving it keeps the selection (MS-8). */
81
+ setSelectionMode(selectionMode: boolean): void;
82
+ /** Sets zoom and pan: a view change, never a history entry (REA-017). */
83
+ setZoom(zoom: ViewportZoom): void;
84
+ /** Returns to the fitted view: 1× with no pan (REA-004). */
85
+ fitToScreen(): void;
86
+ /** Records the size of the drawing area, to place new shapes at the visible center (PL-1). */
87
+ setStageArea(stageArea: Size): void;
88
+ setShowGrid(showGrid: boolean): void;
89
+ };
90
+ export type EditorStore = ReturnType<typeof createEditorStore>;
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createEditorStore = createEditorStore;
4
+ const core_1 = require("@crux-diagram/core");
5
+ const zundo_1 = require("zundo");
6
+ const vanilla_1 = require("zustand/vanilla");
7
+ const config_js_1 = require("./config.js");
8
+ /**
9
+ * The editor's state with a snapshot history (spec 05 section 4). Only the committed
10
+ * document is recorded: a commit is one entry, previews and view changes are none.
11
+ */
12
+ function createEditorStore(initial, options = {}) {
13
+ const store = (0, vanilla_1.createStore)()((0, zundo_1.temporal)(() => ({
14
+ document: initial,
15
+ preview: null,
16
+ view: { showGrid: options.showGrid ?? config_js_1.DEFAULT_EDITOR_CONFIG.showGrid, zoom: core_1.FITTED_ZOOM },
17
+ selection: [],
18
+ selectionMode: false,
19
+ tool: 'select',
20
+ selectedJoint: null,
21
+ naming: null,
22
+ snapHighlight: [],
23
+ stageArea: null,
24
+ }), {
25
+ limit: options.historyLimit ?? config_js_1.DEFAULT_EDITOR_CONFIG.historyLimit,
26
+ partialize: (state) => ({ document: state.document }),
27
+ // A set that keeps the same document instance (a preview or a view change) is not an entry.
28
+ equality: (past, current) => past.document === current.document,
29
+ }));
30
+ const history = () => store.temporal.getState();
31
+ const dropPreview = () => {
32
+ if (store.getState().preview)
33
+ store.setState({ preview: null, snapHighlight: [] });
34
+ };
35
+ const sameIds = (a, b) => a.length === b.length && a.every((id, i) => id === b[i]);
36
+ const setSelection = (selection) => {
37
+ if (!sameIds(selection, store.getState().selection)) {
38
+ store.setState({ selection, ...(selection.length > 0 ? { selectedJoint: null } : {}) });
39
+ }
40
+ };
41
+ // Flutter `_dropStaleSelection`: after the document changes, keep only the shapes that
42
+ // still exist, with their current groups.
43
+ const dropStaleSelection = () => {
44
+ const { document, selection } = store.getState();
45
+ const existing = new Set(document.shapes.map((s) => s.id));
46
+ setSelection((0, core_1.withGroupMates)(document, selection.filter((id) => existing.has(id))));
47
+ // A joint, or an open name editor, whose joint is gone (a new joint lives only in the preview).
48
+ const { preview, selectedJoint, naming } = store.getState();
49
+ const joints = new Set((preview ?? document).joints.map((j) => j.id));
50
+ if (selectedJoint && !joints.has(selectedJoint))
51
+ store.setState({ selectedJoint: null });
52
+ if (naming && !joints.has(naming.jointId))
53
+ store.setState({ naming: null });
54
+ };
55
+ return {
56
+ getState: store.getState,
57
+ getInitialState: store.getInitialState,
58
+ subscribe: store.subscribe,
59
+ /** The committed document. */
60
+ getDocument: () => store.getState().document,
61
+ /** Calls `listener` whenever the undo or redo stacks change (for `canUndo`/`canRedo` in the UI). */
62
+ subscribeHistory: (listener) => store.temporal.subscribe(listener),
63
+ canUndo: () => history().pastStates.length > 0,
64
+ canRedo: () => history().futureStates.length > 0,
65
+ /**
66
+ * Commits `document` as one entry and ends any gesture; the same instance adds none.
67
+ * With `selection`, the selection becomes those shapes (and their groups) in the same update.
68
+ */
69
+ commit(document, selection) {
70
+ // Resolve the selection first: an unknown id throws before anything is recorded.
71
+ const next = selection ? (0, core_1.withGroupMates)(document, selection) : null;
72
+ store.setState({ document, preview: null, snapHighlight: [] });
73
+ if (next)
74
+ setSelection(next);
75
+ else
76
+ dropStaleSelection();
77
+ },
78
+ /** Shows `document` during a gesture without committing it; `null` cancels the gesture. */
79
+ preview(document, snapHighlight = []) {
80
+ store.setState({ preview: document, snapHighlight: document ? snapHighlight : [] });
81
+ },
82
+ undo() {
83
+ dropPreview();
84
+ history().undo();
85
+ dropStaleSelection();
86
+ },
87
+ redo() {
88
+ dropPreview();
89
+ history().redo();
90
+ dropStaleSelection();
91
+ },
92
+ /** Replaces the document and clears the history, adding no entry. */
93
+ reset(document) {
94
+ store.setState({ document, preview: null });
95
+ history().clear();
96
+ dropStaleSelection();
97
+ },
98
+ /** Selects the shape with `id` and the rest of its group, or clears the selection with `null` (Flutter `select`). */
99
+ select(id) {
100
+ setSelection(id === null ? [] : (0, core_1.withGroupMates)(store.getState().document, [id]));
101
+ },
102
+ /** Adds the shape with `id` and its group to the selection, or removes them when it is selected (MS-1, MS-6). */
103
+ toggleSelected(id) {
104
+ const { document, selection } = store.getState();
105
+ const members = new Set((0, core_1.withGroupMates)(document, [id]));
106
+ const next = selection.includes(id)
107
+ ? selection.filter((s) => !members.has(s))
108
+ : (0, core_1.withGroupMates)(document, [...selection, ...members]);
109
+ setSelection(next);
110
+ },
111
+ /** Adds the shapes with `ids`, and their groups, to the selection (MS-3). */
112
+ selectAll(ids) {
113
+ const { document, selection } = store.getState();
114
+ setSelection((0, core_1.withGroupMates)(document, [...selection, ...ids]));
115
+ },
116
+ /** Switches the tool: a view change, never a history entry. An open name editor closes. */
117
+ setTool(tool) {
118
+ if (store.getState().tool !== tool)
119
+ store.setState({ tool, naming: null });
120
+ },
121
+ /** Selects the joint with `id` (and no shapes), or clears the joint selection with `null`. */
122
+ selectJoint(id) {
123
+ const state = store.getState();
124
+ if (id === null) {
125
+ if (state.selectedJoint !== null)
126
+ store.setState({ selectedJoint: null });
127
+ }
128
+ else {
129
+ store.setState({ selectedJoint: id, selection: [] });
130
+ }
131
+ },
132
+ /** Opens (or with `null` closes) the joint name editor. */
133
+ setNaming(naming) {
134
+ store.setState({ naming });
135
+ },
136
+ /** Enters or leaves selection mode; leaving it keeps the selection (MS-8). */
137
+ setSelectionMode(selectionMode) {
138
+ if (store.getState().selectionMode !== selectionMode)
139
+ store.setState({ selectionMode });
140
+ },
141
+ /** Sets zoom and pan: a view change, never a history entry (REA-017). */
142
+ setZoom(zoom) {
143
+ store.setState({ view: { ...store.getState().view, zoom } });
144
+ },
145
+ /** Returns to the fitted view: 1× with no pan (REA-004). */
146
+ fitToScreen() {
147
+ store.setState({ view: { ...store.getState().view, zoom: core_1.FITTED_ZOOM } });
148
+ },
149
+ /** Records the size of the drawing area, to place new shapes at the visible center (PL-1). */
150
+ setStageArea(stageArea) {
151
+ const current = store.getState().stageArea;
152
+ if (!current || current.width !== stageArea.width || current.height !== stageArea.height)
153
+ store.setState({ stageArea });
154
+ },
155
+ setShowGrid(showGrid) {
156
+ store.setState({ view: { ...store.getState().view, showGrid } });
157
+ },
158
+ };
159
+ }
@@ -0,0 +1,34 @@
1
+ import { type DrawingEditorHandle, type EditorProviderProps } from './editor-context.js';
2
+ export type DrawingEditorProps = EditorProviderProps & {
3
+ /**
4
+ * Shows the document without selection, dragging or keyboard shortcuts (REA-005).
5
+ * Changes from the parent's `value` and the imperative handle still apply.
6
+ */
7
+ readOnly?: boolean;
8
+ /** Alternative description for screen readers (REA-052); a summary of the drawing by default. */
9
+ alt?: string;
10
+ };
11
+ /**
12
+ * Controlled drawing editor (REA-002). Click or drag shapes to select and move them;
13
+ * while the editor has the focus, `Delete`/`Backspace` delete, `Ctrl/Cmd+Z` undoes,
14
+ * `Ctrl/Cmd+Shift+Z` redoes, `Ctrl/Cmd+D` duplicates and the arrow keys move the
15
+ * selection by 1 (`Shift`: 10) (REA-010 to REA-018).
16
+ */
17
+ export declare const DrawingEditor: import("react").ForwardRefExoticComponent<EditorProviderProps & {
18
+ /**
19
+ * Shows the document without selection, dragging or keyboard shortcuts (REA-005).
20
+ * Changes from the parent's `value` and the imperative handle still apply.
21
+ */
22
+ readOnly?: boolean;
23
+ /** Alternative description for screen readers (REA-052); a summary of the drawing by default. */
24
+ alt?: string;
25
+ } & import("react").RefAttributes<DrawingEditorHandle>>;
26
+ /**
27
+ * The editor's stage: the gesture preview while there is one, else the document, with
28
+ * the selection drawn in the `editor-ui` layer. Pointer gestures and shortcuts drive the
29
+ * enclosing editor's store.
30
+ */
31
+ export declare function EditorCanvas({ readOnly, alt }: {
32
+ readOnly?: boolean;
33
+ alt?: string;
34
+ }): import("react").JSX.Element;
@@ -0,0 +1,285 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { anchorPositionOf, anchorsOf, boundsOfShapes, clampZoom, DEFAULT_JOINT_STYLE, handleLocalPosition, handlesFor, visibleGridStep, } from '@crux-diagram/core';
4
+ import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
+ import { Circle, Group, Layer, Line, Rect } from 'react-konva';
6
+ import { useStore } from 'zustand';
7
+ import { EditorProvider, useEditor, useEditorConfig } from './editor-context.js';
8
+ import { beginDrag, beginLabelDrag, cancelDrag, endDrag, HANDLE_VISUAL_RADIUS, labelAt, ROTATION_STEM_LENGTH, tap, TAP_SLOP, updateDrag, } from './interaction/gestures.js';
9
+ import { NameEditor } from './NameEditor.js';
10
+ import { ANCHOR_VISUAL_RADIUS, beginRename, cancelNaming, confirmNaming, jointToolTap } from './interaction/joints.js';
11
+ import { commandForKey, isTextEntry, runCommand } from './interaction/keyboard.js';
12
+ import { panBy, wheelZoom } from './interaction/viewport.js';
13
+ import { DrawingStage } from './render/DrawingStage.js';
14
+ import { useFontsReady, useLabelMeasurer } from './render/fonts.js';
15
+ import { placeJoints } from './render/scene.js';
16
+ /** Longest time between the two taps of a double tap on a label, in milliseconds (ZM-4). */
17
+ const DOUBLE_TAP_TIMEOUT = 300;
18
+ /**
19
+ * Controlled drawing editor (REA-002). Click or drag shapes to select and move them;
20
+ * while the editor has the focus, `Delete`/`Backspace` delete, `Ctrl/Cmd+Z` undoes,
21
+ * `Ctrl/Cmd+Shift+Z` redoes, `Ctrl/Cmd+D` duplicates and the arrow keys move the
22
+ * selection by 1 (`Shift`: 10) (REA-010 to REA-018).
23
+ */
24
+ export const DrawingEditor = forwardRef(function DrawingEditor({ readOnly, alt, children, ...props }, ref) {
25
+ return (_jsx(EditorProvider, { ref: ref, ...props, children: children === undefined ? (_jsx(EditorCanvas, { readOnly: readOnly, alt: alt })) : (_jsxs("div", { style: { display: 'flex', flexDirection: 'column', width: '100%', height: '100%' }, children: [children, _jsx("div", { style: { flex: 1, minHeight: 0, position: 'relative' }, children: _jsx(EditorCanvas, { readOnly: readOnly, alt: alt }) })] })) }));
26
+ });
27
+ /** Color of the selection outline and the selection rectangle. */
28
+ const SELECTION_COLOR = '#1e88e5';
29
+ /** Color of the ring on the anchor a shape is snapping onto (SN-3). */
30
+ const SNAP_COLOR = '#ff9800';
31
+ /**
32
+ * The editor's stage: the gesture preview while there is one, else the document, with
33
+ * the selection drawn in the `editor-ui` layer. Pointer gestures and shortcuts drive the
34
+ * enclosing editor's store.
35
+ */
36
+ export function EditorCanvas({ readOnly = false, alt }) {
37
+ const editor = useEditor();
38
+ const config = useEditorConfig();
39
+ const document = useStore(editor, (state) => state.preview ?? state.document);
40
+ const zoom = useStore(editor, (state) => state.view.zoom);
41
+ const tool = useStore(editor, (state) => state.tool);
42
+ const naming = useStore(editor, (state) => state.naming);
43
+ const selectedJoint = useStore(editor, (state) => state.selectedJoint);
44
+ const snapHighlight = useStore(editor, (state) => state.snapHighlight);
45
+ const selection = useStore(editor, (state) => state.selection);
46
+ const [marquee, setMarquee] = useState(null);
47
+ const focusable = useRef(null);
48
+ const session = useRef(null);
49
+ const spaceDown = useRef(false);
50
+ const lastLabelTap = useRef(null);
51
+ const fontsReady = useFontsReady();
52
+ const measurer = useLabelMeasurer();
53
+ // The labels as drawn, to hit-test them; before the fonts load none are drawn.
54
+ const labelRects = useCallback(() => {
55
+ if (!fontsReady)
56
+ return [];
57
+ return placeJoints(editor.getDocument(), DEFAULT_JOINT_STYLE, measurer()).map((p) => ({ jointId: p.joint.id, rect: p.labelRect }));
58
+ }, [editor, fontsReady, measurer]);
59
+ // A pointer still down when the editor unmounts, or turns read-only, ends with no change.
60
+ const endSession = useCallback(() => {
61
+ const current = session.current;
62
+ if (!current)
63
+ return;
64
+ session.current = null;
65
+ current.dispose();
66
+ if (current.gesture)
67
+ cancelDrag(editor, current.gesture);
68
+ setMarquee(null);
69
+ }, [editor]);
70
+ useEffect(() => endSession, [endSession]);
71
+ useEffect(() => {
72
+ if (readOnly)
73
+ endSession();
74
+ }, [readOnly, endSession]);
75
+ const onPointerDown = (event) => {
76
+ const evt = event.evt;
77
+ if (readOnly || evt.button > 0)
78
+ return;
79
+ // The same pointer pressed again means its release was lost: start over. Another
80
+ // pointer while one is down is ignored (multi-touch is a zoom gesture).
81
+ if (session.current?.pointerId === evt.pointerId)
82
+ endSession();
83
+ if (session.current)
84
+ return;
85
+ const stage = event.target.getStage();
86
+ const downCanvas = stage?.getRelativePointerPosition();
87
+ if (!stage || !downCanvas)
88
+ return;
89
+ focusable.current?.focus({ preventScroll: true });
90
+ const { gridSize, gridMajorEvery, anchorSnapThreshold } = config;
91
+ const grid = {
92
+ gridSize,
93
+ // The threshold is in screen pixels (REA-026); gestures work in canvas units.
94
+ anchorSnapDistance: anchorSnapThreshold === null ? null : anchorSnapThreshold / stage.scaleX(),
95
+ visibleStep: gridSize !== null && editor.getState().view.showGrid
96
+ ? visibleGridStep({ gridSize, majorEvery: gridMajorEvery, scale: stage.scaleX() })
97
+ : null,
98
+ };
99
+ const handles = {
100
+ scale: stage.scaleX(),
101
+ rotationSnap: { step: config.rotationSnapStep, tolerance: config.rotationSnapTolerance },
102
+ labels: labelRects(),
103
+ };
104
+ const area = { width: stage.width(), height: stage.height() };
105
+ const shownZoom = () => clampZoom(editor.getState().view.zoom, editor.getDocument().canvas, area);
106
+ const canvasPoint = (e) => {
107
+ stage.setPointersPositions(e);
108
+ return stage.getRelativePointerPosition() ?? downCanvas;
109
+ };
110
+ const onMove = (e) => {
111
+ const current = session.current;
112
+ if (!current || e.pointerId !== current.pointerId)
113
+ return;
114
+ if (!current.pan && !current.gesture) {
115
+ if (Math.hypot(e.clientX - current.downScreen.x, e.clientY - current.downScreen.y) < TAP_SLOP)
116
+ return;
117
+ // The joint tool never moves, resizes or rotates shapes (JT-1).
118
+ // Labels can be dragged in any tool (REA-022).
119
+ current.gesture =
120
+ editor.getState().tool === 'joint'
121
+ ? (beginLabelDrag(editor, current.downCanvas, handles.labels ?? []) ?? { kind: 'none' })
122
+ : beginDrag(editor, current.downCanvas, grid, handles);
123
+ // A drag that grabs nothing pans when zoomed in (REA-016); in selection mode it is a marquee.
124
+ if (current.gesture.kind === 'none' && editor.getState().view.zoom.zoom > 1)
125
+ current.pan = shownZoom();
126
+ }
127
+ if (current.pan) {
128
+ const delta = { dx: e.clientX - current.downScreen.x, dy: e.clientY - current.downScreen.y };
129
+ editor.setZoom(panBy(current.pan, delta, editor.getDocument().canvas, area));
130
+ return;
131
+ }
132
+ if (!current.gesture)
133
+ return;
134
+ current.gesture = updateDrag(editor, current.gesture, canvasPoint(e));
135
+ setMarquee(current.gesture.kind === 'marquee' ? current.gesture.rect : null);
136
+ };
137
+ const onUp = (e) => {
138
+ const current = session.current;
139
+ if (!current || e.pointerId !== current.pointerId)
140
+ return;
141
+ session.current = null;
142
+ current.dispose();
143
+ if (current.gesture)
144
+ endDrag(editor, current.gesture);
145
+ else if (!current.pan) {
146
+ if (editor.getState().tool === 'joint') {
147
+ jointToolTap(editor, current.downCanvas, {
148
+ scale: handles.scale,
149
+ namePrefix: config.jointNamePrefix,
150
+ nameMaxLength: config.jointNameMaxLength,
151
+ labels: handles.labels,
152
+ });
153
+ }
154
+ else
155
+ tap(editor, current.downCanvas, handles);
156
+ // The first tap of a double tap acts at once; the second, on the same label, renames (NM-2, ZM-4).
157
+ const labeled = labelAt(handles.labels ?? [], current.downCanvas);
158
+ const now = performance.now();
159
+ const last = lastLabelTap.current;
160
+ if (labeled && last?.jointId === labeled && now - last.time <= DOUBLE_TAP_TIMEOUT) {
161
+ lastLabelTap.current = null;
162
+ beginRename(editor, labeled);
163
+ }
164
+ else
165
+ lastLabelTap.current = labeled ? { jointId: labeled, time: now } : null;
166
+ }
167
+ setMarquee(null);
168
+ };
169
+ const onCancel = (e) => {
170
+ if (session.current && e.pointerId === session.current.pointerId)
171
+ endSession();
172
+ };
173
+ window.addEventListener('pointermove', onMove);
174
+ window.addEventListener('pointerup', onUp);
175
+ window.addEventListener('pointercancel', onCancel);
176
+ session.current = {
177
+ pointerId: evt.pointerId,
178
+ downScreen: { x: evt.clientX, y: evt.clientY },
179
+ downCanvas,
180
+ gesture: null,
181
+ // With the space bar down the drag pans from the start, over shapes too (REA-016).
182
+ pan: spaceDown.current ? shownZoom() : null,
183
+ dispose: () => {
184
+ window.removeEventListener('pointermove', onMove);
185
+ window.removeEventListener('pointerup', onUp);
186
+ window.removeEventListener('pointercancel', onCancel);
187
+ },
188
+ };
189
+ };
190
+ const onWheel = (event) => {
191
+ const stage = event.target.getStage();
192
+ const focal = stage?.getPointerPosition();
193
+ if (!stage || !focal)
194
+ return;
195
+ event.evt.preventDefault();
196
+ const { deltaY, deltaMode, ctrlKey } = event.evt;
197
+ const area = { width: stage.width(), height: stage.height() };
198
+ editor.setZoom(wheelZoom(editor.getState().view.zoom, { deltaY, deltaMode, ctrlKey, focal }, editor.getDocument().canvas, area));
199
+ };
200
+ // The space bar pans only while the container itself has the focus, so it still activates buttons.
201
+ const onKeyUp = (event) => {
202
+ if (event.key === ' ')
203
+ spaceDown.current = false;
204
+ };
205
+ const onKeyDown = (event) => {
206
+ if (readOnly || isTextEntry(event.target))
207
+ return;
208
+ if (event.key === ' ' && event.target === event.currentTarget) {
209
+ event.preventDefault();
210
+ spaceDown.current = true;
211
+ return;
212
+ }
213
+ const command = commandForKey(event);
214
+ if (!command)
215
+ return;
216
+ event.preventDefault();
217
+ runCommand(editor, command);
218
+ };
219
+ const selected = useMemo(() => {
220
+ if (readOnly || selection.length === 0)
221
+ return null;
222
+ const ids = new Set(selection);
223
+ const shapes = document.shapes.filter((s) => ids.has(s.id));
224
+ return shapes.length > 0 ? shapes : null;
225
+ }, [readOnly, selection, document]);
226
+ return (_jsxs("div", { ref: focusable, tabIndex: 0, onKeyDown: onKeyDown, onKeyUp: onKeyUp, onBlur: () => void (spaceDown.current = false), style: { position: 'relative', width: '100%', height: '100%' }, children: [_jsx(DrawingStage, { document: document, listening: true, zoom: zoom, onWheel: onWheel, onPointerDown: onPointerDown, onAreaChange: editor.setStageArea, alt: alt, selection: readOnly ? undefined : selection, overlay: (viewport) => naming &&
227
+ !readOnly && (_jsx(NameEditor
228
+ // A new editor per name editing session, so the field starts from the joint's name.
229
+ , { document: document, naming: naming, viewport: viewport, suggestions: config.jointNameSuggestions, onConfirm: (name) => confirmNaming(editor, name, config.jointNameMaxLength), onCancel: () => cancelNaming(editor) }, naming.jointId)), children: (scale) => (_jsxs(Layer, { name: "editor-ui", listening: false, children: [selected && _jsx(SelectionOverlay, { shapes: selected, scale: scale }), !readOnly && tool === 'joint' && _jsx(AnchorDots, { document: document, scale: scale }), snapHighlight.map((at) => (_jsx(Circle, { name: "snap-highlight", x: at.x, y: at.y, radius: (ANCHOR_VISUAL_RADIUS + 4) / scale, stroke: SNAP_COLOR, strokeWidth: 2.5, strokeScaleEnabled: false }, `${at.x},${at.y}`))), selectedJoint && _jsx(JointRing, { document: document, jointId: selectedJoint, scale: scale }), marquee && (_jsx(Rect, { name: "selection-marquee", x: marquee.left, y: marquee.top, width: marquee.width, height: marquee.height, stroke: SELECTION_COLOR, strokeWidth: 1, strokeScaleEnabled: false, dash: [4, 4], fill: "rgba(30, 136, 229, 0.08)" }))] })) }), zoom.zoom > FIT_BUTTON_MIN_ZOOM && _jsx(ZoomControls, { zoom: zoom.zoom, onFit: editor.fitToScreen })] }));
230
+ }
231
+ /** The fit button and the percentage show while the zoom is above 1× (ZM-1). */
232
+ const FIT_BUTTON_MIN_ZOOM = 1.005;
233
+ /** Fit-to-screen button with the zoom percentage, bottom right of the drawing area (ZM-1, ZM-2). */
234
+ function ZoomControls({ zoom, onFit }) {
235
+ return (_jsxs("div", { style: { position: 'absolute', right: 16, bottom: 16, display: 'flex', alignItems: 'center', gap: 8, font: '12px sans-serif' }, children: [_jsx("span", { children: `${Math.round(zoom * 100)}%` }), _jsx("button", { type: "button", onClick: onFit, children: "Fit to screen" })] }));
236
+ }
237
+ /** Anchor dots of every shape for the joint tool; filled where a joint exists (JT-1). Sizes are screen pixels. */
238
+ function AnchorDots({ document, scale }) {
239
+ const occupied = new Set(document.joints.map((j) => `${j.shapeId}/${j.anchorId}`));
240
+ return (_jsx(_Fragment, { children: document.shapes.flatMap((shape) => anchorsOf(shape).map((anchor) => {
241
+ const taken = occupied.has(`${shape.id}/${anchor.id}`);
242
+ return (_jsx(Circle, { name: taken ? 'anchor-dot anchor-occupied' : 'anchor-dot', x: anchor.position.x, y: anchor.position.y, radius: ANCHOR_VISUAL_RADIUS / scale, fill: taken ? SELECTION_COLOR : '#ffffff', stroke: SELECTION_COLOR, strokeWidth: 1.5, strokeScaleEnabled: false }, `${shape.id}/${anchor.id}`));
243
+ })) }));
244
+ }
245
+ /** The ring around the anchor of the selected joint (AW-7). */
246
+ function JointRing({ document, jointId, scale }) {
247
+ const joint = document.joints.find((j) => j.id === jointId);
248
+ const shape = joint && document.shapes.find((s) => s.id === joint.shapeId);
249
+ const anchor = shape && joint ? anchorPositionOf(shape, joint.anchorId) : null;
250
+ if (!anchor)
251
+ return null;
252
+ return (_jsx(Circle, { name: "joint-selection-ring", x: anchor.x, y: anchor.y, radius: (ANCHOR_VISUAL_RADIUS + 4) / scale, stroke: SELECTION_COLOR, strokeWidth: 2, strokeScaleEnabled: false }));
253
+ }
254
+ const toDegrees = (radians) => (radians * 180) / Math.PI;
255
+ /**
256
+ * The selection outline and, for a single shape, its resize handles and rotation handle
257
+ * with stem (FR-7). A lone shape's outline follows its rotation; several shapes get the
258
+ * outline of their bounds and no handles (MS-5). Sizes are screen pixels, so they are
259
+ * divided by the view `scale`.
260
+ */
261
+ function SelectionOverlay({ shapes, scale }) {
262
+ const single = shapes.length === 1 ? shapes[0] : null;
263
+ const bounds = single ? null : boundsOfShapes(shapes);
264
+ const center = single
265
+ ? single.center
266
+ : {
267
+ x: bounds.left + bounds.width / 2,
268
+ y: bounds.top + bounds.height / 2,
269
+ };
270
+ const width = single ? single.size.width : bounds.width;
271
+ const height = single ? single.size.height : bounds.height;
272
+ const rotation = single ? toDegrees(single.rotation) : 0;
273
+ const stem = ROTATION_STEM_LENGTH / scale;
274
+ const handle = {
275
+ radius: HANDLE_VISUAL_RADIUS / scale,
276
+ fill: '#ffffff',
277
+ stroke: SELECTION_COLOR,
278
+ strokeWidth: 1.5,
279
+ strokeScaleEnabled: false,
280
+ };
281
+ return (_jsxs(_Fragment, { children: [_jsx(Rect, { name: "selection-outline", x: center.x, y: center.y, offsetX: width / 2, offsetY: height / 2, rotation: rotation, width: width, height: height, stroke: SELECTION_COLOR, strokeWidth: 1.5, strokeScaleEnabled: false }), single && (_jsxs(Group, { name: "selection-handles", x: center.x, y: center.y, rotation: rotation, children: [_jsx(Line, { name: "rotation-stem", points: [0, -height / 2, 0, -height / 2 - stem], stroke: SELECTION_COLOR, strokeWidth: 1.5, strokeScaleEnabled: false }), _jsx(Circle, { name: "rotation-handle", x: 0, y: -height / 2 - stem, ...handle }), handlesFor(single.type).map((h) => {
282
+ const at = handleLocalPosition(h, single.size);
283
+ return _jsx(Circle, { name: `resize-handle handle-${h}`, x: at.x, y: at.y, ...handle }, h);
284
+ })] }))] }));
285
+ }