@widgetic/canvas 0.5.35 → 0.5.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -36
- package/dist/canvas/DomCanvas.svelte +449 -0
- package/dist/canvas/DomCanvas.svelte.d.ts +221 -0
- package/dist/canvas/boardFrame.d.ts +13 -0
- package/dist/canvas/boardFrame.js +13 -0
- package/dist/canvas/boardSurface.d.ts +9 -0
- package/dist/canvas/boardSurface.js +9 -0
- package/dist/canvas/chromeLayout.d.ts +76 -0
- package/dist/canvas/chromeLayout.js +121 -0
- package/dist/canvas/emptyBoardHint.d.ts +17 -0
- package/dist/canvas/emptyBoardHint.js +12 -0
- package/dist/canvas/eventScope.d.ts +1 -1
- package/dist/canvas/eventScope.js +1 -1
- package/dist/canvas/host/CanvasHost.d.ts +348 -0
- package/dist/canvas/host/CanvasHost.js +1715 -0
- package/dist/canvas/host/CanvasHostApi.d.ts +30 -0
- package/dist/canvas/host/CanvasHostApi.js +95 -0
- package/dist/canvas/host/browserServices.d.ts +46 -0
- package/dist/canvas/host/browserServices.js +167 -0
- package/dist/canvas/host/conversion.d.ts +53 -0
- package/dist/canvas/host/conversion.js +125 -0
- package/dist/canvas/host/hostObject.d.ts +40 -0
- package/dist/canvas/host/hostObject.js +93 -0
- package/dist/canvas/host/pageEvents.d.ts +24 -0
- package/dist/canvas/host/pageEvents.js +35 -0
- package/dist/canvas/host/screenRects.d.ts +66 -0
- package/dist/canvas/host/screenRects.js +102 -0
- package/dist/canvas/host/strokeSnap.d.ts +67 -0
- package/dist/canvas/host/strokeSnap.js +165 -0
- package/dist/canvas/index.d.ts +7 -7
- package/dist/canvas/index.js +8 -8
- package/dist/canvas/openMarks.d.ts +17 -0
- package/dist/canvas/openMarks.js +26 -0
- package/dist/canvas/panZoomPosition.d.ts +15 -0
- package/dist/canvas/panZoomPosition.js +16 -0
- package/dist/canvas/preferredTextFont.d.ts +12 -0
- package/dist/canvas/preferredTextFont.js +38 -0
- package/dist/canvas/shapes/ShapeLibrary.d.ts +1 -1
- package/dist/canvas/shapes/ShapeLibrary.js +13 -1
- package/dist/canvas/shapes/strokeShapeSnap.d.ts +14 -12
- package/dist/canvas/shapes/strokeShapeSnap.js +10 -8
- package/dist/canvas/toolbarPosition.d.ts +11 -11
- package/dist/canvas/toolbarPosition.js +11 -24
- package/dist/canvas/types.d.ts +14 -0
- package/dist/canvas/ui/CanvasContextMenu.svelte +173 -0
- package/dist/canvas/ui/CanvasContextMenu.svelte.d.ts +12 -0
- package/dist/canvas/ui/CanvasHint.svelte +21 -0
- package/dist/canvas/ui/CanvasHint.svelte.d.ts +18 -0
- package/dist/canvas/ui/CanvasToolbar.svelte +95 -0
- package/dist/canvas/ui/CanvasToolbar.svelte.d.ts +14 -0
- package/dist/canvas/ui/ColorField.svelte +156 -0
- package/dist/canvas/ui/ColorField.svelte.d.ts +14 -0
- package/dist/canvas/ui/LoadNotice.svelte +39 -0
- package/dist/canvas/ui/LoadNotice.svelte.d.ts +8 -0
- package/dist/canvas/ui/SelectionPanel.svelte +300 -0
- package/dist/canvas/ui/SelectionPanel.svelte.d.ts +20 -0
- package/dist/canvas/ui/SelectorBar.svelte +82 -0
- package/dist/canvas/ui/SelectorBar.svelte.d.ts +12 -0
- package/dist/canvas/ui/ShapesMenu.svelte +185 -0
- package/dist/canvas/ui/ShapesMenu.svelte.d.ts +15 -0
- package/dist/canvas/ui/ShortcutsPanel.svelte +124 -0
- package/dist/canvas/ui/ShortcutsPanel.svelte.d.ts +7 -0
- package/dist/canvas/ui/ToolButton.svelte +78 -0
- package/dist/canvas/ui/ToolButton.svelte.d.ts +20 -0
- package/dist/canvas/ui/WidgetActions.svelte +145 -0
- package/dist/canvas/ui/WidgetActions.svelte.d.ts +19 -0
- package/dist/canvas/ui/ZoomControl.svelte +89 -0
- package/dist/canvas/ui/ZoomControl.svelte.d.ts +18 -0
- package/dist/canvas/ui/colorModel.d.ts +18 -0
- package/dist/canvas/ui/colorModel.js +85 -0
- package/dist/canvas/ui/colorPickerMessages.d.ts +5 -0
- package/dist/canvas/ui/colorPickerMessages.js +15 -0
- package/dist/canvas/ui/floatingCard.d.ts +107 -0
- package/dist/canvas/ui/floatingCard.js +107 -0
- package/dist/canvas/ui/floatingLayer.d.ts +21 -0
- package/dist/canvas/ui/floatingLayer.js +52 -0
- package/dist/canvas/ui/icons.d.ts +12 -0
- package/dist/canvas/ui/icons.js +7 -0
- package/dist/canvas/ui/keyHints.d.ts +27 -0
- package/dist/canvas/ui/keyHints.js +43 -0
- package/dist/canvas/ui/popoverSide.d.ts +5 -0
- package/dist/canvas/ui/popoverSide.js +20 -0
- package/dist/canvas/ui/selectionTraits.d.ts +61 -0
- package/dist/canvas/ui/selectionTraits.js +99 -0
- package/dist/canvas/view/CanvasStage.svelte +132 -0
- package/dist/canvas/view/CanvasStage.svelte.d.ts +21 -0
- package/dist/canvas/view/EraserTrail.svelte +50 -0
- package/dist/canvas/view/EraserTrail.svelte.d.ts +9 -0
- package/dist/canvas/view/ObjectView.svelte +245 -0
- package/dist/canvas/view/ObjectView.svelte.d.ts +21 -0
- package/dist/canvas/view/SelectionOverlay.svelte +487 -0
- package/dist/canvas/view/SelectionOverlay.svelte.d.ts +17 -0
- package/dist/canvas/view/TextEditor.svelte +76 -0
- package/dist/canvas/view/TextEditor.svelte.d.ts +9 -0
- package/dist/canvas/view/WidgetChromeLayer.svelte +83 -0
- package/dist/canvas/view/WidgetChromeLayer.svelte.d.ts +13 -0
- package/dist/canvas/view/erasingMarks.d.ts +13 -0
- package/dist/canvas/view/erasingMarks.js +34 -0
- package/dist/canvas/view/geometry.d.ts +169 -0
- package/dist/canvas/view/geometry.js +272 -0
- package/dist/components/CanvasBoardPlaceholder.svelte +5 -3
- package/dist/components/CanvasBoardPlaceholder.svelte.d.ts +3 -3
- package/dist/components/index.js +1 -1
- package/dist/components/input-controls/ColorIC.svelte +2 -2
- package/dist/engine/EngineCore.d.ts +273 -0
- package/dist/engine/EngineCore.js +1051 -0
- package/dist/engine/codec/canvasDocument.d.ts +57 -0
- package/dist/engine/codec/canvasDocument.js +471 -0
- package/dist/engine/codec/hostReadableKeys.d.ts +25 -0
- package/dist/engine/codec/hostReadableKeys.js +25 -0
- package/dist/engine/core/arrange.d.ts +20 -0
- package/dist/engine/core/arrange.js +81 -0
- package/dist/engine/core/arrow.d.ts +91 -0
- package/dist/engine/core/arrow.js +182 -0
- package/dist/engine/core/brush.d.ts +68 -0
- package/dist/engine/core/brush.js +173 -0
- package/dist/engine/core/defaults.d.ts +70 -0
- package/dist/engine/core/defaults.js +158 -0
- package/dist/engine/core/freehand.d.ts +130 -0
- package/dist/engine/core/freehand.js +430 -0
- package/dist/engine/core/geometry.d.ts +44 -0
- package/dist/engine/core/geometry.js +216 -0
- package/dist/engine/core/history.d.ts +39 -0
- package/dist/engine/core/history.js +69 -0
- package/dist/engine/core/hitTest.d.ts +54 -0
- package/dist/engine/core/hitTest.js +298 -0
- package/dist/engine/core/matrix.d.ts +47 -0
- package/dist/engine/core/matrix.js +101 -0
- package/dist/engine/core/pathData.d.ts +50 -0
- package/dist/engine/core/pathData.js +550 -0
- package/dist/engine/core/rotationReset.d.ts +10 -0
- package/dist/engine/core/rotationReset.js +17 -0
- package/dist/engine/core/scene.d.ts +99 -0
- package/dist/engine/core/scene.js +450 -0
- package/dist/engine/core/scribble.d.ts +64 -0
- package/dist/engine/core/scribble.js +121 -0
- package/dist/engine/core/shapePaths.d.ts +34 -0
- package/dist/engine/core/shapePaths.js +69 -0
- package/dist/engine/core/shapeTools.d.ts +80 -0
- package/dist/engine/core/shapeTools.js +161 -0
- package/dist/engine/core/snapping.d.ts +64 -0
- package/dist/engine/core/snapping.js +164 -0
- package/dist/engine/core/style.d.ts +40 -0
- package/dist/engine/core/style.js +151 -0
- package/dist/engine/core/transform.d.ts +79 -0
- package/dist/engine/core/transform.js +258 -0
- package/dist/engine/core/types.d.ts +238 -0
- package/dist/engine/core/types.js +31 -0
- package/dist/engine/core/viewport.d.ts +32 -0
- package/dist/engine/core/viewport.js +84 -0
- package/dist/engine/input/PointerController.d.ts +38 -0
- package/dist/engine/input/PointerController.js +545 -0
- package/dist/engine/input/arrowHandles.d.ts +38 -0
- package/dist/engine/input/arrowHandles.js +60 -0
- package/dist/engine/input/gestures.d.ts +79 -0
- package/dist/engine/input/gestures.js +769 -0
- package/dist/engine/input/hoverCursor.d.ts +29 -0
- package/dist/engine/input/hoverCursor.js +23 -0
- package/dist/engine/input/keyboard.d.ts +75 -0
- package/dist/engine/input/keyboard.js +264 -0
- package/dist/engine/input/selectionHandles.d.ts +89 -0
- package/dist/engine/input/selectionHandles.js +169 -0
- package/dist/engine/input/types.d.ts +82 -0
- package/dist/engine/input/types.js +5 -0
- package/dist/engine/render/rasterize.d.ts +74 -0
- package/dist/engine/render/rasterize.js +273 -0
- package/dist/engine/state.d.ts +124 -0
- package/dist/engine/state.js +47 -0
- package/dist/engine/text/layoutText.d.ts +53 -0
- package/dist/engine/text/layoutText.js +170 -0
- package/dist/engine/widgets.d.ts +124 -0
- package/dist/engine/widgets.js +345 -0
- package/dist/i18n/labels.d.ts +4 -15
- package/dist/i18n/labels.js +33 -53
- package/dist/i18n/language.d.ts +3 -3
- package/dist/i18n/messages.d.ts +52 -124
- package/dist/i18n/messages.js +59 -133
- package/dist/i18n/shortcuts.d.ts +0 -1
- package/dist/i18n/shortcuts.js +2 -11
- package/dist/index.d.ts +4 -2
- package/dist/index.js +5 -3
- package/package.json +30 -5
- package/dist/canvas/Canvas.svelte +0 -13363
- package/dist/canvas/Canvas.svelte.d.ts +0 -286
- package/dist/canvas/CanvasToolbar.svelte +0 -1498
- package/dist/canvas/CanvasToolbar.svelte.d.ts +0 -69
- package/dist/canvas/ContextMenu.svelte +0 -305
- package/dist/canvas/ContextMenu.svelte.d.ts +0 -42
- package/dist/canvas/PanZoomPanel.svelte +0 -478
- package/dist/canvas/PanZoomPanel.svelte.d.ts +0 -38
- package/dist/canvas/WidgetSelectionLayer.svelte +0 -156
- package/dist/canvas/WidgetSelectionLayer.svelte.d.ts +0 -11
- package/dist/canvas/props-panel/PropsPanel.svelte +0 -2075
- package/dist/canvas/props-panel/PropsPanel.svelte.d.ts +0 -84
- package/dist/canvas/props-panel/TextPropsICSection.svelte +0 -242
- package/dist/canvas/props-panel/TextPropsICSection.svelte.d.ts +0 -40
- package/dist/canvas/shadowRootText.d.ts +0 -5
- package/dist/canvas/shadowRootText.js +0 -43
- package/dist/canvas/shapes/FrameShape.d.ts +0 -97
- package/dist/canvas/shapes/FrameShape.js +0 -953
- package/dist/canvas/shapes/ImageShape.d.ts +0 -47
- package/dist/canvas/shapes/ImageShape.js +0 -339
- package/dist/canvas/shapes/WidgetShape.d.ts +0 -30
- package/dist/canvas/shapes/WidgetShape.js +0 -200
- package/dist/canvas/widgetPreviewGeometry.d.ts +0 -19
- package/dist/canvas/widgetPreviewGeometry.js +0 -66
- package/dist/i18n/shapeWords.d.ts +0 -30
- package/dist/i18n/shapeWords.js +0 -36
- package/dist/i18n/slots.d.ts +0 -20
- package/dist/i18n/slots.js +0 -40
|
@@ -0,0 +1,1715 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host of one canvas: the object the Svelte shell talks to, and the only place where the engine meets the page.
|
|
3
|
+
*
|
|
4
|
+
* It owns the engine, the pointer controller, the autosave buffer and the registry of conversions in flight, and it
|
|
5
|
+
* keeps every promise the canvas this one replaces made to the widget creator and the other modules that mount it:
|
|
6
|
+
* the props they set (read at the moment they are needed, so a change takes effect without a remount), the functions
|
|
7
|
+
* they call (the shell re-exports them one by one), the callbacks they are given, and the order in which these happen.
|
|
8
|
+
*
|
|
9
|
+
* Plain TypeScript with no Svelte and no DOM at construction, so a page that is rendered on the server can make one;
|
|
10
|
+
* the shell calls `attach` from `onMount` and `destroy` from `onDestroy`. The engine's state and the host's own UI state
|
|
11
|
+
* are offered as stores (`engineStore`, `uiStore`), so legacy and runes components read them the same way.
|
|
12
|
+
*/
|
|
13
|
+
import { createObjectId, createImageObject, createRectObject } from '../../engine/core/defaults.js';
|
|
14
|
+
import { boundsOfObjects, shapeBounds } from '../../engine/core/scene.js';
|
|
15
|
+
import { buildDraggedShape } from '../../engine/core/shapeTools.js';
|
|
16
|
+
import { EngineCore } from '../../engine/EngineCore.js';
|
|
17
|
+
import { releaseHeldKeys, routeKeyDown, routeKeyUp } from '../../engine/input/keyboard.js';
|
|
18
|
+
import { PointerController } from '../../engine/input/PointerController.js';
|
|
19
|
+
import { renderShapesToDataUrl } from '../../engine/render/rasterize.js';
|
|
20
|
+
import { layoutTextObject } from '../../engine/text/layoutText.js';
|
|
21
|
+
import { ConversionRegistry, absorbSketchIntoWidget, addWidgetCard, commitWidgetCardMove, findWidgetCard, hydrateWidgetMetadata, keepOnlyWidgetCard, linkedWidgetIds, markOrphanedWidgetCards, moveWidgetCardByScreen, primaryWidgetId, removeSketchObjectsKeeping, replaceObjectWithWidgetCard, selectWidgetCard, selectedWidgetId, setPrimaryWidgetCard, updateWidgetThumbnail } from '../../engine/widgets.js';
|
|
22
|
+
import { createAutosaveScheduler } from '../autosaveScheduler.js';
|
|
23
|
+
import { readPreferredTextFontFamily } from '../preferredTextFont.js';
|
|
24
|
+
import { canvasLog, canvasWarn, setCanvasLogsEnabled } from '../canvasLogger.js';
|
|
25
|
+
import { CANVAS_OPEN_MARKS, markCanvasOpenStep } from '../openMarks.js';
|
|
26
|
+
import { eventIsForScope, getEventOrigin, shouldTakeFocusBack } from '../eventScope.js';
|
|
27
|
+
import { getShapeImageStore } from '../shapes/shapeImageStore.js';
|
|
28
|
+
import { chooseImageFiles, createBrowserMeasureText, createBrowserRasterServices, readImageFile } from './browserServices.js';
|
|
29
|
+
import { buildCapturePayload } from './conversion.js';
|
|
30
|
+
import { announceSelectTool, announceWidgetPointerBlock } from './pageEvents.js';
|
|
31
|
+
import { hostObjectById, selectedHostObject } from './hostObject.js';
|
|
32
|
+
import { screenRectOfBounds, widgetPreviewGeometry } from './screenRects.js';
|
|
33
|
+
import { isShapeSnapOn, snapDrawnStroke } from './strokeSnap.js';
|
|
34
|
+
/** What each prop is until the page sets it (the values the canvas this one replaces had, but for `panZoomPosition`). */
|
|
35
|
+
export const DEFAULT_HOST_PROPS = Object.freeze({
|
|
36
|
+
showContainerFrame: true,
|
|
37
|
+
widgetSelectionLayerTarget: '',
|
|
38
|
+
onObjectClick: null,
|
|
39
|
+
panZoomPosition: 'BL',
|
|
40
|
+
toolbarPosition: 'BC',
|
|
41
|
+
wireframeMode: true,
|
|
42
|
+
advancedFeatures: false,
|
|
43
|
+
showElementSelector: false,
|
|
44
|
+
showDrawingTools: true,
|
|
45
|
+
elementSelectorActive: false,
|
|
46
|
+
onToggleElementSelector: null,
|
|
47
|
+
selectorGuide: null,
|
|
48
|
+
showZoomPanel: true,
|
|
49
|
+
mediaBtsOnBar: true,
|
|
50
|
+
initialData: null,
|
|
51
|
+
onReady: null,
|
|
52
|
+
isExternalDataLoading: false,
|
|
53
|
+
onBeforeUnmount: null,
|
|
54
|
+
onAutoSave: null,
|
|
55
|
+
autosaveDelayMs: 3000,
|
|
56
|
+
autosaveMaxWaitMs: 10000,
|
|
57
|
+
suspendAutosave: false,
|
|
58
|
+
showSaveButton: false,
|
|
59
|
+
onCanvasDirty: null,
|
|
60
|
+
onCanvasCleared: null,
|
|
61
|
+
onWidgetImageClick: null,
|
|
62
|
+
onRecognizeStroke: null,
|
|
63
|
+
onNonWidgetSelected: null,
|
|
64
|
+
onWidgetShapeDuplicated: null,
|
|
65
|
+
onWidgetShapeDeleting: null,
|
|
66
|
+
onWidgetRename: null,
|
|
67
|
+
onRefreshScreenshot: null,
|
|
68
|
+
onSetPrimaryWidget: null,
|
|
69
|
+
onAfterRender: null,
|
|
70
|
+
getWidgetName: null,
|
|
71
|
+
widgetNameRevision: 0,
|
|
72
|
+
isWidgetKnown: null,
|
|
73
|
+
showLogs: false,
|
|
74
|
+
shapeSnap: false
|
|
75
|
+
});
|
|
76
|
+
/** A store the way Svelte reads one (`$store` and `fromStore` both work on it). */
|
|
77
|
+
class ValueStore {
|
|
78
|
+
#value;
|
|
79
|
+
#subscribers = new Set();
|
|
80
|
+
constructor(initial) {
|
|
81
|
+
this.#value = initial;
|
|
82
|
+
}
|
|
83
|
+
get value() {
|
|
84
|
+
return this.#value;
|
|
85
|
+
}
|
|
86
|
+
set(next) {
|
|
87
|
+
if (Object.is(next, this.#value))
|
|
88
|
+
return;
|
|
89
|
+
this.#value = next;
|
|
90
|
+
for (const run of [...this.#subscribers])
|
|
91
|
+
run(next);
|
|
92
|
+
}
|
|
93
|
+
subscribe(run) {
|
|
94
|
+
this.#subscribers.add(run);
|
|
95
|
+
run(this.#value);
|
|
96
|
+
return () => {
|
|
97
|
+
this.#subscribers.delete(run);
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const INITIAL_UI_STATE = Object.freeze({
|
|
102
|
+
loadPhase: 'initializing',
|
|
103
|
+
loadStatus: null,
|
|
104
|
+
saveState: 'saved',
|
|
105
|
+
contextMenu: null,
|
|
106
|
+
shapesMenuOpen: false,
|
|
107
|
+
shortcutsOpen: false,
|
|
108
|
+
selectionPanelDismissed: true,
|
|
109
|
+
spacePan: false,
|
|
110
|
+
gestureKind: null,
|
|
111
|
+
nameRevision: 0,
|
|
112
|
+
emptyHintGateOpen: false
|
|
113
|
+
});
|
|
114
|
+
/** Text put on the system clipboard by a copy on the board, so that a picture copied earlier does not win the next paste. */
|
|
115
|
+
export const CLIPBOARD_MARKER = 'widgetic-canvas-selection';
|
|
116
|
+
/** The longest side a picture gets when it is put on the board (the picture itself keeps its size). */
|
|
117
|
+
export const IMAGE_INSERT_MAX_SIDE = 480;
|
|
118
|
+
/** The smallest side of a picture put on the board. */
|
|
119
|
+
export const IMAGE_INSERT_MIN_SIDE = 24;
|
|
120
|
+
/**
|
|
121
|
+
* How long a finger rests on the board before the press is a long press (it opens the menu a right click opens), and how
|
|
122
|
+
* far the finger may wander meanwhile, in board pixels. The host times it itself: a browser that sends a `contextmenu`
|
|
123
|
+
* for a long press (Android) is not needed, and one that does not (an iPad) is served the same.
|
|
124
|
+
*/
|
|
125
|
+
export const TOUCH_LONG_PRESS_DELAY_MS = 500;
|
|
126
|
+
export const TOUCH_LONG_PRESS_SLOP = 8;
|
|
127
|
+
/** How long after the finger that opened the menu lifts its release is still told apart from a choice (see `isMenuHeldByItsFinger`). */
|
|
128
|
+
export const TOUCH_MENU_RELEASE_GRACE_MS = 400;
|
|
129
|
+
/** A picture's size on the board: its own size, or the biggest one that fits `IMAGE_INSERT_MAX_SIDE`. */
|
|
130
|
+
export function fitImageSize(naturalWidth, naturalHeight) {
|
|
131
|
+
const width = Math.max(1, naturalWidth || IMAGE_INSERT_MAX_SIDE);
|
|
132
|
+
const height = Math.max(1, naturalHeight || IMAGE_INSERT_MAX_SIDE);
|
|
133
|
+
const scale = Math.min(1, IMAGE_INSERT_MAX_SIDE / Math.max(width, height));
|
|
134
|
+
return {
|
|
135
|
+
width: Math.max(IMAGE_INSERT_MIN_SIDE, Math.round(width * scale)),
|
|
136
|
+
height: Math.max(IMAGE_INSERT_MIN_SIDE, Math.round(height * scale))
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
const isEditableTarget = (element) => {
|
|
140
|
+
if (!element)
|
|
141
|
+
return false;
|
|
142
|
+
const tag = element.tagName;
|
|
143
|
+
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || element.isContentEditable === true;
|
|
144
|
+
};
|
|
145
|
+
/** Elements that read the arrow keys (and Home, End, Page Up and Down) themselves: a slider, a tab list, a list box. */
|
|
146
|
+
const ARROW_KEY_ROLES = new Set([
|
|
147
|
+
'slider',
|
|
148
|
+
'spinbutton',
|
|
149
|
+
'scrollbar',
|
|
150
|
+
'tablist',
|
|
151
|
+
'tab',
|
|
152
|
+
'radio',
|
|
153
|
+
'radiogroup',
|
|
154
|
+
'combobox',
|
|
155
|
+
'listbox',
|
|
156
|
+
'option',
|
|
157
|
+
'tree',
|
|
158
|
+
'treeitem',
|
|
159
|
+
'grid',
|
|
160
|
+
'gridcell'
|
|
161
|
+
]);
|
|
162
|
+
/** The keys such an element moves with. */
|
|
163
|
+
const NAVIGATION_KEYS = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown']);
|
|
164
|
+
/** An element with the focus that moves with the arrow keys itself: the selection must not move under it. */
|
|
165
|
+
const ownsNavigationKeys = (element) => {
|
|
166
|
+
const role = element?.getAttribute?.('role');
|
|
167
|
+
return role !== null && role !== undefined && ARROW_KEY_ROLES.has(role);
|
|
168
|
+
};
|
|
169
|
+
/** A button, link or menu entry that has the focus: Space belongs to it, not to the pan. */
|
|
170
|
+
const isActivatableTarget = (element) => {
|
|
171
|
+
if (!element)
|
|
172
|
+
return false;
|
|
173
|
+
const tag = element.tagName;
|
|
174
|
+
if (tag === 'BUTTON' || tag === 'A' || tag === 'SUMMARY')
|
|
175
|
+
return true;
|
|
176
|
+
const role = element.getAttribute('role');
|
|
177
|
+
return role === 'button' || role === 'menuitem' || role === 'menuitemcheckbox' || role === 'menuitemradio' || role === 'option' || role === 'switch' || role === 'checkbox' || role === 'tab';
|
|
178
|
+
};
|
|
179
|
+
/** The part of the page a paste is not meant for (the creator's own panels and lists). */
|
|
180
|
+
const PASTE_EXCLUDED_SELECTOR = '.widget-details-floating-panel, .widgets-list-panel, [data-widget-details]';
|
|
181
|
+
// ──────────────────────────────────────────────────────────── the host
|
|
182
|
+
export class CanvasHost {
|
|
183
|
+
engine;
|
|
184
|
+
controller;
|
|
185
|
+
conversions = new ConversionRegistry();
|
|
186
|
+
/** The engine's state as a store. */
|
|
187
|
+
engineStore;
|
|
188
|
+
/** The host's own state as a store. */
|
|
189
|
+
uiStore;
|
|
190
|
+
props = { ...DEFAULT_HOST_PROPS };
|
|
191
|
+
/** The words the host draws or says (the shell gives it the language of the page). */
|
|
192
|
+
translate = (key) => key;
|
|
193
|
+
#ui = new ValueStore(INITIAL_UI_STATE);
|
|
194
|
+
#scheduler;
|
|
195
|
+
#measureText = createBrowserMeasureText();
|
|
196
|
+
#raster = createBrowserRasterServices(this.#measureText);
|
|
197
|
+
#root = null;
|
|
198
|
+
#board = null;
|
|
199
|
+
#resizeObserver = null;
|
|
200
|
+
#removeListeners = [];
|
|
201
|
+
#destroyed = false;
|
|
202
|
+
#loadDepth = 0;
|
|
203
|
+
/** A finger that is resting on the board and may become a long press. */
|
|
204
|
+
#longPress = null;
|
|
205
|
+
/** The last press was a finger's: a `contextmenu` that follows it is the browser's own long-press menu. */
|
|
206
|
+
#touchWasLast = false;
|
|
207
|
+
/** The finger whose long press opened the menu, and when it lifted (null while it is still down). */
|
|
208
|
+
#menuFinger = null;
|
|
209
|
+
#lastOverlayState = null;
|
|
210
|
+
#afterRenderQueued = false;
|
|
211
|
+
/** The widget whose card is being stretched, as the page was told (null: the page was told nothing, or that it ended). */
|
|
212
|
+
#resizingWidgetId = null;
|
|
213
|
+
/** The lines of every text, kept for as long as the text object is the same record and the fonts are the same. */
|
|
214
|
+
#textLayouts = new WeakMap();
|
|
215
|
+
#textLayoutsFontRevision = -1;
|
|
216
|
+
#applyingAfterRender = false;
|
|
217
|
+
#unsubscribeEngine = null;
|
|
218
|
+
/** The last payload handed to `onAutoSave`, so a timer that fires with no real change does not serialize again. */
|
|
219
|
+
#lastAutosavedJson = null;
|
|
220
|
+
/** A text was being typed at the last change of the engine (its field is on the page). */
|
|
221
|
+
#wasEditingText = false;
|
|
222
|
+
/** The board is about to take the keyboard back from a text field that left the page (asked for the next frame). */
|
|
223
|
+
#keyboardReturnQueued = false;
|
|
224
|
+
/** The animation frame that steps the eraser's trail (null: none asked for), and when the trail was last stepped (null: the clock is idle). */
|
|
225
|
+
#scribbleFrame = null;
|
|
226
|
+
#scribbleClockLast = null;
|
|
227
|
+
constructor(initialProps = {}) {
|
|
228
|
+
this.props = { ...DEFAULT_HOST_PROPS, ...initialProps };
|
|
229
|
+
this.engine = new EngineCore({ measureText: this.#measureText });
|
|
230
|
+
this.engine.wireframeMode = this.props.wireframeMode;
|
|
231
|
+
// The font the person chose for their texts the last time: the first text of this board starts with it too (null where nothing is kept).
|
|
232
|
+
const preferredTextFontFamily = readPreferredTextFontFamily();
|
|
233
|
+
if (preferredTextFontFamily)
|
|
234
|
+
this.engine.setPreferredTextFontFamily(preferredTextFontFamily);
|
|
235
|
+
this.controller = new PointerController(this.engine, {
|
|
236
|
+
snapEnabled: () => true,
|
|
237
|
+
onStrokeFinished: (stroke, handLine) => this.#handleStrokeFinished(stroke, handLine),
|
|
238
|
+
onGestureChange: (kind) => {
|
|
239
|
+
this.#updateUi({ gestureKind: kind });
|
|
240
|
+
this.#announceWidgetResize(kind);
|
|
241
|
+
},
|
|
242
|
+
onActivate: (id) => this.#handleActivate(id),
|
|
243
|
+
plainCardChrome: () => !this.props.advancedFeatures
|
|
244
|
+
});
|
|
245
|
+
this.engineStore = {
|
|
246
|
+
subscribe: (run) => {
|
|
247
|
+
run(this.engine.state);
|
|
248
|
+
return this.engine.subscribe(run);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
this.uiStore = this.#ui;
|
|
252
|
+
this.#scheduler = createAutosaveScheduler({
|
|
253
|
+
getDelayMs: () => this.props.autosaveDelayMs,
|
|
254
|
+
getMaxWaitMs: () => this.props.autosaveMaxWaitMs,
|
|
255
|
+
isSuspended: () => this.props.suspendAutosave,
|
|
256
|
+
save: () => this.#runAutosave(),
|
|
257
|
+
onSaveFailed: (error) => {
|
|
258
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
259
|
+
canvasWarn('Canvas: autosave failed, the changes stay unsaved until the next change', error);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
this.#wireEngineHooks();
|
|
263
|
+
this.#unsubscribeEngine = this.engine.subscribe((state) => this.#onEngineState(state));
|
|
264
|
+
setCanvasLogsEnabled(this.props.showLogs);
|
|
265
|
+
}
|
|
266
|
+
// ────────────────────────────────────────────────────── props and ui
|
|
267
|
+
/** The page changed some props. */
|
|
268
|
+
setProps(patch) {
|
|
269
|
+
const previous = this.props;
|
|
270
|
+
this.props = { ...previous, ...patch };
|
|
271
|
+
if (this.props.showLogs !== previous.showLogs)
|
|
272
|
+
setCanvasLogsEnabled(this.props.showLogs);
|
|
273
|
+
if (this.props.wireframeMode !== previous.wireframeMode)
|
|
274
|
+
this.engine.wireframeMode = this.props.wireframeMode;
|
|
275
|
+
if (this.props.widgetNameRevision !== previous.widgetNameRevision || this.props.getWidgetName !== previous.getWidgetName) {
|
|
276
|
+
this.#updateUi({ nameRevision: this.#ui.value.nameRevision + 1 });
|
|
277
|
+
}
|
|
278
|
+
if (this.props.onAfterRender && !previous.onAfterRender)
|
|
279
|
+
this.#queueAfterRender();
|
|
280
|
+
if (this.props.showDrawingTools !== previous.showDrawingTools)
|
|
281
|
+
this.#dropToolsThePageHides();
|
|
282
|
+
if (this.props.isExternalDataLoading !== previous.isExternalDataLoading) {
|
|
283
|
+
queueMicrotask(() => this.#syncEmptyHintGate());
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* A tool whose button the page hides must not stay armed: once the page takes the drawing tools off (after the first
|
|
288
|
+
* generation) the pencil, the eraser, the arrow and the text go, and the Select tool takes over. The letter keys are
|
|
289
|
+
* ignored for them as well (see `tools`). The shapes stay: they are not part of the drawing group.
|
|
290
|
+
*/
|
|
291
|
+
#dropToolsThePageHides() {
|
|
292
|
+
if (this.props.showDrawingTools)
|
|
293
|
+
return;
|
|
294
|
+
const { tool } = this.engine.state;
|
|
295
|
+
const drawingGroup = ['draw', 'erase', 'arrow', 'text'];
|
|
296
|
+
if (drawingGroup.includes(tool))
|
|
297
|
+
this.engine.setTool('select');
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* A widget card is being stretched (or the stretch ended): the page is told, so it can let the pointer through the live
|
|
301
|
+
* widget laid over the card. Sent once at each end of the gesture.
|
|
302
|
+
*/
|
|
303
|
+
#announceWidgetResize(kind) {
|
|
304
|
+
if (kind === 'resize') {
|
|
305
|
+
if (this.#resizingWidgetId !== null)
|
|
306
|
+
return;
|
|
307
|
+
const widgetId = selectedWidgetId(this.engine);
|
|
308
|
+
if (!widgetId)
|
|
309
|
+
return;
|
|
310
|
+
this.#resizingWidgetId = widgetId;
|
|
311
|
+
announceWidgetPointerBlock({ widgetId, active: true });
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (this.#resizingWidgetId === null)
|
|
315
|
+
return;
|
|
316
|
+
this.#resizingWidgetId = null;
|
|
317
|
+
announceWidgetPointerBlock({ widgetId: null, active: false });
|
|
318
|
+
}
|
|
319
|
+
/** The shell gives the host the words of the page's language. */
|
|
320
|
+
setTranslator(translate) {
|
|
321
|
+
if (translate === this.translate)
|
|
322
|
+
return;
|
|
323
|
+
this.translate = translate;
|
|
324
|
+
// The names drawn on widget cards are made with these words: the views read them again.
|
|
325
|
+
this.#updateUi({ nameRevision: this.#ui.value.nameRevision + 1 });
|
|
326
|
+
}
|
|
327
|
+
get ui() {
|
|
328
|
+
return this.#ui.value;
|
|
329
|
+
}
|
|
330
|
+
updateUi(patch) {
|
|
331
|
+
this.#updateUi(patch);
|
|
332
|
+
}
|
|
333
|
+
#updateUi(patch) {
|
|
334
|
+
if (this.#destroyed)
|
|
335
|
+
return;
|
|
336
|
+
const current = this.#ui.value;
|
|
337
|
+
for (const key of Object.keys(patch)) {
|
|
338
|
+
if (!Object.is(patch[key], current[key])) {
|
|
339
|
+
this.#ui.set({ ...current, ...patch });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/** True while the board is loading or the page says it is (the loader shows, input waits). */
|
|
345
|
+
get isLoading() {
|
|
346
|
+
return this.#ui.value.loadPhase !== 'ready' || this.props.isExternalDataLoading;
|
|
347
|
+
}
|
|
348
|
+
/** The tools the page lets people use: the drawing group is the page's to hide, the shapes are always there. */
|
|
349
|
+
get tools() {
|
|
350
|
+
return { drawing: this.props.showDrawingTools };
|
|
351
|
+
}
|
|
352
|
+
// ────────────────────────────────────────────────────── lifecycle
|
|
353
|
+
/** The shell mounted: the board element exists and has a size. Starts listening and loads the data the page gave. */
|
|
354
|
+
attach(root, board) {
|
|
355
|
+
if (this.#destroyed)
|
|
356
|
+
return;
|
|
357
|
+
this.#root = root;
|
|
358
|
+
this.#board = board;
|
|
359
|
+
this.#measureBoard();
|
|
360
|
+
if (typeof ResizeObserver !== 'undefined') {
|
|
361
|
+
this.#resizeObserver = new ResizeObserver(() => this.#measureBoard());
|
|
362
|
+
this.#resizeObserver.observe(board);
|
|
363
|
+
}
|
|
364
|
+
this.#listen(window, 'keydown', (event) => this.#onKeyDown(event), true);
|
|
365
|
+
this.#listen(window, 'keyup', (event) => this.#onKeyUp(event));
|
|
366
|
+
this.#listen(window, 'blur', () => this.#onWindowBlur());
|
|
367
|
+
this.#listen(window, 'paste', (event) => this.#onPaste(event));
|
|
368
|
+
this.#listen(window, 'pagehide', () => void this.#scheduler.flush());
|
|
369
|
+
this.#listen(document, 'visibilitychange', () => {
|
|
370
|
+
if (document.visibilityState === 'hidden')
|
|
371
|
+
void this.#scheduler.flush();
|
|
372
|
+
});
|
|
373
|
+
this.#listen(board, 'wheel', (event) => this.#onWheel(event), false, { passive: false });
|
|
374
|
+
if (typeof document !== 'undefined' && document.fonts && typeof document.fonts.addEventListener === 'function') {
|
|
375
|
+
this.#listen(document.fonts, 'loadingdone', () => this.engine.notifyFontsChanged());
|
|
376
|
+
}
|
|
377
|
+
this.engine.notifyFontsChanged();
|
|
378
|
+
void this.#start();
|
|
379
|
+
}
|
|
380
|
+
async #start() {
|
|
381
|
+
// One turn of the event loop first: the page that mounted the shell assigns its reference to it (`bind:this`) in
|
|
382
|
+
// the same flush as this mount, and `onReady` is the moment the page starts to call the host's functions.
|
|
383
|
+
await Promise.resolve();
|
|
384
|
+
if (this.#destroyed)
|
|
385
|
+
return;
|
|
386
|
+
const initial = this.props.initialData;
|
|
387
|
+
this.#closeEmptyHintGate();
|
|
388
|
+
if (initial) {
|
|
389
|
+
try {
|
|
390
|
+
await this.loadCanvas(initial);
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
console.error('Canvas: could not load the initial data', error);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (this.#destroyed)
|
|
397
|
+
return;
|
|
398
|
+
// The first tool: the pencil, when the page shows the drawing tools (a board opens ready for a sketch), else Select.
|
|
399
|
+
this.engine.setTool(this.props.showDrawingTools ? 'draw' : 'select');
|
|
400
|
+
this.#updateUi({ loadPhase: 'ready' });
|
|
401
|
+
this.#queueAfterRender();
|
|
402
|
+
markCanvasOpenStep(CANVAS_OPEN_MARKS.READY);
|
|
403
|
+
try {
|
|
404
|
+
this.props.onReady?.();
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
canvasWarn('Canvas: onReady failed', error);
|
|
408
|
+
}
|
|
409
|
+
queueMicrotask(() => queueMicrotask(() => this.#syncEmptyHintGate()));
|
|
410
|
+
}
|
|
411
|
+
#openEmptyHintGate() {
|
|
412
|
+
if (!this.#ui.value.emptyHintGateOpen)
|
|
413
|
+
this.#updateUi({ emptyHintGateOpen: true });
|
|
414
|
+
}
|
|
415
|
+
#closeEmptyHintGate() {
|
|
416
|
+
if (this.#ui.value.emptyHintGateOpen)
|
|
417
|
+
this.#updateUi({ emptyHintGateOpen: false });
|
|
418
|
+
}
|
|
419
|
+
/** Opens the empty-board hint gate only when the host and the page are done loading (see `emptyBoardHint.ts`). */
|
|
420
|
+
#syncEmptyHintGate() {
|
|
421
|
+
if (this.#destroyed)
|
|
422
|
+
return;
|
|
423
|
+
const waiting = this.#ui.value.loadPhase !== 'ready' ||
|
|
424
|
+
this.#loadDepth > 0 ||
|
|
425
|
+
this.engine.state.loading ||
|
|
426
|
+
this.props.isExternalDataLoading;
|
|
427
|
+
if (waiting) {
|
|
428
|
+
this.#closeEmptyHintGate();
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
this.#openEmptyHintGate();
|
|
432
|
+
}
|
|
433
|
+
/** The shell is going away: hands the page its last chance to keep the board, then lets go of everything. */
|
|
434
|
+
destroy() {
|
|
435
|
+
if (this.#destroyed)
|
|
436
|
+
return;
|
|
437
|
+
try {
|
|
438
|
+
this.props.onBeforeUnmount?.(this.saveCanvas());
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
canvasWarn('Canvas: onBeforeUnmount failed', error);
|
|
442
|
+
}
|
|
443
|
+
this.#announceWidgetResize(null);
|
|
444
|
+
this.#destroyed = true;
|
|
445
|
+
this.#cancelLongPress();
|
|
446
|
+
if (this.#scribbleFrame !== null && typeof cancelAnimationFrame === 'function')
|
|
447
|
+
cancelAnimationFrame(this.#scribbleFrame);
|
|
448
|
+
this.#scribbleFrame = null;
|
|
449
|
+
this.#scribbleClockLast = null;
|
|
450
|
+
this.#scheduler.dispose();
|
|
451
|
+
for (const remove of this.#removeListeners)
|
|
452
|
+
remove();
|
|
453
|
+
this.#removeListeners = [];
|
|
454
|
+
this.#resizeObserver?.disconnect();
|
|
455
|
+
this.#resizeObserver = null;
|
|
456
|
+
this.#unsubscribeEngine?.();
|
|
457
|
+
this.#unsubscribeEngine = null;
|
|
458
|
+
this.controller.dispose();
|
|
459
|
+
this.engine.dispose();
|
|
460
|
+
this.conversions.clear();
|
|
461
|
+
this.#root = null;
|
|
462
|
+
this.#board = null;
|
|
463
|
+
}
|
|
464
|
+
#listen(target, type, listener, capture = false, options = {}) {
|
|
465
|
+
target.addEventListener(type, listener, { capture, ...options });
|
|
466
|
+
this.#removeListeners.push(() => target.removeEventListener(type, listener, { capture }));
|
|
467
|
+
}
|
|
468
|
+
/** The element the board's pointer events come from. */
|
|
469
|
+
get boardElement() {
|
|
470
|
+
return this.#board;
|
|
471
|
+
}
|
|
472
|
+
get rootElement() {
|
|
473
|
+
return this.#root;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Gives the board the keyboard.
|
|
477
|
+
*
|
|
478
|
+
* A press of the pointer passes `focusVisible: false`: the browser draws the focus ring for a focus that a script moves
|
|
479
|
+
* when the last thing the person did was a key, and a press on the board is not asking for a ring (the keyboard still
|
|
480
|
+
* has the focus, and a Tab or an arrow shows it). Browsers that do not know the option ignore it.
|
|
481
|
+
*/
|
|
482
|
+
focusBoard(options = {}) {
|
|
483
|
+
try {
|
|
484
|
+
const focusOptions = { preventScroll: true, ...options };
|
|
485
|
+
this.#board?.focus(focusOptions);
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
// A board that cannot take the focus keeps working.
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
// ────────────────────────────────────────────────────── the board element
|
|
492
|
+
#measureBoard() {
|
|
493
|
+
const board = this.#board;
|
|
494
|
+
if (!board)
|
|
495
|
+
return;
|
|
496
|
+
this.engine.setViewSize({ width: board.clientWidth, height: board.clientHeight });
|
|
497
|
+
}
|
|
498
|
+
/** The board on the page (its rectangle and its layout size), for everything the page lays over it. */
|
|
499
|
+
#frame() {
|
|
500
|
+
const board = this.#board;
|
|
501
|
+
if (!board)
|
|
502
|
+
return null;
|
|
503
|
+
const rect = board.getBoundingClientRect();
|
|
504
|
+
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, layoutWidth: board.clientWidth, layoutHeight: board.clientHeight };
|
|
505
|
+
}
|
|
506
|
+
/** How much the page scales the board (a partner that zooms its whole screen): rendered size over layout size. */
|
|
507
|
+
#cssScale() {
|
|
508
|
+
const frame = this.#frame();
|
|
509
|
+
if (!frame || !frame.layoutWidth || !frame.layoutHeight)
|
|
510
|
+
return { x: 1, y: 1 };
|
|
511
|
+
return { x: frame.width / frame.layoutWidth || 1, y: frame.height / frame.layoutHeight || 1 };
|
|
512
|
+
}
|
|
513
|
+
#pointerInput(event, kind) {
|
|
514
|
+
const frame = this.#frame();
|
|
515
|
+
if (!frame)
|
|
516
|
+
return null;
|
|
517
|
+
const scaleX = frame.width / (frame.layoutWidth || frame.width || 1) || 1;
|
|
518
|
+
const scaleY = frame.height / (frame.layoutHeight || frame.height || 1) || 1;
|
|
519
|
+
const toBoard = (clientX, clientY) => ({ x: (clientX - frame.left) / scaleX, y: (clientY - frame.top) / scaleY });
|
|
520
|
+
const point = toBoard(event.clientX, event.clientY);
|
|
521
|
+
const pointerEvent = event;
|
|
522
|
+
const type = kind ?? (pointerEvent.pointerType === 'pen' ? 'pen' : pointerEvent.pointerType === 'touch' ? 'touch' : 'mouse');
|
|
523
|
+
const pressureOf = (sample) => typeof sample.pressure === 'number' && Number.isFinite(sample.pressure) ? { pressure: sample.pressure } : {};
|
|
524
|
+
const coalesced = typeof pointerEvent.getCoalescedEvents === 'function'
|
|
525
|
+
? pointerEvent.getCoalescedEvents().map((sample) => ({ ...toBoard(sample.clientX, sample.clientY), time: sample.timeStamp, ...pressureOf(sample) }))
|
|
526
|
+
: undefined;
|
|
527
|
+
return {
|
|
528
|
+
pointerId: pointerEvent.pointerId ?? 1,
|
|
529
|
+
pointerType: type,
|
|
530
|
+
x: point.x,
|
|
531
|
+
y: point.y,
|
|
532
|
+
button: event.button,
|
|
533
|
+
time: event.timeStamp,
|
|
534
|
+
shiftKey: event.shiftKey,
|
|
535
|
+
altKey: event.altKey,
|
|
536
|
+
metaKey: event.metaKey,
|
|
537
|
+
ctrlKey: event.ctrlKey,
|
|
538
|
+
...pressureOf(pointerEvent),
|
|
539
|
+
...(coalesced && coalesced.length > 1 ? { coalesced } : {})
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
handlePointerDown(event) {
|
|
543
|
+
if (this.isLoading || this.#destroyed)
|
|
544
|
+
return;
|
|
545
|
+
const input = this.#pointerInput(event);
|
|
546
|
+
if (!input)
|
|
547
|
+
return;
|
|
548
|
+
this.#closeTransientUi();
|
|
549
|
+
this.focusBoard({ focusVisible: false });
|
|
550
|
+
this.#touchWasLast = input.pointerType === 'touch';
|
|
551
|
+
// A second finger is a pinch, never a long press.
|
|
552
|
+
if (event.isPrimary === false)
|
|
553
|
+
this.#cancelLongPress();
|
|
554
|
+
const captured = this.controller.pointerDown(input);
|
|
555
|
+
if (captured) {
|
|
556
|
+
event.preventDefault();
|
|
557
|
+
try {
|
|
558
|
+
this.#board?.setPointerCapture(event.pointerId);
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
// A pointer that is already gone cannot be captured: the gesture ends with it.
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (input.pointerType === 'touch' && event.isPrimary !== false)
|
|
565
|
+
this.#startLongPress(input);
|
|
566
|
+
}
|
|
567
|
+
// ────────────────────────────────────────────────────── a finger's long press
|
|
568
|
+
#startLongPress(input) {
|
|
569
|
+
this.#cancelLongPress();
|
|
570
|
+
// Only the select tool has a menu to open: with a pen, an eraser or a shape tool the finger is drawing.
|
|
571
|
+
if (this.engine.state.tool !== 'select' || this.engine.state.editingTextId)
|
|
572
|
+
return;
|
|
573
|
+
const timer = setTimeout(() => this.#fireLongPress(), TOUCH_LONG_PRESS_DELAY_MS);
|
|
574
|
+
this.#longPress = { timer, pointerId: input.pointerId, x: input.x, y: input.y };
|
|
575
|
+
}
|
|
576
|
+
#cancelLongPress() {
|
|
577
|
+
if (!this.#longPress)
|
|
578
|
+
return;
|
|
579
|
+
clearTimeout(this.#longPress.timer);
|
|
580
|
+
this.#longPress = null;
|
|
581
|
+
}
|
|
582
|
+
#fireLongPress() {
|
|
583
|
+
const pending = this.#longPress;
|
|
584
|
+
this.#longPress = null;
|
|
585
|
+
if (!pending || this.#destroyed || this.isLoading)
|
|
586
|
+
return;
|
|
587
|
+
// What the finger started (a pan, a move that has not moved yet, a marquee) ends here: the press became a menu.
|
|
588
|
+
this.controller.pointerCancel({ pointerId: pending.pointerId });
|
|
589
|
+
this.controller.prepareContextMenu({ x: pending.x, y: pending.y });
|
|
590
|
+
this.#menuFinger = { pointerId: pending.pointerId, liftedAt: null };
|
|
591
|
+
this.#updateUi({ contextMenu: { x: pending.x, y: pending.y, byTouch: true }, shapesMenuOpen: false });
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Is the menu still held by the finger that opened it? True while that finger is down, and for a moment after it lifts:
|
|
595
|
+
* the browser sends the finger's `click` a moment after `pointerup`, to whatever is under it, and that is not a choice.
|
|
596
|
+
* The menu asks before it acts on an item, so a long press never picks the entry that opened under the finger.
|
|
597
|
+
*/
|
|
598
|
+
isMenuHeldByItsFinger() {
|
|
599
|
+
const finger = this.#menuFinger;
|
|
600
|
+
if (!finger)
|
|
601
|
+
return false;
|
|
602
|
+
if (finger.liftedAt === null)
|
|
603
|
+
return true;
|
|
604
|
+
if (Date.now() - finger.liftedAt <= TOUCH_MENU_RELEASE_GRACE_MS)
|
|
605
|
+
return true;
|
|
606
|
+
this.#menuFinger = null;
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
#noteFingerLifted(pointerId) {
|
|
610
|
+
if (this.#menuFinger && this.#menuFinger.pointerId === pointerId && this.#menuFinger.liftedAt === null)
|
|
611
|
+
this.#menuFinger.liftedAt = Date.now();
|
|
612
|
+
}
|
|
613
|
+
handlePointerMove(event) {
|
|
614
|
+
if (this.isLoading || this.#destroyed)
|
|
615
|
+
return;
|
|
616
|
+
const input = this.#pointerInput(event);
|
|
617
|
+
if (!input)
|
|
618
|
+
return;
|
|
619
|
+
const resting = this.#longPress;
|
|
620
|
+
if (resting && resting.pointerId === input.pointerId && Math.hypot(input.x - resting.x, input.y - resting.y) > TOUCH_LONG_PRESS_SLOP) {
|
|
621
|
+
this.#cancelLongPress();
|
|
622
|
+
}
|
|
623
|
+
this.controller.pointerMove(input);
|
|
624
|
+
}
|
|
625
|
+
handlePointerUp(event) {
|
|
626
|
+
if (this.#destroyed)
|
|
627
|
+
return;
|
|
628
|
+
this.#cancelLongPress();
|
|
629
|
+
this.#noteFingerLifted(event.pointerId);
|
|
630
|
+
const input = this.#pointerInput(event);
|
|
631
|
+
try {
|
|
632
|
+
this.#board?.releasePointerCapture(event.pointerId);
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
// Nothing was captured.
|
|
636
|
+
}
|
|
637
|
+
if (input)
|
|
638
|
+
this.controller.pointerUp(input);
|
|
639
|
+
}
|
|
640
|
+
handlePointerCancel(event) {
|
|
641
|
+
if (this.#destroyed)
|
|
642
|
+
return;
|
|
643
|
+
this.#cancelLongPress();
|
|
644
|
+
this.#noteFingerLifted(event.pointerId);
|
|
645
|
+
this.controller.pointerCancel({ pointerId: event.pointerId });
|
|
646
|
+
}
|
|
647
|
+
handlePointerLeave(event) {
|
|
648
|
+
if (event.pointerType === 'touch')
|
|
649
|
+
return;
|
|
650
|
+
this.controller.pointerLeave();
|
|
651
|
+
}
|
|
652
|
+
#onWheel(event) {
|
|
653
|
+
if (this.isLoading || this.#destroyed)
|
|
654
|
+
return;
|
|
655
|
+
const base = this.#pointerInput(event, 'mouse');
|
|
656
|
+
if (!base)
|
|
657
|
+
return;
|
|
658
|
+
event.preventDefault();
|
|
659
|
+
const input = {
|
|
660
|
+
x: base.x,
|
|
661
|
+
y: base.y,
|
|
662
|
+
deltaX: event.deltaX,
|
|
663
|
+
deltaY: event.deltaY,
|
|
664
|
+
deltaMode: event.deltaMode,
|
|
665
|
+
shiftKey: event.shiftKey,
|
|
666
|
+
altKey: event.altKey,
|
|
667
|
+
metaKey: event.metaKey,
|
|
668
|
+
ctrlKey: event.ctrlKey
|
|
669
|
+
};
|
|
670
|
+
this.controller.wheel(input);
|
|
671
|
+
}
|
|
672
|
+
handleContextMenu(event) {
|
|
673
|
+
if (this.isLoading || this.#destroyed)
|
|
674
|
+
return;
|
|
675
|
+
event.preventDefault();
|
|
676
|
+
// The browser's own menu for a long press (Android sends one) is kept from showing: the host's timer opens ours.
|
|
677
|
+
const sentBy = event.pointerType;
|
|
678
|
+
if (sentBy === 'touch' || (sentBy === undefined && this.#touchWasLast))
|
|
679
|
+
return;
|
|
680
|
+
const input = this.#pointerInput(event, 'mouse');
|
|
681
|
+
if (!input)
|
|
682
|
+
return;
|
|
683
|
+
this.focusBoard({ focusVisible: false });
|
|
684
|
+
this.#menuFinger = null;
|
|
685
|
+
this.controller.prepareContextMenu({ x: input.x, y: input.y });
|
|
686
|
+
this.#updateUi({ contextMenu: { x: input.x, y: input.y }, shapesMenuOpen: false });
|
|
687
|
+
}
|
|
688
|
+
/** A picture is being dragged over the board: say that it can be dropped. */
|
|
689
|
+
handleDragOver(event) {
|
|
690
|
+
if (this.isLoading)
|
|
691
|
+
return;
|
|
692
|
+
const types = event.dataTransfer?.types;
|
|
693
|
+
if (!types || !Array.from(types).includes('Files'))
|
|
694
|
+
return;
|
|
695
|
+
event.preventDefault();
|
|
696
|
+
if (event.dataTransfer)
|
|
697
|
+
event.dataTransfer.dropEffect = 'copy';
|
|
698
|
+
}
|
|
699
|
+
/** Pictures were dropped on the board: they land where the pointer is. */
|
|
700
|
+
handleDrop(event) {
|
|
701
|
+
if (this.isLoading)
|
|
702
|
+
return;
|
|
703
|
+
const files = Array.from(event.dataTransfer?.files ?? []).filter((file) => file.type.startsWith('image/') || /\.svg$/i.test(file.name));
|
|
704
|
+
if (files.length === 0)
|
|
705
|
+
return;
|
|
706
|
+
event.preventDefault();
|
|
707
|
+
const input = this.#pointerInput(event, 'mouse');
|
|
708
|
+
const at = input ? this.engine.toWorld({ x: input.x, y: input.y }) : undefined;
|
|
709
|
+
void this.insertImageFiles(files, at);
|
|
710
|
+
}
|
|
711
|
+
#closeTransientUi() {
|
|
712
|
+
const { contextMenu, shapesMenuOpen } = this.#ui.value;
|
|
713
|
+
this.#menuFinger = null;
|
|
714
|
+
if (contextMenu || shapesMenuOpen)
|
|
715
|
+
this.#updateUi({ contextMenu: null, shapesMenuOpen: false });
|
|
716
|
+
}
|
|
717
|
+
// ────────────────────────────────────────────────────── keyboard and clipboard
|
|
718
|
+
#keyboardActions() {
|
|
719
|
+
return {
|
|
720
|
+
chooseTool: (tool) => this.chooseShortcutTool(tool),
|
|
721
|
+
save: () => this.saveNow(),
|
|
722
|
+
toggleShortcuts: () => this.#updateUi({ shortcutsOpen: !this.#ui.value.shortcutsOpen }),
|
|
723
|
+
closePanels: () => {
|
|
724
|
+
const { contextMenu, shapesMenuOpen, shortcutsOpen } = this.#ui.value;
|
|
725
|
+
if (!contextMenu && !shapesMenuOpen && !shortcutsOpen)
|
|
726
|
+
return false;
|
|
727
|
+
this.#updateUi({ contextMenu: null, shapesMenuOpen: false, shortcutsOpen: false });
|
|
728
|
+
return true;
|
|
729
|
+
},
|
|
730
|
+
afterCopy: () => this.#markClipboardAsOurs(),
|
|
731
|
+
spacePanChanged: (held) => this.#updateUi({ spacePan: held })
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
#keyboardHost(origin) {
|
|
735
|
+
let hasTextSelection = false;
|
|
736
|
+
try {
|
|
737
|
+
hasTextSelection = (window.getSelection()?.toString().length ?? 0) > 0;
|
|
738
|
+
}
|
|
739
|
+
catch {
|
|
740
|
+
hasTextSelection = false;
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
engine: this.engine,
|
|
744
|
+
controller: this.controller,
|
|
745
|
+
actions: this.#keyboardActions(),
|
|
746
|
+
tools: this.tools,
|
|
747
|
+
typingInField: isEditableTarget(origin),
|
|
748
|
+
hasTextSelection,
|
|
749
|
+
selectorHintOpen: this.props.showElementSelector && this.props.elementSelectorActive
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
#onKeyDown(event) {
|
|
753
|
+
if (this.#destroyed || !this.#root || this.isLoading)
|
|
754
|
+
return;
|
|
755
|
+
if (!eventIsForScope(event, this.#root))
|
|
756
|
+
return;
|
|
757
|
+
const origin = getEventOrigin(event);
|
|
758
|
+
// A key pressed inside an open menu or dialog is that menu's (its typeahead, its arrows), not a tool's letter.
|
|
759
|
+
if (origin?.closest?.('[role="menu"], [role="dialog"], [role="listbox"]'))
|
|
760
|
+
return;
|
|
761
|
+
// A focused slider, tab list or list box keeps its arrow keys: they move its value, and not the selection on the board.
|
|
762
|
+
if (NAVIGATION_KEYS.has(event.key) && ownsNavigationKeys(origin))
|
|
763
|
+
return;
|
|
764
|
+
// A focused button, link or menu entry keeps its Space (the pan has its own button, and the hand tool).
|
|
765
|
+
if (event.code === 'Space' && isActivatableTarget(origin))
|
|
766
|
+
return;
|
|
767
|
+
const input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey, repeat: event.repeat };
|
|
768
|
+
// Shift, Alt and the like change what a running gesture does without moving the pointer.
|
|
769
|
+
if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
|
|
770
|
+
this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
let handled = false;
|
|
774
|
+
try {
|
|
775
|
+
handled = routeKeyDown(input, this.#keyboardHost(origin));
|
|
776
|
+
}
|
|
777
|
+
catch (error) {
|
|
778
|
+
canvasWarn('Canvas: a key press failed', error);
|
|
779
|
+
}
|
|
780
|
+
if (handled) {
|
|
781
|
+
event.preventDefault();
|
|
782
|
+
event.stopPropagation();
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
#onKeyUp(event) {
|
|
786
|
+
if (this.#destroyed || !this.#root)
|
|
787
|
+
return;
|
|
788
|
+
if (event.key === 'Shift' || event.key === 'Alt' || event.key === 'Control' || event.key === 'Meta') {
|
|
789
|
+
this.controller.modifiersChanged({ shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey });
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (!eventIsForScope(event, this.#root)) {
|
|
793
|
+
// A Space released outside the canvas still ends the pan.
|
|
794
|
+
if (event.code === 'Space')
|
|
795
|
+
this.controller.setSpaceHeld(false);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
const input = { key: event.key, code: event.code, shiftKey: event.shiftKey, altKey: event.altKey, metaKey: event.metaKey, ctrlKey: event.ctrlKey };
|
|
799
|
+
if (routeKeyUp(input, this.#keyboardHost(getEventOrigin(event)))) {
|
|
800
|
+
event.preventDefault();
|
|
801
|
+
this.#updateUi({ spacePan: false });
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
#onWindowBlur() {
|
|
805
|
+
releaseHeldKeys(this.#keyboardHost(null));
|
|
806
|
+
}
|
|
807
|
+
/** Cmd+C on the board puts a marker on the system clipboard, so the next paste is the board's, not an older picture's. */
|
|
808
|
+
#markClipboardAsOurs() {
|
|
809
|
+
try {
|
|
810
|
+
const clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;
|
|
811
|
+
void clipboard?.writeText?.(CLIPBOARD_MARKER).catch(() => undefined);
|
|
812
|
+
}
|
|
813
|
+
catch {
|
|
814
|
+
// A browser that refuses leaves the older clipboard in place: the paste then prefers its picture.
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
#onPaste(event) {
|
|
818
|
+
if (this.#destroyed || !this.#root || this.isLoading)
|
|
819
|
+
return;
|
|
820
|
+
if (!eventIsForScope(event, this.#root))
|
|
821
|
+
return;
|
|
822
|
+
if (this.engine.state.editingTextId)
|
|
823
|
+
return;
|
|
824
|
+
const origin = getEventOrigin(event);
|
|
825
|
+
if (isEditableTarget(origin))
|
|
826
|
+
return;
|
|
827
|
+
if (origin?.closest?.(PASTE_EXCLUDED_SELECTOR))
|
|
828
|
+
return;
|
|
829
|
+
const items = Array.from(event.clipboardData?.items ?? []);
|
|
830
|
+
const picture = items.find((item) => item.type.startsWith('image/'));
|
|
831
|
+
const pasteInside = this.engine.hasClipboard() && event.clipboardData?.getData('text/plain') === CLIPBOARD_MARKER;
|
|
832
|
+
if (picture && !pasteInside) {
|
|
833
|
+
const blob = picture.getAsFile();
|
|
834
|
+
if (!blob)
|
|
835
|
+
return;
|
|
836
|
+
event.preventDefault();
|
|
837
|
+
const at = this.engine.lastPointerWorld ?? undefined;
|
|
838
|
+
void this.insertImageFiles([blob], at);
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
if (this.engine.hasClipboard()) {
|
|
842
|
+
event.preventDefault();
|
|
843
|
+
this.engine.paste();
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
// ────────────────────────────────────────────────────── engine hooks
|
|
847
|
+
#wireEngineHooks() {
|
|
848
|
+
const hooks = {
|
|
849
|
+
onDirty: () => this.#markDirty(),
|
|
850
|
+
onCleared: () => this.#safely(() => this.props.onCanvasCleared?.(), 'onCanvasCleared'),
|
|
851
|
+
onSelectionChange: (ids) => this.#onSelectionChange(ids),
|
|
852
|
+
confirmWidgetDeletion: (widgetId) => {
|
|
853
|
+
const ask = this.props.onWidgetShapeDeleting;
|
|
854
|
+
return ask ? ask(widgetId) : true;
|
|
855
|
+
},
|
|
856
|
+
onWidgetDuplicated: (sourceWidgetId, clone) => this.#onWidgetDuplicated(sourceWidgetId, clone),
|
|
857
|
+
onError: (message, error) => canvasWarn(`Canvas: ${message}`, error)
|
|
858
|
+
};
|
|
859
|
+
this.engine.hooks = hooks;
|
|
860
|
+
}
|
|
861
|
+
#safely(run, name) {
|
|
862
|
+
try {
|
|
863
|
+
run();
|
|
864
|
+
}
|
|
865
|
+
catch (error) {
|
|
866
|
+
canvasWarn(`Canvas: ${name} failed`, error);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
#markDirty() {
|
|
870
|
+
if (this.#destroyed)
|
|
871
|
+
return;
|
|
872
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
873
|
+
this.#safely(() => this.props.onCanvasDirty?.(), 'onCanvasDirty');
|
|
874
|
+
this.#scheduler.markChanged();
|
|
875
|
+
}
|
|
876
|
+
#onSelectionChange(ids) {
|
|
877
|
+
if (ids.length === 0)
|
|
878
|
+
return;
|
|
879
|
+
const selected = this.engine.selectedObjects();
|
|
880
|
+
const onlyAWidget = selected.length === 1 && selected[0].type === 'widget';
|
|
881
|
+
if (!onlyAWidget)
|
|
882
|
+
this.#safely(() => this.props.onNonWidgetSelected?.(), 'onNonWidgetSelected');
|
|
883
|
+
}
|
|
884
|
+
#onWidgetDuplicated(sourceWidgetId, clone) {
|
|
885
|
+
const notify = this.props.onWidgetShapeDuplicated;
|
|
886
|
+
if (!notify)
|
|
887
|
+
return;
|
|
888
|
+
// The page gets a view of the card, under the names the old canvas kept (`_widgetId`, `_objectId`).
|
|
889
|
+
const view = hostObjectById(this.engine, clone.id);
|
|
890
|
+
this.#safely(() => notify(sourceWidgetId, view), 'onWidgetShapeDuplicated');
|
|
891
|
+
}
|
|
892
|
+
#handleActivate(id) {
|
|
893
|
+
const object = this.engine.getObject(id);
|
|
894
|
+
if (!object || object.type !== 'widget')
|
|
895
|
+
return;
|
|
896
|
+
const notify = this.props.onWidgetImageClick;
|
|
897
|
+
if (notify && object.widgetId)
|
|
898
|
+
this.#safely(() => notify(object.widgetId), 'onWidgetImageClick');
|
|
899
|
+
}
|
|
900
|
+
/** After every change of the engine: the page's overlays are told to move, once a frame, when something they follow moved. */
|
|
901
|
+
#onEngineState(state) {
|
|
902
|
+
// The eraser's trail lives on the frame clock: it starts with the trail and stops when the trail is gone.
|
|
903
|
+
if (state.scribble !== null)
|
|
904
|
+
this.#startScribbleClock();
|
|
905
|
+
const isEditingText = state.editingTextId !== null;
|
|
906
|
+
if (this.#wasEditingText && !isEditingText)
|
|
907
|
+
this.#takeKeyboardBackSoon();
|
|
908
|
+
this.#wasEditingText = isEditingText;
|
|
909
|
+
const last = this.#lastOverlayState;
|
|
910
|
+
if (!last ||
|
|
911
|
+
last.scene !== state.scene ||
|
|
912
|
+
last.viewport !== state.viewport ||
|
|
913
|
+
last.viewSize !== state.viewSize ||
|
|
914
|
+
last.widgets !== state.widgets ||
|
|
915
|
+
last.pending !== state.pending ||
|
|
916
|
+
last.hoverWidgetId !== state.hoverWidgetId ||
|
|
917
|
+
last.selectedIds !== state.selectedIds ||
|
|
918
|
+
last.overlayDragActive !== state.overlayDragActive) {
|
|
919
|
+
this.#lastOverlayState = {
|
|
920
|
+
scene: state.scene,
|
|
921
|
+
viewport: state.viewport,
|
|
922
|
+
viewSize: state.viewSize,
|
|
923
|
+
widgets: state.widgets,
|
|
924
|
+
pending: state.pending,
|
|
925
|
+
hoverWidgetId: state.hoverWidgetId,
|
|
926
|
+
selectedIds: state.selectedIds,
|
|
927
|
+
overlayDragActive: state.overlayDragActive
|
|
928
|
+
};
|
|
929
|
+
this.#queueAfterRender();
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
/**
|
|
933
|
+
* A text that was being typed has ended, and its field has left the page, so the focus fell to nothing. In a shadow root
|
|
934
|
+
* the shortcuts follow the focus (see `eventScope`): without this the next Ctrl+Z or letter key would be ignored until the
|
|
935
|
+
* next click on the board. The board takes the keyboard back unless the focus went somewhere of its own (a field of the
|
|
936
|
+
* creator, or of the partner's page), which `shouldTakeFocusBack` tells. Asked after the field is gone, on the next frame.
|
|
937
|
+
*/
|
|
938
|
+
#takeKeyboardBackSoon() {
|
|
939
|
+
if (this.#keyboardReturnQueued || typeof requestAnimationFrame !== 'function')
|
|
940
|
+
return;
|
|
941
|
+
this.#keyboardReturnQueued = true;
|
|
942
|
+
requestAnimationFrame(() => {
|
|
943
|
+
this.#keyboardReturnQueued = false;
|
|
944
|
+
if (this.#destroyed || !this.#board)
|
|
945
|
+
return;
|
|
946
|
+
try {
|
|
947
|
+
if (shouldTakeFocusBack(this.#board)) {
|
|
948
|
+
this.focusBoard();
|
|
949
|
+
canvasLog('Canvas: the board took the keyboard back after a text was typed');
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
catch (error) {
|
|
953
|
+
canvasWarn('Canvas: could not give the keyboard back to the board', error);
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
/** Asks for the next frame of the eraser's trail, unless one is asked for already. Nothing runs while there is no trail. */
|
|
958
|
+
#startScribbleClock() {
|
|
959
|
+
if (this.#scribbleFrame !== null || this.#destroyed || typeof requestAnimationFrame !== 'function')
|
|
960
|
+
return;
|
|
961
|
+
if (this.#scribbleClockLast === null)
|
|
962
|
+
this.#scribbleClockLast = typeof performance !== 'undefined' ? performance.now() : 0;
|
|
963
|
+
this.#scribbleFrame = requestAnimationFrame((time) => this.#onScribbleFrame(time));
|
|
964
|
+
}
|
|
965
|
+
#onScribbleFrame(time) {
|
|
966
|
+
this.#scribbleFrame = null;
|
|
967
|
+
if (this.#destroyed)
|
|
968
|
+
return;
|
|
969
|
+
const elapsedMs = Math.max(0, time - (this.#scribbleClockLast ?? time));
|
|
970
|
+
this.#scribbleClockLast = time;
|
|
971
|
+
let alive = false;
|
|
972
|
+
try {
|
|
973
|
+
alive = this.engine.stepScribble(elapsedMs);
|
|
974
|
+
}
|
|
975
|
+
catch (error) {
|
|
976
|
+
canvasWarn('Canvas: the eraser trail could not be stepped', error);
|
|
977
|
+
}
|
|
978
|
+
if (!alive) {
|
|
979
|
+
this.#scribbleClockLast = null;
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
this.#startScribbleClock();
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* Tells the page that its overlays (the live widgets over the cards) must move. At most once a frame, and never from
|
|
986
|
+
* inside its own answer: what the page changes while it moves them does not call it again in the same turn.
|
|
987
|
+
*/
|
|
988
|
+
#queueAfterRender() {
|
|
989
|
+
if (!this.props.onAfterRender || this.#afterRenderQueued || this.#applyingAfterRender || this.#destroyed)
|
|
990
|
+
return;
|
|
991
|
+
if (typeof requestAnimationFrame !== 'function')
|
|
992
|
+
return;
|
|
993
|
+
this.#afterRenderQueued = true;
|
|
994
|
+
requestAnimationFrame(() => {
|
|
995
|
+
this.#afterRenderQueued = false;
|
|
996
|
+
const callback = this.props.onAfterRender;
|
|
997
|
+
if (!callback || this.#applyingAfterRender || this.#destroyed)
|
|
998
|
+
return;
|
|
999
|
+
this.#applyingAfterRender = true;
|
|
1000
|
+
try {
|
|
1001
|
+
callback();
|
|
1002
|
+
}
|
|
1003
|
+
catch (error) {
|
|
1004
|
+
canvasWarn('Canvas: onAfterRender failed', error);
|
|
1005
|
+
}
|
|
1006
|
+
finally {
|
|
1007
|
+
this.#applyingAfterRender = false;
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
// ────────────────────────────────────────────────────── stroke snap
|
|
1012
|
+
#handleStrokeFinished(stroke, handLine) {
|
|
1013
|
+
// Off unless the page asked (shapeSnap) or the package's own flag is flipped.
|
|
1014
|
+
if (!isShapeSnapOn(this.props.shapeSnap))
|
|
1015
|
+
return;
|
|
1016
|
+
void snapDrawnStroke(this.engine, stroke, { recognize: this.props.onRecognizeStroke, log: (message, details) => canvasLog(message, details) }, handLine);
|
|
1017
|
+
}
|
|
1018
|
+
// ────────────────────────────────────────────────────── saving and loading
|
|
1019
|
+
#runAutosave() {
|
|
1020
|
+
const json = this.#serializeCanvasText();
|
|
1021
|
+
if (json === null) {
|
|
1022
|
+
// The board has nothing to give right now (it is loading): ask the buffer for another go a delay later.
|
|
1023
|
+
canvasLog('Canvas: autosave: the board cannot be serialized yet, trying again after the delay');
|
|
1024
|
+
this.#scheduler.markChanged();
|
|
1025
|
+
return undefined;
|
|
1026
|
+
}
|
|
1027
|
+
if (json === this.#lastAutosavedJson) {
|
|
1028
|
+
this.#updateUi({ saveState: 'saved' });
|
|
1029
|
+
return undefined;
|
|
1030
|
+
}
|
|
1031
|
+
canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
|
|
1032
|
+
this.#updateUi({ saveState: 'saving' });
|
|
1033
|
+
let outcome;
|
|
1034
|
+
try {
|
|
1035
|
+
outcome = this.props.onAutoSave?.(json);
|
|
1036
|
+
}
|
|
1037
|
+
catch (error) {
|
|
1038
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
1039
|
+
throw error;
|
|
1040
|
+
}
|
|
1041
|
+
const finish = (savedJson) => {
|
|
1042
|
+
this.#lastAutosavedJson = savedJson;
|
|
1043
|
+
this.#updateUi({ saveState: this.#scheduler.isDirty ? 'dirty' : 'saved' });
|
|
1044
|
+
};
|
|
1045
|
+
if (outcome && typeof outcome.then === 'function') {
|
|
1046
|
+
return outcome.then((value) => {
|
|
1047
|
+
finish(json);
|
|
1048
|
+
return value;
|
|
1049
|
+
}, (error) => {
|
|
1050
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
1051
|
+
throw error;
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
finish(json);
|
|
1055
|
+
return outcome;
|
|
1056
|
+
}
|
|
1057
|
+
/** Saves whatever the buffer still holds, now. Resolves once the page's save is done. */
|
|
1058
|
+
flushAutosave() {
|
|
1059
|
+
return this.#scheduler.flush();
|
|
1060
|
+
}
|
|
1061
|
+
/** An immediate save (Cmd+S, the save button, the page's own flushes). */
|
|
1062
|
+
saveNow() {
|
|
1063
|
+
// What the buffer was waiting to save is in this save.
|
|
1064
|
+
this.#scheduler.cancel();
|
|
1065
|
+
const json = this.saveCanvas();
|
|
1066
|
+
this.#updateUi({ saveState: 'saving' });
|
|
1067
|
+
let outcome;
|
|
1068
|
+
try {
|
|
1069
|
+
outcome = this.props.onAutoSave?.(json);
|
|
1070
|
+
}
|
|
1071
|
+
catch (error) {
|
|
1072
|
+
canvasWarn('Canvas: the save failed', error);
|
|
1073
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
const finish = () => {
|
|
1077
|
+
if (json)
|
|
1078
|
+
this.#lastAutosavedJson = json;
|
|
1079
|
+
this.#updateUi({ saveState: this.#scheduler.isDirty ? 'dirty' : 'saved' });
|
|
1080
|
+
};
|
|
1081
|
+
if (outcome && typeof outcome.then === 'function') {
|
|
1082
|
+
outcome.then(finish, (error) => {
|
|
1083
|
+
canvasWarn('Canvas: the save failed', error);
|
|
1084
|
+
this.#updateUi({ saveState: 'dirty' });
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
else {
|
|
1088
|
+
finish();
|
|
1089
|
+
}
|
|
1090
|
+
canvasLog('Canvas: manual save triggered');
|
|
1091
|
+
}
|
|
1092
|
+
/** Serializes the board without writing to the console (autosave compares payloads here first). */
|
|
1093
|
+
#serializeCanvasText() {
|
|
1094
|
+
if (this.#destroyed)
|
|
1095
|
+
return null;
|
|
1096
|
+
if (this.#loadDepth > 0 || this.engine.state.loading) {
|
|
1097
|
+
canvasLog('Canvas: saveCanvas skipped (the board is loading)');
|
|
1098
|
+
return null;
|
|
1099
|
+
}
|
|
1100
|
+
try {
|
|
1101
|
+
return this.engine.serialize({ imageStore: getShapeImageStore() });
|
|
1102
|
+
}
|
|
1103
|
+
catch (error) {
|
|
1104
|
+
console.error('Canvas: saveCanvas failed', error);
|
|
1105
|
+
return null;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
/** The board as the text the page keeps. Null while the board is loading. */
|
|
1109
|
+
saveCanvas() {
|
|
1110
|
+
const text = this.#serializeCanvasText();
|
|
1111
|
+
if (text !== null) {
|
|
1112
|
+
canvasLog('Canvas: saveCanvas serialized', this.engine.state.scene.length, 'objects');
|
|
1113
|
+
}
|
|
1114
|
+
return text;
|
|
1115
|
+
}
|
|
1116
|
+
/**
|
|
1117
|
+
* Shows saved data. Never throws: text the board cannot read (a canvas of the older engine, or something that is not
|
|
1118
|
+
* a canvas) opens as an empty board, says so, and nothing is saved until the person changes something.
|
|
1119
|
+
*/
|
|
1120
|
+
async loadCanvas(jsonString) {
|
|
1121
|
+
if (this.#destroyed)
|
|
1122
|
+
return;
|
|
1123
|
+
markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_START);
|
|
1124
|
+
this.#closeEmptyHintGate();
|
|
1125
|
+
this.#loadDepth += 1;
|
|
1126
|
+
this.engine.setLoading(true);
|
|
1127
|
+
this.#updateUi({ loadPhase: 'loading' });
|
|
1128
|
+
try {
|
|
1129
|
+
const parsed = this.engine.loadDocument(jsonString);
|
|
1130
|
+
this.#scheduler.cancel();
|
|
1131
|
+
this.#lastAutosavedJson = null;
|
|
1132
|
+
this.#updateUi({ loadStatus: parsed.status, saveState: 'saved' });
|
|
1133
|
+
if (parsed.status === 'unsupported' || parsed.status === 'invalid') {
|
|
1134
|
+
// Not gated by the page's log switch: a board that opens empty is something its owner has to be able to find out.
|
|
1135
|
+
console.warn(`Canvas: this canvas could not be opened (${parsed.status}); showing an empty board, nothing is overwritten until it is changed`, parsed.warnings);
|
|
1136
|
+
}
|
|
1137
|
+
else if (parsed.warnings.length > 0) {
|
|
1138
|
+
canvasWarn('Canvas: some objects of the saved canvas could not be read', parsed.warnings);
|
|
1139
|
+
}
|
|
1140
|
+
await this.#resolveStoredImages();
|
|
1141
|
+
}
|
|
1142
|
+
catch (error) {
|
|
1143
|
+
console.error('Canvas: loadCanvas failed', error);
|
|
1144
|
+
}
|
|
1145
|
+
finally {
|
|
1146
|
+
this.#loadDepth = Math.max(0, this.#loadDepth - 1);
|
|
1147
|
+
if (this.#loadDepth === 0)
|
|
1148
|
+
this.engine.setLoading(false);
|
|
1149
|
+
this.#updateUi({ loadPhase: 'ready' });
|
|
1150
|
+
queueMicrotask(() => this.#syncEmptyHintGate());
|
|
1151
|
+
markCanvasOpenStep(CANVAS_OPEN_MARKS.LOAD_END);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/** Pictures the saved board only points at (by reference) are read from the page's store and put in without a history step. */
|
|
1155
|
+
async #resolveStoredImages() {
|
|
1156
|
+
const store = getShapeImageStore();
|
|
1157
|
+
if (!store)
|
|
1158
|
+
return;
|
|
1159
|
+
const scene = this.engine.state.scene;
|
|
1160
|
+
const missing = scene.filter((object) => (object.type === 'image' && !object.src && !!object.imageRef) || (object.type === 'widget' && !object.thumbnail && !!object.thumbnailRef));
|
|
1161
|
+
if (missing.length === 0)
|
|
1162
|
+
return;
|
|
1163
|
+
const found = new Map();
|
|
1164
|
+
await Promise.all(missing.map(async (object) => {
|
|
1165
|
+
const reference = object.type === 'image' ? object.imageRef : object.type === 'widget' ? object.thumbnailRef : null;
|
|
1166
|
+
if (!reference)
|
|
1167
|
+
return;
|
|
1168
|
+
try {
|
|
1169
|
+
const dataUrl = await store.load(reference);
|
|
1170
|
+
if (dataUrl)
|
|
1171
|
+
found.set(object.id, dataUrl);
|
|
1172
|
+
}
|
|
1173
|
+
catch (error) {
|
|
1174
|
+
canvasWarn('Canvas: a stored picture could not be read', reference, error);
|
|
1175
|
+
}
|
|
1176
|
+
}));
|
|
1177
|
+
if (found.size === 0 || this.#destroyed)
|
|
1178
|
+
return;
|
|
1179
|
+
// What was loaded since is left alone: only the objects that are still the ones that were missing a picture are filled in.
|
|
1180
|
+
const next = this.engine.state.scene.map((object) => {
|
|
1181
|
+
const dataUrl = found.get(object.id);
|
|
1182
|
+
if (!dataUrl)
|
|
1183
|
+
return object;
|
|
1184
|
+
if (object.type === 'image' && !object.src)
|
|
1185
|
+
return { ...object, src: dataUrl };
|
|
1186
|
+
if (object.type === 'widget' && !object.thumbnail)
|
|
1187
|
+
return { ...object, thumbnail: dataUrl };
|
|
1188
|
+
return object;
|
|
1189
|
+
});
|
|
1190
|
+
this.engine.applySilently(next);
|
|
1191
|
+
}
|
|
1192
|
+
/** Empties the board (an undo step) and tells the page. */
|
|
1193
|
+
onClearAllObjects() {
|
|
1194
|
+
this.#scheduler.cancel();
|
|
1195
|
+
this.engine.clearAll();
|
|
1196
|
+
canvasLog('Clear all objects created');
|
|
1197
|
+
}
|
|
1198
|
+
// ────────────────────────────────────────────────────── tools
|
|
1199
|
+
setTool(tool, options = {}) {
|
|
1200
|
+
this.engine.setTool(tool, options);
|
|
1201
|
+
}
|
|
1202
|
+
/** A letter of the keyboard chose a tool (or the menu did). */
|
|
1203
|
+
chooseShortcutTool(tool) {
|
|
1204
|
+
switch (tool) {
|
|
1205
|
+
case 'select':
|
|
1206
|
+
return this.onSelectSelectTool();
|
|
1207
|
+
case 'erase':
|
|
1208
|
+
return this.onSelectEraseTool();
|
|
1209
|
+
case 'draw':
|
|
1210
|
+
return this.onSelectDrawTool();
|
|
1211
|
+
case 'pan':
|
|
1212
|
+
return this.onSelectPanTool();
|
|
1213
|
+
case 'arrow':
|
|
1214
|
+
return this.onSelectArrowTool();
|
|
1215
|
+
case 'rect':
|
|
1216
|
+
return this.onSelectShapeTool('rect');
|
|
1217
|
+
case 'triangle':
|
|
1218
|
+
return this.onSelectShapeTool('triangle');
|
|
1219
|
+
case 'ellipse':
|
|
1220
|
+
return this.onSelectShapeTool('circle');
|
|
1221
|
+
case 'text':
|
|
1222
|
+
return this.onSelectTextTool();
|
|
1223
|
+
case 'image':
|
|
1224
|
+
return this.onSelectImageTool();
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
/** The Select tool: the creator closes the element selector of its widgets when it hears of it. */
|
|
1228
|
+
onSelectSelectTool() {
|
|
1229
|
+
this.engine.setTool('select');
|
|
1230
|
+
announceSelectTool();
|
|
1231
|
+
}
|
|
1232
|
+
onSelectDrawTool() {
|
|
1233
|
+
this.engine.setTool('draw');
|
|
1234
|
+
}
|
|
1235
|
+
onSelectEraseTool() {
|
|
1236
|
+
this.engine.setTool('erase');
|
|
1237
|
+
}
|
|
1238
|
+
onSelectTextTool() {
|
|
1239
|
+
this.engine.setTool('text');
|
|
1240
|
+
}
|
|
1241
|
+
onSelectArrowTool() {
|
|
1242
|
+
this.engine.setTool('arrow');
|
|
1243
|
+
}
|
|
1244
|
+
onSelectPanTool() {
|
|
1245
|
+
this.engine.setTool('pan');
|
|
1246
|
+
}
|
|
1247
|
+
/** The names are the old ones: `circle` is the oval, `circle-true` the circle. */
|
|
1248
|
+
onSelectShapeTool(shapeType) {
|
|
1249
|
+
const tool = { rect: 'rect', 'rounded-rect': 'rounded-rect', circle: 'ellipse', 'circle-true': 'circle', triangle: 'triangle', arrow: 'arrow' };
|
|
1250
|
+
this.engine.setTool(tool[shapeType] ?? 'rect');
|
|
1251
|
+
}
|
|
1252
|
+
/** The second argument of the old call (the path of the shape) is still accepted, and not needed: the library knows the shape by its key. */
|
|
1253
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- part of the signature pages call
|
|
1254
|
+
onSelectLibraryShapeTool(shapeKey, _pathData) {
|
|
1255
|
+
this.engine.setTool('library-shape', { libraryShapeKey: shapeKey });
|
|
1256
|
+
}
|
|
1257
|
+
/** The image tool opens the file chooser (it needs the click that called it, which is how the toolbar and the key call it). */
|
|
1258
|
+
onSelectImageTool() {
|
|
1259
|
+
void this.addImage();
|
|
1260
|
+
}
|
|
1261
|
+
/** There are no frames on this board: kept so a page that still calls it keeps working. */
|
|
1262
|
+
onSelectFrameTool() {
|
|
1263
|
+
canvasLog('Canvas: the frame tool is gone, nothing was done');
|
|
1264
|
+
}
|
|
1265
|
+
/** There is no video on this board: kept so a page that still calls it keeps working. */
|
|
1266
|
+
onSelectVideoTool() {
|
|
1267
|
+
canvasLog('Canvas: the video tool is gone, nothing was done');
|
|
1268
|
+
}
|
|
1269
|
+
// ────────────────────────────────────────────────────── view
|
|
1270
|
+
zoomIn() {
|
|
1271
|
+
this.engine.zoomStep(1);
|
|
1272
|
+
}
|
|
1273
|
+
zoomOut() {
|
|
1274
|
+
this.engine.zoomStep(-1);
|
|
1275
|
+
}
|
|
1276
|
+
zoomTo(percent) {
|
|
1277
|
+
if (!Number.isFinite(percent))
|
|
1278
|
+
return;
|
|
1279
|
+
this.engine.zoomTo(percent / 100);
|
|
1280
|
+
}
|
|
1281
|
+
zoomReset() {
|
|
1282
|
+
this.engine.zoomReset();
|
|
1283
|
+
}
|
|
1284
|
+
zoomFit() {
|
|
1285
|
+
this.engine.zoomToFit();
|
|
1286
|
+
}
|
|
1287
|
+
// ────────────────────────────────────────────────────── selection and arrangement
|
|
1288
|
+
deselectAll() {
|
|
1289
|
+
this.engine.clearSelection();
|
|
1290
|
+
}
|
|
1291
|
+
onSelectAllObjects() {
|
|
1292
|
+
this.engine.selectAll();
|
|
1293
|
+
}
|
|
1294
|
+
onDeselectAllObjects() {
|
|
1295
|
+
this.engine.clearSelection();
|
|
1296
|
+
}
|
|
1297
|
+
/** The same as the keys and the menu: copies the selection. Widget cards are made into new widgets by the page. */
|
|
1298
|
+
duplicateSelectedObjects() {
|
|
1299
|
+
return this.engine.duplicateSelection();
|
|
1300
|
+
}
|
|
1301
|
+
deleteSelectedObjects() {
|
|
1302
|
+
return this.engine.deleteSelection();
|
|
1303
|
+
}
|
|
1304
|
+
/** The same as the Copy key: remembers the selection for a paste and marks the system clipboard as the board's. */
|
|
1305
|
+
copySelection() {
|
|
1306
|
+
const copied = this.engine.copySelection();
|
|
1307
|
+
if (copied)
|
|
1308
|
+
this.#markClipboardAsOurs();
|
|
1309
|
+
return copied;
|
|
1310
|
+
}
|
|
1311
|
+
/** The same as the Cut key. */
|
|
1312
|
+
cutSelection() {
|
|
1313
|
+
const cut = this.engine.cutSelection();
|
|
1314
|
+
if (cut)
|
|
1315
|
+
this.#markClipboardAsOurs();
|
|
1316
|
+
return cut;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Paste from the menu, centred on a point of the board (in pixels of the board). A copy made on the board wins; without
|
|
1320
|
+
* one, a picture on the system clipboard is put on the board when the browser lets the page read it.
|
|
1321
|
+
*/
|
|
1322
|
+
async pasteAt(boardPoint) {
|
|
1323
|
+
const world = boardPoint ? this.engine.toWorld(boardPoint) : null;
|
|
1324
|
+
if (this.engine.hasClipboard()) {
|
|
1325
|
+
this.engine.paste(world);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
const items = (await navigator.clipboard?.read?.()) ?? [];
|
|
1330
|
+
for (const item of items) {
|
|
1331
|
+
const pictureType = item.types.find((type) => type.startsWith('image/'));
|
|
1332
|
+
if (!pictureType)
|
|
1333
|
+
continue;
|
|
1334
|
+
const picture = await item.getType(pictureType);
|
|
1335
|
+
await this.insertImageFiles([picture], world ?? undefined);
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
catch (error) {
|
|
1340
|
+
canvasLog('Canvas: the system clipboard could not be read, nothing was pasted', error);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
/** A colour for a new shape: a random hue, so that shapes drawn in a row can be told apart. */
|
|
1344
|
+
shapeFillColor() {
|
|
1345
|
+
return `hsl(${this.engine.services.random() * 360}, 70%, 50%)`;
|
|
1346
|
+
}
|
|
1347
|
+
onGroupSelection() {
|
|
1348
|
+
if (!this.engine.groupSelection())
|
|
1349
|
+
return null;
|
|
1350
|
+
return this.engine.state.selectedIds[0] ?? null;
|
|
1351
|
+
}
|
|
1352
|
+
onUngroupSelection() {
|
|
1353
|
+
this.engine.ungroupSelection();
|
|
1354
|
+
}
|
|
1355
|
+
async undo() {
|
|
1356
|
+
this.engine.undo();
|
|
1357
|
+
}
|
|
1358
|
+
async redo() {
|
|
1359
|
+
this.engine.redo();
|
|
1360
|
+
}
|
|
1361
|
+
/** What the page reads of the selection: a view of the one object, or of the several. */
|
|
1362
|
+
getSelectedObject() {
|
|
1363
|
+
return selectedHostObject(this.engine);
|
|
1364
|
+
}
|
|
1365
|
+
// ────────────────────────────────────────────────────── adding things
|
|
1366
|
+
#placeAtCenter(kind) {
|
|
1367
|
+
const center = this.engine.visibleCenter();
|
|
1368
|
+
return buildDraggedShape({
|
|
1369
|
+
kind,
|
|
1370
|
+
start: center,
|
|
1371
|
+
end: center,
|
|
1372
|
+
constrain: false,
|
|
1373
|
+
dragged: false,
|
|
1374
|
+
wireframe: this.engine.wireframeMode,
|
|
1375
|
+
createId: this.engine.services.createId,
|
|
1376
|
+
random: this.engine.services.random
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
addRect() {
|
|
1380
|
+
return this.engine.addObjects([this.#placeAtCenter('rect')], { select: true })[0] ?? null;
|
|
1381
|
+
}
|
|
1382
|
+
addCircle() {
|
|
1383
|
+
return this.engine.addObjects([this.#placeAtCenter('circle')], { select: true })[0] ?? null;
|
|
1384
|
+
}
|
|
1385
|
+
addTriangle() {
|
|
1386
|
+
return this.engine.addObjects([this.#placeAtCenter('triangle')], { select: true })[0] ?? null;
|
|
1387
|
+
}
|
|
1388
|
+
/** A label in the middle of the view, ready to be typed in. */
|
|
1389
|
+
addText() {
|
|
1390
|
+
this.engine.setTool('select');
|
|
1391
|
+
return this.engine.createText(this.engine.visibleCenter());
|
|
1392
|
+
}
|
|
1393
|
+
/** There are no frames on this board: kept so a page that still calls it keeps working. */
|
|
1394
|
+
addFrame() {
|
|
1395
|
+
canvasLog('Canvas: frames are gone, nothing was added');
|
|
1396
|
+
return null;
|
|
1397
|
+
}
|
|
1398
|
+
/** Opens the file chooser and puts the pictures that are chosen on the board. */
|
|
1399
|
+
async addImage() {
|
|
1400
|
+
const files = await chooseImageFiles(this.#root, { multiple: true });
|
|
1401
|
+
if (files.length > 0)
|
|
1402
|
+
await this.insertImageFiles(files);
|
|
1403
|
+
}
|
|
1404
|
+
/** The SVG entry of the shapes menu: the same as `addImage`, but the chooser only offers vector files. */
|
|
1405
|
+
async addSvg() {
|
|
1406
|
+
const files = await chooseImageFiles(this.#root, { multiple: true, accept: 'image/svg+xml,.svg' });
|
|
1407
|
+
if (files.length > 0)
|
|
1408
|
+
await this.insertImageFiles(files);
|
|
1409
|
+
}
|
|
1410
|
+
/** Reads picture files and puts them on the board, side by side from `at` (the middle of the view by default), as one step. */
|
|
1411
|
+
async insertImageFiles(files, at) {
|
|
1412
|
+
const loaded = [];
|
|
1413
|
+
for (const file of files) {
|
|
1414
|
+
try {
|
|
1415
|
+
loaded.push(await readImageFile(file, file.name || 'pasted-image.png'));
|
|
1416
|
+
}
|
|
1417
|
+
catch (error) {
|
|
1418
|
+
canvasWarn('Canvas: a picture could not be read', error);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return this.insertLoadedImages(loaded, at);
|
|
1422
|
+
}
|
|
1423
|
+
insertLoadedImages(pictures, at) {
|
|
1424
|
+
if (pictures.length === 0 || this.#destroyed)
|
|
1425
|
+
return [];
|
|
1426
|
+
const center = at ?? this.engine.visibleCenter();
|
|
1427
|
+
const objects = pictures.map((picture, position) => {
|
|
1428
|
+
const size = fitImageSize(picture.width, picture.height);
|
|
1429
|
+
// Several pictures are laid out in a cascade, so each one can still be seen.
|
|
1430
|
+
const shift = position * 24;
|
|
1431
|
+
return createImageObject({
|
|
1432
|
+
id: this.engine.services.createId('img'),
|
|
1433
|
+
x: center.x - size.width / 2 + shift,
|
|
1434
|
+
y: center.y - size.height / 2 + shift,
|
|
1435
|
+
width: size.width,
|
|
1436
|
+
height: size.height,
|
|
1437
|
+
src: picture.src,
|
|
1438
|
+
fileName: picture.fileName || null,
|
|
1439
|
+
naturalWidth: picture.width,
|
|
1440
|
+
naturalHeight: picture.height
|
|
1441
|
+
});
|
|
1442
|
+
});
|
|
1443
|
+
this.engine.setTool('select');
|
|
1444
|
+
const ids = this.engine.addObjects(objects, { select: true });
|
|
1445
|
+
canvasLog('Canvas: pictures put on the board', ids.length);
|
|
1446
|
+
return ids;
|
|
1447
|
+
}
|
|
1448
|
+
// ────────────────────────────────────────────────────── capture and conversion
|
|
1449
|
+
/** A PNG of everything on the board, cropped to it; an empty string for an empty board. */
|
|
1450
|
+
async captureCanvasSketch() {
|
|
1451
|
+
const shapes = this.engine.state.scene.filter((object) => object.type !== 'group');
|
|
1452
|
+
if (shapes.length === 0)
|
|
1453
|
+
return '';
|
|
1454
|
+
try {
|
|
1455
|
+
return await renderShapesToDataUrl(shapes, this.#raster, {
|
|
1456
|
+
scale: 2,
|
|
1457
|
+
background: '#ffffff',
|
|
1458
|
+
widgetFallbackName: this.translate('canvas.draw.widgetName')
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
catch (error) {
|
|
1462
|
+
console.warn('Canvas: could not capture the sketch', error);
|
|
1463
|
+
return '';
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
/** The selection panel's "capture": hands the page a screenshot of the selection. */
|
|
1467
|
+
async captureSelection() {
|
|
1468
|
+
const notify = this.props.onObjectClick;
|
|
1469
|
+
if (!notify)
|
|
1470
|
+
return;
|
|
1471
|
+
try {
|
|
1472
|
+
const payload = await buildCapturePayload({
|
|
1473
|
+
engine: this.engine,
|
|
1474
|
+
raster: this.#raster,
|
|
1475
|
+
widgetFallbackName: this.translate('canvas.draw.widgetName')
|
|
1476
|
+
});
|
|
1477
|
+
if (!payload) {
|
|
1478
|
+
canvasWarn('Canvas: nothing is selected to capture');
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
notify(payload);
|
|
1482
|
+
}
|
|
1483
|
+
catch (error) {
|
|
1484
|
+
console.error('Canvas: captureSelection failed', error);
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
// ────────────────────────────────────────────────────── widget cards
|
|
1488
|
+
/** The whole board becomes one card of the widget. Resolves to the id of the card. */
|
|
1489
|
+
async absorbCanvasSketchIntoWidget(widgetId, screenshotDataUrl) {
|
|
1490
|
+
if (!widgetId)
|
|
1491
|
+
return null;
|
|
1492
|
+
try {
|
|
1493
|
+
return absorbSketchIntoWidget(this.engine, widgetId, screenshotDataUrl);
|
|
1494
|
+
}
|
|
1495
|
+
catch (error) {
|
|
1496
|
+
console.error('Canvas: absorbCanvasSketchIntoWidget failed', error);
|
|
1497
|
+
return null;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
/** Gives a card (or any object, which becomes one) the widget it stands for. */
|
|
1501
|
+
linkObjectToWidget(target, widgetId, widgetName) {
|
|
1502
|
+
const id = typeof target === 'string' ? target : (target?._objectId ?? target?.id);
|
|
1503
|
+
if (!id || !widgetId)
|
|
1504
|
+
return;
|
|
1505
|
+
if (!this.engine.linkObjectToWidget(id, widgetId, widgetName))
|
|
1506
|
+
canvasWarn('Canvas: could not link the object to the widget', { id, widgetId });
|
|
1507
|
+
}
|
|
1508
|
+
/** Gives the card with that id its widget (the page learned the id of the widget it made). */
|
|
1509
|
+
linkFrameToWidget(objectId, widgetId) {
|
|
1510
|
+
const object = this.engine.getObject(objectId);
|
|
1511
|
+
if (!object || object.type !== 'widget') {
|
|
1512
|
+
canvasLog('Canvas: linkFrameToWidget found no card', { objectId, widgetId });
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
this.engine.linkObjectToWidget(objectId, widgetId);
|
|
1516
|
+
}
|
|
1517
|
+
/** Marks the selected cards as being copied: a loader shows over them until the page links them. */
|
|
1518
|
+
markSelectedAsDuplicating() {
|
|
1519
|
+
for (const object of this.engine.selectedObjects()) {
|
|
1520
|
+
if (object.type === 'widget')
|
|
1521
|
+
this.engine.setPending(object.id, 'duplicating');
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
/** Replaces an object, or the selection a conversion remembered under that id, by a card of the widget. */
|
|
1525
|
+
async replaceObjectWithWidgetImage(objectId, widgetId, screenshotDataUrl) {
|
|
1526
|
+
try {
|
|
1527
|
+
return replaceObjectWithWidgetCard(this.engine, this.conversions, objectId, widgetId, screenshotDataUrl);
|
|
1528
|
+
}
|
|
1529
|
+
catch (error) {
|
|
1530
|
+
console.error('Canvas: replaceObjectWithWidgetImage failed', error);
|
|
1531
|
+
return null;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
updateWidgetImage(widgetId, newScreenshotDataUrl) {
|
|
1535
|
+
if (!updateWidgetThumbnail(this.engine, widgetId, newScreenshotDataUrl)) {
|
|
1536
|
+
canvasWarn('Canvas: updateWidgetImage found no card for', widgetId);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
selectWidgetShape(widgetId) {
|
|
1540
|
+
return selectWidgetCard(this.engine, widgetId);
|
|
1541
|
+
}
|
|
1542
|
+
selectWidgetShapeById(widgetId) {
|
|
1543
|
+
return selectWidgetCard(this.engine, widgetId);
|
|
1544
|
+
}
|
|
1545
|
+
getSelectedWidgetShapeId() {
|
|
1546
|
+
return selectedWidgetId(this.engine);
|
|
1547
|
+
}
|
|
1548
|
+
getHoveredWidgetShapeId() {
|
|
1549
|
+
return this.engine.state.hoverWidgetId;
|
|
1550
|
+
}
|
|
1551
|
+
/** The cards a live widget can be drawn over, with where each is on the page. */
|
|
1552
|
+
listWidgetShapeScreenRects() {
|
|
1553
|
+
const frame = this.#frame();
|
|
1554
|
+
if (!frame)
|
|
1555
|
+
return [];
|
|
1556
|
+
const state = this.engine.state;
|
|
1557
|
+
const results = [];
|
|
1558
|
+
for (const object of state.scene) {
|
|
1559
|
+
if (object.type !== 'widget' || !object.widgetId)
|
|
1560
|
+
continue;
|
|
1561
|
+
if (state.pending[object.id])
|
|
1562
|
+
continue;
|
|
1563
|
+
const runtime = this.engine.widgetRuntime(object.widgetId);
|
|
1564
|
+
if (runtime.orphaned)
|
|
1565
|
+
continue;
|
|
1566
|
+
const geometry = widgetPreviewGeometry(object, state.viewport, frame);
|
|
1567
|
+
if (!geometry || !geometry.matrix.every(Number.isFinite) || geometry.width < 4 || geometry.height < 4)
|
|
1568
|
+
continue;
|
|
1569
|
+
results.push({ widgetId: object.widgetId, hovered: object.widgetId === state.hoverWidgetId, ...geometry });
|
|
1570
|
+
}
|
|
1571
|
+
return results;
|
|
1572
|
+
}
|
|
1573
|
+
/** Where the card of a widget is on the page, with the board it is on. */
|
|
1574
|
+
getWidgetShapeScreenRect(widgetId) {
|
|
1575
|
+
const frame = this.#frame();
|
|
1576
|
+
if (!frame || !widgetId)
|
|
1577
|
+
return null;
|
|
1578
|
+
const card = findWidgetCard(this.engine, widgetId);
|
|
1579
|
+
if (!card) {
|
|
1580
|
+
// Draft convert shapes exist before the widget card is registered — expected on embedded create.
|
|
1581
|
+
if (!widgetId.startsWith('draft_convert_')) {
|
|
1582
|
+
canvasLog('Canvas: getWidgetShapeScreenRect found no card for', widgetId);
|
|
1583
|
+
}
|
|
1584
|
+
return null;
|
|
1585
|
+
}
|
|
1586
|
+
return screenRectOfBounds(shapeBounds(card), this.engine.state.viewport, frame);
|
|
1587
|
+
}
|
|
1588
|
+
/** Where any object is on the page: the id of an object, of a group, or of a selection a conversion remembered. */
|
|
1589
|
+
getObjectScreenRect(objectId) {
|
|
1590
|
+
const frame = this.#frame();
|
|
1591
|
+
if (!frame || !objectId)
|
|
1592
|
+
return null;
|
|
1593
|
+
let bounds = null;
|
|
1594
|
+
if (this.engine.getObject(objectId))
|
|
1595
|
+
bounds = boundsOfObjects(this.engine.state.scene, [objectId]);
|
|
1596
|
+
else
|
|
1597
|
+
bounds = this.conversions.peek(objectId)?.bounds ?? null;
|
|
1598
|
+
if (!bounds) {
|
|
1599
|
+
canvasLog('Canvas: getObjectScreenRect found no object for', objectId);
|
|
1600
|
+
return null;
|
|
1601
|
+
}
|
|
1602
|
+
return screenRectOfBounds(bounds, this.engine.state.viewport, frame);
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* The picture of a card as a data address, or null. A card shows its last screenshot; the answer is that one when it
|
|
1606
|
+
* is inline (the page asks for it at a moment it cannot wait, so the board does not draw anything new here).
|
|
1607
|
+
*/
|
|
1608
|
+
getWidgetShapeDataUrl(widgetId) {
|
|
1609
|
+
const card = findWidgetCard(this.engine, widgetId);
|
|
1610
|
+
const thumbnail = card?.thumbnail ?? null;
|
|
1611
|
+
return thumbnail && thumbnail.startsWith('data:image/') ? thumbnail : null;
|
|
1612
|
+
}
|
|
1613
|
+
/** Hides the screenshot of a card while a live widget covers it (so it does not show through the padding). */
|
|
1614
|
+
setWidgetShapeLivePreviewHiddenImage(widgetId, hidden) {
|
|
1615
|
+
if (!widgetId)
|
|
1616
|
+
return;
|
|
1617
|
+
this.engine.setWidgetRuntime(widgetId, { hiddenImage: !!hidden });
|
|
1618
|
+
}
|
|
1619
|
+
/** Puts a card for a widget in the middle of the view (rows of up to four for a batch). */
|
|
1620
|
+
addWidgetShape(widgetId, widgetName, gridIndex = 0, totalCount = 1, previewImageUrl) {
|
|
1621
|
+
if (!widgetId)
|
|
1622
|
+
return null;
|
|
1623
|
+
return addWidgetCard(this.engine, widgetId, { name: widgetName ?? null, gridIndex, totalCount, previewImage: previewImageUrl ?? null });
|
|
1624
|
+
}
|
|
1625
|
+
getLinkedWidgetIds() {
|
|
1626
|
+
return linkedWidgetIds(this.engine);
|
|
1627
|
+
}
|
|
1628
|
+
keepOnlyWidgetShape(widgetId) {
|
|
1629
|
+
return keepOnlyWidgetCard(this.engine, widgetId);
|
|
1630
|
+
}
|
|
1631
|
+
/** Takes everything but the card of one widget off the board. Returns how many objects went. */
|
|
1632
|
+
removeSketchObjectsKeepingWidget(widgetId) {
|
|
1633
|
+
return removeSketchObjectsKeeping(this.engine, widgetId);
|
|
1634
|
+
}
|
|
1635
|
+
hydrateWidgetShapeMetadata(widgetsById) {
|
|
1636
|
+
return hydrateWidgetMetadata(this.engine, widgetsById);
|
|
1637
|
+
}
|
|
1638
|
+
markOrphanedWidgetShapes(validWidgetIds) {
|
|
1639
|
+
return markOrphanedWidgetCards(this.engine, validWidgetIds);
|
|
1640
|
+
}
|
|
1641
|
+
setPrimaryWidgetShape(widgetId) {
|
|
1642
|
+
return setPrimaryWidgetCard(this.engine, widgetId);
|
|
1643
|
+
}
|
|
1644
|
+
/** The selection chrome's "set as primary": marks the card, then tells the page so it can keep it. */
|
|
1645
|
+
handleSetPrimaryFromPanel(widgetId) {
|
|
1646
|
+
this.setPrimaryWidgetShape(widgetId);
|
|
1647
|
+
this.#safely(() => this.props.onSetPrimaryWidget?.(widgetId), 'onSetPrimaryWidget');
|
|
1648
|
+
}
|
|
1649
|
+
getPrimaryWidgetId() {
|
|
1650
|
+
return primaryWidgetId(this.engine);
|
|
1651
|
+
}
|
|
1652
|
+
/** A live widget covers the card: its own bar moves it, so the body does not. */
|
|
1653
|
+
setWidgetShapeBodyDragAllowed(widgetId, allowed) {
|
|
1654
|
+
if (!widgetId)
|
|
1655
|
+
return;
|
|
1656
|
+
this.engine.setWidgetRuntime(widgetId, { bodyDragAllowed: !!allowed });
|
|
1657
|
+
}
|
|
1658
|
+
/** The page's bar drags a card by a distance in page pixels (the zoom, and a board the page scales, are accounted for). */
|
|
1659
|
+
translateWidgetShapeByScreen(widgetId, dxScreen, dyScreen) {
|
|
1660
|
+
if (!widgetId)
|
|
1661
|
+
return false;
|
|
1662
|
+
const scale = this.#cssScale();
|
|
1663
|
+
return moveWidgetCardByScreen(this.engine, widgetId, dxScreen / scale.x, dyScreen / scale.y);
|
|
1664
|
+
}
|
|
1665
|
+
/** The page's bar let go: the move is one step and the board is marked as changed. */
|
|
1666
|
+
/** The id the old call carries (the creator still passes it) is not needed: only one card is carried at a time, and the engine knows which. */
|
|
1667
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- part of the signature pages call
|
|
1668
|
+
commitWidgetShapeTranslate(_widgetId) {
|
|
1669
|
+
commitWidgetCardMove(this.engine);
|
|
1670
|
+
}
|
|
1671
|
+
setWidgetShapeOverlayDragActive(active) {
|
|
1672
|
+
this.engine.setOverlayDragActive(!!active);
|
|
1673
|
+
}
|
|
1674
|
+
// ────────────────────────────────────────────────────── helpers for the shell
|
|
1675
|
+
/**
|
|
1676
|
+
* The lines a text is drawn on. The board draws exactly these (never letting the browser wrap), and the sketch handed to
|
|
1677
|
+
* the AI is drawn from the same lines, so what is on the screen is what is sent. Kept per record: a text that did not
|
|
1678
|
+
* change is not laid out again on the next frame, and all of them are when the fonts finished loading.
|
|
1679
|
+
*/
|
|
1680
|
+
textLayoutOf(text) {
|
|
1681
|
+
const fontRevision = this.engine.state.fontRevision;
|
|
1682
|
+
if (fontRevision !== this.#textLayoutsFontRevision) {
|
|
1683
|
+
this.#textLayouts = new WeakMap();
|
|
1684
|
+
this.#textLayoutsFontRevision = fontRevision;
|
|
1685
|
+
}
|
|
1686
|
+
let layout = this.#textLayouts.get(text);
|
|
1687
|
+
if (!layout) {
|
|
1688
|
+
layout = layoutTextObject(text, this.#measureText);
|
|
1689
|
+
this.#textLayouts.set(text, layout);
|
|
1690
|
+
}
|
|
1691
|
+
return layout;
|
|
1692
|
+
}
|
|
1693
|
+
/** The name drawn on a card: what the page calls the widget, what the card was saved with, or the generic word. */
|
|
1694
|
+
widgetLabel(card) {
|
|
1695
|
+
const fromPage = this.props.getWidgetName?.(card.widgetId);
|
|
1696
|
+
return fromPage || card.widgetName || this.translate('canvas.draw.widgetName');
|
|
1697
|
+
}
|
|
1698
|
+
/** Whether the widget behind a card is gone (the card is kept, with a label that says so). */
|
|
1699
|
+
isCardOrphaned(card) {
|
|
1700
|
+
if (this.engine.widgetRuntime(card.widgetId).orphaned)
|
|
1701
|
+
return true;
|
|
1702
|
+
const known = this.props.isWidgetKnown;
|
|
1703
|
+
return known ? !known(card.widgetId) : false;
|
|
1704
|
+
}
|
|
1705
|
+
/** A new id for something the shell makes. */
|
|
1706
|
+
createId(prefix = 'obj') {
|
|
1707
|
+
return createObjectId(prefix);
|
|
1708
|
+
}
|
|
1709
|
+
/** A plain rectangle in the middle of the view (used by the stress page). */
|
|
1710
|
+
makeRect(fields = {}) {
|
|
1711
|
+
const center = this.engine.visibleCenter();
|
|
1712
|
+
const rect = createRectObject({ id: this.engine.services.createId('obj'), x: center.x - 50, y: center.y - 50, width: 100, height: 100, ...fields });
|
|
1713
|
+
return this.engine.addObjects([rect])[0];
|
|
1714
|
+
}
|
|
1715
|
+
}
|