@widgetic/canvas 0.5.14 → 0.5.15

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.
@@ -1,5 +1,5 @@
1
1
  import { SvelteComponentTyped } from "svelte";
2
- import type { WidgetConversionPayload } from './types';
2
+ import type { WidgetConversionPayload, StrokeRecognizer } from './types';
3
3
  declare const __propDef: {
4
4
  props: {
5
5
  /**
@@ -36,6 +36,7 @@ declare const __propDef: {
36
36
  onCanvasCleared?: (() => void) | null;
37
37
  onConvertToWidget?: ((data: WidgetConversionPayload) => void) | null;
38
38
  onWidgetImageClick?: ((widgetId: string) => void) | null;
39
+ onRecognizeStroke?: StrokeRecognizer | null;
39
40
  onNonWidgetSelected?: (() => void) | null;
40
41
  onWidgetShapeDuplicated?: ((sourceWidgetId: string, clonedObject: any) => void) | null;
41
42
  onWidgetShapeDeleting?: ((widgetId: string) => Promise<boolean>) | null;
@@ -62,9 +63,9 @@ declare const __propDef: {
62
63
  top: number;
63
64
  width: number;
64
65
  height: number;
65
- localWidth: any;
66
- localHeight: any;
67
- matrix: any[];
66
+ localWidth: number;
67
+ localHeight: number;
68
+ matrix: number[];
68
69
  widgetId: string;
69
70
  hovered: boolean;
70
71
  }[];
@@ -113,6 +114,7 @@ declare const __propDef: {
113
114
  setWidgetShapeOverlayDragActive?: (active: boolean) => void;
114
115
  selectWidgetShapeById?: (widgetId: string) => boolean;
115
116
  getSelectedWidgetShapeId?: () => string | null;
117
+ getSelectedObject?: () => any;
116
118
  getHoveredWidgetShapeId?: () => string | null;
117
119
  onSelectImageTool?: () => void;
118
120
  onSelectVideoTool?: () => void;
@@ -163,9 +165,9 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
163
165
  top: number;
164
166
  width: number;
165
167
  height: number;
166
- localWidth: any;
167
- localHeight: any;
168
- matrix: any[];
168
+ localWidth: number;
169
+ localHeight: number;
170
+ matrix: number[];
169
171
  widgetId: string;
170
172
  hovered: boolean;
171
173
  }[];
@@ -214,6 +216,7 @@ export default class Canvas extends SvelteComponentTyped<CanvasProps, CanvasEven
214
216
  get setWidgetShapeOverlayDragActive(): (active: boolean) => void;
215
217
  get selectWidgetShapeById(): (widgetId: string) => boolean;
216
218
  get getSelectedWidgetShapeId(): () => string | null;
219
+ get getSelectedObject(): () => any;
217
220
  get getHoveredWidgetShapeId(): () => string | null;
218
221
  get onSelectImageTool(): () => void;
219
222
  get onSelectVideoTool(): () => void;
@@ -9,7 +9,7 @@
9
9
  // Tool type definition
10
10
  type ToolName = 'select' | 'erase' | 'draw' | 'arrow' | 'text' | 'rect' | 'circle' | 'circle-true' | 'triangle' | 'frame' | 'pan' | 'image' | 'video' | 'library-shape';
11
11
  // Shape tool sub-type for the shapes dropdown (Arrow is a dedicated button, not in dropdown)
12
- type ShapeToolName = 'rect' | 'circle' | 'circle-true' | 'triangle';
12
+ type ShapeToolName = 'rect' | 'circle' | 'circle-true' | 'triangle' | 'arrow';
13
13
 
14
14
  // Class
15
15
  let className = '';
@@ -60,7 +60,9 @@
60
60
 
61
61
  // ── Shape library (special shapes: media, arrows, UI) ────────────────────
62
62
  /** Called when user clicks a library shape. Canvas inserts it as a Path. */
63
- export let onInsertLibraryShape: (shapeKey: string, pathData: string) => void = () => {};
63
+ /** Passed by Canvas.svelte but never read here — export const keeps the
64
+ * init-set contract without the unused-reactive warning. */
65
+ export const onInsertLibraryShape: (shapeKey: string, pathData: string) => void = () => {};
64
66
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */
65
67
  export let onSelectLibraryShapeTool: (shapeKey: string, pathData: string) => void = () => {};
66
68
 
@@ -136,6 +138,12 @@
136
138
  label: 'Circle',
137
139
  key: '',
138
140
  },
141
+ arrow: {
142
+ icon: '↗',
143
+ iconSvg: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path d="M6 18C6 18 6.06617 12.5162 8.00001 10.5521C10.862 7.64522 19 9 19 9M19 9L15 5M19 9L15 13" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
144
+ label: 'Arrow',
145
+ key: 'A',
146
+ },
139
147
  };
