@widgetic/canvas 0.5.43 → 0.5.44

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.
@@ -426,6 +426,10 @@
426
426
  export const executeSketchTool = forwardToHost(host, 'executeSketchTool');
427
427
  export const beginSketchToolBatch = forwardToHost(host, 'beginSketchToolBatch');
428
428
  export const endSketchToolBatch = forwardToHost(host, 'endSketchToolBatch');
429
+ // The camera: the view eases to some objects, to a point, or back to 100% on everything drawn (position and zoom together).
430
+ export const flyToObjects = forwardToHost(host, 'flyToObjects');
431
+ export const flyToPoint = forwardToHost(host, 'flyToPoint');
432
+ export const flyToContent = forwardToHost(host, 'flyToContent');
429
433
  </script>
430
434
 
431
435
  <Tooltip.Provider delayDuration={400} skipDelayDuration={200}>
@@ -155,6 +155,9 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
155
155
  executeSketchTool?: (name: string, args: Record<string, unknown>) => import("../tools/types.js").ToolResult;
156
156
  beginSketchToolBatch?: () => void;
157
157
  endSketchToolBatch?: () => void;
158
+ flyToObjects?: (objectIds: readonly string[], options?: import("./types.js").CanvasFlyOptions) => boolean;
159
+ flyToPoint?: (point: import("../engine/core/types.js").Point, options?: import("./types.js").CanvasFlyOptions) => boolean;
160
+ flyToContent?: (options?: import("./types.js").CanvasMoveOptions) => boolean;
158
161
  }, {
159
162
  [evt: string]: CustomEvent<any>;
160
163
  }, {}, {
@@ -235,6 +238,9 @@ declare const DomCanvas: $$__sveltets_2_IsomorphicComponent<{
235
238
  executeSketchTool: (name: string, args: Record<string, unknown>) => import("../tools/types.js").ToolResult;
236
239
  beginSketchToolBatch: () => void;
237
240
  endSketchToolBatch: () => void;
241
+ flyToObjects: (objectIds: readonly string[], options?: import("./types.js").CanvasFlyOptions) => boolean;
242
+ flyToPoint: (point: import("../engine/core/types.js").Point, options?: import("./types.js").CanvasFlyOptions) => boolean;
243
+ flyToContent: (options?: import("./types.js").CanvasMoveOptions) => boolean;
238
244
  }, string>;
239
245
  type DomCanvas = InstanceType<typeof DomCanvas>;
240
246
  export default DomCanvas;
@@ -25,7 +25,7 @@ import type { PanZoomPosition } from '../panZoomPosition.js';
25
25
  import type { ToolbarPosition } from '../toolbarPosition.js';
26
26
  import type { Translate as CatalogTranslate } from '@widgetic/design-system/i18n';
27
27
  import type { CanvasMessageKey } from '../../i18n/messages.js';
28
- import type { ObjectClickPayload, StrokeRecognizer } from '../types.js';
28
+ import type { CanvasFlyOptions, CanvasMoveOptions, ObjectClickPayload, StrokeRecognizer } from '../types.js';
29
29
  import type { LoadedImageFile } from './browserServices.js';
30
30
  import type { HostObject } from './hostObject.js';
31
31
  import type { ListWidgetScreenRectsOptions, ScreenRect, WidgetScreenRect } from './screenRects.js';
@@ -305,6 +305,24 @@ export declare class CanvasHost {
305
305
  zoomTo(percent: number): void;
306
306
  zoomReset(): void;
307
307
  zoomFit(): void;
308
+ /**
309
+ * Eases the view to some objects (objects of the board, groups included; ids that are not on the board are left out): the
310
+ * position and the zoom move together and arrive together, with the middle of the objects in the middle of the board. The
311
+ * objects fill the board unless `zoomPercent` or `keepZoom` says otherwise. False when none of the ids is on the board.
312
+ * A press on the board, a scroll or a pinch takes the view back at once.
313
+ */
314
+ flyToObjects(objectIds: readonly string[], options?: CanvasFlyOptions): boolean;
315
+ /**
316
+ * Eases the view to a point of the world (the point that ends in the middle of the board), position and zoom together. The
317
+ * zoom stays what it is unless `zoomPercent` says another (100 is 100%). False when the point is not a point of numbers or the
318
+ * view is there already.
319
+ */
320
+ flyToPoint(point: Point, options?: CanvasFlyOptions): boolean;
321
+ /**
322
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board: what a double click on
323
+ * the empty board does. Position and zoom move together. An empty board goes back to where a new board starts.
324
+ */
325
+ flyToContent(options?: CanvasMoveOptions): boolean;
308
326
  deselectAll(): void;
309
327
  onSelectAllObjects(): void;
310
328
  onDeselectAllObjects(): void;
@@ -1502,6 +1502,66 @@ export class CanvasHost {
1502
1502
  zoomFit() {
1503
1503
  this.engine.zoomToFit();
1504
1504
  }
1505
+ /**
1506
+ * Eases the view to some objects (objects of the board, groups included; ids that are not on the board are left out): the
1507
+ * position and the zoom move together and arrive together, with the middle of the objects in the middle of the board. The
1508
+ * objects fill the board unless `zoomPercent` or `keepZoom` says otherwise. False when none of the ids is on the board.
1509
+ * A press on the board, a scroll or a pinch takes the view back at once.
1510
+ */
1511
+ flyToObjects(objectIds, options = {}) {
1512
+ try {
1513
+ if (!Array.isArray(objectIds)) {
1514
+ canvasWarn('Canvas: flyToObjects needs a list of object ids; the view was not moved', objectIds);
1515
+ return false;
1516
+ }
1517
+ const idsOnBoard = objectIds.filter((objectId) => typeof objectId === 'string' && !!this.engine.getObject(objectId));
1518
+ if (idsOnBoard.length === 0) {
1519
+ canvasLog('Canvas: flyToObjects found none of the objects on the board; the view was not moved', objectIds);
1520
+ return false;
1521
+ }
1522
+ const { zoomPercent, keepZoom, ...moveOptions } = options;
1523
+ // Fitting is the default for objects; the other two ways to say what the zoom is win over it, "keep" before a number.
1524
+ const zoom = keepZoom ? 'keep' : Number.isFinite(zoomPercent) ? zoomPercent / 100 : 'fit';
1525
+ return this.engine.flyToObjects(idsOnBoard, { ...moveOptions, zoom });
1526
+ }
1527
+ catch (error) {
1528
+ canvasWarn('Canvas: flyToObjects failed', error);
1529
+ return false;
1530
+ }
1531
+ }
1532
+ /**
1533
+ * Eases the view to a point of the world (the point that ends in the middle of the board), position and zoom together. The
1534
+ * zoom stays what it is unless `zoomPercent` says another (100 is 100%). False when the point is not a point of numbers or the
1535
+ * view is there already.
1536
+ */
1537
+ flyToPoint(point, options = {}) {
1538
+ try {
1539
+ if (!point || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
1540
+ canvasWarn('Canvas: flyToPoint needs a point with an x and a y that are numbers; the view was not moved', point);
1541
+ return false;
1542
+ }
1543
+ const { zoomPercent, keepZoom, ...moveOptions } = options;
1544
+ const zoom = !keepZoom && Number.isFinite(zoomPercent) ? zoomPercent / 100 : undefined;
1545
+ return this.engine.flyTo({ center: { x: point.x, y: point.y }, zoom }, moveOptions);
1546
+ }
1547
+ catch (error) {
1548
+ canvasWarn('Canvas: flyToPoint failed', error);
1549
+ return false;
1550
+ }
1551
+ }
1552
+ /**
1553
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board: what a double click on
1554
+ * the empty board does. Position and zoom move together. An empty board goes back to where a new board starts.
1555
+ */
1556
+ flyToContent(options = {}) {
1557
+ try {
1558
+ return this.engine.flyToContent(options);
1559
+ }
1560
+ catch (error) {
1561
+ canvasWarn('Canvas: flyToContent failed', error);
1562
+ return false;
1563
+ }
1564
+ }
1505
1565
  // ────────────────────────────────────────────────────── selection and arrangement
1506
1566
  deselectAll() {
1507
1567
  this.engine.clearSelection();
@@ -17,9 +17,9 @@ export declare const CANVAS_CONTRACT_FUNCTION_NAMES: readonly ["shapeFillColor",
17
17
  * (feat/shopify-feedback-canvas) adds the same one, so it keeps the name and the answer (how many objects went): removes
18
18
  * the sketch objects around one widget card and keeps the card.
19
19
  */
20
- export declare const CANVAS_ADDED_FUNCTION_NAMES: readonly ["removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch"];
20
+ export declare const CANVAS_ADDED_FUNCTION_NAMES: readonly ["removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent"];
21
21
  /** Every function the shell exports. */
22
- export declare const CANVAS_EXPORTED_FUNCTION_NAMES: readonly ["shapeFillColor", "captureCanvasSketch", "absorbCanvasSketchIntoWidget", "deselectAll", "duplicateSelectedObjects", "deleteSelectedObjects", "markSelectedAsDuplicating", "linkObjectToWidget", "linkFrameToWidget", "replaceObjectWithWidgetImage", "updateWidgetImage", "selectWidgetShape", "listWidgetShapeScreenRects", "getWidgetShapeScreenRect", "getObjectScreenRect", "getWidgetShapeDataUrl", "setWidgetShapeLivePreviewHiddenImage", "addWidgetShape", "getLinkedWidgetIds", "keepOnlyWidgetShape", "hydrateWidgetShapeMetadata", "markOrphanedWidgetShapes", "onSelectSelectTool", "onSelectLibraryShapeTool", "onSelectEraseTool", "onSelectDrawTool", "onSelectTextTool", "onSelectArrowTool", "onSelectShapeTool", "onSelectFrameTool", "setPrimaryWidgetShape", "getPrimaryWidgetId", "setWidgetShapeBodyDragAllowed", "translateWidgetShapeByScreen", "commitWidgetShapeTranslate", "setWidgetShapeOverlayDragActive", "selectWidgetShapeById", "getSelectedWidgetShapeId", "getSelectedObject", "getHoveredWidgetShapeId", "onSelectImageTool", "onSelectVideoTool", "onSelectPanTool", "zoomIn", "zoomOut", "zoomTo", "zoomReset", "zoomFit", "onGroupSelection", "onUngroupSelection", "onSelectAllObjects", "onDeselectAllObjects", "flushAutosave", "saveNow", "undo", "redo", "saveCanvas", "loadCanvas", "onClearAllObjects", "addText", "addTriangle", "addRect", "addCircle", "addFrame", "addImage", "removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch"];
22
+ export declare const CANVAS_EXPORTED_FUNCTION_NAMES: readonly ["shapeFillColor", "captureCanvasSketch", "absorbCanvasSketchIntoWidget", "deselectAll", "duplicateSelectedObjects", "deleteSelectedObjects", "markSelectedAsDuplicating", "linkObjectToWidget", "linkFrameToWidget", "replaceObjectWithWidgetImage", "updateWidgetImage", "selectWidgetShape", "listWidgetShapeScreenRects", "getWidgetShapeScreenRect", "getObjectScreenRect", "getWidgetShapeDataUrl", "setWidgetShapeLivePreviewHiddenImage", "addWidgetShape", "getLinkedWidgetIds", "keepOnlyWidgetShape", "hydrateWidgetShapeMetadata", "markOrphanedWidgetShapes", "onSelectSelectTool", "onSelectLibraryShapeTool", "onSelectEraseTool", "onSelectDrawTool", "onSelectTextTool", "onSelectArrowTool", "onSelectShapeTool", "onSelectFrameTool", "setPrimaryWidgetShape", "getPrimaryWidgetId", "setWidgetShapeBodyDragAllowed", "translateWidgetShapeByScreen", "commitWidgetShapeTranslate", "setWidgetShapeOverlayDragActive", "selectWidgetShapeById", "getSelectedWidgetShapeId", "getSelectedObject", "getHoveredWidgetShapeId", "onSelectImageTool", "onSelectVideoTool", "onSelectPanTool", "zoomIn", "zoomOut", "zoomTo", "zoomReset", "zoomFit", "onGroupSelection", "onUngroupSelection", "onSelectAllObjects", "onDeselectAllObjects", "flushAutosave", "saveNow", "undo", "redo", "saveCanvas", "loadCanvas", "onClearAllObjects", "addText", "addTriangle", "addRect", "addCircle", "addFrame", "addImage", "removeSketchObjectsKeepingWidget", "getSketchSceneSummary", "executeSketchTool", "beginSketchToolBatch", "endSketchToolBatch", "flyToObjects", "flyToPoint", "flyToContent"];
23
23
  export type CanvasExportedFunctionName = (typeof CANVAS_EXPORTED_FUNCTION_NAMES)[number];
24
24
  /** What a page gets from `bind:this` besides the component's props: the host's own type of each function. */
25
25
  export type CanvasHostApi = Pick<CanvasHost, CanvasExportedFunctionName>;
@@ -87,7 +87,11 @@ export const CANVAS_ADDED_FUNCTION_NAMES = [
87
87
  'getSketchSceneSummary',
88
88
  'executeSketchTool',
89
89
  'beginSketchToolBatch',
90
- 'endSketchToolBatch'
90
+ 'endSketchToolBatch',
91
+ // The camera: the view eases to a place (position and zoom together). A page jumps from one object to another, or to a point.
92
+ 'flyToObjects',
93
+ 'flyToPoint',
94
+ 'flyToContent'
91
95
  ];
92
96
  /** Every function the shell exports. */
93
97
  export const CANVAS_EXPORTED_FUNCTION_NAMES = [...CANVAS_CONTRACT_FUNCTION_NAMES, ...CANVAS_ADDED_FUNCTION_NAMES];
@@ -13,6 +13,7 @@ export type { ToolbarPosition } from './toolbarPosition';
13
13
  export { PAN_ZOOM_POSITIONS, DEFAULT_PAN_ZOOM_POSITION } from './panZoomPosition';
14
14
  export type { PanZoomPosition } from './panZoomPosition';
15
15
  export type { StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './types';
16
+ export type { CanvasFlyOptions, CanvasMoveOptions } from './types';
16
17
  export { CANVAS_SHAPE_SNAP_ENABLED, STROKE_SNAP_IMAGE_SIDE, projectStrokeToImagePoints, renderStrokeSnapImage } from './shapes/strokeShapeSnap';
17
18
  export { canvasLog, canvasWarn, canvasDebug, setCanvasLogsEnabled, isCanvasLogsEnabled } from './canvasLogger';
18
19
  export { setShapeImageStore, getShapeImageStore, SHAPE_IMAGE_STORE_OBJECT_URLS } from './shapes/shapeImageStore';
@@ -3,6 +3,7 @@
3
3
  * Importable by both the canvas project and consuming apps (e.g. widget-creator).
4
4
  */
5
5
  import type { CanvasSnapShape, SnapRanking, StrokeMeasurements } from './shapes/strokeShapeSnap';
6
+ import type { ViewMoveOptions } from '../engine/EngineCore.js';
6
7
  /** Payload emitted when a frame is converted to a widget via onConvertToWidget callback. */
7
8
  export interface WidgetConversionPayload {
8
9
  frameName: string;
@@ -77,3 +78,19 @@ export interface StrokeRecognitionResult {
77
78
  }
78
79
  /** The recognizer a host supplies to enable stroke snapping. */
79
80
  export type StrokeRecognizer = (request: StrokeRecognitionRequest) => Promise<StrokeRecognitionResult | null>;
81
+ /**
82
+ * How a move of the view goes (`flyToPoint`, `flyToObjects`, `flyToContent`): a page can set how long it takes, the shape of the
83
+ * motion (`easing`), whether the position and the zoom ease together or the view flies (`path`: `'ease'`, the default, or `'fly'`),
84
+ * and be told when it is over (and whether the view arrived or the person took it first).
85
+ */
86
+ export type CanvasMoveOptions = ViewMoveOptions;
87
+ /** What `flyToPoint` and `flyToObjects` take besides how the move goes: the zoom to arrive at. */
88
+ export interface CanvasFlyOptions extends CanvasMoveOptions {
89
+ /**
90
+ * The zoom to arrive at, in percent as `zoomTo` takes it (100 is 100%). Left out: `flyToObjects` fits the objects to the board
91
+ * (never past 200%) and `flyToPoint` keeps the zoom the board has.
92
+ */
93
+ zoomPercent?: number;
94
+ /** Keeps the zoom the board has and only moves to the place (`flyToObjects` would otherwise fit the objects to the board). Wins over `zoomPercent`. */
95
+ keepZoom?: boolean;
96
+ }
@@ -104,10 +104,15 @@
104
104
  data-canvas-color-picker-trigger
105
105
  aria-label="{label}: {fieldText}"
106
106
  title={$t('canvas.panel.pickColor')}
107
- class="flex h-9 w-[185px] min-h-9 items-center justify-between gap-2 rounded-lg bg-accent py-0 ps-3 pe-2 text-body text-foreground transition-colors duration-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:ring-2 data-[state=open]:ring-ring"
107
+ class="group/color-field flex h-9 w-[185px] min-h-9 items-center justify-between gap-2 rounded-lg bg-accent py-0 ps-3 pe-2 text-body text-foreground transition-colors duration-fast focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:ring-2 data-[state=open]:ring-ring"
108
108
  >
109
109
  <span class="truncate tabular-nums">{fieldText}</span>
110
- <span class="size-5 shrink-0 rounded-md border border-border" style:background={swatchBackground}></span>
110
+ <!-- The press cue is the swatch shrinking a little, never the field: a field is a component, and only a real button or a
111
+ small icon inside a component shrinks when it is pressed. A person who asks for less motion gets no shrink. -->
112
+ <span
113
+ class="size-5 shrink-0 rounded-md border border-border transition-transform duration-fast ease-out group-active/color-field:scale-90 motion-reduce:transition-none motion-reduce:group-active/color-field:scale-100"
114
+ style:background={swatchBackground}
115
+ ></span>
111
116
  </button>
112
117
  {/snippet}
113
118
  </Popover.Trigger>
@@ -20,7 +20,7 @@
20
20
  <script lang="ts">
21
21
  import { onDestroy } from 'svelte';
22
22
  import type { Attachment } from 'svelte/attachments';
23
- import { IconButton, NumberStepper, Select, Slider } from '@widgetic/design-system/components';
23
+ import { IconButton, NumberControls, Select, Slider } from '@widgetic/design-system/components';
24
24
  import type { StylePatch } from '../../engine/core/style.js';
25
25
  import type { EngineState } from '../../engine/state.js';
26
26
  import { useCanvasLanguage } from '../../i18n/language.js';
@@ -234,19 +234,20 @@
234
234
  {#if traits.strokeWidth.kind !== 'none'}
235
235
  <div class="flex h-9 w-full items-start" data-canvas-panel-row="strokeWidth">
236
236
  <span class="flex h-9 min-w-0 flex-1 items-center gap-1 text-body">{$t('canvas.panel.strokeWidth')}</span>
237
- <!-- The design system's number stepper (IC Number): the value can be typed or stepped, and the group names the two buttons after the row. -->
238
- <NumberStepper
239
- class="w-[185px]"
240
- label={$t('canvas.panel.strokeWidth')}
241
- decreaseLabel={$t('canvas.panel.decrease')}
242
- increaseLabel={$t('canvas.panel.increase')}
243
- value={traits.strokeWidth.kind === 'same' ? Number(strokeWidthValue.toFixed(1)) : null}
244
- fallbackValue={strokeWidthValue}
245
- min={0}
246
- max={200}
247
- step={1}
248
- onChange={(next) => changeStyle({ strokeWidth: next })}
249
- />
237
+ <!-- The design system's number control (IC Number), the one the editor draws: the value can be typed or stepped, and the group names the two buttons after the row. -->
238
+ <div class="w-[185px] shrink-0">
239
+ <NumberControls
240
+ label={$t('canvas.panel.strokeWidth')}
241
+ decreaseLabel={$t('canvas.panel.decrease')}
242
+ increaseLabel={$t('canvas.panel.increase')}
243
+ value={traits.strokeWidth.kind === 'same' ? Number(strokeWidthValue.toFixed(1)) : null}
244
+ fallbackValue={strokeWidthValue}
245
+ min={0}
246
+ max={200}
247
+ step={1}
248
+ onChange={(next) => changeStyle({ strokeWidth: next })}
249
+ />
250
+ </div>
250
251
  </div>
251
252
  {/if}
252
253
 
@@ -316,18 +317,19 @@
316
317
 
317
318
  <div class="flex h-9 w-full items-start">
318
319
  <span class="flex h-9 min-w-0 flex-1 items-center gap-1 text-body">{$t('canvas.panel.fontSize')}</span>
319
- <NumberStepper
320
- class="w-[185px]"
321
- label={$t('canvas.panel.fontSize')}
322
- decreaseLabel={$t('canvas.panel.decrease')}
323
- increaseLabel={$t('canvas.panel.increase')}
324
- value={typeof fontSizeDisplay === 'number' ? fontSizeDisplay : null}
325
- fallbackValue={fontSizeValue}
326
- min={8}
327
- max={200}
328
- step={1}
329
- onChange={(next) => changeStyle({ fontSize: next })}
330
- />
320
+ <div class="w-[185px] shrink-0">
321
+ <NumberControls
322
+ label={$t('canvas.panel.fontSize')}
323
+ decreaseLabel={$t('canvas.panel.decrease')}
324
+ increaseLabel={$t('canvas.panel.increase')}
325
+ value={typeof fontSizeDisplay === 'number' ? fontSizeDisplay : null}
326
+ fallbackValue={fontSizeValue}
327
+ min={8}
328
+ max={200}
329
+ step={1}
330
+ onChange={(next) => changeStyle({ fontSize: next })}
331
+ />
332
+ </div>
331
333
  </div>
332
334
 
333
335
  <div class="flex items-center justify-between gap-1" role="group" aria-label={$t('canvas.control.textStyle')}>
@@ -45,8 +45,10 @@
45
45
 
46
46
  // Written out in full, so that the stylesheet of a page that installs the canvas picks every class up.
47
47
  const SQUARE_CLASSES = { toolbar: 'size-9', compact: 'size-8' } as const;
48
+ // The zoom level is a real button, so it shrinks a little while it is pressed like the zoom buttons beside it, through the design
49
+ // system's `press-feedback` (which keeps still for a person who asked for less motion).
48
50
  const LEVEL_CLASSES =
49
- 'inline-flex h-8 w-10 shrink-0 items-center justify-center rounded-lg text-xs font-medium text-muted-foreground transition-colors duration-fast motion-reduce:transition-none hover:bg-accent hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50';
51
+ 'press-feedback inline-flex h-8 w-10 shrink-0 items-center justify-center rounded-lg text-xs font-medium text-muted-foreground transition-colors duration-fast motion-reduce:transition-none hover:bg-accent hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50';
50
52
  // The design system's Icon Button shows the keyboard focus by a tint of its background, and the brand tint of the tool that is on
51
53
  // is a background too, that wins over it: the tool in use, which is where the keyboard begins, showed no focus at all (found with
52
54
  // the accessibility check). It gets the ring that the zoom level and the Shapes button show, and only when the keyboard has the focus.
@@ -10,6 +10,7 @@
10
10
  * end, so one gesture is one undo step. The pointer controller drives them; everything else (the menus, the
11
11
  * keyboard, the host's own calls) uses the commands below, each of which is one step.
12
12
  */
13
+ import type { CameraPathShape } from './core/cameraMove.js';
13
14
  import type { ParsedCanvas, SerializeOptions } from './codec/canvasDocument.js';
14
15
  import type { AlignMode, DistributeAxis } from './core/arrange.js';
15
16
  import type { ArrowHandleId } from './core/arrow.js';
@@ -40,6 +41,50 @@ export interface EngineServices {
40
41
  random?: () => number;
41
42
  /** Schedules an animation frame; returns a function that cancels it (tests pass a manual clock). */
42
43
  requestAnimationFrame?: (callback: (time: number) => void) => () => void;
44
+ /**
45
+ * Whether the person asked their system for less motion (the browser's `prefers-reduced-motion` in the app, `false` in
46
+ * tests unless a test says otherwise). A move of the view (`flyTo` and the other `flyTo…` calls) then puts the view
47
+ * in its place at once instead of easing it there.
48
+ */
49
+ prefersReducedMotion?: () => boolean;
50
+ }
51
+ /** A place to look at: the point of the world that goes to the middle of the board element, and the zoom to arrive at. */
52
+ export interface ViewTarget {
53
+ center: Point;
54
+ /** The zoom to arrive at (1 is 100%). Left out: the zoom stays what it is. */
55
+ zoom?: number;
56
+ }
57
+ /** How a move of the view goes (`flyTo` and the other `flyTo…` calls). */
58
+ export interface ViewMoveOptions {
59
+ /** How long the move takes, in milliseconds. Left out: worked out from how far the view goes, and always under a second. */
60
+ duration?: number;
61
+ /**
62
+ * The shape of the move: how much of the way is done (0 to 1) when this much of the time has passed (0 to 1), for the
63
+ * position and the zoom together. Left out: slow start, quick middle, slow end.
64
+ */
65
+ easing?: (progress: number) => number;
66
+ /**
67
+ * The way the view travels. `'ease'` (the default): the position and the zoom ease together, on the one `easing`, and arrive at
68
+ * the same moment; the zoom never goes beyond its two ends. `'fly'`: the path of van Wijk and Nuij, which for a long way zooms out
69
+ * on the way and in again at the end so the person keeps sight of where the view goes (it suits a jump across a big board); the
70
+ * zoom then changes at another rate than the position. Any other value is taken for `'ease'`. The time of the move does not depend
71
+ * on it.
72
+ */
73
+ path?: CameraPathShape;
74
+ /**
75
+ * Called once when the move is over, with `true` when the view arrived at the place and `false` when somebody else took the
76
+ * view first (the person pressed on the board, scrolled or pinched it; another move or a new board started). Also called, with
77
+ * `true`, when there was nothing to move because the view was there already.
78
+ */
79
+ onEnd?: (arrived: boolean) => void;
80
+ }
81
+ /** A move of the view to some objects. */
82
+ export interface ViewObjectsMoveOptions extends ViewMoveOptions {
83
+ /**
84
+ * The zoom to arrive at: a number (1 is 100%), `'fit'` (the objects fill the board with room around them, never past 200%,
85
+ * as "zoom to selection" does) or `'keep'` (the zoom the board has). Left out: `'fit'`.
86
+ */
87
+ zoom?: number | 'fit' | 'keep';
43
88
  }
44
89
  /** What the engine tells the host shell. Every hook is optional and read at the moment it is needed. */
45
90
  export interface EngineHooks {
@@ -206,6 +251,7 @@ export declare class EngineCore {
206
251
  force?: boolean;
207
252
  }): void;
208
253
  setStickyTool(sticky: boolean): void;
254
+ /** Puts the view where it is asked at once. A move of the view that was on its way (see `flyTo`) is over: the view is the person's. */
209
255
  setViewport(viewport: Viewport): void;
210
256
  panBy(deltaX: number, deltaY: number): void;
211
257
  /** Zooms and keeps the world point under `screenPoint` where it is. */
@@ -220,6 +266,34 @@ export declare class EngineCore {
220
266
  zoomToFit(): void;
221
267
  /** Shows the selection, or everything when nothing is selected. */
222
268
  zoomToSelection(): void;
269
+ /** Whether the view is on its way to a place (a move started by `flyTo` or one of the other `flyTo…` calls has not ended). */
270
+ get isViewMoving(): boolean;
271
+ /**
272
+ * Eases the view to a place: the point that ends in the middle of the board and the zoom change together, on one progress,
273
+ * so the move is a single motion and not a pan followed by a zoom, and both arrive at the same moment. With `options.path` set
274
+ * to `'fly'` a long way zooms out on the way and in again at the end instead (see `core/cameraMove.ts`). The view ends exactly
275
+ * on the place, and the size of the board is read at every frame, so a board that is resized on the way still ends with the
276
+ * place in its middle.
277
+ *
278
+ * Any other change of the view ends the move where the view is: a press on the board, a scroll, a pinch, `setViewport` or a new
279
+ * board, so the person is never fought for the view. With "reduce motion" on in the system, the view goes there at once.
280
+ *
281
+ * Returns whether the view moved (or jumped); false when it is there already or the place is not a place.
282
+ */
283
+ flyTo(target: ViewTarget, options?: ViewMoveOptions): boolean;
284
+ /**
285
+ * Eases the view to some objects (groups count as one, as in a selection): the middle of the objects goes to the middle of the
286
+ * board while the zoom changes to what `options.zoom` asks (the objects fill the board unless it says otherwise).
287
+ * False when none of the ids is an object of the board.
288
+ */
289
+ flyToObjects(ids: readonly ObjectId[], options?: ViewObjectsMoveOptions): boolean;
290
+ /**
291
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board (a double click on the
292
+ * empty board does this). An empty board goes back to where a new board starts.
293
+ */
294
+ flyToContent(options?: ViewMoveOptions): boolean;
295
+ /** Ends a move of the view where it is (the view keeps the place it had reached) and tells its `onEnd` that it did not arrive. */
296
+ cancelViewportMove(): void;
223
297
  /** The rectangle of the world that is on screen. */
224
298
  visibleRect(): Rect;
225
299
  /** The point of the world at a point of the board element. */
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import { parseCanvasDocument, serializeCanvasDocument } from './codec/canvasDocument.js';
14
14
  import { rotationAfterResetProgress, rotationResetProgress } from './core/rotationReset.js';
15
+ import { cameraOfViewport, createCameraPath, easeInOutCubic, viewportOfCamera, viewportsMatch } from './core/cameraMove.js';
15
16
  import { alignObjects, distributeObjects } from './core/arrange.js';
16
17
  import { reconcileArrowBindings } from './core/arrowBinding.js';
17
18
  import { createImageObject, createObjectId, createRectObject, createTextObject, createWidgetObject, TEXT_DEFAULTS } from './core/defaults.js';
@@ -59,6 +60,8 @@ export class EngineCore {
59
60
  services;
60
61
  #state = createInitialState();
61
62
  #rotationResetCancel = null;
63
+ /** Stops the move of the view that is on its way (see `flyTo`); null when the view is not moving by itself. */
64
+ #viewportMoveCancel = null;
62
65
  #listeners = new Set();
63
66
  #history;
64
67
  #clipboard = null;
@@ -79,6 +82,8 @@ export class EngineCore {
79
82
  measureText: services.measureText ?? createFixedAdvanceMeasure(),
80
83
  now: services.now ?? (() => Date.now()),
81
84
  random: services.random ?? Math.random,
85
+ prefersReducedMotion: services.prefersReducedMotion ??
86
+ (() => typeof globalThis.matchMedia === 'function' && globalThis.matchMedia('(prefers-reduced-motion: reduce)').matches),
82
87
  requestAnimationFrame: services.requestAnimationFrame ??
83
88
  ((callback) => {
84
89
  if (typeof globalThis.requestAnimationFrame === 'function') {
@@ -105,6 +110,7 @@ export class EngineCore {
105
110
  /** Lets go of every listener and hook (the board was removed from the page). */
106
111
  dispose() {
107
112
  this.cancelRotationReset();
113
+ this.cancelViewportMove();
108
114
  this.#listeners.clear();
109
115
  this.hooks = {};
110
116
  this.#textSession = null;
@@ -189,6 +195,8 @@ export class EngineCore {
189
195
  // ──────────────────────────────────────────────────────── loading and saving
190
196
  /** Shows a canvas that was read from saved data. History starts again from it, and it is not "changed". */
191
197
  load(parsed, options = {}) {
198
+ // A new board has its own view: a move that was on its way to a place of the old board is over.
199
+ this.cancelViewportMove();
192
200
  this.#textSession = null;
193
201
  // The texts are laid out first: an arrow tied to one rests on the box its letters make.
194
202
  const scene = reconcileArrowBindings(this.#fitTexts(parsed.scene));
@@ -622,7 +630,13 @@ export class EngineCore {
622
630
  this.#set({ stickyTool: sticky });
623
631
  }
624
632
  // ──────────────────────────────────────────────────────── viewport
633
+ /** Puts the view where it is asked at once. A move of the view that was on its way (see `flyTo`) is over: the view is the person's. */
625
634
  setViewport(viewport) {
635
+ this.cancelViewportMove();
636
+ this.#writeViewport(viewport);
637
+ }
638
+ /** Writes the view without ending a move in progress: the one way the move itself puts the view where the frame says. */
639
+ #writeViewport(viewport) {
626
640
  const next = sanitizeViewport(viewport);
627
641
  const current = this.#state.viewport;
628
642
  if (next.x === current.x && next.y === current.y && next.zoom === current.zoom)
@@ -674,6 +688,120 @@ export class EngineCore {
674
688
  }
675
689
  this.setViewport(fitViewportToRect(bounds, this.#state.viewSize, VIEW_FIT_PADDING, 2));
676
690
  }
691
+ // ──────────────────────────────────────────────────────── moving the view with an ease
692
+ /** Whether the view is on its way to a place (a move started by `flyTo` or one of the other `flyTo…` calls has not ended). */
693
+ get isViewMoving() {
694
+ return this.#viewportMoveCancel !== null;
695
+ }
696
+ /**
697
+ * Eases the view to a place: the point that ends in the middle of the board and the zoom change together, on one progress,
698
+ * so the move is a single motion and not a pan followed by a zoom, and both arrive at the same moment. With `options.path` set
699
+ * to `'fly'` a long way zooms out on the way and in again at the end instead (see `core/cameraMove.ts`). The view ends exactly
700
+ * on the place, and the size of the board is read at every frame, so a board that is resized on the way still ends with the
701
+ * place in its middle.
702
+ *
703
+ * Any other change of the view ends the move where the view is: a press on the board, a scroll, a pinch, `setViewport` or a new
704
+ * board, so the person is never fought for the view. With "reduce motion" on in the system, the view goes there at once.
705
+ *
706
+ * Returns whether the view moved (or jumped); false when it is there already or the place is not a place.
707
+ */
708
+ flyTo(target, options = {}) {
709
+ // A move on its way is over: this one starts from where the view is now.
710
+ this.cancelViewportMove();
711
+ const viewSize = this.#state.viewSize;
712
+ const startView = cameraOfViewport(this.#state.viewport, viewSize);
713
+ const endView = {
714
+ center: { x: target.center.x, y: target.center.y },
715
+ zoom: clampZoom(target.zoom ?? startView.zoom)
716
+ };
717
+ // A board that is not on the page yet has no middle to put a place in, and a place that is not a point is the caller's mistake:
718
+ // the view stays as it is.
719
+ if (!(viewSize.width > 0) || !(viewSize.height > 0) || !Number.isFinite(endView.center.x) || !Number.isFinite(endView.center.y)) {
720
+ this.#callHook(() => options.onEnd?.(false), 'view move end callback');
721
+ return false;
722
+ }
723
+ const endViewport = viewportOfCamera(endView, viewSize);
724
+ if (viewportsMatch(endViewport, this.#state.viewport)) {
725
+ // Nothing to move, and nothing to wait for.
726
+ this.#callHook(() => options.onEnd?.(true), 'view move end callback');
727
+ return false;
728
+ }
729
+ const path = createCameraPath(startView, endView, viewSize, options.path);
730
+ const duration = options.duration ?? path?.duration ?? 0;
731
+ if (!path || !(duration > 0) || this.services.prefersReducedMotion()) {
732
+ // No time to move in, or a person who asked their system for no motion: the view is in its place at once.
733
+ this.#writeViewport(endViewport);
734
+ this.#callHook(() => options.onEnd?.(true), 'view move end callback');
735
+ return true;
736
+ }
737
+ const easing = options.easing ?? easeInOutCubic;
738
+ const startedAt = this.services.now();
739
+ let cancelFrame = null;
740
+ let over = false;
741
+ const finish = (arrived) => {
742
+ if (over)
743
+ return;
744
+ over = true;
745
+ cancelFrame?.();
746
+ if (this.#viewportMoveCancel === stopMove)
747
+ this.#viewportMoveCancel = null;
748
+ this.#callHook(() => options.onEnd?.(arrived), 'view move end callback');
749
+ };
750
+ const stopMove = () => finish(false);
751
+ const advance = () => {
752
+ if (over)
753
+ return;
754
+ const timeProgress = Math.min(1, Math.max(0, (this.services.now() - startedAt) / duration));
755
+ const arrived = timeProgress >= 1;
756
+ // The board is measured now, not when the move began, and the last frame is the place itself, not a step close to it.
757
+ const view = arrived ? endView : path.at(easing(timeProgress));
758
+ this.#writeViewport(viewportOfCamera(view, this.#state.viewSize));
759
+ // What listens to the view may have taken it in the meantime (a call to `setViewport` from a listener ends the move).
760
+ if (over)
761
+ return;
762
+ if (arrived) {
763
+ finish(true);
764
+ return;
765
+ }
766
+ cancelFrame = this.services.requestAnimationFrame(advance);
767
+ };
768
+ this.#viewportMoveCancel = stopMove;
769
+ cancelFrame = this.services.requestAnimationFrame(advance);
770
+ return true;
771
+ }
772
+ /**
773
+ * Eases the view to some objects (groups count as one, as in a selection): the middle of the objects goes to the middle of the
774
+ * board while the zoom changes to what `options.zoom` asks (the objects fill the board unless it says otherwise).
775
+ * False when none of the ids is an object of the board.
776
+ */
777
+ flyToObjects(ids, options = {}) {
778
+ const { zoom = 'fit', ...moveOptions } = options;
779
+ const bounds = boundsOfObjects(this.#state.scene, ids);
780
+ if (!bounds)
781
+ return false;
782
+ const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
783
+ const targetZoom = zoom === 'keep' ? undefined : zoom === 'fit' ? fitViewportToRect(bounds, this.#state.viewSize, VIEW_FIT_PADDING, 2).zoom : zoom;
784
+ return this.flyTo({ center, zoom: targetZoom }, moveOptions);
785
+ }
786
+ /**
787
+ * Eases the view back to 100% with the middle of everything that is drawn in the middle of the board (a double click on the
788
+ * empty board does this). An empty board goes back to where a new board starts.
789
+ */
790
+ flyToContent(options = {}) {
791
+ const bounds = boardVisualBounds(this.#state.scene);
792
+ const center = bounds
793
+ ? { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 }
794
+ : cameraOfViewport(INITIAL_VIEWPORT, this.#state.viewSize).center;
795
+ return this.flyTo({ center, zoom: 1 }, options);
796
+ }
797
+ /** Ends a move of the view where it is (the view keeps the place it had reached) and tells its `onEnd` that it did not arrive. */
798
+ cancelViewportMove() {
799
+ const stopMove = this.#viewportMoveCancel;
800
+ if (!stopMove)
801
+ return;
802
+ this.#viewportMoveCancel = null;
803
+ stopMove();
804
+ }
677
805
  /** The rectangle of the world that is on screen. */
678
806
  visibleRect() {
679
807
  return visibleWorldRect(this.#state.viewport, this.#state.viewSize);
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Moving the view the way a camera moves: from where it looks now to a place it is asked to look at, with the position and the
3
+ * zoom changing together, on one eased progress, and ending exactly on the place.
4
+ *
5
+ * A view is what the board looks at (`CameraView`): the point of the world in the middle of the board element, and the zoom (1 is
6
+ * 100%). The viewport the engine keeps (`x`, `y`, `zoom`) is worked out from it for the size of the board at that moment, so a board
7
+ * that is resized on the way still ends with the place in its middle.
8
+ *
9
+ * There are two shapes of path between two views (`CameraPathShape`):
10
+ *
11
+ * - `'ease'`, the default: the position and the zoom ease together. The centre goes in a straight line and the zoom changes by the
12
+ * same factor at every step, both on the one eased progress, so they start, speed up, slow down and arrive at the same moment, and
13
+ * the zoom never goes beyond its two ends. This is what "ease the position and the zoom at the same time" asks for.
14
+ * - `'fly'`: the path of van Wijk and Nuij, "Smooth and efficient zooming and panning" (2003), the one d3's `interpolateZoom` draws.
15
+ * A view that only zooms moves like a plain zoom; a view that has to go far zooms out on the way and in again at the end, so what
16
+ * the person looks at does not rush past. The position and the zoom still ride on one progress, but not at the same rate (the view
17
+ * zooms out while it pans and in as it arrives), so it is not the plain ease above.
18
+ *
19
+ * Both last as long as the length of the van Wijk path says, so a move takes the same time whichever shape it has.
20
+ *
21
+ * Nothing here knows the clock or the page: the engine asks for the view at a progress, and a test asks for the same.
22
+ */
23
+ import type { Point, Size, Viewport } from './types.js';
24
+ /**
25
+ * The way a move goes between two views: `'ease'` (the default) changes the position and the zoom together at the same rate, and
26
+ * `'fly'` is the path of van Wijk and Nuij, which zooms out on the way when the move is long. Any other value is taken for `'ease'`.
27
+ */
28
+ export type CameraPathShape = 'ease' | 'fly';
29
+ /** What the board looks at: the point of the world in the middle of the board element, and the zoom. */
30
+ export interface CameraView {
31
+ center: Point;
32
+ /** The scale of the world on screen (1 is 100%). */
33
+ zoom: number;
34
+ }
35
+ /** The path of a move between two views. */
36
+ export interface CameraPath {
37
+ /** How far the view travels, in the units of the path: a plain zoom of about four times is 1, and a longer way is more. */
38
+ length: number;
39
+ /** How long the move should last, in milliseconds, worked out from its length (never under the shortest or over the longest). */
40
+ duration: number;
41
+ /** The view `progress` of the way along the path: 0 is the start, 1 is exactly the end. */
42
+ at(progress: number): CameraView;
43
+ }
44
+ /** The shape a move has when nobody chose one: the position and the zoom ease together. */
45
+ export declare const DEFAULT_CAMERA_PATH_SHAPE: CameraPathShape;
46
+ /** The shortest a move lasts when nobody gave its length, in milliseconds: a shorter one is too quick for the eye to follow. */
47
+ export declare const CAMERA_MOVE_MIN_DURATION_MS = 380;
48
+ /** The longest a move lasts when nobody gave its length, in milliseconds: a long way across the board still takes under a second. */
49
+ export declare const CAMERA_MOVE_MAX_DURATION_MS = 1000;
50
+ /** The time for each unit of the length of a path, in milliseconds. */
51
+ export declare const CAMERA_MOVE_MS_PER_UNIT = 800;
52
+ /** The view that a viewport shows in a board element of `viewSize`. */
53
+ export declare function cameraOfViewport(viewport: Viewport, viewSize: Size): CameraView;
54
+ /** The viewport that shows `camera` in a board element of `viewSize`. */
55
+ export declare function viewportOfCamera(camera: CameraView, viewSize: Size): Viewport;
56
+ /** Whether two viewports look the same to a person: less than half a pixel apart, with a zoom that differs by less than 0.01%. */
57
+ export declare function viewportsMatch(first: Viewport, second: Viewport): boolean;
58
+ /** Slow start, quick middle, slow end: the way a person expects a camera to move. `progress` and the answer are between 0 and 1. */
59
+ export declare function easeInOutCubic(progress: number): number;
60
+ /**
61
+ * The path from one view to another, or `null` when there is no path to draw: the board has no size yet, or one of the views is not
62
+ * a view (a centre that is not a point, a zoom that is not above 0). The caller then puts the view in place at once.
63
+ *
64
+ * `shape` is how the view goes (see `CameraPathShape`): by default the position and the zoom ease together, and `'fly'` takes the
65
+ * path of van Wijk and Nuij. How long the move lasts comes from the length of that path whichever shape is asked for.
66
+ */
67
+ export declare function createCameraPath(from: CameraView, to: CameraView, viewSize: Size, shape?: CameraPathShape): CameraPath | null;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Moving the view the way a camera moves: from where it looks now to a place it is asked to look at, with the position and the
3
+ * zoom changing together, on one eased progress, and ending exactly on the place.
4
+ *
5
+ * A view is what the board looks at (`CameraView`): the point of the world in the middle of the board element, and the zoom (1 is
6
+ * 100%). The viewport the engine keeps (`x`, `y`, `zoom`) is worked out from it for the size of the board at that moment, so a board
7
+ * that is resized on the way still ends with the place in its middle.
8
+ *
9
+ * There are two shapes of path between two views (`CameraPathShape`):
10
+ *
11
+ * - `'ease'`, the default: the position and the zoom ease together. The centre goes in a straight line and the zoom changes by the
12
+ * same factor at every step, both on the one eased progress, so they start, speed up, slow down and arrive at the same moment, and
13
+ * the zoom never goes beyond its two ends. This is what "ease the position and the zoom at the same time" asks for.
14
+ * - `'fly'`: the path of van Wijk and Nuij, "Smooth and efficient zooming and panning" (2003), the one d3's `interpolateZoom` draws.
15
+ * A view that only zooms moves like a plain zoom; a view that has to go far zooms out on the way and in again at the end, so what
16
+ * the person looks at does not rush past. The position and the zoom still ride on one progress, but not at the same rate (the view
17
+ * zooms out while it pans and in as it arrives), so it is not the plain ease above.
18
+ *
19
+ * Both last as long as the length of the van Wijk path says, so a move takes the same time whichever shape it has.
20
+ *
21
+ * Nothing here knows the clock or the page: the engine asks for the view at a progress, and a test asks for the same.
22
+ */
23
+ import { clampNumber } from './geometry.js';
24
+ import { clampZoom, screenToWorld } from './viewport.js';
25
+ /** The shape a move has when nobody chose one: the position and the zoom ease together. */
26
+ export const DEFAULT_CAMERA_PATH_SHAPE = 'ease';
27
+ /** The shortest a move lasts when nobody gave its length, in milliseconds: a shorter one is too quick for the eye to follow. */
28
+ export const CAMERA_MOVE_MIN_DURATION_MS = 380;
29
+ /** The longest a move lasts when nobody gave its length, in milliseconds: a long way across the board still takes under a second. */
30
+ export const CAMERA_MOVE_MAX_DURATION_MS = 1000;
31
+ /** The time for each unit of the length of a path, in milliseconds. */
32
+ export const CAMERA_MOVE_MS_PER_UNIT = 800;
33
+ /**
34
+ * How much the path zooms out on its way when the move is long (ρ in the paper). The square root of 2 is the value its authors
35
+ * found the most pleasing: a larger one zooms out more, and 0 would be a straight line.
36
+ */
37
+ const PATH_CURVATURE = Math.SQRT2;
38
+ /** A move whose centres are closer than this fraction of the narrower view is a plain zoom: there is nothing to pan. */
39
+ const PLAIN_ZOOM_DISTANCE_RATIO = 1e-6;
40
+ /** Two viewports less than this many pixels apart look the same to a person. */
41
+ const SAME_VIEWPORT_PIXELS = 0.5;
42
+ /** Two zooms that differ by less than this fraction look the same to a person. */
43
+ const SAME_ZOOM_RATIO = 1e-4;
44
+ /** The view that a viewport shows in a board element of `viewSize`. */
45
+ export function cameraOfViewport(viewport, viewSize) {
46
+ return { center: screenToWorld(viewport, { x: viewSize.width / 2, y: viewSize.height / 2 }), zoom: viewport.zoom };
47
+ }
48
+ /** The viewport that shows `camera` in a board element of `viewSize`. */
49
+ export function viewportOfCamera(camera, viewSize) {
50
+ return {
51
+ x: viewSize.width / 2 - camera.center.x * camera.zoom,
52
+ y: viewSize.height / 2 - camera.center.y * camera.zoom,
53
+ zoom: camera.zoom
54
+ };
55
+ }
56
+ /** Whether two viewports look the same to a person: less than half a pixel apart, with a zoom that differs by less than 0.01%. */
57
+ export function viewportsMatch(first, second) {
58
+ return (Math.abs(first.x - second.x) < SAME_VIEWPORT_PIXELS &&
59
+ Math.abs(first.y - second.y) < SAME_VIEWPORT_PIXELS &&
60
+ Math.abs(first.zoom - second.zoom) < SAME_ZOOM_RATIO * Math.max(first.zoom, second.zoom));
61
+ }
62
+ /** Slow start, quick middle, slow end: the way a person expects a camera to move. `progress` and the answer are between 0 and 1. */
63
+ export function easeInOutCubic(progress) {
64
+ const clampedProgress = clampNumber(progress, 0, 1);
65
+ return clampedProgress < 0.5 ? 4 * clampedProgress ** 3 : 1 - (-2 * clampedProgress + 2) ** 3 / 2;
66
+ }
67
+ function isUsableView(view) {
68
+ return Number.isFinite(view.center.x) && Number.isFinite(view.center.y) && Number.isFinite(view.zoom) && view.zoom > 0;
69
+ }
70
+ /** A zoom ratio this close to 1 (its logarithm is this close to 0) is no zoom: the centre then goes by the plain share of the progress. */
71
+ const NO_ZOOM_LOGARITHM = 1e-9;
72
+ /**
73
+ * The view between two views with no detour: the zoom changes by the same factor at every step, and the centre goes along the
74
+ * straight line between the two centres, the way it does when a person zooms about one fixed point of the board and pans nothing
75
+ * else.
76
+ *
77
+ * The centre is not simply `progress` of the way along that line. The world grows on screen by the same factor at every step, so
78
+ * once the zoom grows by more than about 2.7 times in all, the place would first be carried away from the middle of the board, and
79
+ * only then come back to it (the swing of a plain tween). Here the share of the line is
80
+ * `(1 - zoomRatio^-progress) / (1 - 1 / zoomRatio)`, with which the place only ever comes closer to the middle of the board, on
81
+ * screen, as the zoom goes on; with no change of zoom it is `progress` itself, and zooming out it is the same formula.
82
+ */
83
+ function straightView(from, to, progress) {
84
+ const zoomLogarithm = Math.log(to.zoom / from.zoom);
85
+ const lineShare = Math.abs(zoomLogarithm) < NO_ZOOM_LOGARITHM ? progress : Math.expm1(-progress * zoomLogarithm) / Math.expm1(-zoomLogarithm);
86
+ return {
87
+ center: { x: from.center.x + (to.center.x - from.center.x) * lineShare, y: from.center.y + (to.center.y - from.center.y) * lineShare },
88
+ zoom: clampZoom(from.zoom * Math.exp(zoomLogarithm * progress))
89
+ };
90
+ }
91
+ /**
92
+ * The path from one view to another, or `null` when there is no path to draw: the board has no size yet, or one of the views is not
93
+ * a view (a centre that is not a point, a zoom that is not above 0). The caller then puts the view in place at once.
94
+ *
95
+ * `shape` is how the view goes (see `CameraPathShape`): by default the position and the zoom ease together, and `'fly'` takes the
96
+ * path of van Wijk and Nuij. How long the move lasts comes from the length of that path whichever shape is asked for.
97
+ */
98
+ export function createCameraPath(from, to, viewSize, shape = DEFAULT_CAMERA_PATH_SHAPE) {
99
+ // The path measures a view by the width of the world it shows along the longer side of the board.
100
+ const extent = Math.max(viewSize.width, viewSize.height);
101
+ if (!(extent > 0) || !isUsableView(from) || !isUsableView(to))
102
+ return null;
103
+ const startWidth = extent / from.zoom;
104
+ const endWidth = extent / to.zoom;
105
+ const deltaX = to.center.x - from.center.x;
106
+ const deltaY = to.center.y - from.center.y;
107
+ const distance = Math.hypot(deltaX, deltaY);
108
+ let length;
109
+ let sampleAt;
110
+ if (distance < Math.min(startWidth, endWidth) * PLAIN_ZOOM_DISTANCE_RATIO) {
111
+ // Nothing to pan: a plain zoom, by the same factor at every step.
112
+ length = Math.log(endWidth / startWidth) / PATH_CURVATURE;
113
+ sampleAt = (progress) => ({ fraction: progress, width: startWidth * Math.exp(PATH_CURVATURE * length * progress) });
114
+ }
115
+ else {
116
+ const curvatureSquared = PATH_CURVATURE ** 2;
117
+ const widthGrowth = endWidth ** 2 - startWidth ** 2;
118
+ const panPart = curvatureSquared ** 2 * distance ** 2;
119
+ // `asinh` rather than the logarithm of the square root: for a view that zooms in a long way with a short pan, the
120
+ // difference of two nearly equal numbers would come out as 0.
121
+ const startAngle = -Math.asinh((widthGrowth + panPart) / (2 * startWidth * curvatureSquared * distance));
122
+ const endAngle = -Math.asinh((widthGrowth - panPart) / (2 * endWidth * curvatureSquared * distance));
123
+ length = (endAngle - startAngle) / PATH_CURVATURE;
124
+ sampleAt = (progress) => {
125
+ const along = PATH_CURVATURE * length * progress + startAngle;
126
+ return {
127
+ fraction: (startWidth / (curvatureSquared * distance)) * (Math.cosh(startAngle) * Math.tanh(along) - Math.sinh(startAngle)),
128
+ width: (startWidth * Math.cosh(startAngle)) / Math.cosh(along)
129
+ };
130
+ };
131
+ }
132
+ const pathLength = Number.isFinite(length) ? Math.abs(length) : 1;
133
+ return {
134
+ length: pathLength,
135
+ duration: clampNumber(pathLength * CAMERA_MOVE_MS_PER_UNIT, CAMERA_MOVE_MIN_DURATION_MS, CAMERA_MOVE_MAX_DURATION_MS),
136
+ at(progress) {
137
+ if (!Number.isFinite(progress) || progress <= 0)
138
+ return { center: { ...from.center }, zoom: from.zoom };
139
+ if (progress >= 1)
140
+ return { center: { ...to.center }, zoom: to.zoom };
141
+ // No detour: the centre and the zoom change at the same rate on the one progress, and arrive together.
142
+ if (shape !== 'fly')
143
+ return straightView(from, to, progress);
144
+ const sample = sampleAt(progress);
145
+ // A path that came out as something that is not a number (a move across a distance no board has) is walked in a straight line.
146
+ if (!Number.isFinite(sample.fraction) || !(sample.width > 0) || !Number.isFinite(sample.width))
147
+ return straightView(from, to, progress);
148
+ return {
149
+ center: { x: from.center.x + deltaX * sample.fraction, y: from.center.y + deltaY * sample.fraction },
150
+ zoom: clampZoom(extent / sample.width)
151
+ };
152
+ }
153
+ };
154
+ }
@@ -112,6 +112,8 @@ export class PointerController {
112
112
  pointerDown(input) {
113
113
  this.#lastInput = input;
114
114
  this.#engine.cancelRotationReset();
115
+ // A press on the board takes the view back from a move that is on its way (see `EngineCore.flyTo`).
116
+ this.#engine.cancelViewportMove();
115
117
  this.#forgetStalePointers(input.time);
116
118
  this.#pointers.set(input.pointerId, { x: input.x, y: input.y, seenAt: input.time });
117
119
  this.#engine.lastPointerWorld = this.#engine.toWorld({ x: input.x, y: input.y });
@@ -278,6 +280,12 @@ export class PointerController {
278
280
  this.#begin(createMoveGesture(this.#context, input, moving, { onClick, immovable: this.#isHeldByLiveWidget(moving) }));
279
281
  return true;
280
282
  }
283
+ // Empty board, and this is the second press of a double click (or a double tap): the view eases back to 100%, with the middle of
284
+ // everything that is drawn in the middle of the board. The first press already cleared the selection.
285
+ if (doubleClick) {
286
+ engine.flyToContent();
287
+ return true;
288
+ }
281
289
  // Empty board. A finger pans (a tap clears the selection); a mouse drags a marquee.
282
290
  if (input.pointerType === 'touch') {
283
291
  this.#begin(createPanGesture(this.#context, input, { onTap: () => engine.clearSelection() }));
@@ -478,6 +486,10 @@ export class PointerController {
478
486
  pointerUp(input) {
479
487
  this.#lastInput = input;
480
488
  this.#pointers.delete(input.pointerId);
489
+ // A press that was dragged away from where it began was not a click, so the next press at that place is not its second half.
490
+ if (this.#lastClick && distanceBetween({ x: this.#lastClick.x, y: this.#lastClick.y }, { x: input.x, y: input.y }) > DOUBLE_CLICK_DISTANCE) {
491
+ this.#lastClick = null;
492
+ }
481
493
  if (this.#pinch) {
482
494
  if (this.#pointers.size < 2)
483
495
  this.#endPinch();
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * - Dynamic: const { Canvas } = await import('@widgetic/canvas')
8
8
  */
9
9
  export { Canvas } from './canvas';
10
- export type { WidgetConversionPayload, StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult } from './canvas';
10
+ export type { WidgetConversionPayload, StrokeRecognizer, StrokeRecognitionRequest, StrokeRecognitionResult, CanvasFlyOptions, CanvasMoveOptions } from './canvas';
11
11
  export { TOOLBAR_POSITIONS, DEFAULT_TOOLBAR_POSITION } from './canvas';
12
12
  export type { ToolbarPosition } from './canvas';
13
13
  export { PAN_ZOOM_POSITIONS, DEFAULT_PAN_ZOOM_POSITION } from './canvas';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/canvas",
3
- "version": "0.5.43",
3
+ "version": "0.5.44",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "svelte": "./dist/index.js",