@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,14 @@
1
+ import type { DrawingDocument, JointStyle } from '@crux-diagram/core';
2
+ export interface DrawingViewerProps {
3
+ readonly document: DrawingDocument;
4
+ /** Look of leader arrows and labels; the reference style (spec 02, section 12) by default. */
5
+ readonly jointStyle?: JointStyle;
6
+ /** Alternative description for screen readers (REA-052); a summary of the drawing by default. */
7
+ readonly alt?: string;
8
+ }
9
+ /**
10
+ * Read-only view of a drawing (REA-001), like Flutter's `DrawingView`: white canvas,
11
+ * shapes and joints, fitted and centered in its parent, which must have a size. It
12
+ * ignores gestures.
13
+ */
14
+ export declare function DrawingViewer({ document, jointStyle, alt }: DrawingViewerProps): import("react").JSX.Element;
@@ -0,0 +1,11 @@
1
+ 'use client';
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { DrawingStage } from './render/DrawingStage.js';
4
+ /**
5
+ * Read-only view of a drawing (REA-001), like Flutter's `DrawingView`: white canvas,
6
+ * shapes and joints, fitted and centered in its parent, which must have a size. It
7
+ * ignores gestures.
8
+ */
9
+ export function DrawingViewer({ document, jointStyle, alt }) {
10
+ return _jsx(DrawingStage, { document: document, jointStyle: jointStyle, alt: alt, listening: false });
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { CSSProperties } from 'react';
2
+ /**
3
+ * Joint display bar (REA-024): label size as a single choice, and show/hide. With a joint
4
+ * selected it adds Rename and Delete. Render it inside a `DrawingEditor`.
5
+ */
6
+ export declare function JointDisplayBar({ style }: {
7
+ style?: CSSProperties;
8
+ }): import("react").JSX.Element;
@@ -0,0 +1,19 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { JOINT_LABEL_SIZES } from '@crux-diagram/core';
4
+ import { useStore } from 'zustand';
5
+ import { useEditor, useEditorLabels } from './editor-context.js';
6
+ import { beginRename, setJointLabelSize, setJointsVisible } from './interaction/joints.js';
7
+ import { runCommand } from './interaction/keyboard.js';
8
+ import { ControlButton, controlRowStyle } from './controls.js';
9
+ /**
10
+ * Joint display bar (REA-024): label size as a single choice, and show/hide. With a joint
11
+ * selected it adds Rename and Delete. Render it inside a `DrawingEditor`.
12
+ */
13
+ export function JointDisplayBar({ style }) {
14
+ const editor = useEditor();
15
+ const labels = useEditorLabels();
16
+ const { labelSize, visible } = useStore(editor, (state) => state.document.jointDisplay);
17
+ const selectedJoint = useStore(editor, (state) => state.selectedJoint);
18
+ return (_jsxs("div", { role: "toolbar", "aria-label": "Joint display", style: { ...controlRowStyle, ...style }, children: [JOINT_LABEL_SIZES.map((size) => (_jsx(ControlButton, { label: labels[size], pressed: labelSize === size, onClick: () => setJointLabelSize(editor, size) }, size))), _jsx(ControlButton, { label: visible ? labels.hide : labels.show, title: visible ? labels.hideJoints : labels.showJoints, pressed: !visible, onClick: () => setJointsVisible(editor, !visible) }), selectedJoint && (_jsxs(_Fragment, { children: [_jsx(ControlButton, { label: labels.rename, onClick: () => beginRename(editor, selectedJoint) }), _jsx(ControlButton, { label: labels.delete, onClick: () => runCommand(editor, { type: 'delete' }) })] }))] }));
19
+ }
@@ -0,0 +1,15 @@
1
+ import { type CanvasViewport, type DrawingDocument } from '@crux-diagram/core';
2
+ import type { JointNaming } from './store.js';
3
+ export interface NameEditorProps {
4
+ /** The document that shows the joint (a new joint is only in the preview). */
5
+ readonly document: DrawingDocument;
6
+ readonly naming: JointNaming;
7
+ readonly viewport: CanvasViewport;
8
+ /** Names offered as buttons (config `jointNameSuggestions`). */
9
+ readonly suggestions: readonly string[];
10
+ readonly onConfirm: (name: string) => void;
11
+ readonly onCancel: () => void;
12
+ }
13
+ /** Names from `suggestions` that no other joint uses; the joint being named does not count (NS-4). */
14
+ export declare function freeSuggestions(document: DrawingDocument, jointId: string, suggestions: readonly string[]): string[];
15
+ export declare function NameEditor({ document, naming, viewport, suggestions, onConfirm, onCancel }: NameEditorProps): import("react").JSX.Element | null;
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The joint name editor: an HTML input over the label, in the label font (REA-021, REA-031).
3
+ import { anchorPositionOf, DEFAULT_JOINT_STYLE, labelFontSize, toScreen } from '@crux-diagram/core';
4
+ import { useState } from 'react';
5
+ import { LABEL_FONT_FAMILY } from './render/scene.js';
6
+ /** Names from `suggestions` that no other joint uses; the joint being named does not count (NS-4). */
7
+ export function freeSuggestions(document, jointId, suggestions) {
8
+ const used = new Set(document.joints.filter((j) => j.id !== jointId).map((j) => j.name));
9
+ return suggestions.filter((name) => !used.has(name));
10
+ }
11
+ export function NameEditor({ document, naming, viewport, suggestions, onConfirm, onCancel }) {
12
+ const joint = document.joints.find((j) => j.id === naming.jointId);
13
+ const shape = joint && document.shapes.find((s) => s.id === joint.shapeId);
14
+ const anchor = shape && joint ? anchorPositionOf(shape, joint.anchorId) : null;
15
+ const [text, setText] = useState(joint?.name ?? '');
16
+ if (!joint || !anchor)
17
+ return null;
18
+ const center = toScreen(viewport, { x: anchor.x + joint.labelOffset.dx, y: anchor.y + joint.labelOffset.dy });
19
+ const fontSize = labelFontSize(DEFAULT_JOINT_STYLE, document.jointDisplay.labelSize) * viewport.scale;
20
+ const free = freeSuggestions(document, joint.id, suggestions);
21
+ const onKeyDown = (event) => {
22
+ // The editor's own keys: they must not reach the editor's shortcuts.
23
+ event.stopPropagation();
24
+ if (event.key === 'Enter')
25
+ onConfirm(text);
26
+ else if (event.key === 'Escape')
27
+ onCancel();
28
+ };
29
+ return (_jsxs("div", { style: { position: 'absolute', left: center.x, top: center.y, transform: 'translate(-50%, -50%)', textAlign: 'center' }, children: [_jsx("input", { type: "text", "aria-label": "Joint name", autoFocus: true, value: text, onChange: (event) => setText(event.target.value), onFocus: (event) => event.target.select(), onBlur: () => onConfirm(text), onKeyDown: onKeyDown, style: { width: '8em', textAlign: 'center', fontFamily: `${LABEL_FONT_FAMILY}, sans-serif`, fontWeight: 'bold', fontSize } }), free.length > 0 && (_jsx("div", { style: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: 4, marginTop: 4 }, children: free.map((name) => (_jsx("button", { type: "button",
30
+ // Keep the focus in the input so that the click, not a blur, confirms.
31
+ onMouseDown: (event) => event.preventDefault(), onClick: () => onConfirm(name), children: name }, name))) }))] }));
32
+ }
@@ -0,0 +1,8 @@
1
+ import type { CSSProperties } from 'react';
2
+ /**
3
+ * Ready-made toolbar (REA-053): the selection bar above the create bar. Render it inside a
4
+ * `DrawingEditor`, as a child.
5
+ */
6
+ export declare function Toolbar({ style }: {
7
+ style?: CSSProperties;
8
+ }): import("react").JSX.Element;
@@ -0,0 +1,31 @@
1
+ 'use client';
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useStore } from 'zustand';
4
+ import { ControlButton, controlRowStyle } from './controls.js';
5
+ import { useEditor, useEditorConfig, useEditorLabels } from './editor-context.js';
6
+ import { useHistoryAvailability } from './hooks.js';
7
+ import { runCommand, wholeGroup } from './interaction/keyboard.js';
8
+ import { addPaletteShape, visibleCenterOf } from './interaction/palette.js';
9
+ import { JointDisplayBar } from './JointDisplayBar.js';
10
+ /** Height of both rows, so selecting never moves a button or resizes the drawing area (TB-2). */
11
+ const ROW_HEIGHT = 56;
12
+ /**
13
+ * Ready-made toolbar (REA-053): the selection bar above the create bar. Render it inside a
14
+ * `DrawingEditor`, as a child.
15
+ */
16
+ export function Toolbar({ style }) {
17
+ const editor = useEditor();
18
+ const config = useEditorConfig();
19
+ const labels = useEditorLabels();
20
+ const tool = useStore(editor, (state) => state.tool);
21
+ const showGrid = useStore(editor, (state) => state.view.showGrid);
22
+ const selectionMode = useStore(editor, (state) => state.selectionMode);
23
+ const selection = useStore(editor, (state) => state.selection);
24
+ const { canUndo, canRedo } = useHistoryAvailability(editor);
25
+ const document = useStore(editor, (state) => state.document);
26
+ const add = (type) => addPaletteShape(editor, type, { center: visibleCenterOf(editor), gridSize: config.gridSize, style: config.shapeStyle });
27
+ // Rotate 90° only turns a single shape that is not in a group (MS-5).
28
+ const single = selection.length === 1 && !document.groups.some((g) => g.shapeIds.includes(selection[0]));
29
+ const rowStyle = { ...controlRowStyle, minHeight: ROW_HEIGHT, boxSizing: 'border-box' };
30
+ return (_jsxs("div", { style: { display: 'flex', flexDirection: 'column', ...style }, children: [tool === 'joint' ? (_jsx(JointDisplayBar, { style: rowStyle })) : (_jsxs("div", { role: "toolbar", "aria-label": labels.selectionBar, style: rowStyle, children: [_jsx(ControlButton, { label: labels.select, title: labels.selectMode, pressed: selectionMode, onClick: () => editor.setSelectionMode(!selectionMode) }), selection.length > 0 && (_jsxs(_Fragment, { children: [wholeGroup(document, selection) ? (_jsx(ControlButton, { label: labels.ungroup, onClick: () => runCommand(editor, { type: 'ungroup' }) })) : (selection.length > 1 && _jsx(ControlButton, { label: labels.group, onClick: () => runCommand(editor, { type: 'group' }) })), single && _jsx(ControlButton, { label: labels.rotate, title: labels.rotate90, onClick: () => runCommand(editor, { type: 'rotate90' }) }), _jsx(ControlButton, { label: labels.duplicate, onClick: () => runCommand(editor, { type: 'duplicate' }) }), _jsx(ControlButton, { label: labels.front, title: labels.bringToFront, onClick: () => runCommand(editor, { type: 'front' }) }), _jsx(ControlButton, { label: labels.back, title: labels.sendToBack, onClick: () => runCommand(editor, { type: 'back' }) }), _jsx(ControlButton, { label: labels.delete, onClick: () => runCommand(editor, { type: 'delete' }) })] }))] })), _jsxs("div", { role: "toolbar", "aria-label": labels.createBar, style: rowStyle, children: [_jsx(ControlButton, { label: labels.square, onClick: () => add('square') }), _jsx(ControlButton, { label: labels.rectangle, onClick: () => add('rectangle') }), _jsx(ControlButton, { label: labels.circle, onClick: () => add('circle') }), _jsx(ControlButton, { label: labels.joint, title: labels.jointTool, pressed: tool === 'joint', onClick: () => editor.setTool(tool === 'joint' ? 'select' : 'joint') }), config.gridSize !== null && (_jsx(ControlButton, { label: labels.grid, title: showGrid ? labels.hideGrid : labels.showGrid, pressed: showGrid, onClick: () => editor.setShowGrid(!showGrid) })), _jsx(ControlButton, { label: labels.undo, disabled: !canUndo, onClick: () => editor.undo() }), _jsx(ControlButton, { label: labels.redo, disabled: !canRedo, onClick: () => editor.redo() })] })] }));
31
+ }
@@ -0,0 +1,33 @@
1
+ import type { DrawingDocument } from '@crux-diagram/core';
2
+ import { type CSSProperties } from 'react';
3
+ /** One saved version (REA-071). */
4
+ export interface VersionEntry {
5
+ readonly id: string;
6
+ readonly version: number;
7
+ /** ISO 8601. */
8
+ readonly savedAt: string;
9
+ readonly author?: string;
10
+ readonly label?: string;
11
+ readonly document: DrawingDocument;
12
+ }
13
+ export interface VersionHistoryLabels {
14
+ readonly restore: string;
15
+ readonly current: string;
16
+ readonly empty: string;
17
+ readonly selectPrompt: string;
18
+ }
19
+ export declare const DEFAULT_VERSION_HISTORY_LABELS: VersionHistoryLabels;
20
+ export interface VersionHistoryProps {
21
+ readonly versions: readonly VersionEntry[];
22
+ /** Entries whose `version` equals this one are marked as current. */
23
+ readonly currentVersion?: number;
24
+ /** Called with the chosen entry; the component changes nothing else (REA-074). */
25
+ readonly onRestore: (entry: VersionEntry) => void;
26
+ readonly labels?: Partial<VersionHistoryLabels>;
27
+ readonly style?: CSSProperties;
28
+ }
29
+ /**
30
+ * Controlled version history (REA-070): lists, previews and asks to restore; it reads and
31
+ * stores nothing. Works on its own, outside a `DrawingEditor`.
32
+ */
33
+ export declare function VersionHistory({ versions, currentVersion, onRestore, labels, style }: VersionHistoryProps): import("react").JSX.Element;
@@ -0,0 +1,45 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useMemo, useState } from 'react';
4
+ import { DrawingViewer } from './DrawingViewer.js';
5
+ import { controlRowStyle } from './controls.js';
6
+ export const DEFAULT_VERSION_HISTORY_LABELS = {
7
+ restore: 'Restore',
8
+ current: 'Current',
9
+ empty: 'No versions yet',
10
+ selectPrompt: 'Select a version to preview',
11
+ };
12
+ function time(savedAt) {
13
+ const ms = Date.parse(savedAt);
14
+ return Number.isNaN(ms) ? Number.NEGATIVE_INFINITY : ms;
15
+ }
16
+ /** Newest version first; ties by `savedAt` (invalid last), then input order (REA-072). */
17
+ function ordered(versions) {
18
+ return versions
19
+ .map((entry, index) => ({ entry, index, at: time(entry.savedAt) }))
20
+ .sort((a, b) => b.entry.version - a.entry.version || (a.at === b.at ? 0 : b.at > a.at ? 1 : -1) || a.index - b.index)
21
+ .map((row) => row.entry);
22
+ }
23
+ /** A fixed UTC format, so server and client render the same text. */
24
+ function formatDate(savedAt) {
25
+ const ms = Date.parse(savedAt);
26
+ return Number.isNaN(ms) ? savedAt : `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
27
+ }
28
+ /**
29
+ * Controlled version history (REA-070): lists, previews and asks to restore; it reads and
30
+ * stores nothing. Works on its own, outside a `DrawingEditor`.
31
+ */
32
+ export function VersionHistory({ versions, currentVersion, onRestore, labels, style }) {
33
+ const text = { ...DEFAULT_VERSION_HISTORY_LABELS, ...labels };
34
+ const list = useMemo(() => ordered(versions), [versions]);
35
+ const [selectedId, setSelectedId] = useState(null);
36
+ const selected = list.find((entry) => entry.id === selectedId) ?? null;
37
+ useEffect(() => {
38
+ if (selectedId !== null && selected === null)
39
+ setSelectedId(null);
40
+ }, [selectedId, selected]);
41
+ if (list.length === 0)
42
+ return _jsx("div", { style: { font: '12px sans-serif', padding: 8, ...style }, children: text.empty });
43
+ const isCurrent = (entry) => entry.version === currentVersion;
44
+ return (_jsxs("div", { style: { display: 'flex', flexDirection: 'column', gap: 8, font: '12px sans-serif', ...style }, children: [_jsx("ul", { style: { listStyle: 'none', margin: 0, padding: 0, maxHeight: 240, overflowY: 'auto' }, children: list.map((entry) => (_jsx("li", { children: _jsxs("button", { type: "button", "aria-pressed": entry.id === selected?.id, onClick: () => setSelectedId(entry.id), style: { display: 'flex', gap: 8, width: '100%', minHeight: 48, alignItems: 'center', font: 'inherit', textAlign: 'left', fontWeight: isCurrent(entry) ? 700 : 400 }, children: [_jsx("span", { children: `v${entry.version}` }), _jsx("time", { dateTime: entry.savedAt, children: formatDate(entry.savedAt) }), entry.author && _jsx("span", { children: entry.author }), entry.label && _jsx("span", { children: entry.label }), isCurrent(entry) && _jsx("span", { children: text.current })] }) }, entry.id))) }), _jsx("div", { style: { position: 'relative', minHeight: 200, flex: 1, border: '1px solid #ccc' }, children: selected ? _jsx(DrawingViewer, { document: selected.document }) : _jsx("div", { style: { padding: 8 }, children: text.selectPrompt }) }), _jsx("div", { style: controlRowStyle, children: _jsx("button", { type: "button", disabled: selected === null || isCurrent(selected), onClick: () => selected && !isCurrent(selected) && onRestore(selected), style: { flex: '1 0 48px', minHeight: 48, font: 'inherit' }, children: text.restore }) })] }));
45
+ }
@@ -0,0 +1,12 @@
1
+ import type { DrawingDocument } from '@crux-diagram/core';
2
+ /** The default alternative description of a drawing. */
3
+ export declare function describeDrawing(document: DrawingDocument): string;
4
+ /** One phrase per shape, back to front, marking the selected ones. */
5
+ export declare function describeShapes(document: DrawingDocument, selection: readonly string[]): string[];
6
+ /** One phrase per visible joint; none while the joints are hidden (REA-023). */
7
+ export declare function describeJoints(document: DrawingDocument): string[];
8
+ /** The shape and joint list of a drawing, for screen readers. */
9
+ export declare function DrawingList({ document, selection }: {
10
+ document: DrawingDocument;
11
+ selection?: readonly string[];
12
+ }): import("react").JSX.Element;
@@ -0,0 +1,47 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
3
+ const typeName = (shape) => shape.type.charAt(0).toUpperCase() + shape.type.slice(1);
4
+ /** The default alternative description of a drawing. */
5
+ export function describeDrawing(document) {
6
+ return `Drawing with ${plural(document.shapes.length, 'shape')} and ${plural(document.joints.length, 'joint')}`;
7
+ }
8
+ /** One phrase per shape, back to front, marking the selected ones. */
9
+ export function describeShapes(document, selection) {
10
+ const selected = new Set(selection);
11
+ return document.shapes.map((shape, index) => {
12
+ const degrees = Math.round((shape.rotation * 180) / Math.PI);
13
+ const parts = [
14
+ `${typeName(shape)} ${index + 1} of ${document.shapes.length} at ${Math.round(shape.center.x)}, ${Math.round(shape.center.y)}, ${Math.round(shape.size.width)} by ${Math.round(shape.size.height)}`,
15
+ ];
16
+ if (degrees !== 0)
17
+ parts.push(`rotated ${degrees}°`);
18
+ if (selected.has(shape.id))
19
+ parts.push('selected');
20
+ return parts.join(', ');
21
+ });
22
+ }
23
+ /** One phrase per visible joint; none while the joints are hidden (REA-023). */
24
+ export function describeJoints(document) {
25
+ if (!document.jointDisplay.visible)
26
+ return [];
27
+ return document.joints.flatMap((joint) => {
28
+ const index = document.shapes.findIndex((s) => s.id === joint.shapeId);
29
+ return index < 0 ? [] : [`Joint ${joint.name} on ${typeName(document.shapes[index])} ${index + 1}`];
30
+ });
31
+ }
32
+ /** Hidden by clipping, not `display: none`, so it stays in the accessibility tree. */
33
+ const visuallyHidden = {
34
+ position: 'absolute',
35
+ width: 1,
36
+ height: 1,
37
+ margin: -1,
38
+ padding: 0,
39
+ overflow: 'hidden',
40
+ clip: 'rect(0 0 0 0)',
41
+ whiteSpace: 'nowrap',
42
+ border: 0,
43
+ };
44
+ /** The shape and joint list of a drawing, for screen readers. */
45
+ export function DrawingList({ document, selection = [] }) {
46
+ return (_jsx("ul", { style: { ...visuallyHidden, listStyle: 'none' }, children: [...describeShapes(document, selection), ...describeJoints(document)].map((text, index) => (_jsx("li", { children: text }, index))) }));
47
+ }
@@ -0,0 +1,50 @@
1
+ import type { Size } from '@crux-diagram/core';
2
+ /** Style given to new shapes; colors are ARGB integers (FMT-004). */
3
+ export interface ShapeStyle {
4
+ readonly fill: number;
5
+ readonly stroke: number;
6
+ readonly strokeWidth: number;
7
+ }
8
+ /**
9
+ * Editor settings, replicating Flutter's `DrawingEditorConfig` (REA-006). Angles are
10
+ * in radians, like the format.
11
+ */
12
+ export interface DrawingEditorConfig {
13
+ /** Canvas of new documents. */
14
+ readonly canvasSize: Size;
15
+ /** Grid step in canvas units; `null` disables the grid and grid snapping. */
16
+ readonly gridSize: number | null;
17
+ /** Initial grid visibility (a view setting, never in history). */
18
+ readonly showGrid: boolean;
19
+ /** Every how many lines a major grid line is drawn. */
20
+ readonly gridMajorEvery: number;
21
+ /** Rotation snap step; 0 disables it. */
22
+ readonly rotationSnapStep: number;
23
+ /** How close to a step a rotation must be to snap. */
24
+ readonly rotationSnapTolerance: number;
25
+ /** Style of new shapes. */
26
+ readonly shapeStyle: ShapeStyle;
27
+ /** Prefix of automatic joint names. */
28
+ readonly jointNamePrefix: string;
29
+ /** Maximum joint name length, in grapheme clusters. */
30
+ readonly jointNameMaxLength: number;
31
+ /** Names offered as buttons in the joint name editor. */
32
+ readonly jointNameSuggestions: readonly string[];
33
+ /** Anchor snap distance in screen pixels; `null` disables anchor snapping. */
34
+ readonly anchorSnapThreshold: number | null;
35
+ /** Maximum number of undo entries. */
36
+ readonly historyLimit: number;
37
+ /** Most pixels an exported image may have (REA-043). */
38
+ readonly exportMaxPixels: number;
39
+ }
40
+ /** What a caller may pass: any field, with a partial shape style. */
41
+ export type DrawingEditorConfigInput = Partial<Omit<DrawingEditorConfig, 'shapeStyle'>> & {
42
+ readonly shapeStyle?: Partial<ShapeStyle>;
43
+ };
44
+ /** Flutter's defaults (`DrawingEditorConfig`, `ShapeElement` default style). */
45
+ export declare const DEFAULT_EDITOR_CONFIG: DrawingEditorConfig;
46
+ /**
47
+ * Fills the missing fields with the defaults; a field given as `undefined` counts as
48
+ * missing. Throws `RangeError` on an invalid history limit.
49
+ */
50
+ export declare function resolveEditorConfig(input?: DrawingEditorConfigInput): DrawingEditorConfig;
@@ -0,0 +1,35 @@
1
+ /** Flutter's defaults (`DrawingEditorConfig`, `ShapeElement` default style). */
2
+ export const DEFAULT_EDITOR_CONFIG = Object.freeze({
3
+ canvasSize: Object.freeze({ width: 1600, height: 1200 }),
4
+ gridSize: 10,
5
+ showGrid: false,
6
+ gridMajorEvery: 5,
7
+ rotationSnapStep: (15 * Math.PI) / 180,
8
+ rotationSnapTolerance: (5 * Math.PI) / 180,
9
+ shapeStyle: Object.freeze({ fill: 0x00ffffff, stroke: 0xff757575, strokeWidth: 2 }),
10
+ jointNamePrefix: 'J',
11
+ jointNameMaxLength: 12,
12
+ jointNameSuggestions: Object.freeze([]),
13
+ anchorSnapThreshold: 12,
14
+ historyLimit: 100,
15
+ exportMaxPixels: 16_000_000,
16
+ });
17
+ /** The entries of `object` whose value is not `undefined`. */
18
+ const defined = (object) => Object.fromEntries(Object.entries(object ?? {}).filter(([, value]) => value !== undefined));
19
+ /**
20
+ * Fills the missing fields with the defaults; a field given as `undefined` counts as
21
+ * missing. Throws `RangeError` on an invalid history limit.
22
+ */
23
+ export function resolveEditorConfig(input = {}) {
24
+ const config = {
25
+ ...DEFAULT_EDITOR_CONFIG,
26
+ ...defined(input),
27
+ shapeStyle: { ...DEFAULT_EDITOR_CONFIG.shapeStyle, ...defined(input.shapeStyle) },
28
+ };
29
+ if (!Number.isInteger(config.historyLimit) || config.historyLimit < 1) {
30
+ throw new RangeError('historyLimit must be a positive integer');
31
+ }
32
+ if (!(config.exportMaxPixels > 0))
33
+ throw new RangeError('exportMaxPixels must be a positive number');
34
+ return config;
35
+ }
@@ -0,0 +1,12 @@
1
+ import type { CSSProperties } from 'react';
2
+ export declare const controlRowStyle: CSSProperties;
3
+ export interface ControlButtonProps {
4
+ readonly label: string;
5
+ /** The longer text, shown as the tooltip; defaults to the label. */
6
+ readonly title?: string;
7
+ /** Marks a toggle or a choice as selected (`aria-pressed`); omit for a plain action. */
8
+ readonly pressed?: boolean;
9
+ readonly disabled?: boolean;
10
+ readonly onClick: () => void;
11
+ }
12
+ export declare function ControlButton({ label, title, pressed, disabled, onClick }: ControlButtonProps): import("react").JSX.Element;
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ export const controlRowStyle = {
3
+ display: 'flex',
4
+ gap: 4,
5
+ padding: 4,
6
+ overflowX: 'auto',
7
+ font: '12px sans-serif',
8
+ };
9
+ export function ControlButton({ label, title, pressed, disabled, onClick }) {
10
+ return (_jsx("button", { type: "button", title: title ?? label, "aria-pressed": pressed, disabled: disabled, onClick: onClick, style: { flex: '1 0 48px', minHeight: 48, font: 'inherit', fontWeight: pressed ? 700 : 400 }, children: label }));
11
+ }
@@ -0,0 +1,45 @@
1
+ import type { DrawingDocument } from '@crux-diagram/core';
2
+ import { type ExportImageOptions } from './export/export-image.js';
3
+ import { type ReactNode } from 'react';
4
+ import { type DrawingEditorConfig, type DrawingEditorConfigInput } from './config.js';
5
+ import { type EditorLabels, type EditorLabelsInput } from './labels.js';
6
+ import { type EditorStore } from './store.js';
7
+ /** Imperative API of the editor (REA-004). Members are added as their tasks land. */
8
+ export interface DrawingEditorHandle {
9
+ undo(): void;
10
+ redo(): void;
11
+ readonly canUndo: boolean;
12
+ readonly canRedo: boolean;
13
+ /** The committed document (never a gesture preview). */
14
+ getDocument(): DrawingDocument;
15
+ /** Replaces the document and clears the history, without calling `onChange` (opening another drawing). */
16
+ reset(document: DrawingDocument): void;
17
+ /** Returns to the fitted view, 1× with no pan; not a document change (REA-016, REA-017). */
18
+ fitToScreen(): void;
19
+ /** Renders the committed document to a PNG or JPEG `Blob`, optionally saving it (REA-040 to REA-043). */
20
+ exportImage(options: ExportImageOptions): Promise<Blob>;
21
+ }
22
+ export interface EditorProviderProps {
23
+ /**
24
+ * The document to show. A value the editor did not produce is applied as one undoable
25
+ * change; a late echo of an emitted document is ignored (REA-007). To open another
26
+ * drawing with an empty history, change the editor's `key` or call `reset`.
27
+ */
28
+ value: DrawingDocument;
29
+ /** Receives a new document on every committed change (REA-002). */
30
+ onChange: (document: DrawingDocument) => void;
31
+ /** Receives the document during a continuous gesture, before the release commits it (REA-003). */
32
+ onPreview?: (document: DrawingDocument) => void;
33
+ config?: DrawingEditorConfigInput;
34
+ /** Texts of the ready-made controls (REA-053); English by default. */
35
+ labels?: EditorLabelsInput;
36
+ children?: ReactNode;
37
+ }
38
+ /** Owns the editor store and binds it to the controlled `value`/`onChange` pair. */
39
+ export declare const EditorProvider: import("react").ForwardRefExoticComponent<EditorProviderProps & import("react").RefAttributes<DrawingEditorHandle>>;
40
+ /** The store of the enclosing editor. */
41
+ export declare const useEditor: () => EditorStore;
42
+ /** The resolved config of the enclosing editor. */
43
+ export declare const useEditorConfig: () => DrawingEditorConfig;
44
+ /** The texts of the enclosing editor's controls. */
45
+ export declare const useEditorLabels: () => EditorLabels;
@@ -0,0 +1,95 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { exportImage } from './export/export-image.js';
3
+ import { createContext, forwardRef, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
4
+ import { resolveEditorConfig } from './config.js';
5
+ import { resolveEditorLabels } from './labels.js';
6
+ import { createEditorStore } from './store.js';
7
+ const EditorContext = createContext(null);
8
+ // useLayoutEffect warns during server rendering on React 18; nothing runs there anyway.
9
+ const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
10
+ /** Owns the editor store and binds it to the controlled `value`/`onChange` pair. */
11
+ export const EditorProvider = forwardRef(function EditorProvider({ value, onChange, onPreview, config: configInput, labels: labelsInput, children }, ref) {
12
+ const config = useMemo(() => resolveEditorConfig(configInput), [configInput]);
13
+ const labels = useMemo(() => resolveEditorLabels(labelsInput), [labelsInput]);
14
+ // Created once: the history limit and the initial grid visibility are read at mount.
15
+ const [editor] = useState(() => createEditorStore(value, { historyLimit: config.historyLimit, showGrid: config.showGrid }));
16
+ const latest = useRef({ onChange, onPreview });
17
+ useIsomorphicLayoutEffect(() => {
18
+ latest.current = { onChange, onPreview };
19
+ });
20
+ // Documents emitted since the parent last held the editor's document: a parent that
21
+ // adopts late may still render one of them, and that echo must not undo newer commits.
22
+ // Only the most recent ones are kept, so a parent that never adopts cannot grow it forever.
23
+ const unadopted = useRef(new Set());
24
+ const maxUnadopted = config.historyLimit + 1;
25
+ // Runs `change` without emitting: for the parent's own value and for `reset`.
26
+ const quiet = useRef(false);
27
+ const quietly = (change) => {
28
+ quiet.current = true;
29
+ try {
30
+ change();
31
+ }
32
+ finally {
33
+ quiet.current = false;
34
+ }
35
+ };
36
+ // Every committed change made in the editor is emitted, including an undo back to the
37
+ // parent's current value; previews go to onPreview.
38
+ useEffect(() => editor.subscribe((state, previous) => {
39
+ if (state.document !== previous.document && !quiet.current) {
40
+ const pending = unadopted.current;
41
+ pending.delete(state.document);
42
+ pending.add(state.document);
43
+ for (const oldest of pending) {
44
+ if (pending.size <= maxUnadopted)
45
+ break;
46
+ pending.delete(oldest);
47
+ }
48
+ latest.current.onChange(state.document);
49
+ }
50
+ if (state.preview && state.preview !== previous.preview)
51
+ latest.current.onPreview?.(state.preview);
52
+ }), [editor, maxUnadopted]);
53
+ // REA-007: a new value never clears the history by itself.
54
+ useEffect(() => {
55
+ if (value === editor.getDocument()) {
56
+ unadopted.current.clear();
57
+ return;
58
+ }
59
+ if (unadopted.current.has(value))
60
+ return;
61
+ unadopted.current.clear();
62
+ quietly(() => editor.commit(value));
63
+ }, [editor, value]);
64
+ useImperativeHandle(ref, () => ({
65
+ undo: editor.undo,
66
+ redo: editor.redo,
67
+ get canUndo() {
68
+ return editor.canUndo();
69
+ },
70
+ get canRedo() {
71
+ return editor.canRedo();
72
+ },
73
+ getDocument: editor.getDocument,
74
+ fitToScreen: editor.fitToScreen,
75
+ exportImage: (options) => exportImage(editor.getDocument(), options, { maxPixels: config.exportMaxPixels }),
76
+ reset(document) {
77
+ quietly(() => editor.reset(document));
78
+ unadopted.current.clear();
79
+ },
80
+ }), [editor, config]);
81
+ const context = useMemo(() => ({ editor, config, labels }), [editor, config, labels]);
82
+ return _jsx(EditorContext.Provider, { value: context, children: children });
83
+ });
84
+ function useEditorContext() {
85
+ const context = useContext(EditorContext);
86
+ if (!context)
87
+ throw new Error('This component must be rendered inside a DrawingEditor');
88
+ return context;
89
+ }
90
+ /** The store of the enclosing editor. */
91
+ export const useEditor = () => useEditorContext().editor;
92
+ /** The resolved config of the enclosing editor. */
93
+ export const useEditorConfig = () => useEditorContext().config;
94
+ /** The texts of the enclosing editor's controls. */
95
+ export const useEditorLabels = () => useEditorContext().labels;
@@ -0,0 +1,29 @@
1
+ import { type DrawingDocument } from '@crux-diagram/core';
2
+ import Konva from 'konva';
3
+ /** Most pixels an exported image may have unless `config.exportMaxPixels` says otherwise (REA-043). */
4
+ export declare const DEFAULT_EXPORT_MAX_PIXELS = 16000000;
5
+ export interface ExportImageOptions {
6
+ readonly format: 'png' | 'jpeg';
7
+ /** Image pixels per canvas unit (default 1). */
8
+ readonly pixelRatio?: number;
9
+ /** JPEG quality in [0, 1] (default 0.92); ignored for PNG. */
10
+ readonly quality?: number;
11
+ /** Leaves the background transparent; PNG only (default false). */
12
+ readonly transparentBackground?: boolean;
13
+ /** A file name: the image is also saved under it, with the extension added when missing. */
14
+ readonly download?: string;
15
+ }
16
+ /**
17
+ * The stage of the image: layers `background` (white unless transparent), `shapes` and
18
+ * `joints`, in canvas units. Hidden joints are not drawn (REA-042).
19
+ */
20
+ export declare function createExportStage(document: DrawingDocument, { transparentBackground }: {
21
+ transparentBackground: boolean;
22
+ }): Konva.Stage;
23
+ /**
24
+ * Renders `document` to an image `Blob` (REA-040). Waits for the fonts first (REA-032).
25
+ * `maxPixels` is `config.exportMaxPixels`.
26
+ */
27
+ export declare function exportImage(document: DrawingDocument, options: ExportImageOptions, { maxPixels }?: {
28
+ maxPixels?: number;
29
+ }): Promise<Blob>;