140
148
 
141
149
  // Image dropdown entry — placed at the bottom of the shapes dropdown with a divider
@@ -1180,10 +1188,7 @@ button:disabled {
1180
1188
  flex-shrink: 0;
1181
1189
  }
1182
1190
 
1183
- /* Left: shape icon button — same size as other tool buttons */
1184
- .shapes-main-bt {
1185
- /* Inherits .wdg-tool-bt 48×48 */
1186
- }
1191
+ /* Left: shape icon button (.shapes-main-bt) — inherits .wdg-tool-bt 48×48 */
1187
1192
  /* When active, give all shape SVGs a semi-transparent fill for visual weight */
1188
1193
  .shapes-main-bt.wdg-tool-active :global(svg rect),
1189
1194
  .shapes-main-bt.wdg-tool-active :global(svg circle),
@@ -10,7 +10,7 @@ declare const __propDef: {
10
10
  onSelectSelectTool?: () => void;
11
11
  onSelectEraseTool?: () => void;
12
12
  onSelectDrawTool?: () => void;
13
- onSelectShapeTool?: (shapeType: "rect" | "circle" | "circle-true" | "triangle") => void;
13
+ onSelectShapeTool?: (shapeType: "rect" | "arrow" | "circle" | "circle-true" | "triangle") => void;
14
14
  onSelectFrameTool?: () => void;
15
15
  onSelectTextTool?: () => void;
16
16
  onSelectPanTool?: () => void;
@@ -31,7 +31,8 @@ declare const __propDef: {
31
31
  /** Disables the Redo button when there is no future state to redo to. */ canRedo?: boolean;
32
32
  /** When true, the drawing tool stays active after placing a shape. */ stickyToolEnabled?: boolean;
33
33
  onToggleStickyTool?: () => void;
34
- /** Called when user clicks a library shape. Canvas inserts it as a Path. */ onInsertLibraryShape?: (shapeKey: string, pathData: string) => void;
34
+ /** Passed by Canvas.svelte but never read here — export const keeps the
35
+ * init-set contract without the unused-reactive warning. */ onInsertLibraryShape?: (shapeKey: string, pathData: string) => void;
35
36
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */ onSelectLibraryShapeTool?: (shapeKey: string, pathData: string) => void;
36
37
  /** Extra tools (undo/redo/lock). Code stays; UI is gated. */ advancedFeatures?: boolean;
37
38
  /**
@@ -56,5 +57,6 @@ export type CanvasToolbarProps = typeof __propDef.props;
56
57
  export type CanvasToolbarEvents = typeof __propDef.events;
57
58
  export type CanvasToolbarSlots = typeof __propDef.slots;
58
59
  export default class CanvasToolbar extends SvelteComponentTyped<CanvasToolbarProps, CanvasToolbarEvents, CanvasToolbarSlots> {
60
+ get onInsertLibraryShape(): (shapeKey: string, pathData: string) => void;
59
61
  }
60
62
  export {};
@@ -8,7 +8,9 @@
8
8
 
9
9
  // ── Context: what was right-clicked ───────────────────────────────────────
10
10
  export let hasSelection: boolean = false;
11
- export let selectionCount: number = 0;
11
+ // Passed by Canvas.svelte but never read here — export const keeps the
12
+ // init-set contract without the unused-reactive warning.
13
+ export const selectionCount: number = 0;
12
14
  export let canGroup: boolean = false;
13
15
  export let canUngroup: boolean = false;
14
16
  export let canPaste: boolean = false;
@@ -32,5 +32,6 @@ export type ContextMenuProps = typeof __propDef.props;
32
32
  export type ContextMenuEvents = typeof __propDef.events;
33
33
  export type ContextMenuSlots = typeof __propDef.slots;
34
34
  export default class ContextMenu extends SvelteComponentTyped<ContextMenuProps, ContextMenuEvents, ContextMenuSlots> {
35
+ get selectionCount(): number;
35
36
  }
36
37
  export {};
@@ -87,6 +87,7 @@
87
87
  <button
88
88
  class="panel-btn grid-btn {showGrid ? 'active' : ''}"
89
89
  onclick={onGridToggle}
90
+ aria-label="Toggle grid"
90
91
  >
91
92
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
92
93
  <rect x="3" y="3" width="7" height="7"/>
@@ -104,6 +105,7 @@
104
105
  <button
105
106
  class="panel-btn pan-btn {isPanActive ? 'active' : ''}"
106
107
  onclick={onPanToggle}
108
+ aria-label="Hand / pan tool"
107
109
  >
108
110
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
109
111
  <path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0"/>
@@ -123,6 +125,7 @@
123
125
  class="panel-btn"
124
126
  onclick={onZoomOut}
125
127
  disabled={zoomLevel <= 10}
128
+ aria-label="Zoom out"
126
129
  >
127
130
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
128
131
  <circle cx="11" cy="11" r="8"/>
@@ -165,6 +168,7 @@
165
168
  class="panel-btn"
166
169
  onclick={onZoomIn}
167
170
  disabled={zoomLevel >= 500}
171
+ aria-label="Zoom in"
168
172
  >
169
173
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
170
174
  <circle cx="11" cy="11" r="8"/>
@@ -193,6 +197,7 @@
193
197
  <button
194
198
  class="panel-btn"
195
199
  onclick={onZoomFit}
200
+ aria-label="Fit content to view"
196
201
  >
197
202
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
198
203
  <path d="M8 3H5a2 2 0 0 0-2 2v3"/>
@@ -1,22 +1,23 @@
1
- <script>
1
+ <script lang="ts">
2
2
  import { onMount } from 'svelte';
3
+ import type { Canvas } from 'fabric';
3
4
  import { Portal } from '@widgetic/design-system';
4
5
  import { canvasWarn } from './canvasLogger';
5
6
 
6
- let { fabricCanvas, target, class: className = '', style = '' } = $props();
7
- let drawingCanvas;
8
- function captureDrawingCanvas(node) {
7
+ let { fabricCanvas, target, class: className = '', style = '' }: { fabricCanvas: Canvas; target: string; class?: string; style?: string } = $props();
8
+ let drawingCanvas: HTMLCanvasElement | null = null;
9
+ function captureDrawingCanvas(node: HTMLCanvasElement) {
9
10
  drawingCanvas = node;
10
11
  return { destroy() { drawingCanvas = null; } };
11
12
  }
12
- let controls = $state([]);
13
+ let controls: { key: string; points: string; cursor: string }[] = $state([]);
13
14
  let viewport = $state({ left: 0, top: 0, width: 0, height: 0 });
14
- let activePointer = null;
15
- let lastPointerEvent = null;
15
+ let activePointer: number | null = null;
16
+ let lastPointerEvent: PointerEvent | null = null;
16
17
 
17
18
  // Route only control gestures through Fabric's existing DOM event handlers.
18
19
  // Pointer capture prevents neighboring iframes from stealing the gesture.
19
- function routeMouseEvent(type, event) {
20
+ function routeMouseEvent(type: 'mousedown' | 'mousemove' | 'mouseup', event: PointerEvent) {
20
21
  fabricCanvas.upperCanvasEl.dispatchEvent(new MouseEvent(type, {
21
22
  bubbles: true, cancelable: true, clientX: event.clientX, clientY: event.clientY,
22
23
  button: 0, buttons: type === 'mouseup' ? 0 : 1,
@@ -25,12 +26,12 @@
25
26
  }));
26
27
  }
27
28
 
28
- function startControl(event) {
29
+ function startControl(event: PointerEvent) {
29
30
  if (event.button !== 0 || activePointer !== null) return;
30
31
  event.preventDefault();
31
32
  event.stopPropagation();
32
33
  try {
33
- event.currentTarget.setPointerCapture(event.pointerId);
34
+ (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
34
35
  activePointer = event.pointerId;
35
36
  lastPointerEvent = event;
36
37
  routeMouseEvent('mousedown', event);
@@ -40,18 +41,19 @@
40
41
  }
41
42
  }
42
43
 
43
- function moveControl(event) {
44
+ function moveControl(event: PointerEvent) {
44
45
  if (activePointer !== event.pointerId) return;
45
46
  lastPointerEvent = event;
46
47
  routeMouseEvent('mousemove', event);
47
48
  }
48
49
 
49
- function finishControl(event) {
50
+ function finishControl(event: PointerEvent) {
50
51
  if (activePointer !== event.pointerId) return;
51
52
  activePointer = null;
52
53
  routeMouseEvent('mouseup', event);
53
- if (event.currentTarget?.hasPointerCapture?.(event.pointerId)) {
54
- event.currentTarget.releasePointerCapture(event.pointerId);
54
+ const target = event.currentTarget as HTMLElement | null;
55
+ if (target?.hasPointerCapture?.(event.pointerId)) {
56
+ target.releasePointerCapture(event.pointerId);
55
57
  }
56
58
  }
57
59
 
@@ -67,7 +69,7 @@
67
69
  context.setTransform(1, 0, 0, 1, 0, 0);
68
70
  context.clearRect(0, 0, drawingCanvas.width, drawingCanvas.height);
69
71
  const selected = fabricCanvas.getActiveObject();
70
- if (!selected?._isWidgetImage || fabricCanvas.skipTargetFind || fabricCanvas.isDrawingMode) {
72
+ if (!selected || !(selected as any)._isWidgetImage || fabricCanvas.skipTargetFind || fabricCanvas.isDrawingMode) {
71
73
  controls = [];
72
74
  return;
73
75
  }
@@ -75,11 +77,11 @@
75
77
  context.setTransform(retina, 0, 0, retina, 0, 0);
76
78
  // Red primary stroke is part of the object, not the selection border.
77
79
  // Paint it with the same viewport/object matrices above the HTML preview.
78
- if (selected._isPrimaryWidget && selected.strokeWidth) {
80
+ if ((selected as any)._isPrimaryWidget && selected.strokeWidth) {
79
81
  context.save();
80
82
  context.transform(...fabricCanvas.viewportTransform);
81
83
  context.transform(...selected.calcTransformMatrix());
82
- context.strokeStyle = selected.stroke;
84
+ context.strokeStyle = selected.stroke as string;
83
85
  context.lineWidth = selected.strokeWidth;
84
86
  context.strokeRect(-selected.width / 2, -selected.height / 2, selected.width, selected.height);
85
87
  context.restore();
@@ -88,11 +90,14 @@
88
90
  selected._renderControls(context);
89
91
  const scaleX = bounds.width / fabricCanvas.getWidth();
90
92
  const scaleY = bounds.height / fabricCanvas.getHeight();
91
- controls = Object.entries(selected.oCoords || {}).flatMap(([key, position]) => {
92
- const control = selected.controls[key];
93
- if (!selected.hasControls || !control?.getVisibility(selected, key)) return [];
93
+ // Fabric's internal control geometry (oCoords/controls) isn't on the
94
+ // public FabricObject type; this layer re-renders it as hit regions.
95
+ const sel = selected as any;
96
+ controls = Object.entries(sel.oCoords || {}).flatMap(([key, position]: [string, any]) => {
97
+ const control = sel.controls[key];
98
+ if (!sel.hasControls || !control?.getVisibility(sel, key)) return [];
94
99
  const points = position.corner;
95
- return [{ key, points: ['tl', 'tr', 'br', 'bl'].map(corner => `${points[corner].x * scaleX},${points[corner].y * scaleY}`).join(' '), cursor: control.cursorStyleHandler({}, control, selected) }];
100
+ return [{ key, points: ['tl', 'tr', 'br', 'bl'].map(corner => `${points[corner].x * scaleX},${points[corner].y * scaleY}`).join(' '), cursor: control.cursorStyleHandler({}, control, sel) }];
96
101
  });
97
102
  }
98
103
 
@@ -1,23 +1,14 @@
1
- /** @typedef {typeof __propDef.props} WidgetSelectionLayerProps */
2
- /** @typedef {typeof __propDef.events} WidgetSelectionLayerEvents */
3
- /** @typedef {typeof __propDef.slots} WidgetSelectionLayerSlots */
4
- export default class WidgetSelectionLayer extends SvelteComponentTyped<{
5
- [x: string]: never;
6
- }, {
7
- [evt: string]: CustomEvent<any>;
8
- }, {}> {
9
- }
10
- export type WidgetSelectionLayerProps = typeof __propDef.props;
11
- export type WidgetSelectionLayerEvents = typeof __propDef.events;
12
- export type WidgetSelectionLayerSlots = typeof __propDef.slots;
13
1
  import { SvelteComponentTyped } from "svelte";
14
2
  declare const __propDef: {
15
- props: {
16
- [x: string]: never;
17
- };
3
+ props: Record<string, never>;
18
4
  events: {
19
5
  [evt: string]: CustomEvent<any>;
20
6
  };
21
7
  slots: {};
22
8
  };
9
+ export type WidgetSelectionLayerProps = typeof __propDef.props;
10
+ export type WidgetSelectionLayerEvents = typeof __propDef.events;
11
+ export type WidgetSelectionLayerSlots = typeof __propDef.slots;
12
+ export default class WidgetSelectionLayer extends SvelteComponentTyped<WidgetSelectionLayerProps, WidgetSelectionLayerEvents, WidgetSelectionLayerSlots> {
13
+ }
23
14
  export {};
@@ -10,6 +10,8 @@ export { default as ContextMenu } from './ContextMenu.svelte';
10
10
  export { default as PanZoomPanel } from './PanZoomPanel.svelte';
11
11
  export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
12
12
  export type { WidgetConversionPayload } from './types';
13
+ export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
14
+ export { CANVAS_SHAPE_SNAP_ENABLED } from './shapes/strokeShapeSnap';
13
15
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
14
16
  export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
15
17
  export type { ShapeImageStore } from './shapes/shapeImageStore';
@@ -9,5 +9,6 @@ export { default as CanvasToolbar } from './CanvasToolbar.svelte';
9
9
  export { default as ContextMenu } from './ContextMenu.svelte';
10
10
  export { default as PanZoomPanel } from './PanZoomPanel.svelte';
11
11
  export { default as PropsPanel } from './props-panel/PropsPanel.svelte';
12
+ export { CANVAS_SHAPE_SNAP_ENABLED } from './shapes/strokeShapeSnap';
12
13
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
13
14
  export { setShapeImageStore, getShapeImageStore } from './shapes/shapeImageStore';
@@ -151,7 +151,10 @@
151
151
  $: isDuplicating = !!selectedObject?._isDuplicating;
152
152
  $: isConverting = !!selectedObject?._isConverting;
153
153
  $: showWidgetLoader = isPendingWidgetLink || isDuplicating || isConverting;
154
- $: resolvedWidgetName = (widgetNameRevision, widgetId && getWidgetName)
154
+ // Reading widgetNameRevision registers it as a dependency so renamed
155
+ // widgets re-resolve; the value itself is unused.
156
+ $: void widgetNameRevision;
157
+ $: resolvedWidgetName = widgetId && getWidgetName
155
158
  ? getWidgetName(widgetId)
156
159
  : null;
157
160
  $: isOrphanedWidgetShape = !!(
@@ -392,8 +395,9 @@
392
395
  }
393
396
 
394
397
  // Dismissal belongs to this selection, not to property-change notifications.
395
- let dismissedSelection = null;
396
- let previousSelection = null;
398
+ // selectedObject is `any`, so these mirror it.
399
+ let dismissedSelection: any = null;
400
+ let previousSelection: any = null;
397
401
  $: if (selectedObject !== previousSelection) {
398
402
  previousSelection = selectedObject;
399
403
  dismissedSelection = null;
@@ -1865,10 +1869,12 @@
1865
1869
  background: white;
1866
1870
  outline: none;
1867
1871
  -moz-appearance: textfield;
1872
+ appearance: textfield;
1868
1873
  }
1869
1874
  .dimension-input::-webkit-outer-spin-button,
1870
1875
  .dimension-input::-webkit-inner-spin-button {
1871
1876
  -webkit-appearance: none;
1877
+ appearance: none;
1872
1878
  margin: 0;
1873
1879
  }
1874
1880
  .dimension-input:focus {
@@ -0,0 +1,165 @@
1
+ /**
2
+ * @file strokeShapeSnap.ts
3
+ * @description Turn a hand-drawn freehand stroke into the shape it was meant to be.
4
+ *
5
+ * The Draw tool uses Fabric's `PencilBrush`, so a "shape" the user tries to draw
6
+ * arrives as a wobbly polyline — dozens of sampled points, corners that overshoot,
7
+ * edges that bow. This module measures that polyline and decides whether it is a
8
+ * clean enough instance of a shape the canvas can actually build.
9
+ *
10
+ * **Geometry belongs in code.** JEV cannot see a stroke: it judges text, and the
11
+ * only thing that could be said to it in text is a *measurement* of the stroke,
12
+ * which code has to compute anyway. So the pipeline is:
13
+ *
14
+ * 1. measure the stroke here, deterministically (closed? how many corners? how
15
+ * circular? how far off axis? aspect ratio?) — 0ms, no network;
16
+ * 2. gate every shape the canvas can build through the conditions it *cannot*
17
+ * be — a shape whose gate fails is never offered to anyone, so nothing
18
+ * impossible can be chosen;
19
+ * 3. rank the survivors by how well they match, and a decisive winner is
20
+ * applied immediately with no model call;
21
+ * 4. only when the survivors are ambiguous (a near-square, an oval that is
22
+ * almost a circle) does the caller escalate to JEV, which is exactly the
23
+ * closed-set choice with a confidence gate it is good at — and which can
24
+ * only ever replace a wrong *snap* with the stroke left as drawn.
25
+ *
26
+ * Everything here is pure: it takes command data and points, never a Fabric
27
+ * object, so it can be tested with `npm test` and reused by any caller that can
28
+ * produce a polyline.
29
+ */
30
+ /**
31
+ * The feature flag for this whole behaviour, as requested for the experiment:
32
+ * `true` means a recognized stroke is replaced by the clean shape, `false` means
33
+ * every stroke stays exactly as it was drawn. One line to roll back.
34
+ */
35
+ export declare const CANVAS_SHAPE_SNAP_ENABLED = true;
36
+ /**
37
+ * The shapes snapping can produce — the shapes the canvas can *build from
38
+ * scratch*, which is what makes the replacement faithful to what the user would
39
+ * have got from the toolbar:
40
+ *
41
+ * - `rect` → Fabric `Rect` (a square is a `rect` whose bounds are square)
42
+ * - `circle` → Fabric `Circle` (the toolbar's Circle, not the Ellipse)
43
+ * - `oval` → Fabric `Ellipse` (the toolbar's oval/ellipse tool)
44
+ * - `triangle` → the same regenerated path the Triangle tool produces
45
+ * - `diamond` → the `diamond` library shape
46
+ * - `hexagon` → the `hexagon` library shape
47
+ *
48
+ * Deliberately absent: **line and arrow**. The canvas has no bare-line tool — the
49
+ * only straight-line object it offers is an arrow, which always draws a head, so
50
+ * snapping a straight stroke to one would *add* a mark the user did not draw. A
51
+ * straight stroke therefore has no candidates at all and is left alone.
52
+ */
53
+ export type CanvasSnapShape = 'rect' | 'circle' | 'oval' | 'triangle' | 'diamond' | 'hexagon';
54
+ export declare const CANVAS_SNAP_SHAPES: readonly CanvasSnapShape[];
55
+ /** How each candidate is described when the roster is shown to JEV. */
56
+ export declare const CANVAS_SNAP_SHAPE_LABELS: Record<CanvasSnapShape, string>;
57
+ export interface StrokePoint {
58
+ x: number;
59
+ y: number;
60
+ }
61
+ /** One Fabric/SVG path command: `['M', x, y]`, `['Q', cx, cy, x, y]`, … */
62
+ export type PathCommand = [string, ...number[]];
63
+ /**
64
+ * A stroke's measurements — the vocabulary the shape profiles are written in and
65
+ * the vocabulary JEV is shown. Every field is scale-free (a ratio or a 0..1
66
+ * score) except the bounds, so the same drawing at any zoom measures the same.
67
+ */
68
+ export interface StrokeMeasurements {
69
+ /** Sampled points the measurements were taken from (after resampling). */
70
+ pointCount: number;
71
+ /** True when the ends nearly meet (gap ≤ `CLOSED_GAP_RATIO` of the diagonal). */
72
+ closed: boolean;
73
+ /** Gap between the stroke's ends, as a fraction of the bounding-box diagonal. */
74
+ gapRatio: number;
75
+ /** Vertices left after simplification — the outline's straight edges. */
76
+ vertexCount: number;
77
+ /** Corners found on the outline (3 ≈ triangle, 4 ≈ rectangle, 6 ≈ hexagon). */
78
+ cornerCount: number;
79
+ /** Mean sharpness of the detected corners; 1 ≈ hard corners, 0 ≈ rounded. */
80
+ cornerSharpness: number;
81
+ /** Bounding-box width ÷ height, always ≥ 1 (orientation-independent). */
82
+ aspectRatio: number;
83
+ /** 1 = a single straight line. Only meaningful for an open stroke. */
84
+ straightness: number;
85
+ /** 4πA / P² — 1 for a perfect circle, lower for anything else. */
86
+ circularity: number;
87
+ /** Share of the outline (by length) running within 20° of horizontal or vertical. */
88
+ axisAlignment: number;
89
+ /** 0 = edges sit on the axes, 1 = edges sit on the diagonals (a diamond). */
90
+ axisTilt: number;
91
+ /** 1 = every boundary point the same distance from the centre (a circle). */
92
+ radialUniformity: number;
93
+ /** The stroke's bounds in the path's own coordinates. */
94
+ bounds: SnapBounds;
95
+ }
96
+ export interface SnapRanking {
97
+ shape: CanvasSnapShape;
98
+ /** 0..1 — how well the measurements match this shape's profile. */
99
+ score: number;
100
+ }
101
+ /**
102
+ * A decisive winner needs a solid score *and* a lead over the runner-up. Below
103
+ * either bar the caller escalates to JEV instead of snapping on a coin flip.
104
+ */
105
+ export declare const STROKE_SNAP_MIN_SCORE = 0.78;
106
+ export declare const STROKE_SNAP_MIN_MARGIN = 0.12;
107
+ /**
108
+ * Flatten path commands into a polyline.
109
+ *
110
+ * Fabric's `PencilBrush` emits `M` followed by a run of quadratic curves whose
111
+ * control point is the sampled pointer and whose endpoint is the midpoint of the
112
+ * next segment, so the curves must be sampled rather than read as endpoints.
113
+ * `L`, `H`, `V` and `Z` are handled too, which makes this usable on any path the
114
+ * canvas holds — including the clean shapes themselves.
115
+ */
116
+ export declare function flattenPathCommands(commands: readonly PathCommand[], samplesPerCurve?: number): StrokePoint[];
117
+ /** Uniform arc-length resample, so fast and slow strokes are measured the same. */
118
+ export declare function resample(points: readonly StrokePoint[], count?: number): StrokePoint[];
119
+ /** Ramer–Douglas–Peucker — the vertices a human would name as the corners. */
120
+ export declare function simplify(points: readonly StrokePoint[], tolerance: number): StrokePoint[];
121
+ export declare function measureStroke(rawPoints: readonly StrokePoint[]): StrokeMeasurements | null;
122
+ /**
123
+ * The shapes this stroke could still plausibly be, best first.
124
+ *
125
+ * Empty means "not a shape the canvas can build" — a line, a scribble, a
126
+ * signature, a check mark, a tilted quad — and the caller must leave the drawing
127
+ * untouched. The returned list doubles as the roster for the JEV escalation, so
128
+ * JEV is only ever asked to choose between shapes the stroke could actually be.
129
+ */
130
+ export declare function rankSnapShapes(measurements: StrokeMeasurements): SnapRanking[];
131
+ /**
132
+ * The winner when it is decisive — a solid score *and* a clear lead over the
133
+ * runner-up. `null` means "ask JEV", or, when there is no JEV to ask, leave the
134
+ * stroke as drawn.
135
+ */
136
+ export declare function confidentSnapShape(rankings: readonly SnapRanking[]): SnapRanking | null;
137
+ export interface SnapBounds {
138
+ left: number;
139
+ top: number;
140
+ width: number;
141
+ height: number;
142
+ }
143
+ export interface SnapPlacement {
144
+ /** Bounds the replacement shape should occupy. */
145
+ bounds: SnapBounds;
146
+ /**
147
+ * For shapes that must stay proportional (the circle, and the square-designed
148
+ * library shapes), the side length to use, centred inside `bounds`. Undefined
149
+ * when the shape may stretch to fill them.
150
+ */
151
+ forcedSide?: number;
152
+ }
153
+ /**
154
+ * Where the clean shape goes: exactly the stroke's bounds.
155
+ *
156
+ * Three shapes refuse to stretch, because stretching them would change which
157
+ * shape they are: a circle whose bounds are 2:1 is an oval, and the library
158
+ * shapes are square-designed symbols. Those get the smaller side, centred on the
159
+ * stroke — the same thing the toolbar does when `lockAspectRatio` is set.
160
+ *
161
+ * Rotation is deliberately not applied: the replacement is upright, which is
162
+ * what the toolbar would have given the user, and strokes tilted far enough to
163
+ * matter never reach here (see `SHAPE_GATES`).
164
+ */
165
+ export declare function planSnapPlacement(shape: CanvasSnapShape, bounds: SnapBounds): SnapPlacement;