@bevelo/canvas 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2654 @@
1
+ import { Point, Point as Point$1, Rect, Rect as Rect$1, Size, Size as Size$1 } from "@bevelo/runtime";
2
+ /**
3
+ * The largest backing size the model will ask for by default: 16,384 device
4
+ * pixels per side — WebKit's per-side limit, and the point at which a square
5
+ * canvas reaches Chromium's total-area limit (16,384² pixels). A surface at or
6
+ * under it allocates in every browser that draws; a host that draws further can
7
+ * cap tighter through `maxSide`.
8
+ */
9
+ export declare const MAX_BACKING_SIDE = 16384;
10
+ /** What a surface is measured at. */
11
+ interface CanvasSizing {
12
+ /** The element's size in CSS pixels, with unusable sides read as 0. */
13
+ readonly css: Size$1;
14
+ /** The ratio actually used, after the cap; never 0. */
15
+ readonly dpr: number;
16
+ /** The backing store, in whole device pixels. */
17
+ readonly backing: Size$1;
18
+ /** `backing.width / css.width` — the x scale a 2D context draws with. 0 when
19
+ * there is no CSS width to draw into. */
20
+ readonly scaleX: number;
21
+ /** `backing.height / css.height` — the y scale a 2D context draws with. 0
22
+ * when there is no CSS height to draw into. */
23
+ readonly scaleY: number;
24
+ }
25
+ /** How a host may narrow the size model. */
26
+ interface CanvasSizingOptions {
27
+ /**
28
+ * The largest side the backing store may have. Pass `Infinity` to opt out;
29
+ * an unusable number keeps the default.
30
+ */
31
+ readonly maxSide?: number;
32
+ }
33
+ /**
34
+ * The device pixel ratio a surface draws at. A browser reports 0 while a page is
35
+ * printed or a tab is being snapshotted, and a host may pass a value read before
36
+ * layout; neither is a scale a transform can use, so both read as 1.
37
+ */
38
+ export declare function usableDpr(dpr: number): number;
39
+ /**
40
+ * The size model for a CSS size and a device pixel ratio.
41
+ *
42
+ * The cap is applied to the ratio and the ratio is clamped at the requested
43
+ * value, never raised: asking for dpr 1 on a small box must not draw it at 2.
44
+ */
45
+ export declare function canvasSizing(css: Size$1, dpr: number, options?: CanvasSizingOptions): CanvasSizing;
46
+ /** Whether a surface has anything to paint: both CSS sides are usable. */
47
+ export declare function isPaintable(sizing: CanvasSizing): boolean;
48
+ /**
49
+ * Whether two sizings describe the same backing store.
50
+ *
51
+ * This is the question a caller asks before writing `canvas.width`: assigning a
52
+ * canvas's size resets its context (transform, clip, fill style) and clears the
53
+ * bitmap even when the number is unchanged, so a repaint loop that writes every
54
+ * frame pays for a full clear it did not need.
55
+ */
56
+ export declare function backingChanged(previous: CanvasSizing, next: CanvasSizing): boolean;
57
+ /** Whether two sizings are identical, transform included. */
58
+ export declare function sameSizing(previous: CanvasSizing, next: CanvasSizing): boolean;
59
+ /**
60
+ * Where the world sits on the surface: `offset` is the world origin's position
61
+ * in CSS pixels from the surface's top-left corner, and `scale` is world units
62
+ * per CSS pixel. `scale` is positive; a degenerate camera would make the
63
+ * mapping a division by zero.
64
+ */
65
+ interface Camera {
66
+ readonly scale: number;
67
+ readonly offset: Point$1;
68
+ }
69
+ /** The camera that draws world units as CSS pixels, from the surface's corner. */
70
+ export declare const IDENTITY_CAMERA: Camera;
71
+ /**
72
+ * Keeps a scale inside a range, order-independent.
73
+ *
74
+ * A non-finite scale is the minimum, like the image cropper's zoom: a camera
75
+ * with an infinite scale draws nothing at any finite coordinate, so the honest
76
+ * reading of a broken number is "as far out as allowed". A range whose
77
+ * minimum is above its maximum is read as the pair it meant, not as an empty
78
+ * range.
79
+ */
80
+ export declare function clampScale(scale: number, min: number, max: number): number;
81
+ /** A world point's position in CSS pixels on the surface. */
82
+ export declare function worldToScreen(camera: Camera, point: Point$1): Point$1;
83
+ /** A point in CSS pixels on the surface, in world units. */
84
+ export declare function screenToWorld(camera: Camera, point: Point$1): Point$1;
85
+ /** A world box in CSS pixels. */
86
+ export declare function worldRectToScreen(camera: Camera, rect: Rect$1): Rect$1;
87
+ /** A box in CSS pixels, in world units. */
88
+ export declare function screenRectToWorld(camera: Camera, rect: Rect$1): Rect$1;
89
+ /** The camera moved by a screen distance, in CSS pixels. */
90
+ export declare function panBy(camera: Camera, dx: number, dy: number): Camera;
91
+ /**
92
+ * The camera zoomed to a scale with the world point under `anchor` staying under
93
+ * it — the wheel and pinch gesture, and what makes a zoom feel anchored rather
94
+ * than centred.
95
+ *
96
+ * An unusable scale (0, negative, NaN) leaves the camera alone: the alternative
97
+ * is a camera no point can be mapped from, and the gesture that produced it is
98
+ * already over. The anchor is in CSS pixels on the surface.
99
+ */
100
+ export declare function zoomAt(camera: Camera, scale: number, anchor: Point$1): Camera;
101
+ /** How a fit is framed. */
102
+ interface FitOptions {
103
+ /** Screen pixels of breathing room on every side. @defaultValue 0 */
104
+ readonly padding?: number;
105
+ /** The closest the fit may zoom out to. @defaultValue 0.1 */
106
+ readonly minScale?: number;
107
+ /** The furthest the fit may zoom in to; a fit does not magnify. @defaultValue 1 */
108
+ readonly maxScale?: number;
109
+ }
110
+ /** The defaults a fit uses, in one place so a host can read them. */
111
+ export declare const FIT_DEFAULTS: {
112
+ readonly padding: 0;
113
+ readonly minScale: 0.1;
114
+ readonly maxScale: 1;
115
+ };
116
+ /**
117
+ * The camera that shows a world box whole and centred in a surface.
118
+ *
119
+ * A box with no width or height is a line or a point — an empty board, a single
120
+ * node — and is fitted as if it were one unit across rather than divided by
121
+ * zero, which is what a "zoom to fit" button needs to stay useful on an empty document.
122
+ *
123
+ * Padding that leaves no room at all falls back to no padding: the padding is
124
+ * an aesthetic, and the box that was asked to be shown outranks it.
125
+ */
126
+ export declare function fitToBounds(bounds: Rect$1, surface: Size$1, options?: FitOptions): Camera;
127
+ /** Options for {@link clampCameraToBounds}. */
128
+ interface ClampCameraOptions extends FitOptions {
129
+ /** Whether zooming out past fit-to-bounds is permitted. Defaults to false. */
130
+ readonly allowZoomOut?: boolean | undefined;
131
+ }
132
+ /**
133
+ * Clamps a camera's scale and offset so the surface remains framed within `bounds`
134
+ * (centering an axis whenever the scaled bounds fit inside the padded viewport).
135
+ */
136
+ export declare function clampCameraToBounds(camera: Camera, bounds: Rect$1, surface: Size$1, options?: ClampCameraOptions): Camera;
137
+ /** The part of the world on screen, in world units. */
138
+ export declare function visibleWorldRect(camera: Camera, surface: Size$1): Rect$1;
139
+ /**
140
+ * A point in CSS pixels on the surface, in backing-store pixels.
141
+ *
142
+ * The mapping is per axis because the size model rounds each axis on its own: a
143
+ * surface whose CSS size and backing size disagree by a fraction on one axis and
144
+ * not the other must not be drawn as if the ratios were equal.
145
+ */
146
+ export declare function cssToBacking(point: Point$1, sizing: CanvasSizing): Point$1;
147
+ /** A backing-store point in CSS pixels on the surface. */
148
+ export declare function backingToCss(point: Point$1, sizing: CanvasSizing): Point$1;
149
+ /** A box in CSS pixels, in backing-store pixels. */
150
+ export declare function cssRectToBacking(rect: Rect$1, sizing: CanvasSizing): Rect$1;
151
+ /** A box in backing-store pixels, in CSS pixels. */
152
+ export declare function backingRectToCss(rect: Rect$1, sizing: CanvasSizing): Rect$1;
153
+ /** A world point, in backing-store pixels — the coordinate a context hands to
154
+ * `moveTo` when the camera is applied to the transform. */
155
+ export declare function worldToBacking(camera: Camera, point: Point$1, sizing: CanvasSizing): Point$1;
156
+ /** A backing-store point, in world units. */
157
+ export declare function backingToWorld(point: Point$1, camera: Camera, sizing: CanvasSizing): Point$1;
158
+ /**
159
+ * The matrix a 2D context draws with for this camera and sizing, in the order
160
+ * `setTransform(a, b, c, d, e, f)` takes. A host that draws in world units writes
161
+ * it once per frame instead of multiplying every coordinate by hand.
162
+ */
163
+ export declare function cameraMatrix(camera: Camera, sizing: CanvasSizing): readonly [number, number, number, number, number, number];
164
+ /** One thing on the canvas that a pointer can land on. */
165
+ interface HitTarget {
166
+ /** What the caller calls it; the hit test returns the whole target. */
167
+ readonly key: string;
168
+ /** Its box, in world units. */
169
+ readonly bounds: Rect$1;
170
+ /** Whether it may be hit at all; an omitted or true value means yes. A
171
+ * disabled target is skipped without being removed from the list, so the
172
+ * caller's indices stay stable. */
173
+ readonly enabled?: boolean;
174
+ }
175
+ /**
176
+ * Whether a world point is inside a box, with the right and bottom edges
177
+ * excluded.
178
+ *
179
+ * The exclusion is what keeps the answer stable for adjacent rects. It also
180
+ * means a 1-unit box contains exactly one coordinate, which is the same rule a
181
+ * painted pixel follows.
182
+ */
183
+ export declare function containsPoint(bounds: Rect$1, point: Point$1): boolean;
184
+ /**
185
+ * The topmost hit target under a world point, or undefined when nothing is
186
+ * there.
187
+ *
188
+ * The search runs from the end of the list because the list is paint order: the
189
+ * last target painted is the one in front.
190
+ */
191
+ export declare function hitTest(point: Point$1, targets: readonly HitTarget[]): HitTarget | undefined;
192
+ /** Every hit target under a world point, topmost first. */
193
+ export declare function hitTestAll(point: Point$1, targets: readonly HitTarget[]): readonly HitTarget[];
194
+ /**
195
+ * The topmost hit target under a point in CSS pixels on the surface.
196
+ *
197
+ * This is the call a pointer handler makes: the event carries screen
198
+ * coordinates, and the camera knows what world coordinates they are, so the
199
+ * handler never converts by hand and never uses the wrong camera.
200
+ */
201
+ export declare function hitTestScreen(camera: Camera, screenPoint: Point$1, targets: readonly HitTarget[]): HitTarget | undefined;
202
+ /** What is waiting to be repainted. */
203
+ interface DirtyBatch {
204
+ /** The surface, in world or CSS units — the caller's; nothing outside it can
205
+ * be dirty. */
206
+ readonly clip: Rect$1;
207
+ /** The dirty rectangles, each already clipped to `clip`. Empty is a clean
208
+ * frame, and also what `all` leaves behind. */
209
+ readonly rects: readonly Rect$1[];
210
+ /** Whether the whole surface is dirty. */
211
+ readonly all: boolean;
212
+ /** The most rectangles the batch keeps before collapsing; at least 1. */
213
+ readonly maxRects: number;
214
+ }
215
+ /** How many rects a batch keeps before it collapses to their union.
216
+ * @defaultValue 4 */
217
+ export declare const DEFAULT_DIRTY_RECTS = 4;
218
+ /** How a batch is built. */
219
+ interface DirtyOptions {
220
+ /** The most rectangles kept before collapsing. A value below 1 is read as 1;
221
+ * a broken one keeps the default. */
222
+ readonly maxRects?: number;
223
+ }
224
+ /** The smallest box containing both boxes. */
225
+ export declare function unionRect(a: Rect$1, b: Rect$1): Rect$1;
226
+ /**
227
+ * The overlap of two boxes, or undefined when they do not overlap.
228
+ *
229
+ * Boxes that merely touch share no pixels, so their intersection is undefined
230
+ * rather than a zero-width rect; a caller that keeps zero-width rects in a batch
231
+ * would issue an empty draw call per frame.
232
+ */
233
+ export declare function intersectRects(a: Rect$1, b: Rect$1): Rect$1 | undefined;
234
+ /** An empty batch for a surface. */
235
+ export declare function dirtyBatch(clip: Rect$1, options?: DirtyOptions): DirtyBatch;
236
+ /** Whether a batch has anything to paint. */
237
+ export declare function isDirty(batch: DirtyBatch): boolean;
238
+ /**
239
+ * The batch with one more dirty area.
240
+ *
241
+ * A rect outside the clip is dropped; a rect that overlaps it is clipped. A rect
242
+ * an existing dirty rect already covers changes nothing, and a rect that covers
243
+ * existing ones replaces them — repainting the larger area repaints the smaller,
244
+ * so keeping both would pay twice for the shared pixels.
245
+ */
246
+ export declare function markDirty(batch: DirtyBatch, rect: Rect$1): DirtyBatch;
247
+ /** The batch with the whole surface marked. */
248
+ export declare function markEverythingDirty(batch: DirtyBatch): DirtyBatch;
249
+ /**
250
+ * The rectangles to repaint this frame: the clip alone when everything is dirty,
251
+ * otherwise the accumulated ones. The returned array is the batch's own and must
252
+ * not be mutated.
253
+ */
254
+ export declare function dirtyRects(batch: DirtyBatch): readonly Rect$1[];
255
+ /**
256
+ * A box grown outward to whole units.
257
+ *
258
+ * Dirty rects are usually in CSS or world units, while a bitmap is clipped in
259
+ * whole pixels, and rounding inward leaves a row or column of the previous frame
260
+ * beside the repaint. Rounding outward costs at most one pixel per side.
261
+ */
262
+ export declare function outwardRect(rect: Rect$1): Rect$1;
263
+ /**
264
+ * The element's size in CSS pixels.
265
+ *
266
+ * `getBoundingClientRect` is used rather than `clientWidth` because a canvas
267
+ * scaled by a stylesheet (a zoomed board, a scaled page) must be drawn at the
268
+ * size it is *painted*, not the size its layout box has. A hidden element
269
+ * reports zeros, which the size model reads as "nothing to paint".
270
+ */
271
+ export declare function readCanvasCssSize(element: Element): Size$1;
272
+ /** The device pixel ratio the window draws at, with an unusable value read as 1
273
+ * (a page being printed reports 0). */
274
+ export declare function readDevicePixelRatio(view: Window): number;
275
+ /**
276
+ * Writes a sizing's backing store onto a canvas, and reports whether it wrote.
277
+ *
278
+ * Assigning `width` or `height` clears the bitmap and resets the context even
279
+ * when the number is the value it already had, so a repaint loop that computes a
280
+ * sizing every frame must compare first. Both sides are written together when
281
+ * either changed because one assignment already cleared the canvas.
282
+ */
283
+ export declare function applyCanvasSizing(canvas: HTMLCanvasElement, sizing: CanvasSizing): boolean;
284
+ /** What a sizing pass produced. */
285
+ interface CanvasSync {
286
+ /** The size model for the canvas as it is now. */
287
+ readonly sizing: CanvasSizing;
288
+ /** Whether the backing store was written, which is also whether the canvas
289
+ * was cleared and needs a full repaint. */
290
+ readonly resized: boolean;
291
+ }
292
+ /** Measures a canvas and brings its backing store in line with its CSS size. */
293
+ export declare function syncCanvasSizing(canvas: HTMLCanvasElement, view: Window, options?: CanvasSizingOptions): CanvasSync;
294
+ /**
295
+ * Calls `onChange` whenever the canvas's size model changes — a layout resize or
296
+ * a device pixel ratio change, which is what a browser zoom or a monitor move
297
+ * reports.
298
+ *
299
+ * Only changes are reported: a resize observer fires for the size an element
300
+ * already has often enough (a sibling's transition, a scroll container's
301
+ * fractional rounding) that forwarding every notification would repaint for
302
+ * nothing. The ratio is watched through a `resolution` media query, because a
303
+ * page has no ratio-change event; the query is re-bound after each change
304
+ * because it names the ratio it matched. A window with no observer and no query
305
+ * support still gets the window's own resize event, and the size comparison
306
+ * keeps that from firing on every unrelated resize.
307
+ *
308
+ * Returns a cleanup function. Nothing is called during binding.
309
+ */
310
+ export declare function bindCanvasResize(canvas: HTMLCanvasElement, view: Window, onChange: (sizing: CanvasSizing) => void, options?: CanvasSizingOptions): () => void;
311
+ /** Why the camera moved. A host shows this in diagnostics or a status line. */
312
+ type CameraReason = "wheel" | "drag" | "pinch" | "zoom-key" | "reset" | "imperative";
313
+ /** A wheel event, reduced to the numbers the reducer needs. */
314
+ interface WheelInput {
315
+ readonly deltaX: number;
316
+ readonly deltaY: number;
317
+ /** `0` pixels, `1` lines, `2` pages — the DOM's `WheelEvent.deltaMode`. */
318
+ readonly deltaMode: number;
319
+ readonly ctrlKey: boolean;
320
+ readonly metaKey: boolean;
321
+ /** The pointer's position in CSS pixels from the surface's corner. */
322
+ readonly x: number;
323
+ readonly y: number;
324
+ }
325
+ /** A key press, reduced. */
326
+ interface KeyInput {
327
+ readonly key: string;
328
+ readonly shiftKey: boolean;
329
+ readonly ctrlKey: boolean;
330
+ readonly metaKey: boolean;
331
+ }
332
+ /** Which pointer-button pan is armed, decided by the caller's policy. */
333
+ type PanMode = "none" | "primary" | "middle" | "space";
334
+ /** Limits and policy. Everything a host might legitimately want to differ. */
335
+ interface GestureConfig {
336
+ /** Never zoom out past this. */
337
+ readonly minScale: number;
338
+ /** Never zoom in past this. */
339
+ readonly maxScale: number;
340
+ /** Scale multiplier for one `+`/`-` press. */
341
+ readonly keyboardStep: number;
342
+ /** The multiplier when Shift is held. */
343
+ readonly keyboardFineStep: number;
344
+ /** Pan distance per arrow press, in CSS pixels. */
345
+ readonly keyboardPanStep: number;
346
+ /** Trackpad wheel deltas are small; a mouse wheel notch arrives as ~100. */
347
+ readonly wheelZoomSensitivity: number;
348
+ /** Whether wheel with Ctrl/⌘ zooms. Off means `preventDefault` never fires. */
349
+ readonly wheelZoom: boolean;
350
+ /** Whether a plain wheel pans. Off leaves the page's own scrolling alone. */
351
+ readonly wheelPan: boolean;
352
+ /** Mirrors the pan intent on x for a right-to-left surface. */
353
+ readonly mirrored: boolean;
354
+ /** Optional world bounds enforced when `fixedViewport` is enabled. */
355
+ readonly bounds?: Rect$1 | undefined;
356
+ /** Clamps pan and zoom within `bounds`, fitting the viewport on reset. */
357
+ readonly fixedViewport?: boolean | undefined;
358
+ /** Padding around `bounds` in CSS pixels under fixed-viewport mode. */
359
+ readonly boundsPadding?: number | undefined;
360
+ /** What screen readers hear after a keyboard zoom or a pinch settles. */
361
+ readonly announce?: (message: string) => void;
362
+ }
363
+ /** What the reducer needs to know about the surface for `deltaMode: 2`. */
364
+ interface SurfaceSize {
365
+ readonly width: number;
366
+ readonly height: number;
367
+ }
368
+ /** One reduction: the next camera, why it moved, and whether the event was claimed. */
369
+ interface CameraChange {
370
+ readonly camera: Camera;
371
+ readonly reason: CameraReason;
372
+ /**
373
+ * Whether the caller must `preventDefault`. A wheel that zooms must (the
374
+ * browser would otherwise scroll the page); a wheel that pans must when the
375
+ * surface is the scroller. A key that did nothing claims nothing.
376
+ */
377
+ readonly claimed: boolean;
378
+ /** Set when a new zoom level should be spoken. */
379
+ readonly announcement?: string;
380
+ }
381
+ /**
382
+ * One frame of a two-finger gesture, already read from the contacts: both
383
+ * fingers down (`pinch`, with the scale about `origin` and the midpoint's
384
+ * travel), one finger left (`pan`), or none (`ended`). Core's `pinchGesture`
385
+ * returns this shape.
386
+ */
387
+ type PinchReading = {
388
+ readonly kind: "pinch";
389
+ readonly pinch: {
390
+ readonly scale: number;
391
+ readonly origin: Point$1;
392
+ readonly x: number;
393
+ readonly y: number;
394
+ };
395
+ } | {
396
+ readonly kind: "pan";
397
+ } | {
398
+ readonly kind: "ended";
399
+ };
400
+ /**
401
+ * The defaults a canvas surface wants. Zoom range is the one every drawing
402
+ * tool converges on (10% to 400% — you can see the whole board or read a label);
403
+ * the keyboard step is the familiar 1.25, and the fine step is half of it.
404
+ */
405
+ export declare const DEFAULT_GESTURE_CONFIG: GestureConfig;
406
+ /** Builds a bounded fixed-viewport gesture configuration centered on `bounds`. */
407
+ export declare function fixedViewportGestureConfig(bounds: Rect$1, overrides?: Partial<GestureConfig>): GestureConfig;
408
+ /**
409
+ * The pan a wheel asks for, in CSS pixels.
410
+ *
411
+ * A trackpad reports pixels, a mouse wheel reports lines or pages, and a
412
+ * horizontal-only trackpad gesture reports `deltaX` with `deltaY` at zero. The
413
+ * RTL mirror is applied here rather than to the camera, so the camera stays a
414
+ * plain positive-scale transform.
415
+ */
416
+ export declare function wheelPan(input: WheelInput, surface: SurfaceSize, mirrored?: boolean): Point$1;
417
+ /** Whether this wheel is a zoom rather than a pan. */
418
+ export declare function isZoomWheel(input: WheelInput): boolean;
419
+ /**
420
+ * The scale a wheel asks for, clamped. Exponential rather than additive so a
421
+ * fast flick and a slow roll compose the same way, and so zooming in then out by
422
+ * the same gesture returns to where it started.
423
+ */
424
+ export declare function wheelZoomScale(camera: Camera, input: WheelInput, config: GestureConfig): number;
425
+ /**
426
+ * A zoom that holds the anchor even when the scale was clamped.
427
+ *
428
+ * `zoomAt` alone is correct for an unclamped scale. When the requested scale is
429
+ * outside the range, clamping first and then calling `zoomAt` is also correct —
430
+ * the anchor is preserved for *whatever* scale it is given — so the rule this
431
+ * function protects is subtler: the pan must be recomputed for the clamped
432
+ * scale, not scaled by the unclamped ratio. It exists as its own name because
433
+ * that mistake is invisible in the middle of the range and only shows at the
434
+ * ends, which is exactly where a user spends a pinching gesture.
435
+ */
436
+ export declare function zoomToCapped(camera: Camera, requested: number, anchor: Point$1, config: GestureConfig): Camera;
437
+ /** A pan of the camera by a screen distance, mirrored for RTL. */
438
+ export declare function panCamera(camera: Camera, dx: number, dy: number, config: GestureConfig): Camera;
439
+ /** A percentage a host can put in an announcement, rounded to whole numbers. */
440
+ export declare function zoomPercent(camera: Camera): number;
441
+ /**
442
+ * The wheel reduced. Pans when it is a plain wheel, zooms about the pointer when
443
+ * Ctrl/⌘ is held, and reports whether the caller must `preventDefault`.
444
+ *
445
+ * A wheel with both deltas at zero is not a gesture: it claims nothing and moves
446
+ * nothing, which keeps a horizontal-only trackpad's vertical `0` from being read
447
+ * as a leftward pan.
448
+ */
449
+ export declare function reduceWheel(camera: Camera, input: WheelInput, surface: SurfaceSize, config?: GestureConfig): CameraChange;
450
+ /**
451
+ * One keyboard step. Returns `claimed: false` for a key that is not a camera
452
+ * gesture, so the caller can let it through to whatever else wants it.
453
+ */
454
+ export declare function reduceKey(camera: Camera, input: KeyInput, surface: SurfaceSize, config?: GestureConfig): CameraChange;
455
+ /**
456
+ * One frame of a pinch. `reading` is the gesture since the second finger
457
+ * landed; the result carries the camera and the reason the caller needs to know
458
+ * it should not be applied as a pan.
459
+ *
460
+ * A finger lifting mid-pinch reads as `pan` rather than a jump, the same rule
461
+ * the cropper follows.
462
+ */
463
+ export declare function reducePinch(camera: Camera, reading: PinchReading, config?: GestureConfig, surface?: SurfaceSize): CameraChange & {
464
+ readonly phase: "pinch" | "pan" | "ended";
465
+ };
466
+ /**
467
+ * Whether a press that began at `point` should pan.
468
+ *
469
+ * The caller owns hit testing, so this takes the answer rather than computing
470
+ * it: `onItem` means the press landed on something the surface draws, and the
471
+ * gesture belongs to that item (a drag of its own), not to the camera.
472
+ */
473
+ export declare function pressPans(mode: PanMode, onItem: boolean): boolean;
474
+ /**
475
+ * The visible world rectangle, for a culling pass. Declared here rather than in
476
+ * `viewport.ts` because it is the surface's own question ("what do I draw?") and
477
+ * it is the caller's framebuffer size that answers it.
478
+ */
479
+ export declare function cullRect(camera: Camera, surface: SurfaceSize): {
480
+ x: number;
481
+ y: number;
482
+ width: number;
483
+ height: number;
484
+ };
485
+ /** One thing on a canvas. The engine reads these three fields and nothing more. */
486
+ interface CanvasElement {
487
+ readonly id: string;
488
+ /** World-unit bounds covering all painted pixels (including strokes); width and height > 0. */
489
+ readonly bounds: Rect;
490
+ /** Fractional-index z-order key, painted in ascending string order. */
491
+ readonly order: string;
492
+ }
493
+ /** What changed in a document, as the engine hears it. */
494
+ interface CanvasChange {
495
+ readonly kind: "add" | "remove" | "change";
496
+ readonly ids: readonly string[];
497
+ }
498
+ /** Five-member read port for canvas documents (`list`, `get`, `has`, `set`, `subscribe`). */
499
+ interface CanvasDocument<T extends CanvasElement = CanvasElement> {
500
+ /** Every element whose bounds intersect `rect`, ascending by `order`. Supersets allowed. */
501
+ list(rect: Rect): readonly T[];
502
+ /** The element with this id, or `undefined` once it is gone. */
503
+ get(id: string): T | undefined;
504
+ /** Whether the id still resolves. Agrees with `get`. */
505
+ has(id: string): boolean;
506
+ /** Writes one authored field of one element. */
507
+ set(id: string, field: string, value: unknown): void;
508
+ /** Authored-data changes, including the host's own writes. Returns the unsubscribe. */
509
+ subscribe(listener: (change: CanvasChange) => void): () => void;
510
+ }
511
+ /** A document a tool layer can insert and delete elements in. */
512
+ interface CanvasEditableDocument<T extends CanvasElement = CanvasElement> extends CanvasDocument<T> {
513
+ /** Adds an element and reports `add`. Throws when the id already resolves. */
514
+ insert(element: T): void;
515
+ /** Removes an element and reports `remove`. Silent when the id does not resolve. */
516
+ delete(id: string): void;
517
+ }
518
+ /** How the host paints one element and optional overlay in 2D. */
519
+ interface CanvasRenderer<T extends CanvasElement = CanvasElement> {
520
+ /** Paints one element, in world units, into a context already clipped to a dirty rect. */
521
+ draw(ctx: CanvasRenderingContext2D, element: T, camera: Camera): void;
522
+ /** Painted above every element: selection outlines, handles, guides. */
523
+ drawOverlay?(ctx: CanvasRenderingContext2D, camera: Camera): void;
524
+ /** World rect covered by the overlay (including previous frame); `undefined` means whole window. */
525
+ overlayBounds?(): {
526
+ readonly x: number;
527
+ readonly y: number;
528
+ readonly width: number;
529
+ readonly height: number;
530
+ } | undefined;
531
+ }
532
+ /**
533
+ * The order key that sorts after `after`, or the first key when `after` is `undefined`.
534
+ *
535
+ * Each call advances the last digit. When the last digit is already the highest, the key grows by
536
+ * one digit: `"z"` becomes `"z1"`, which sorts after `"z"` because a proper prefix sorts first, and
537
+ * leaves `"z0…"` free for an insert between the two.
538
+ */
539
+ export declare function orderAfter(after: string | undefined): string;
540
+ /** The key that sorts before `before`, or the first key when `before` is `undefined`. */
541
+ export declare function orderBefore(before: string | undefined): string;
542
+ /**
543
+ * A key strictly between `low` and `high`. `undefined` means "no bound" on that side.
544
+ *
545
+ * Throws when `low >= high`, and for the one pair that has no key between them, `k` and `k`
546
+ * followed only by "0" digits, which only keys from before the no-trailing-"0" rule can form.
547
+ */
548
+ export declare function orderBetween(low: string | undefined, high: string | undefined): string;
549
+ /**
550
+ * The paint order of two elements: by `order`, then by `id` when the keys are equal.
551
+ *
552
+ * Two replicas that append at the same time both compute `orderAfter` of the same last key, so
553
+ * equal keys are normal, not an error. Breaking the tie by id gives every replica the same stack,
554
+ * the same paint and the same hit test, whatever order the elements arrived in.
555
+ */
556
+ export declare function compareOrder(left: {
557
+ readonly id: string;
558
+ readonly order: string;
559
+ }, right: {
560
+ readonly id: string;
561
+ readonly order: string;
562
+ }): number;
563
+ type CanvasBackendKind = "webgpu" | "webgl2" | "2d";
564
+ type CanvasBackendPreference = "auto" | CanvasBackendKind;
565
+ interface CanvasBackendAttempt {
566
+ readonly kind: CanvasBackendKind;
567
+ readonly ok: boolean;
568
+ readonly reason: string;
569
+ }
570
+ interface CanvasBackendInfo {
571
+ readonly kind: CanvasBackendKind;
572
+ readonly adapter?: string | undefined;
573
+ readonly isFallbackAdapter?: boolean | undefined;
574
+ readonly tileBasedGpu?: boolean | undefined;
575
+ readonly attempts: readonly CanvasBackendAttempt[];
576
+ }
577
+ type CanvasGpuColor = readonly [number, number, number, number];
578
+ interface CanvasAtlasRegion {
579
+ readonly u0: number;
580
+ readonly v0: number;
581
+ readonly u1: number;
582
+ readonly v1: number;
583
+ readonly x: number;
584
+ readonly y: number;
585
+ readonly width: number;
586
+ readonly height: number;
587
+ }
588
+ interface CanvasGpuAtlas {
589
+ readonly source: HTMLCanvasElement;
590
+ readonly size: number;
591
+ readonly version: number;
592
+ packImage(key: string, image: CanvasImageSource, width: number, height: number): CanvasAtlasRegion | undefined;
593
+ packText(key: string, draw: (ctx: CanvasRenderingContext2D, width: number, height: number) => void, width: number, height: number, dpr?: number): CanvasAtlasRegion | undefined;
594
+ get(key: string): CanvasAtlasRegion | undefined;
595
+ delete(key: string): void;
596
+ clear(): void;
597
+ }
598
+ interface CanvasGpuBatch {
599
+ readonly count: number;
600
+ readonly stride: number;
601
+ readonly data: Float32Array;
602
+ clear(): void;
603
+ clip(rect: Rect): void;
604
+ unclip(): void;
605
+ rect(x: number, y: number, width: number, height: number, fill: string | CanvasGpuColor, stroke?: string | CanvasGpuColor, strokeWidth?: number, radius?: number, rotation?: number): void;
606
+ ellipse(x: number, y: number, width: number, height: number, fill: string | CanvasGpuColor, stroke?: string | CanvasGpuColor, strokeWidth?: number, rotation?: number): void;
607
+ line(x1: number, y1: number, x2: number, y2: number, color: string | CanvasGpuColor, width: number): void;
608
+ image(x: number, y: number, width: number, height: number, uv: CanvasAtlasRegion, tint?: string | CanvasGpuColor, radius?: number, rotation?: number): void;
609
+ polyline(points: readonly Point[], color: string | CanvasGpuColor, width: number, closed?: boolean): void;
610
+ bezier(p0: Point, p1: Point, p2: Point, p3: Point, color: string | CanvasGpuColor, width: number, segments?: number): void;
611
+ }
612
+ interface CanvasGpuEncoder<T extends CanvasElement = CanvasElement> {
613
+ readonly atlas?: CanvasGpuAtlas | undefined;
614
+ encode(batch: CanvasGpuBatch, element: T, camera: Camera): void;
615
+ encodeOverlay?(batch: CanvasGpuBatch, camera: Camera): void;
616
+ readonly clearColor?: CanvasGpuColor | undefined;
617
+ }
618
+ interface CanvasBackendOptions {
619
+ readonly preferred?: CanvasBackendPreference | readonly CanvasBackendKind[] | undefined;
620
+ readonly powerPreference?: "high-performance" | "low-power" | undefined;
621
+ readonly allowSoftwareAdapter?: boolean | undefined;
622
+ readonly failIfMajorPerformanceCaveat?: boolean | undefined;
623
+ readonly preserveDrawingBuffer?: boolean | undefined;
624
+ readonly minBufferSize?: number | undefined;
625
+ readonly onLost?: ((event: {
626
+ readonly kind: CanvasBackendKind;
627
+ readonly reason: string;
628
+ }) => void) | undefined;
629
+ readonly onRestored?: ((event: {
630
+ readonly kind: CanvasBackendKind;
631
+ }) => void) | undefined;
632
+ }
633
+ interface CanvasRenderFrame<T extends CanvasElement = CanvasElement> {
634
+ readonly elements: readonly T[];
635
+ readonly camera: Camera;
636
+ readonly viewport: Size;
637
+ readonly ratio: {
638
+ readonly x: number;
639
+ readonly y: number;
640
+ };
641
+ readonly dirtyRects: readonly Rect[];
642
+ readonly whole: boolean;
643
+ readonly retained?: boolean | undefined;
644
+ readonly dirtyIds?: ReadonlySet<string> | undefined;
645
+ readonly structureDirty?: boolean | undefined;
646
+ }
647
+ interface CanvasRenderBackend<T extends CanvasElement = CanvasElement> {
648
+ readonly info: CanvasBackendInfo;
649
+ readonly lost: boolean;
650
+ readonly supportsRetained?: boolean | undefined;
651
+ render(frame: CanvasRenderFrame<T>): {
652
+ readonly drawn: number;
653
+ readonly overlay: boolean;
654
+ readonly needsFull?: boolean | undefined;
655
+ };
656
+ destroy(): void;
657
+ }
658
+ /** Parses CSS hex/rgb/rgba colors or `[r, g, b, a]` tuples into normalized `[0..1]` RGBA tuples. */
659
+ export declare function parseGpuColor(c: string | CanvasGpuColor, alpha?: number): CanvasGpuColor;
660
+ /** Creates a shelf-packed GPU texture atlas for images, thumbnails, and cached rich text cards. */
661
+ export declare function createGpuAtlas(size?: number, factory?: (w: number, h: number) => HTMLCanvasElement): CanvasGpuAtlas;
662
+ /** Creates an instanced primitive batch backed by a growable 64B-stride buffer. */
663
+ export declare function createGpuBatch(initialCapacity?: number): CanvasGpuBatch;
664
+ /** Probes runtime GPU capabilities without touching any live `<canvas>` element. */
665
+ export declare function probeCanvasBackend(options?: CanvasBackendOptions): Promise<CanvasBackendInfo>;
666
+ /** Creates a rendering backend with autonomous capability probing (`webgpu` -> `webgl2` -> `2d`). */
667
+ export declare function createCanvasBackend<T extends CanvasElement>(canvas: HTMLCanvasElement, encoder: CanvasGpuEncoder<T>, options?: CanvasBackendOptions): Promise<CanvasRenderBackend<T>>;
668
+ /** What {@link createCanvasEngine} takes. */
669
+ interface CanvasEngineOptions<T extends CanvasElement> {
670
+ /** The document to read. The engine never writes through it. */
671
+ readonly document: CanvasDocument<T>;
672
+ /** How the host paints elements in 2D, and optionally overlays in either 2D or GPU mode. */
673
+ readonly renderer?: CanvasRenderer<T> | undefined;
674
+ /** Pluggable GPU (`webgpu` / `webgl2`) or `2d` backend; when absent, uses Canvas 2D via `renderer`. */
675
+ readonly backend?: CanvasRenderBackend<T> | undefined;
676
+ /** Optional 2D overlay canvas layered above a GPU main canvas for selection, handles, and cursors. */
677
+ readonly overlayCanvas?: HTMLCanvasElement | undefined;
678
+ /** The main canvas surface. */
679
+ readonly canvas: HTMLCanvasElement;
680
+ /** The starting camera; `{scale: 1, offset: {x: 0, y: 0}}` when absent. */
681
+ readonly camera?: Camera;
682
+ /** Maximum dirty rects kept before collapsing to their union (`DEFAULT_DIRTY_RECTS`). */
683
+ readonly maxDirtyRects?: number;
684
+ /** Optional fine hit predicate inside an element's bounds. */
685
+ readonly hits?: (element: T, point: Point) => boolean;
686
+ }
687
+ /** What {@link createCanvasEngineAsync} takes for autonomous WebGPU -> WebGL2 -> 2D backend setup. */
688
+ interface CanvasAsyncEngineOptions<T extends CanvasElement> extends Omit<CanvasEngineOptions<T>, "backend"> {
689
+ readonly gpu: CanvasGpuEncoder<T>;
690
+ readonly backendOptions?: CanvasBackendOptions | undefined;
691
+ }
692
+ /** One frame's account, so a host can show what it cost. */
693
+ interface CanvasFrame {
694
+ readonly rects: number;
695
+ readonly drawn: number;
696
+ readonly candidates: number;
697
+ readonly overlay: boolean;
698
+ }
699
+ /** The handle a host keeps. */
700
+ interface CanvasEngine<_T extends CanvasElement> {
701
+ readonly backendKind: CanvasBackendKind;
702
+ camera(): Camera;
703
+ setCamera(camera: Camera): void;
704
+ hitAt(screenPoint: Point): string | undefined;
705
+ hitTargetAt(screenPoint: Point): HitTarget | undefined;
706
+ invalidate(): void;
707
+ invalidateRect(rect: Rect): void;
708
+ paint(): CanvasFrame;
709
+ dirty(): DirtyBatch;
710
+ window(): Rect;
711
+ destroy(): void;
712
+ }
713
+ /** Creates an engine over a document and a canvas, with optional GPU render backend. */
714
+ export declare function createCanvasEngine<T extends CanvasElement>(options: CanvasEngineOptions<T>): CanvasEngine<T>;
715
+ /** Creates an engine after autonomously probing and initializing WebGPU, WebGL2, or 2D. */
716
+ export declare function createCanvasEngineAsync<T extends CanvasElement>(options: CanvasAsyncEngineOptions<T>): Promise<CanvasEngine<T>>;
717
+ /**
718
+ * How a connector runs between its two boxes. `elbow-avoid` is an elbow that steps around the
719
+ * obstacle boxes its caller passes; with none it is the plain elbow.
720
+ */
721
+ type ConnectorRouting = "straight" | "elbow" | "curved" | "elbow-avoid";
722
+ /** Which ends of a connector carry an arrowhead. `end` is the one at `toId`. */
723
+ type ConnectorArrow = "none" | "end" | "start" | "both";
724
+ /**
725
+ * Where on its box a connector end attaches.
726
+ *
727
+ * A name is a point on the box's own frame: a corner, an edge midpoint, or the centre. An object is a
728
+ * point in normalised box coordinates, 0 at the left or top edge and 1 at the right or bottom edge; a
729
+ * coordinate outside that range is clamped into the box. Both forms move with the box, so a resized box
730
+ * keeps its attachment. A non-finite object coordinate is treated as unset.
731
+ */
732
+ type ConnectorAnchor = "centre" | "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w" | {
733
+ readonly x: number;
734
+ readonly y: number;
735
+ };
736
+ /** The attachment of each end of a connector. An unset end is placed by the routing. */
737
+ interface ConnectorAnchors {
738
+ readonly from?: ConnectorAnchor | undefined;
739
+ readonly to?: ConnectorAnchor | undefined;
740
+ }
741
+ /**
742
+ * The fields a connector element carries, on top of the three every element has.
743
+ *
744
+ * The host's element type extends this, and the host's {@link ConnectorPredicate} says which
745
+ * elements are connectors. The engine never reads these fields; only the connector helpers do.
746
+ */
747
+ interface CanvasConnectorFields {
748
+ /** The element the connector starts at. Must not itself be a connector. */
749
+ readonly fromId: string;
750
+ /** The element the connector ends at. Must not itself be a connector. */
751
+ readonly toId: string;
752
+ readonly routing: ConnectorRouting;
753
+ readonly arrow: ConnectorArrow;
754
+ /** World units. Finite and greater than zero for a connector that is drawn. */
755
+ readonly strokeWidth: number;
756
+ /** Where the connector attaches to `fromId`. Unset leaves that end to the routing. */
757
+ readonly fromAnchor?: ConnectorAnchor | undefined;
758
+ /** Where the connector attaches to `toId`. Unset leaves that end to the routing. */
759
+ readonly toAnchor?: ConnectorAnchor | undefined;
760
+ /** One line of text drawn on the route's midpoint. Unset, empty or blank draws no label. */
761
+ readonly label?: string | undefined;
762
+ }
763
+ /**
764
+ * Whether an element is a connector.
765
+ *
766
+ * One definition per host. The host passes it to `createCanvasSession`, which uses it for hit testing,
767
+ * traits and derived connector bounds, so they never disagree about which elements are connectors. A connector is never a valid endpoint.
768
+ */
769
+ type ConnectorPredicate<T extends CanvasElement> = (element: T) => element is T & CanvasConnectorFields;
770
+ /**
771
+ * The point an anchor names on a box, in world units.
772
+ *
773
+ * A name is one of the box's corners, edge midpoints or its centre. An object is normalised: `{x: 0,
774
+ * y: 0}` is the top-left corner and `{x: 1, y: 1}` the bottom-right, and each coordinate is clamped into
775
+ * the box. A non-finite object coordinate, and an unknown name, answer the centre, which is always on the
776
+ * box. Callers that must tell an unset anchor from a placed one check first; the routes do.
777
+ */
778
+ export declare function anchorPoint(box: Rect, anchor: ConnectorAnchor): Point;
779
+ /** Whether two boxes share a region of positive area. */
780
+ export declare function overlaps(a: Rect, b: Rect): boolean;
781
+ /**
782
+ * The point where a ray from a box's centre leaves the box, or the anchor a connector end names.
783
+ *
784
+ * With no `anchor`, the ray runs from the centre toward `toward`. Whether `toward` lies inside the box
785
+ * does not matter: the answer is always on the boundary. When `toward` is the centre there is no
786
+ * direction, so the centre comes back. A zero-size box has its centre as its only point, so it gives the
787
+ * centre too. With a usable `anchor`, the anchor's point comes back and `toward` is not read.
788
+ *
789
+ * The ray's arithmetic can overflow when the centres are further apart than the largest finite number.
790
+ * The answer is then not finite, and the routes refuse it; this function does not hide that.
791
+ */
792
+ export declare function exitPoint(box: Rect, toward: Point, anchor?: ConnectorAnchor | undefined): Point;
793
+ /**
794
+ * The straight route between two boxes: a segment from each end to the other's.
795
+ *
796
+ * An unset end sits where the centre-to-centre line leaves its own box; an anchored end sits on its
797
+ * anchor. For boxes that touch along an edge the two ends coincide, which is a zero-length route rather
798
+ * than NaN. `undefined` when the boxes overlap, one sits inside the other, or a point is not finite.
799
+ */
800
+ export declare function straightRoute(from: Rect, to: Rect, anchors?: ConnectorAnchors): readonly [Point, Point] | undefined;
801
+ /**
802
+ * The orthogonal route between two boxes: at most four points, every segment axis-parallel.
803
+ *
804
+ * The route runs along one axis, and the axis is set by how the boxes are separated, never by an anchor.
805
+ * An unset end is the edge midpoint that faces the other box, as it always was. Two midpoints, one on
806
+ * each side of the gap between the boxes, join them through a perpendicular segment. An anchored end
807
+ * replaces its midpoint with the anchor; the first and last segments are still axis-parallel, because the
808
+ * route leaves the anchor along the chosen axis. When the boxes are separated on both axes, the axis with
809
+ * the larger centre-to-centre distance wins, and a tie goes to the horizontal axis. `undefined` under the
810
+ * same conditions as {@link straightRoute}, and when a point is not finite.
811
+ */
812
+ export declare function elbowRoute(from: Rect, to: Rect, anchors?: ConnectorAnchors): readonly Point[] | undefined;
813
+ /**
814
+ * The control points of a curve between two boxes: `[P0, C1, C2, P3]`, a cubic Bézier.
815
+ *
816
+ * `P0` and `P3` are the ends, placed as {@link exitPoint} places them (or on their anchors). Each handle
817
+ * leaves its end along the end's outward direction: an edge or corner anchor points out of its box, and
818
+ * any other end points along the chord, so the curve runs from `P0` toward `P3` and enters `P3` from the
819
+ * far side. The handle is {@link CURVE_HANDLE_RATIO} of the chord long. A zero-length chord gives
820
+ * `[P0, P0, P3, P3]`, which is a point, not a curve. `undefined` under the same conditions as
821
+ * {@link straightRoute}, and when any control point or chord length is not finite.
822
+ */
823
+ export declare function curvedControls(from: Rect, to: Rect, anchors?: ConnectorAnchors): readonly [Point, Point, Point, Point] | undefined;
824
+ /**
825
+ * The sampled polyline of a curve from its control points, `[P0, C1, C2, P3]`.
826
+ *
827
+ * The curve is sampled at evenly spaced parameters, `N + 1` points in all, with `N` chosen so that no
828
+ * sampled chord is longer than {@link CURVE_STEP_WORLD}. The bound is provable: the curve's speed is
829
+ * `|B'(t)| <= 3M`, where `M` is the longest of the three control legs, since `B'(t)` is a convex
830
+ * combination of those legs scaled by three. So each segment's arc is at most `3M / N`, and `N` is at
831
+ * least `3M / CURVE_STEP_WORLD`. `N` is clamped to `[CURVE_MIN_SEGMENTS, CURVE_MAX_SEGMENTS]`, so a curve
832
+ * longer than `CURVE_MAX_SEGMENTS * CURVE_STEP_WORLD / 3` (341 world units of leg) is sampled coarser than
833
+ * the step; that is a recorded limit, not a claim. The chord-to-curve deviation has no closed-form bound
834
+ * here; it is measured against a dense reference in the tests. The first and last points are exactly `P0`
835
+ * and `P3`. A zero-length curve is `[P0, P3]`, with nothing to sample. `undefined` for any non-finite
836
+ * input or output.
837
+ */
838
+ export declare function curvedRoute(controls: readonly [Point, Point, Point, Point]): readonly Point[] | undefined;
839
+ /**
840
+ * The route for a connector's routing, from its two endpoint boxes.
841
+ *
842
+ * `undefined` when the routing has no route for these boxes (overlap, or containment), and also
843
+ * when either box has no usable extent, or a point of the route is not finite, so a non-finite endpoint
844
+ * never produces a route with NaN in it. The caller treats `undefined` as "do not draw". A curved routing
845
+ * answers its sampled polyline, the same points the curve is drawn, hit-tested and arrowed by.
846
+ */
847
+ export declare function connectorRoute(routing: ConnectorRouting, from: Rect, to: Rect, anchors?: ConnectorAnchors, obstacles?: readonly Rect[]): readonly Point[] | undefined;
848
+ /**
849
+ * The points whose box a connector's bounds cover, for the routing: the route, or the curve's control polygon.
850
+ *
851
+ * A straight or elbow connector's route is its own extent. A curved connector's extent is its control
852
+ * polygon, `[P0, C1, C2, P3]`, because the curve lies inside that polygon's convex hull, so the box of the
853
+ * polygon contains every point of the curve. Sampled points are not used: the extreme of a curve can fall
854
+ * between two samples, outside their box. `undefined` when the boxes have no route, or any point is not
855
+ * finite, or the points span more than the largest finite number; the follower then keeps its placeholder
856
+ * or its old bounds rather than storing an infinite box.
857
+ */
858
+ export declare function connectorExtent(routing: ConnectorRouting, from: Rect, to: Rect, anchors?: ConnectorAnchors, obstacles?: readonly Rect[]): readonly Point[] | undefined;
859
+ /**
860
+ * The box a connector paints in: the route's bounding box, grown on every side.
861
+ *
862
+ * Grown by {@link CONNECTOR_REACH_FACTOR} stroke widths, which covers the stroke and the
863
+ * arrowheads. The result has positive area whenever the stroke width is positive, even for a
864
+ * one-point route, so the element stays hit-testable. Callers pass at least one point; with none
865
+ * the result is an empty box at the origin.
866
+ */
867
+ export declare function connectorBounds(points: readonly Point[], strokeWidth: number): Rect;
868
+ /**
869
+ * The arrowhead triangles a connector's route needs, in world units.
870
+ *
871
+ * `end` is the arrow at the last point, pointing along the final segment. `start` is the arrow at
872
+ * the first point, pointing back along the first segment. `both` is both. An arrow whose segment is
873
+ * zero-length is left out rather than drawn at a guessed angle, which is why a zero-length route
874
+ * has no arrows. `strokeWidth` sizes the arrows, so it is the connector's own width.
875
+ */
876
+ export declare function arrowTriangles(points: readonly Point[], arrow: ConnectorArrow, strokeWidth: number): readonly (readonly [Point, Point, Point])[];
877
+ /** The budgets an avoiding elbow runs under. Each defaults to its exported constant. */
878
+ interface ElbowAvoidBudget {
879
+ readonly maxObstacles?: number;
880
+ readonly maxExpansions?: number;
881
+ }
882
+ /**
883
+ * The region an avoiding elbow between two boxes searches: their union grown by {@link ELBOW_AVOID_MARGIN}.
884
+ *
885
+ * Every box that touches this region is an obstacle the route must consider, and no other box can be
886
+ * crossed, because the route stays inside it. A caller that lists obstacles lists them over this box.
887
+ */
888
+ export declare function avoidRegion(from: Rect, to: Rect): Rect;
889
+ /**
890
+ * The obstacles an avoiding elbow between two boxes routes around, from any list of boxes.
891
+ *
892
+ * A box counts when it is usable, has area inside the region, and shares no area with either endpoint
893
+ * box. A box that overlaps an endpoint (a frame around it, a shape stacked on it) cannot be avoided by
894
+ * a route that starts inside it, so it is ignored rather than making every route fail.
895
+ */
896
+ export declare function avoidObstacles(from: Rect, to: Rect, boxes: readonly Rect[]): Rect[];
897
+ /**
898
+ * The elbow route between two boxes that steps around `obstacles`.
899
+ *
900
+ * The obstacles are first narrowed by {@link avoidObstacles}. When the plain {@link elbowRoute} crosses
901
+ * none of them, it is the answer, unchanged. Otherwise an orthogonal route is searched inside
902
+ * {@link avoidRegion}, keeping {@link ELBOW_AVOID_CLEARANCE} from every box and paying
903
+ * {@link ELBOW_AVOID_BEND_COST} per bend; an unset end may leave through any edge midpoint, an anchored
904
+ * end leaves from its anchor. The plain elbow comes back when there are more obstacles than the
905
+ * budget allows, when the search runs out of budget, or when no route exists. `undefined` exactly when
906
+ * {@link elbowRoute} is.
907
+ */
908
+ export declare function elbowAvoidRoute(from: Rect, to: Rect, obstacles: readonly Rect[], anchors?: ConnectorAnchors, budget?: ElbowAvoidBudget): readonly Point[] | undefined;
909
+ /**
910
+ * The point halfway along a route, measured by length.
911
+ *
912
+ * A zero-length route answers its first point; an empty one answers `undefined`.
913
+ */
914
+ export declare function routeMidpoint(route: readonly Point[]): Point | undefined;
915
+ /** The text a label draws: the stored value when it is a string with something to show, else `undefined`. */
916
+ export declare function labelText(label: unknown): string | undefined;
917
+ /**
918
+ * The box a connector's label paints in, background included, centred on the route's midpoint.
919
+ *
920
+ * `undefined` when there is no label to draw or no route to put it on. The size depends only on the
921
+ * label's character count (code points, up to {@link CONNECTOR_LABEL_MAX_CHARS}), so it is the same
922
+ * on every replica.
923
+ */
924
+ export declare function connectorLabelBox(route: readonly Point[] | undefined, label: unknown): Rect | undefined;
925
+ /** Whether a world point lies on a label's box, edges included. */
926
+ export declare function labelHit(box: Rect | undefined, point: Point): boolean;
927
+ /** Everything a connector paints, solved from its fields and the boxes around it. */
928
+ interface ConnectorGeometry {
929
+ /** The polyline the line is drawn, hit and arrowed along. */
930
+ readonly route: readonly Point[];
931
+ /** The label's box, or `undefined` with no label. */
932
+ readonly labelBox: Rect | undefined;
933
+ /** The box the connector paints in: the route's reach, the arrowheads and the label. */
934
+ readonly bounds: Rect;
935
+ }
936
+ /**
937
+ * A connector's route, label box and painted bounds, from its authored fields and its endpoint boxes.
938
+ *
939
+ * `obstacles` matters only to `elbow-avoid`. `undefined` when the routing has no route for these
940
+ * boxes, the stroke is unusable, or a point is not finite; the caller then draws nothing.
941
+ */
942
+ export declare function connectorGeometry(connector: Pick<CanvasConnectorFields, "routing" | "strokeWidth" | "fromAnchor" | "toAnchor" | "label">, from: Rect, to: Rect, obstacles?: readonly Rect[]): ConnectorGeometry | undefined;
943
+ /** The anchors a connector end snaps to while it is drawn: the four corners and four edge midpoints. */
944
+ export declare const CONNECTOR_PORTS: readonly ["n", "ne", "e", "se", "s", "sw", "w", "nw"];
945
+ /** One of {@link CONNECTOR_PORTS}. */
946
+ type ConnectorPort = (typeof CONNECTOR_PORTS)[number];
947
+ /** A port a point snapped to: the anchor, its world point, and how far the point was from it. */
948
+ interface PortSnap {
949
+ readonly anchor: ConnectorPort;
950
+ readonly point: Point;
951
+ readonly distance: number;
952
+ }
953
+ /**
954
+ * The port of a box nearest a point, when it is within `threshold` world units.
955
+ *
956
+ * Ties go to the earlier port in {@link CONNECTOR_PORTS}. The centre is not a port, and a point at
957
+ * least as near the centre as to every port snaps to none: a release in the middle of a shape, even a
958
+ * small one, keeps the end unset, so the routing still places it.
959
+ */
960
+ export declare function nearestPort(box: Rect, point: Point, threshold: number): PortSnap | undefined;
961
+ /** How a pressure stroke turns into an outline. Lengths are world units. */
962
+ interface StrokeOutlineOptions {
963
+ /** The stroke's width at pressure 0.5. */
964
+ readonly size: number;
965
+ /**
966
+ * How much pressure changes the width, 0..1. At 0 the width ignores pressure; at the default 0.6 a
967
+ * full press is 1.6 times the nominal width and no press is 0.4 times it.
968
+ */
969
+ readonly thinning?: number;
970
+ /** How much the centre line lags its samples, 0..1. 0 follows every sample; the default is 0.35. */
971
+ readonly streamline?: number;
972
+ /** The length over which the start narrows to a point. The default is twice the size. */
973
+ readonly taperStart?: number;
974
+ /** The length over which the end narrows to a point. The default is twice the size. */
975
+ readonly taperEnd?: number;
976
+ }
977
+ /** The outline options a stroke takes beside its width: everything but the size, which the width gives. */
978
+ type InkOutline = Omit<StrokeOutlineOptions, "size">;
979
+ /** The pressure a sample is drawn at: its own when it has a usable one, the nominal pressure otherwise. */
980
+ export declare function pressureOf(point: InkPoint): number;
981
+ /** Whether a stroke carries pressure: any sample with a pressure field. Such a stroke is drawn as an outline. */
982
+ export declare function hasPressure(points: readonly InkPoint[]): boolean;
983
+ /**
984
+ * The filled outline of a stroke: a closed polygon, in world units, ready for `moveTo`/`lineTo`/`fill`.
985
+ *
986
+ * Every vertex is finite. No usable sample is an empty polygon; one usable sample (or several on one
987
+ * spot) is a circle of the radius its pressure gives, so a tap paints a dot. A size that is not a
988
+ * positive number is an empty polygon: there is no width to paint.
989
+ */
990
+ export declare function strokeOutline(points: readonly InkPoint[], options: StrokeOutlineOptions): {
991
+ readonly x: number;
992
+ readonly y: number;
993
+ }[];
994
+ /** A drop shadow, in world units throughout. */
995
+ interface CanvasShadow {
996
+ /** CSS colour of the shadow. */
997
+ readonly colour: string;
998
+ /** Horizontal offset in **world units**, like strokeWidth — not bitmap pixels. */
999
+ readonly offsetX: number;
1000
+ /** Vertical offset in **world units**. */
1001
+ readonly offsetY: number;
1002
+ /** Blur radius in **world units**. */
1003
+ readonly blur: number;
1004
+ }
1005
+ /** How one shape is coloured. */
1006
+ interface CanvasStyle {
1007
+ /** CSS colour, or `null`/undefined for no fill. */
1008
+ readonly fill?: string | null;
1009
+ /** CSS colour, or `null`/undefined for no stroke. */
1010
+ readonly stroke?: string | null;
1011
+ /** Stroke width in **world units**. */
1012
+ readonly strokeWidth?: number;
1013
+ /** 0–1. */
1014
+ readonly opacity?: number;
1015
+ /** A dash pattern in world units. */
1016
+ readonly dash?: readonly number[];
1017
+ /** Drop shadow in world units, or `null`/undefined for none. */
1018
+ readonly shadow?: CanvasShadow | null;
1019
+ }
1020
+ /** Text style and string content. */
1021
+ interface CanvasTextStyle extends CanvasStyle {
1022
+ readonly text: string;
1023
+ readonly font?: string;
1024
+ readonly align?: CanvasTextAlign;
1025
+ readonly baseline?: CanvasTextBaseline;
1026
+ }
1027
+ /** Measures a text run in world units. */
1028
+ type MeasureText = (text: string, font: string | undefined) => number;
1029
+ /** Draws a rectangle in world units. `rect` is its box, not a centre. */
1030
+ export declare function drawRect(ctx: CanvasRenderingContext2D, rect: {
1031
+ readonly x: number;
1032
+ readonly y: number;
1033
+ readonly width: number;
1034
+ readonly height: number;
1035
+ }, style: CanvasStyle): void;
1036
+ /** Draws a rounded rectangle, with the radius in world units. */
1037
+ export declare function drawRoundedRect(ctx: CanvasRenderingContext2D, rect: {
1038
+ readonly x: number;
1039
+ readonly y: number;
1040
+ readonly width: number;
1041
+ readonly height: number;
1042
+ }, radius: number, style: CanvasStyle): void;
1043
+ /** Draws an ellipse inscribed in `rect`, in world units. */
1044
+ export declare function drawEllipse(ctx: CanvasRenderingContext2D, rect: {
1045
+ readonly x: number;
1046
+ readonly y: number;
1047
+ readonly width: number;
1048
+ readonly height: number;
1049
+ }, style: CanvasStyle): void;
1050
+ /** Draws a straight line between two world points. */
1051
+ export declare function drawLine(ctx: CanvasRenderingContext2D, from: {
1052
+ readonly x: number;
1053
+ readonly y: number;
1054
+ }, to: {
1055
+ readonly x: number;
1056
+ readonly y: number;
1057
+ }, style: CanvasStyle): void;
1058
+ /** Draws a connector's route and its arrowheads in world units. */
1059
+ export declare function drawConnector(ctx: CanvasRenderingContext2D, points: readonly Point[], arrow: ConnectorArrow, style: CanvasStyle): void;
1060
+ /** The colours of a connector label: its background, its text and the background's outline. */
1061
+ interface ConnectorLabelStyle {
1062
+ readonly background: string;
1063
+ readonly text: string;
1064
+ readonly border?: string | undefined;
1065
+ readonly opacity?: number | undefined;
1066
+ }
1067
+ /** Draws a connector's label clipped inside `box`. */
1068
+ export declare function drawConnectorLabel(ctx: CanvasRenderingContext2D, box: Rect, text: string, style: ConnectorLabelStyle): void;
1069
+ /** Draws one line of text in world units. */
1070
+ export declare function drawText(ctx: CanvasRenderingContext2D, rect: {
1071
+ readonly x: number;
1072
+ readonly y: number;
1073
+ readonly width: number;
1074
+ readonly height: number;
1075
+ }, style: CanvasTextStyle, measure?: MeasureText): void;
1076
+ /** The font size of a text block, in world units. */
1077
+ export declare const TEXT_FONT_SIZE = 14;
1078
+ /**
1079
+ * The distance from one line of a text block to the next, as a multiple of the font size.
1080
+ *
1081
+ * A multiple rather than a length so the drawn lines and the editor's textarea agree at every size:
1082
+ * the editor sets `line-height` to this same number, and a block of N lines is N × size × this tall.
1083
+ */
1084
+ export declare const TEXT_LINE_HEIGHT = 1.2;
1085
+ /** The font family of a text block, and of the editor's textarea, which must match it. */
1086
+ export declare const TEXT_FONT_FAMILY = "ui-sans-serif, system-ui, sans-serif";
1087
+ /** How {@link layoutText} sizes its lines. Every field defaults to the text block's own value. */
1088
+ interface TextLayoutOptions {
1089
+ /** The CSS font the measure is asked about. Defaults to the text block's font. */
1090
+ readonly font?: string;
1091
+ /** The font size in world units. Defaults to {@link TEXT_FONT_SIZE}. */
1092
+ readonly fontSize?: number;
1093
+ /** The line pitch as a multiple of the font size. Defaults to {@link TEXT_LINE_HEIGHT}. */
1094
+ readonly lineHeight?: number;
1095
+ }
1096
+ /** One line of laid-out text, positioned from the block's top-left corner in world units. */
1097
+ interface TextLine {
1098
+ readonly text: string;
1099
+ /** Offset from the block's left edge; the layout is left-aligned, so always 0. */
1100
+ readonly x: number;
1101
+ /** Offset from the block's top edge to the line's top. */
1102
+ readonly y: number;
1103
+ }
1104
+ export declare function layoutText(text: string, width: number, measure: MeasureText, options?: TextLayoutOptions): TextLine[];
1105
+ /** How text sizing adapts to its target box. */
1106
+ type TextFitMode = "none" | "shrink-text" | "grow-box";
1107
+ /** Options for {@link fitTextLayout}. */
1108
+ interface TextFitOptions extends TextLayoutOptions {
1109
+ readonly mode?: TextFitMode | undefined;
1110
+ readonly fontFamily?: string | undefined;
1111
+ readonly minFontSize?: number | undefined;
1112
+ readonly precision?: number | undefined;
1113
+ }
1114
+ /** Deterministic autofit text layout result. */
1115
+ interface TextFitResult {
1116
+ readonly fontSize: number;
1117
+ readonly scale: number;
1118
+ readonly lines: readonly TextLine[];
1119
+ readonly contentHeight: number;
1120
+ readonly boxHeight: number;
1121
+ readonly overflowed: boolean;
1122
+ }
1123
+ /**
1124
+ * Lays out `text` inside `rect` under `"none"`, `"shrink-text"`, or `"grow-box"` fit rules
1125
+ * without writing back to document state.
1126
+ */
1127
+ export declare function fitTextLayout(text: string, rect: {
1128
+ readonly width: number;
1129
+ readonly height: number;
1130
+ }, measure: MeasureText, options?: TextFitOptions): TextFitResult;
1131
+ /**
1132
+ * Draws a block of wrapped text, top-left aligned, clipped to `rect`.
1133
+ *
1134
+ * The text takes the style's fill colour, or its stroke colour when it has no fill. A style with
1135
+ * neither draws nothing. The clip and the context state are saved and restored around the whole block,
1136
+ * so a block never leaks its font or its clip into the next element.
1137
+ */
1138
+ export declare function drawTextBlock(ctx: CanvasRenderingContext2D, rect: {
1139
+ readonly x: number;
1140
+ readonly y: number;
1141
+ readonly width: number;
1142
+ readonly height: number;
1143
+ }, text: string, style: CanvasStyle, measure: MeasureText): void;
1144
+ /** One point of an ink stroke, in world units. */
1145
+ interface InkPoint {
1146
+ readonly x: number;
1147
+ readonly y: number;
1148
+ /**
1149
+ * How hard the pen pressed, 0..1, with 0.5 the nominal width. Absent on a stroke of one width: a
1150
+ * stroke whose points carry it is drawn as a filled outline (see {@link strokeOutline}).
1151
+ */
1152
+ readonly pressure?: number;
1153
+ }
1154
+ /** How a stroke is painted. */
1155
+ interface InkStyle extends CanvasStyle {
1156
+ /** Line cap for the stroke's ends; rounded is what a pen looks like. Ignored by an outline. */
1157
+ readonly cap?: CanvasLineCap;
1158
+ /** Line join between segments. Ignored by an outline. */
1159
+ readonly join?: CanvasLineJoin;
1160
+ /**
1161
+ * Fill the stroke's variable-width outline instead of stroking its centre line. `true` takes the
1162
+ * outline defaults; an object tunes them. The width is `strokeWidth` at pressure 0.5. Pass the same
1163
+ * value to {@link strokeBounds} and {@link placedGeometry}, or the box will not match the paint.
1164
+ */
1165
+ readonly outline?: boolean | InkOutline;
1166
+ }
1167
+ /**
1168
+ * Draws a decoded ink stroke.
1169
+ *
1170
+ * Points are world units and come from {@link decodeStroke} or the host's own store; the
1171
+ * function is synchronous and knows nothing about assets. That is the split the design
1172
+ * settled on: fetching and decoding is asynchronous and storage-shaped, so it happens in
1173
+ * the adapter, and by the time `draw` runs the points are on the element.
1174
+ *
1175
+ * A stroke of one point is a dot: a zero-length path draws nothing with a round cap, so
1176
+ * it is filled as a circle of the stroke's own radius instead. Getting this wrong makes
1177
+ * the first dot of every pen stroke vanish, which reads as a dropped pointer sample.
1178
+ *
1179
+ * With `style.outline` the stroke is the filled polygon {@link strokeOutline} builds from the
1180
+ * points and their pressure, in the stroke colour, so its width follows the pen. A tap is a
1181
+ * filled circle there too, of the radius its pressure gives.
1182
+ */
1183
+ export declare function drawStroke(ctx: CanvasRenderingContext2D, points: readonly InkPoint[], style: InkStyle): void;
1184
+ /**
1185
+ * How an image fills its rect.
1186
+ *
1187
+ * `stretch` fills the rect whatever the image's aspect, so a picture is distorted to fit. `contain`
1188
+ * keeps the aspect and centres the picture in the rect, leaving bands on the short axis.
1189
+ */
1190
+ type ImageFit = "stretch" | "contain";
1191
+ /**
1192
+ * A sub-rectangle of the source to draw, as fractions of its intrinsic size.
1193
+ *
1194
+ * Each field is 0–1 relative to the source, not pixels: the source's pixel size can change (a decoded
1195
+ * bitmap is replaced, a video frame changes size), and a crop stored in pixels would then read the wrong
1196
+ * part. A value past an edge is clamped to it, so a crop that runs off the source keeps what is inside.
1197
+ */
1198
+ interface CanvasImageCrop {
1199
+ /** Left edge, 0 at the source's left. */
1200
+ readonly x: number;
1201
+ /** Top edge, 0 at the source's top. */
1202
+ readonly y: number;
1203
+ /** Width, as a fraction of the source's width. */
1204
+ readonly width: number;
1205
+ /** Height, as a fraction of the source's height. */
1206
+ readonly height: number;
1207
+ }
1208
+ /**
1209
+ * A shape the picture is clipped to, inside the rect it is drawn into.
1210
+ *
1211
+ * Two shapes only, a product decision: an ellipse inscribed in the rect, or a rounded rectangle whose
1212
+ * radius follows the rule of {@link drawRoundedRect}. Data rather than a `Path2D`, so a style can be
1213
+ * stored and sent.
1214
+ */
1215
+ type CanvasImageMask = {
1216
+ readonly shape: "ellipse";
1217
+ } | {
1218
+ readonly shape: "rounded-rect";
1219
+ readonly radius: number;
1220
+ };
1221
+ /**
1222
+ * The CSS filter functions a picture may be drawn through, as numbers.
1223
+ *
1224
+ * Numbers rather than a CSS string, so no CSS can reach the context. `blur` is in world units and is
1225
+ * converted to bitmap pixels as a shadow's blur is. A blur paints outside the picture's geometric box,
1226
+ * as a shadow does, so a host that turns one on folds the radius into the element's `bounds` (the
1227
+ * painted extent must stay covered; see types.ts) — the same rule {@link CanvasStyle.shadow} states.
1228
+ * `brightness`, `contrast` and `saturate` run 0–10; `grayscale`, `sepia` and `invert` run 0–1; a value
1229
+ * outside its range is clamped, and a non-finite value is dropped. `hueRotate` is in degrees.
1230
+ */
1231
+ interface CanvasImageFilter {
1232
+ readonly blur?: number | undefined;
1233
+ readonly brightness?: number | undefined;
1234
+ readonly contrast?: number | undefined;
1235
+ readonly saturate?: number | undefined;
1236
+ readonly grayscale?: number | undefined;
1237
+ readonly sepia?: number | undefined;
1238
+ readonly invert?: number | undefined;
1239
+ readonly hueRotate?: number | undefined;
1240
+ }
1241
+ /**
1242
+ * How one image is painted.
1243
+ *
1244
+ * Deliberately not a {@link CanvasStyle}: an image has no interior to fill and no outline to stroke,
1245
+ * and a style that carried `fill` or `stroke` would suggest the picture is coloured or outlined. Only
1246
+ * the opacity, the shadow, and the crop, mask and filter below apply, through the same path the shapes
1247
+ * use; the other style fields are not read.
1248
+ */
1249
+ interface CanvasImageStyle {
1250
+ /** How the image fills the rect. `stretch` by default. */
1251
+ readonly fit?: ImageFit;
1252
+ /** 0–1, as for {@link CanvasStyle.opacity}. */
1253
+ readonly opacity?: number;
1254
+ /** A drop shadow, as for {@link CanvasStyle.shadow}. */
1255
+ readonly shadow?: CanvasShadow | null;
1256
+ /** The part of the source to draw, or `null`/undefined for the whole picture. */
1257
+ readonly crop?: CanvasImageCrop | null | undefined;
1258
+ /** A shape the picture is clipped to, or `null`/undefined for no clip. */
1259
+ readonly mask?: CanvasImageMask | null | undefined;
1260
+ /** Filters the picture is drawn through, or `null`/undefined for none. */
1261
+ readonly filter?: CanvasImageFilter | null | undefined;
1262
+ }
1263
+ /**
1264
+ * Draws an image source into a rect, in world units.
1265
+ *
1266
+ * This is a pure paint: it neither loads nor caches. The source must already be decoded, and the
1267
+ * host keeps the decoded `ImageBitmap` (see `loadImageBitmap`). Any `CanvasImageSource` is accepted,
1268
+ * because the platform union is the one a context draws from.
1269
+ *
1270
+ * `fit` decides the rect the picture lands in. `stretch` (the default) draws it into `rect` as given.
1271
+ * `contain` takes the source's intrinsic size, scales it uniformly until it just fits, and centres it,
1272
+ * so it never leaves `rect`. A source with no readable intrinsic size is stretched instead.
1273
+ *
1274
+ * `crop` takes a normalised part of the source first, and `fit` then fits that part. The fractions are
1275
+ * read against the source's size at this call, so a source that changes size keeps the same part. A crop
1276
+ * with a non-finite field, no area, or an unknown source size is no crop: the whole picture is drawn, with
1277
+ * `fit` as usual.
1278
+ *
1279
+ * `mask` clips the picture to an ellipse inscribed in `rect`, or to a rounded rect the size of `rect`.
1280
+ * The clip lives only inside this call, so the next element is not clipped. How a shadow meets that clip
1281
+ * is the platform's, which this code does not check; a host that shadows a masked picture folds the
1282
+ * spill into `bounds` as for any shadow.
1283
+ *
1284
+ * `filter` draws the picture through CSS filter functions given as numbers, see {@link CanvasImageFilter}.
1285
+ * It is written on every call, `none` when there is none, and restored when the call returns. A blur
1286
+ * filter paints a halo around the picture's box, outside `bounds`, so a host that enables one folds the
1287
+ * blur radius into the element's bounds — the same spill rule a shadow states above.
1288
+ *
1289
+ * Video. The engine repaints only when the document changes, or when the camera or the surface does; it
1290
+ * runs no frame loop. A video frame is not a document change, so a playing video needs the host to call
1291
+ * `engine.invalidateRect(bounds)` and then `engine.paint()` on each frame it wants to show, from its own
1292
+ * `requestAnimationFrame` or `requestVideoFrameCallback`. Calls stop when the video is paused or hidden,
1293
+ * and the picture then stays on its last frame. The size is read on every call, so a video that is not
1294
+ * ready yet (`videoWidth` 0) is drawn stretched, and a new frame size is used from the next call on.
1295
+ *
1296
+ * Smoothing is written on every call, from this source's own size and not from the last call's state,
1297
+ * for the same reason the shadow is: canvas state leaks into the elements after. `high` quality is
1298
+ * used only when the picture is drawn larger than it is stored; a downscale, an equal size, an unknown
1299
+ * size and a zero size all get `low`. That rule is not a claim about what the device can do; it is the
1300
+ * choice the function makes.
1301
+ *
1302
+ * A rect with a non-finite field, or with a width or height of zero or less, returns before the context
1303
+ * is touched: no state is written and `drawImage` is not called. A zero-size source is drawn as
1304
+ * stretch, which the platform treats as a no-op, so the canvas is left as it was.
1305
+ *
1306
+ * Exceptions come from the platform, and this function does not catch them. Per the HTML standard, a
1307
+ * broken `HTMLImageElement` (one that failed to load) throws `InvalidStateError`, while an incomplete one
1308
+ * (still loading) draws nothing and throws nothing. The host never passes either, because it draws only
1309
+ * the `ImageBitmap`s it decoded.
1310
+ *
1311
+ * Export needs no separate path. `renderToBitmap` calls the same host draw as a frame does, so a source
1312
+ * the host has decoded paints into the export, and one it has not paints the host's placeholder.
1313
+ */
1314
+ export declare function drawImage(ctx: CanvasRenderingContext2D, source: CanvasImageSource, rect: {
1315
+ readonly x: number;
1316
+ readonly y: number;
1317
+ readonly width: number;
1318
+ readonly height: number;
1319
+ }, style?: CanvasImageStyle): void;
1320
+ /**
1321
+ * Encodes a stroke to bytes: quantised to {@link INK_PRECISION}, delta-coded, varint.
1322
+ *
1323
+ * Measured on a 200-point stroke: 693 bytes, 3.5 per point, against 3,553 as JSON. The
1324
+ * ratio matters because the bytes become an asset whose *charged* document mass is what
1325
+ * limits a board — `jsonMass` charges 96 per array element, and a point as `[x, y]` is
1326
+ * three nodes, so points in a document cost 225× what a reference does.
1327
+ *
1328
+ * Zig-zag on the deltas because a stroke moves a little between samples: without it, a
1329
+ * negative delta would take the full width of the varint instead of one byte.
1330
+ *
1331
+ * Two layouts. A stroke whose pressure does not vary ({@link pressureVaries}) is the plain
1332
+ * layout above, byte for byte what this encoder wrote before pressure existed, and decodes
1333
+ * without pressure. A stroke whose pressure varies starts with a three-byte header (a mark no
1334
+ * plain stroke starts with, then a version) and stores a pressure delta in
1335
+ * {@link INK_PRESSURE_PRECISION} steps after each point's coordinates. Measured on the same
1336
+ * 200-point stroke with a varying pressure: 897 bytes against 693 without, so pressure costs
1337
+ * the header and about one byte per point.
1338
+ */
1339
+ export declare function encodeStroke(points: readonly InkPoint[]): Uint8Array;
1340
+ /**
1341
+ * Whether a stroke's pressure is worth storing: its finite samples carry pressure, and it is not the
1342
+ * same stored step on every one of them. A stroke of one pressure is a stroke of one width, which the
1343
+ * plain format already says, so it is written without the bytes.
1344
+ */
1345
+ export declare function pressureVaries(points: readonly InkPoint[]): boolean;
1346
+ /**
1347
+ * Decodes what {@link encodeStroke} wrote.
1348
+ *
1349
+ * A truncated stream decodes to the points it fully contains rather than throwing: an
1350
+ * asset can be cut off by a failed upload, and a stroke that draws most of itself beats a
1351
+ * canvas that fails to paint because one asset is short. Trailing bits that do not form a
1352
+ * coordinate pair are dropped.
1353
+ *
1354
+ * Both layouts read here: a plain stroke decodes to points without pressure, exactly as it did
1355
+ * before pressure existed, and a versioned one to points that carry it. A version this decoder
1356
+ * does not know decodes to no points.
1357
+ */
1358
+ export declare function decodeStroke(bytes: Uint8Array): readonly InkPoint[];
1359
+ /**
1360
+ * The box a stroke paints, with the pen's width included.
1361
+ *
1362
+ * This is the function an adapter calls to fill in `bounds` for an ink element, and it
1363
+ * exists because `bounds` must cover what is painted (a stroke's width is half its
1364
+ * painted extent outside its centre line). A zero-width or one-point stroke still gets a
1365
+ * positive box, which is what keeps it hit-testable and painted.
1366
+ *
1367
+ * With `outline` (the same value {@link drawStroke} is given), the box is the outline
1368
+ * polygon's own: exactly what the fill paints, which can reach past the centre line by more
1369
+ * than half the width where the pen pressed hard, and by less at a taper.
1370
+ */
1371
+ export declare function strokeBounds(points: readonly InkPoint[], strokeWidth: number, outline?: boolean | InkOutline): {
1372
+ readonly x: number;
1373
+ readonly y: number;
1374
+ readonly width: number;
1375
+ readonly height: number;
1376
+ };
1377
+ /**
1378
+ * Translates **and scales** stored geometry so it paints at the element's current `bounds`.
1379
+ *
1380
+ * The rule this exists for: **`bounds` is the single source of an element's position and
1381
+ * size.** The select tool moves an element by writing `bounds`, and its corner handles resize
1382
+ * one the same way; a host that drew ink or a line from its stored points without mapping them
1383
+ * onto the current box would leave the paint where it was while the engine culled and
1384
+ * hit-tested at the new box — a shape you can select but not see.
1385
+ *
1386
+ * The mapping anchors the pen's width, which does not scale: the centre line fills the box
1387
+ * inset by the pen's radius (`padEff`), and the painted stroke outside it keeps the pen's own
1388
+ * radius, so a resized stroke is the same stroke at a different size, not a fatter line.
1389
+ * Concretely, with `natural` = {@link strokeBounds} of the same points and width:
1390
+ *
1391
+ * - `inner` = `natural` inset by `pad` (the centre line's own box; either axis may span zero),
1392
+ * - `target` = `bounds` inset by `padEff` = `min(pad, bounds / 2)` per axis,
1393
+ * - `x' = target.x + (p.x − inner.x) · sx`, with `sx = target.width / inner.width`, and a
1394
+ * **zero-span axis takes the coefficient 1** (there is no scale to apply, so every point of
1395
+ * that axis lands on the pad-inset edge — no centre special case; the coefficient rule is
1396
+ * the whole rule).
1397
+ *
1398
+ * Three invariants pin it: a bounds equal to `natural` on all four fields returns a copy of
1399
+ * the points; a bounds equal to `natural` plus a translation returns exactly that translation
1400
+ * (`padEff` cancels, `sx = sy = 1`, zero-span axes included); and a bounds *thinner* than the
1401
+ * pen's width on an axis (`padEff` clamps, `sx` falls to 0) collapses that axis to the box's
1402
+ * centre line — the stroke then paints past `bounds` until it is dragged bigger again. That
1403
+ * last case is the recorded cost of "minimum size is screen pixels, pen width is world
1404
+ * units": at a high zoom an 8-px-minimum box can be narrower than the pen.
1405
+ *
1406
+ * Points are mapped, never mutated: two elements sharing decoded bytes stay independent.
1407
+ *
1408
+ * @experimental — may change in any minor release.
1409
+ */
1410
+ export declare function placedGeometry(points: readonly InkPoint[], bounds: Rect, width: number, outline?: boolean | InkOutline): InkPoint[];
1411
+ /** What kind of container an element is, if any. */
1412
+ type ContainerKind = "group" | "frame";
1413
+ /** Read-only containment queries, by id. */
1414
+ interface CanvasStructure {
1415
+ /** The parent id an element names, when that parent exists. */
1416
+ parentOf(id: string): string | undefined;
1417
+ /** Direct members, ascending by order. */
1418
+ childrenOf(id: string): readonly string[];
1419
+ /** Every member at any depth, parents before their members. */
1420
+ descendantsOf(id: string): readonly string[];
1421
+ /** The container kind of an element, or `undefined`. */
1422
+ containerOf(id: string): ContainerKind | undefined;
1423
+ /** What a press on `id` selects: the outermost group around it, or the element itself. */
1424
+ selectionRoot(id: string): string;
1425
+ /** Whether containment is enabled (the host gave a parent field). */
1426
+ readonly enabled: boolean;
1427
+ /** The host's parent field, when enabled. */
1428
+ readonly parentField: string | undefined;
1429
+ }
1430
+ /** What {@link createStructure} takes. */
1431
+ interface StructureOptions<T extends CanvasElement> {
1432
+ readonly document: CanvasEditableDocument<T>;
1433
+ /** The element field holding the parent id. Without one, nothing is contained in anything. */
1434
+ readonly parentField?: string | undefined;
1435
+ /** The host's answer to "is this a group or a frame". */
1436
+ readonly containerOf: (element: T) => ContainerKind | undefined;
1437
+ }
1438
+ /** A structure index and a document view in which groups' bounds are derived from their members. */
1439
+ interface StructureView<T extends CanvasElement> {
1440
+ readonly structure: CanvasStructure;
1441
+ readonly document: CanvasEditableDocument<T>;
1442
+ destroy(): void;
1443
+ }
1444
+ /** Creates the containment index over a document, and the group-deriving view of it. */
1445
+ export declare function createStructure<T extends CanvasElement>(options: StructureOptions<T>): StructureView<T>;
1446
+ /** A structure with no containment: every element is top level. For contexts built without a session. */
1447
+ export declare const NO_STRUCTURE: CanvasStructure;
1448
+ /** The eight handles: four corners and four edge midpoints. */
1449
+ type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
1450
+ /** The handles in draw and hit-test order: corners first, so a corner wins where they are close. */
1451
+ export declare const RESIZE_HANDLES: readonly ResizeHandle[];
1452
+ /** Whether a handle is a corner. */
1453
+ export declare function isCorner(handle: ResizeHandle): boolean;
1454
+ /** The point of a handle on an axis-aligned box. */
1455
+ export declare function handlePoint(box: Rect, handle: ResizeHandle): Point;
1456
+ /** A turned box: its centre, its unturned size, and its angle. */
1457
+ interface TurnedFrame {
1458
+ readonly centre: Point;
1459
+ readonly width: number;
1460
+ readonly height: number;
1461
+ }
1462
+ /** The world point of a handle on a turned frame. */
1463
+ export declare function turnedHandlePoint(frame: TurnedFrame, angle: number, handle: ResizeHandle): Point;
1464
+ /** How a resize is constrained. */
1465
+ interface ResizeOptions {
1466
+ /** The smallest width and height, in the box's units. */
1467
+ readonly min: number;
1468
+ /** Keep the width-to-height ratio. */
1469
+ readonly keepAspect?: boolean;
1470
+ /** Keep the centre where it is and move both opposite edges. */
1471
+ readonly fromCentre?: boolean;
1472
+ }
1473
+ /** The box a handle drag to `pointer` produces from `origin`. */
1474
+ export declare function resizeBox(origin: Rect, handle: ResizeHandle, pointer: Point, options: ResizeOptions): Rect;
1475
+ /** Maps a box inside `from` to the same place inside `to`: a selection's members follow its box. */
1476
+ export declare function scaleInto(box: Rect, from: Rect, to: Rect): Rect;
1477
+ /** Moves a box's centre the way `scaleInto` would, keeping its size: for members that cannot scale. */
1478
+ export declare function moveCentreInto(box: Rect, from: Rect, to: Rect): Rect;
1479
+ /** Resizes a turned frame by a handle, in the frame's own axes. */
1480
+ export declare function resizeTurned(frame: TurnedFrame, angle: number, handle: ResizeHandle, pointer: Point, options: ResizeOptions): TurnedFrame;
1481
+ /** The host's rotation policy. */
1482
+ interface CanvasRotation<T extends CanvasElement> {
1483
+ /** The element field holding the angle in radians. */
1484
+ readonly field: string;
1485
+ /** The painted box of the element turned to `angle` about its centre. */
1486
+ bounds(element: T, angle: number): Rect;
1487
+ /** Whether an element can be turned. Defaults to every element; connectors and containers never are. */
1488
+ rotates?(element: T): boolean;
1489
+ /**
1490
+ * Other authored fields the host keeps with the angle, written in the same gesture: typically the
1491
+ * element's unturned size, which the turned box alone no longer determines. Called with the element
1492
+ * as the press found it.
1493
+ */
1494
+ fields?(element: T, angle: number): Readonly<Record<string, unknown>>;
1495
+ /**
1496
+ * The element's unturned frame: centre, width and height. With {@link CanvasRotation.resize}, a
1497
+ * turned element gets handles on its own axes.
1498
+ */
1499
+ frame?(element: T): TurnedFrame;
1500
+ /** The painted box and the authored fields of the element resized to `frame`, at its current angle. */
1501
+ resize?(element: T, frame: TurnedFrame): {
1502
+ readonly bounds: Rect;
1503
+ readonly fields: Readonly<Record<string, unknown>>;
1504
+ };
1505
+ }
1506
+ /** Rotation as tools and overlays read it. */
1507
+ interface RotationView<T extends CanvasElement> {
1508
+ angleOf(element: T): number;
1509
+ /** The host's extra fields for an angle (see {@link CanvasRotation.fields}). */
1510
+ fieldsAt(element: T, angle: number): Readonly<Record<string, unknown>>;
1511
+ /** The unturned frame, when the host can resize a turned element; otherwise `undefined`. */
1512
+ frameOf(element: T): TurnedFrame | undefined;
1513
+ /** The box and fields for a resized frame (only when {@link RotationView.frameOf} answers). */
1514
+ resizeTo(element: T, frame: TurnedFrame): {
1515
+ readonly bounds: Rect;
1516
+ readonly fields: Readonly<Record<string, unknown>>;
1517
+ };
1518
+ /** Whether the rotate handle is offered for this element. */
1519
+ canRotate(element: T): boolean;
1520
+ boundsAt(element: T, angle: number): Rect;
1521
+ readonly field: string;
1522
+ }
1523
+ /** The rotation view of a host policy. */
1524
+ export declare function rotationView<T extends CanvasElement>(policy: CanvasRotation<T>, excluded?: (element: T) => boolean): RotationView<T>;
1525
+ /** The world point of the rotate handle for a box, at a camera scale. */
1526
+ export declare function rotateHandlePoint(bounds: Rect, scale: number): Point;
1527
+ /** An angle normalized to (-π, π], optionally snapped to {@link ROTATE_SNAP}. */
1528
+ export declare function normalizeAngle(angle: number, snap?: boolean): number;
1529
+ /**
1530
+ * The axis-aligned box of a `width` × `height` rectangle centred on `centre` and turned by `angle`.
1531
+ * A helper for a host's `bounds` policy; stroke width and shadow are the host's to add.
1532
+ */
1533
+ export declare function turnedBox(centre: Point, width: number, height: number, angle: number): Rect;
1534
+ /**
1535
+ * Pointer input. `world` is derived by the session from the camera at the moment of the event.
1536
+ *
1537
+ * `button` is the DOM button index; the tools in this package act on the primary button (0) only.
1538
+ */
1539
+ interface CanvasPointerEvent {
1540
+ /** World units. */
1541
+ readonly world: {
1542
+ readonly x: number;
1543
+ readonly y: number;
1544
+ };
1545
+ /** CSS pixels on the surface, for hit tests and screen-constant thresholds. */
1546
+ readonly screen: {
1547
+ readonly x: number;
1548
+ readonly y: number;
1549
+ };
1550
+ readonly pointerId: number;
1551
+ readonly button: number;
1552
+ readonly shiftKey: boolean;
1553
+ readonly altKey: boolean;
1554
+ readonly ctrlKey: boolean;
1555
+ readonly metaKey: boolean;
1556
+ /**
1557
+ * The DOM pressure, 0..1, when the host passed one. A mouse reports 0.5 while a button is down and
1558
+ * a pen its real pressure, so a tool that draws with it reads `pointerType` before trusting it.
1559
+ */
1560
+ readonly pressure?: number | undefined;
1561
+ /** The DOM pointer type ("mouse", "pen", "touch"), when the host passed one. */
1562
+ readonly pointerType?: string | undefined;
1563
+ /** Milliseconds, from the DOM event when the host passes it: lets a tool tell a double press. */
1564
+ readonly time?: number | undefined;
1565
+ }
1566
+ /** Keyboard input. `key` is the DOM KeyboardEvent.key value. Delivered only by the host from the focused canvas. */
1567
+ interface CanvasKeyEvent {
1568
+ readonly key: string;
1569
+ readonly shiftKey: boolean;
1570
+ readonly altKey: boolean;
1571
+ readonly ctrlKey: boolean;
1572
+ readonly metaKey: boolean;
1573
+ }
1574
+ /**
1575
+ * What a tool asks the host to create. The kit names the gesture's geometry; the host's `shape`
1576
+ * builder names the element. `bounds` is what the tool computed: it covers every painted pixel,
1577
+ * stroke included, and always has positive width and height. `box` is the geometric box a rect or
1578
+ * ellipse outlines, inset from `bounds` by strokeWidth/2 on each side, so the host can draw the
1579
+ * shape without recomputing it. A sticky's `at` is its top-left corner: the card is fixed-size,
1580
+ * so a press carries no drag geometry. An ink intent's points carry `pressure` only when it varies
1581
+ * along the stroke; such a stroke is drawn as an outline, and its `bounds` are the outline's
1582
+ * (`strokeBounds(points, strokeWidth, true)`).
1583
+ */
1584
+ type ToolIntent = {
1585
+ readonly kind: "rect" | "ellipse";
1586
+ readonly box: Rect;
1587
+ readonly strokeWidth: number;
1588
+ readonly bounds: Rect;
1589
+ } | {
1590
+ readonly kind: "line";
1591
+ readonly from: Point;
1592
+ readonly to: Point;
1593
+ readonly strokeWidth: number;
1594
+ readonly bounds: Rect;
1595
+ } | {
1596
+ readonly kind: "ink";
1597
+ readonly points: readonly InkPoint[];
1598
+ readonly strokeWidth: number;
1599
+ readonly bounds: Rect;
1600
+ } | {
1601
+ readonly kind: "text";
1602
+ readonly at: Point;
1603
+ readonly bounds: Rect;
1604
+ } | {
1605
+ readonly kind: "sticky";
1606
+ readonly at: Point;
1607
+ readonly bounds: Rect;
1608
+ } |
1609
+ /** A frame: a container with its own box, drawn by the frame tool. */
1610
+ {
1611
+ readonly kind: "frame";
1612
+ readonly bounds: Rect;
1613
+ } |
1614
+ /**
1615
+ * A group around existing elements, made by `session.group()`. `bounds` is the members' union;
1616
+ * the session derives a group's bounds from its members, so the stored value is a placeholder.
1617
+ */
1618
+ {
1619
+ readonly kind: "group";
1620
+ readonly memberIds: readonly string[];
1621
+ readonly bounds: Rect;
1622
+ } |
1623
+ /**
1624
+ * A connector between two existing elements. The endpoints, routing, arrow and stroke width are
1625
+ * the connector's authored fields; `bounds` is the box of the straight route, the value
1626
+ * derived connector view (connector-derive.ts) computes for it. The session checks the host's element against all six.
1627
+ */
1628
+ {
1629
+ readonly kind: "connector";
1630
+ readonly fromId: string;
1631
+ readonly toId: string;
1632
+ readonly routing: ConnectorRouting;
1633
+ readonly arrow: ConnectorArrow;
1634
+ readonly strokeWidth: number;
1635
+ readonly bounds: Rect;
1636
+ /** The port the end snapped to while it was drawn. Absent when it snapped to none. */
1637
+ readonly toAnchor?: ConnectorAnchor | undefined;
1638
+ };
1639
+ /** The selection as readers see it. Ids that no longer resolve are never returned. */
1640
+ interface SelectionView {
1641
+ /** Selected ids that still resolve, in selection order. */
1642
+ ids(): readonly string[];
1643
+ has(id: string): boolean;
1644
+ }
1645
+ /**
1646
+ * What the host says an element may do, as the tool layer reads it.
1647
+ *
1648
+ * Three answers, each about the element and not about the gesture: `locked` elements are not moved,
1649
+ * resized or selected by handle; `editable` elements take a text edit; `linkable` elements may be a
1650
+ * connector endpoint. The session derives `linkable` itself, so a connector is never linkable
1651
+ * whatever the host returns for it.
1652
+ */
1653
+ interface ElementTraits {
1654
+ readonly locked: boolean;
1655
+ readonly editable: boolean;
1656
+ readonly linkable: boolean;
1657
+ /** Whether the element is a group or a frame (structure.ts). Absent for ordinary elements. */
1658
+ readonly container?: ContainerKind | undefined;
1659
+ /** Whether resize handles are offered. The session sets it false for connectors, whose box is derived. */
1660
+ readonly resizable?: boolean | undefined;
1661
+ }
1662
+ /** What overlays and tools may read. The document is read-only here. */
1663
+ interface ToolView<T extends CanvasElement = CanvasElement> {
1664
+ readonly document: CanvasDocument<T>;
1665
+ readonly camera: Camera;
1666
+ readonly selection: SelectionView;
1667
+ /** The traits of an element, as the session resolves them: the host's answer, with `linkable` false for connectors. */
1668
+ traits(element: T): ElementTraits;
1669
+ /** Groups and frames. Every query answers "no parent" when the host gave no parent field. */
1670
+ readonly structure: CanvasStructure;
1671
+ /** The host's rotation policy, or `undefined` when elements do not rotate. */
1672
+ readonly rotation?: RotationView<T> | undefined;
1673
+ /** Alignment snapping for drags, or `undefined` when it is off. */
1674
+ readonly snap?: SnapView | undefined;
1675
+ }
1676
+ /** What a dragging tool needs for alignment snapping. */
1677
+ interface SnapView {
1678
+ /** The snapping distance in screen pixels. */
1679
+ readonly thresholdPx: number;
1680
+ /** The boxes a drag can align to: every element except the excluded ids, connectors and groups. */
1681
+ targets(excluded: ReadonlySet<string>): readonly Rect[];
1682
+ /** A grid spacing in world units, when the grid is on. */
1683
+ readonly grid?: number | undefined;
1684
+ /** Whether equal spacing between neighbours is snapped. */
1685
+ readonly spacing: boolean;
1686
+ }
1687
+ /** Narrowed engine handle: tools can hit-test and move the camera, but cannot paint or destroy. */
1688
+ type ToolEngine<T extends CanvasElement = CanvasElement> = Pick<CanvasEngine<T>, "hitAt" | "hitTargetAt" | "camera" | "setCamera" | "invalidateRect">;
1689
+ /** Everything a tool gets with an event. */
1690
+ interface ToolContext<T extends CanvasElement = CanvasElement> extends ToolView<T> {
1691
+ readonly document: CanvasEditableDocument<T>;
1692
+ readonly engine: ToolEngine<T>;
1693
+ /** Builds an element for the intent with a session-chosen id and order; returns the id. */
1694
+ create(intent: ToolIntent): string;
1695
+ /** Replaces the selection, or toggles one id in it. Ids that do not resolve are dropped. */
1696
+ select(ids: readonly string[], mode: "replace" | "toggle"): void;
1697
+ /**
1698
+ * Opens the host's text editor on an element. Returns false when there is no editor, the element
1699
+ * is gone, or it is not editable, so a tool can fall back to doing nothing.
1700
+ */
1701
+ edit(id: string): boolean;
1702
+ }
1703
+ /** The members every tool has, whether or not it paints an overlay. */
1704
+ interface CanvasToolCore<T extends CanvasElement = CanvasElement> {
1705
+ readonly id: string;
1706
+ readonly label: string;
1707
+ /** CSS cursor value shown while this tool is active. */
1708
+ readonly cursor: string;
1709
+ onPointerDown?(ctx: ToolContext<T>, event: CanvasPointerEvent): void;
1710
+ onPointerMove?(ctx: ToolContext<T>, event: CanvasPointerEvent): void;
1711
+ onPointerUp?(ctx: ToolContext<T>, event: CanvasPointerEvent): void;
1712
+ /** Returns true when the tool consumed the key. Runs before tool shortcuts. */
1713
+ onKeyDown?(ctx: ToolContext<T>, event: CanvasKeyEvent): boolean;
1714
+ activate?(ctx: ToolContext<T>): void;
1715
+ /** Called when another tool takes over. Must drop any uncommitted gesture state. */
1716
+ deactivate?(ctx: ToolContext<T>): void;
1717
+ /** Aborts an uncommitted gesture. Returns whether one was in progress. Escape and pointer cancel call it. */
1718
+ cancel?(ctx: ToolContext<T>): boolean;
1719
+ }
1720
+ /**
1721
+ * A tool. The overlay members come as a pair enforced by the type: a tool that implements
1722
+ * drawOverlay must also implement overlayBounds, and a tool with no overlay implements neither.
1723
+ *
1724
+ * overlayBounds returns this frame's painted area in world units. A zero-size rect means 'nothing
1725
+ * this frame' and is never unioned into anything. Returning undefined means 'the whole window'.
1726
+ * The composer adds the previous frame's area itself.
1727
+ */
1728
+ type CanvasTool<T extends CanvasElement = CanvasElement> = CanvasToolCore<T> & ({
1729
+ drawOverlay?: undefined;
1730
+ overlayBounds?: undefined;
1731
+ } | {
1732
+ /** Paints in world units, after the host overlay and the selection outline. */
1733
+ drawOverlay(ctx: CanvasRenderingContext2D, camera: Camera, view: ToolView<T>): void;
1734
+ overlayBounds(view: ToolView<T>): Rect | undefined;
1735
+ });
1736
+ /** Builds a fresh tool. The registry calls it once per registration. */
1737
+ type ToolFactory<T extends CanvasElement = CanvasElement> = () => CanvasTool<T>;
1738
+ /** The registry a session exposes. Its methods are the whole public surface of tool switching. */
1739
+ interface CanvasToolRegistry<T extends CanvasElement = CanvasElement> {
1740
+ /** Instantiates the factory and registers the tool under its id, with optional shortcut keys. Throws on a duplicate id or an already-bound key. */
1741
+ register(factory: ToolFactory<T>, keys?: readonly string[]): void;
1742
+ /** Removes a tool. If it is active the registry falls back to 'select'. Throws for 'select' (the fallback can never be removed). */
1743
+ unregister(id: string): void;
1744
+ /** Switches the active tool: cancel() then deactivate() on the old, activate() on the new. Throws on an unknown id. */
1745
+ use(id: string): void;
1746
+ current(): string;
1747
+ ids(): readonly string[];
1748
+ }
1749
+ /** What {@link createTextEditor} takes. */
1750
+ interface CanvasTextEditorOptions<T extends CanvasElement> {
1751
+ /** The document an edit reads and writes. The editor never keeps a copy of an element. */
1752
+ readonly document: CanvasEditableDocument<T>;
1753
+ /** The host's textarea, already inside a `position: relative` container with the canvas's origin. */
1754
+ readonly textarea: HTMLTextAreaElement;
1755
+ /** The authored field the text is written to. Defaults to `"text"`. */
1756
+ readonly textField?: string;
1757
+ /** The smallest height a committed box may take, in world units. Defaults to the text tool's box height. */
1758
+ readonly minHeight?: number;
1759
+ /** The colours the textarea takes for an element. Without it the textarea keeps its own colours. */
1760
+ readonly styleOf?: (element: T) => {
1761
+ readonly colour: string;
1762
+ readonly background: string | null;
1763
+ };
1764
+ /**
1765
+ * Called once each time an edit ends by commit, cancel, or the element's removal. Not called by
1766
+ * `destroy`, which is the host tearing the editor down rather than the user finishing an edit.
1767
+ */
1768
+ readonly onEnd: (id: string) => void;
1769
+ }
1770
+ /** The editor a host creates once and hands to the session. */
1771
+ interface CanvasTextEditor {
1772
+ /**
1773
+ * Opens the editor on an element.
1774
+ *
1775
+ * Returns false, touching nothing, when the id does not resolve or the camera's scale is not a
1776
+ * finite positive number. An edit already open is committed first, with the camera it was given.
1777
+ */
1778
+ begin(id: string, camera: Camera): boolean;
1779
+ /** Places the textarea again for the camera it is given. A no-op while no edit is open. */
1780
+ reposition(camera: Camera): void;
1781
+ /** Writes the text back and ends the edit. A no-op while no edit is open. */
1782
+ commit(): void;
1783
+ /** Ends the edit without writing text. An element left with no text is removed. A no-op while idle. */
1784
+ cancel(): void;
1785
+ /** The id of the element being edited, or `undefined` when no edit is open. */
1786
+ editing(): string | undefined;
1787
+ /**
1788
+ * Commits any open edit without calling `onEnd`, hides the textarea, and removes the listeners and
1789
+ * the document subscription. The editor cannot be opened again after this.
1790
+ */
1791
+ destroy(): void;
1792
+ }
1793
+ /**
1794
+ * Creates a text editor over a document and a host textarea.
1795
+ *
1796
+ * The textarea is styled once here, and styled per element on each placement. Its listeners are the
1797
+ * editor's for as long as the editor lives, and `destroy` removes them.
1798
+ */
1799
+ export declare function createTextEditor<T extends CanvasElement>(options: CanvasTextEditorOptions<T>): CanvasTextEditor;
1800
+ /** The recorded fields of one element: field name to the value the gesture last wrote. */
1801
+ type DraftFields = ReadonlyMap<string, unknown>;
1802
+ /** What {@link createDraftDocument} takes. */
1803
+ interface DraftDocumentOptions<T extends CanvasElement> {
1804
+ /** The host's document. The draft reads it and writes to it on commit. */
1805
+ readonly document: CanvasEditableDocument<T>;
1806
+ /** Called after every change to the recorded fields, and with an empty map when they clear. */
1807
+ readonly onPending?: (pending: ReadonlyMap<string, DraftFields>) => void;
1808
+ }
1809
+ /** A document view with a gesture boundary. */
1810
+ interface DraftDocument<T extends CanvasElement> {
1811
+ /** The view the engine and tools read and write. */
1812
+ readonly document: CanvasEditableDocument<T>;
1813
+ /** Starts recording. A gesture already in progress is committed first. */
1814
+ begin(): void;
1815
+ /** Ends the gesture, writing each recorded field that differs from the host's value. */
1816
+ commit(): void;
1817
+ /** Ends the gesture, dropping what it recorded. */
1818
+ discard(): void;
1819
+ /** Whether a gesture is in progress. */
1820
+ active(): boolean;
1821
+ /** The recorded fields, by element id. */
1822
+ pending(): ReadonlyMap<string, DraftFields>;
1823
+ /** Stops listening to the host's document. Terminal. */
1824
+ destroy(): void;
1825
+ }
1826
+ /** Creates a draft over a host document. */
1827
+ export declare function createDraftDocument<T extends CanvasElement>(options: DraftDocumentOptions<T>): DraftDocument<T>;
1828
+ /** The four z-order moves. */
1829
+ type ArrangeMode = "front" | "back" | "forward" | "backward";
1830
+ /** An element of the stack: its id and its key. */
1831
+ interface StackEntry {
1832
+ readonly id: string;
1833
+ readonly order: string;
1834
+ /**
1835
+ * The highest key in the element's subtree, when it is a container whose members are painted
1836
+ * above it. An element placed after this one goes above `top`, not between it and its members.
1837
+ */
1838
+ readonly top?: string;
1839
+ }
1840
+ /** Keys the arranged stack must stay strictly between: a container's key and the key above its subtree. */
1841
+ interface ArrangeBounds {
1842
+ readonly low?: string | undefined;
1843
+ readonly high?: string | undefined;
1844
+ }
1845
+ /**
1846
+ * The new keys an arrange writes, by id. Elements whose place did not change are not in the map.
1847
+ *
1848
+ * `stack` must be sorted ascending by `order`. Each run of moved elements between two unmoved
1849
+ * neighbours gets keys between those neighbours' keys, in stack order.
1850
+ */
1851
+ export declare function arrangeOrders(stack: readonly StackEntry[], selected: ReadonlySet<string>, mode: ArrangeMode, bounds?: ArrangeBounds): Map<string, string>;
1852
+ /** The six alignments. */
1853
+ type AlignMode = "left" | "centre" | "right" | "top" | "middle" | "bottom";
1854
+ /** The new position of each box that moves, by id. */
1855
+ type Placement = Map<string, {
1856
+ readonly x: number;
1857
+ readonly y: number;
1858
+ }>;
1859
+ /** Aligns boxes, by id. Boxes already on the line are left out of the result. */
1860
+ export declare function alignBoxes(boxes: ReadonlyMap<string, Rect>, mode: AlignMode): Placement;
1861
+ /** Spaces boxes evenly along an axis, keeping the outermost two in place. */
1862
+ export declare function distributeBoxes(boxes: ReadonlyMap<string, Rect>, axis: "x" | "y"): Placement;
1863
+ /** The clipboard format's identifier, for a host's `DataTransfer` type. */
1864
+ export declare const CANVAS_CLIPBOARD_TYPE = "application/x-bevelo-canvas+json";
1865
+ /** What `copy` produces and `paste` takes. */
1866
+ interface CanvasClipboard<T extends CanvasElement = CanvasElement> {
1867
+ readonly version: 1;
1868
+ /** The copied elements, ascending by order. */
1869
+ readonly elements: readonly T[];
1870
+ /** The ids that were selected; the rest came along as members or connectors. */
1871
+ readonly roots: readonly string[];
1872
+ /** The union of the copied roots' bounds. */
1873
+ readonly bounds: Rect;
1874
+ }
1875
+ /** The fields the session rewrites on paste. */
1876
+ interface ClipboardReferences<T extends CanvasElement> {
1877
+ readonly parentField?: string | undefined;
1878
+ readonly isConnector?: ((element: T) => boolean) | undefined;
1879
+ /** Host policy for any other references between elements. Returns the element with them rewritten. */
1880
+ readonly remap?: ((element: T, ids: ReadonlyMap<string, string>) => T) | undefined;
1881
+ }
1882
+ /** Collects the payload for a set of root ids. */
1883
+ export declare function collectClipboard<T extends CanvasElement>(roots: readonly string[], all: readonly T[], descendantsOf: (id: string) => readonly string[], references: ClipboardReferences<T>): CanvasClipboard<T> | undefined;
1884
+ /** The pasted elements, with fresh ids, rewritten references, new order keys and an offset. */
1885
+ export declare function preparePaste<T extends CanvasElement>(payload: CanvasClipboard<T>, options: {
1886
+ readonly newId: () => string;
1887
+ readonly orders: (count: number) => readonly string[];
1888
+ readonly dx: number;
1889
+ readonly dy: number;
1890
+ readonly references: ClipboardReferences<T>;
1891
+ }): {
1892
+ readonly elements: readonly T[];
1893
+ readonly roots: readonly string[];
1894
+ };
1895
+ /** The payload as JSON text. Binary fields (`Uint8Array`) are kept as base64. */
1896
+ export declare function serializeClipboard<T extends CanvasElement>(payload: CanvasClipboard<T>): string;
1897
+ /** Reads a payload written by {@link serializeClipboard}, or `undefined` when the text is not one. */
1898
+ export declare function parseClipboard<T extends CanvasElement>(text: string): CanvasClipboard<T> | undefined;
1899
+ /** One item of the accessible outline. */
1900
+ interface AccessibleNode {
1901
+ readonly id: string;
1902
+ readonly label: string;
1903
+ readonly bounds: Rect;
1904
+ readonly children: readonly AccessibleNode[];
1905
+ }
1906
+ /**
1907
+ * Elements in reading order: rows top to bottom, left to right within a row.
1908
+ *
1909
+ * Two elements share a row when their vertical extents overlap by at least half the smaller height.
1910
+ * Elements are placed in rows in order of their top edge; ties break by id so the order is stable.
1911
+ */
1912
+ export declare function readingOrder<T extends CanvasElement>(elements: readonly T[]): T[];
1913
+ /**
1914
+ * The document as a labelled tree in reading order. Top-level elements are the roots; a frame or
1915
+ * group lists its members as children.
1916
+ */
1917
+ export declare function accessibleOutline<T extends CanvasElement>(document: CanvasDocument<T>, structure: CanvasStructure, describe: (element: T) => string): AccessibleNode[];
1918
+ /** The DOM pointer fields a session reads. Structural, so a test can pass a plain object. */
1919
+ interface PointerLike {
1920
+ readonly clientX: number;
1921
+ readonly clientY: number;
1922
+ readonly pointerId: number;
1923
+ readonly button: number;
1924
+ readonly shiftKey: boolean;
1925
+ readonly altKey: boolean;
1926
+ readonly ctrlKey: boolean;
1927
+ readonly metaKey: boolean;
1928
+ /** The DOM `PointerEvent.pressure`, 0..1. Optional: a host without it gets velocity-simulated ink. */
1929
+ readonly pressure?: number | undefined;
1930
+ /** The DOM `PointerEvent.pointerType`. Optional, as `pressure` is. */
1931
+ readonly pointerType?: string | undefined;
1932
+ /** The DOM event's `timeStamp`. Optional; without it a double press is never recognised. */
1933
+ readonly timeStamp?: number;
1934
+ }
1935
+ /** Where the canvas sits on the page: its border box's origin and its border widths. */
1936
+ interface SurfaceBox {
1937
+ readonly left: number;
1938
+ readonly top: number;
1939
+ readonly borderLeft: number;
1940
+ readonly borderTop: number;
1941
+ }
1942
+ /** A tool to register, with the keys that select it. */
1943
+ interface ToolRegistration<T extends CanvasElement = CanvasElement> {
1944
+ readonly factory: ToolFactory<T>;
1945
+ readonly keys?: readonly string[];
1946
+ }
1947
+ /** What {@link createCanvasSession} takes. */
1948
+ interface CanvasSessionOptions<T extends CanvasElement = CanvasElement> {
1949
+ /** Host editable document. */
1950
+ readonly document: CanvasEditableDocument<T>;
1951
+ /** Optional 2D paint renderer (`draw`, and optional `drawOverlay` / `overlayBounds`). */
1952
+ readonly renderer?: CanvasRenderer<T> | undefined;
1953
+ /** Optional GPU (`webgpu` / `webgl2`) or `2d` backend; makes `renderer` optional. */
1954
+ readonly backend?: CanvasRenderBackend<T> | undefined;
1955
+ /** Optional 2D overlay canvas above a GPU main canvas. */
1956
+ readonly overlayCanvas?: HTMLCanvasElement | undefined;
1957
+ readonly canvas: HTMLCanvasElement;
1958
+ readonly camera?: Camera;
1959
+ readonly maxDirtyRects?: number;
1960
+ /** Host policy returning a fresh, unique id per created element. */
1961
+ readonly newId: () => string;
1962
+ /** Host policy mapping an intent to an element with the given `id`, `order`, and `intent.bounds`. */
1963
+ readonly shape: (intent: ToolIntent, id: string, order: string) => T;
1964
+ /** Optional z-order key generator for new elements. */
1965
+ readonly nextOrder?: (document: CanvasDocument<T>) => string;
1966
+ /** Defaults to `canvasTools` with default shortcuts. */
1967
+ readonly tools?: readonly ToolRegistration<T>[];
1968
+ /** Element traits predicate; connectors always force `linkable: false`. */
1969
+ readonly traits?: (element: T) => ElementTraits;
1970
+ /** Connector predicate enabling derived bounds and obstacle routing. */
1971
+ readonly isConnector?: ConnectorPredicate<T>;
1972
+ /** Optional text editor committed before pointer presses. */
1973
+ readonly editor?: CanvasTextEditor;
1974
+ /** Gesture-in-progress pending field callback for presence broadcasting. */
1975
+ readonly onPending?: (pending: ReadonlyMap<string, DraftFields>) => void;
1976
+ /** Element field name storing container parent id. */
1977
+ readonly parentField?: string;
1978
+ /** Host rotation policy. */
1979
+ readonly rotation?: CanvasRotation<T>;
1980
+ /** Optional fine hit-test inside element bounds. */
1981
+ readonly hitTest?: (element: T, world: Point) => boolean;
1982
+ /** Alignment snapping configuration (`true` uses 6 px threshold). */
1983
+ readonly snap?: boolean | {
1984
+ readonly thresholdPx?: number;
1985
+ readonly grid?: number;
1986
+ readonly spacing?: boolean;
1987
+ };
1988
+ /** Element label formatter for screen-reader announcements and outline. */
1989
+ readonly describe?: (element: T) => string;
1990
+ /** `aria-live` announcement callback. */
1991
+ readonly announce?: (message: string) => void;
1992
+ /** Custom id remapper during clipboard paste. */
1993
+ readonly remap?: (element: T, ids: ReadonlyMap<string, string>) => T;
1994
+ }
1995
+ /** A session: engine, tool registry, selection, and event entry points. */
1996
+ interface CanvasSession<T extends CanvasElement = CanvasElement> {
1997
+ readonly engine: CanvasEngine<T>;
1998
+ readonly document: CanvasEditableDocument<T>;
1999
+ readonly tools: CanvasToolRegistry<T>;
2000
+ readonly selection: SelectionView;
2001
+ editing(): string | undefined;
2002
+ beginEdit(id: string): boolean;
2003
+ pointer(phase: "down" | "move" | "up" | "cancel", event: PointerLike, surface: SurfaceBox): void;
2004
+ keyDown(event: CanvasKeyEvent): boolean;
2005
+ arrange(mode: ArrangeMode): boolean;
2006
+ group(): boolean;
2007
+ ungroup(): boolean;
2008
+ readonly structure: CanvasStructure;
2009
+ connectorGeometry(id: string): ConnectorGeometry | undefined;
2010
+ outline(): AccessibleNode[];
2011
+ copy(): CanvasClipboard<T> | undefined;
2012
+ cut(): CanvasClipboard<T> | undefined;
2013
+ paste(payload: CanvasClipboard<T>, options?: {
2014
+ readonly at?: Point;
2015
+ }): readonly string[];
2016
+ duplicate(): readonly string[];
2017
+ align(mode: AlignMode): boolean;
2018
+ distribute(axis: "x" | "y"): boolean;
2019
+ destroy(): void;
2020
+ }
2021
+ /**
2022
+ * Creates a session over a document and a canvas.
2023
+ *
2024
+ * Throws when the tool list does not register `select`, because `select` is the fallback every
2025
+ * other tool returns to, and a session without it has no state it can always be in.
2026
+ */
2027
+ export declare function createCanvasSession<T extends CanvasElement>(options: CanvasSessionOptions<T>): CanvasSession<T>;
2028
+ /** One default registration: a tool factory and the keys that select it. */
2029
+ interface DefaultToolRegistration<T extends CanvasElement> {
2030
+ readonly factory: ToolFactory<T>;
2031
+ readonly keys: readonly string[];
2032
+ }
2033
+ /**
2034
+ * The ten default tools, as fresh registrations.
2035
+ *
2036
+ * A function rather than a constant so every session gets its own list. The factories already
2037
+ * make a fresh tool per call; the list is the part that could otherwise be shared.
2038
+ */
2039
+ export declare function canvasTools<T extends CanvasElement>(): readonly DefaultToolRegistration<T>[];
2040
+ /** Creates the connector tool. It has no shortcut of its own here: the default set binds it to `c`. */
2041
+ export declare function connectorTool<T extends CanvasElement>(): CanvasTool<T>;
2042
+ /** Creates a frame tool. */
2043
+ export declare function frameTool<T extends CanvasElement>(): CanvasTool<T>;
2044
+ /** Whether `point` is inside the closed polygon `path` (even-odd). */
2045
+ export declare function insidePolygon(point: Point, path: readonly Point[]): boolean;
2046
+ /** Creates a lasso tool. Not in the default list: a host registers it. */
2047
+ export declare function lassoTool<T extends CanvasElement>(): CanvasTool<T>;
2048
+ /** The handle set of the current selection. */
2049
+ type HandleTarget<T extends CanvasElement> = {
2050
+ readonly kind: "box";
2051
+ readonly element: T;
2052
+ readonly box: Rect;
2053
+ } | {
2054
+ readonly kind: "turned";
2055
+ readonly element: T;
2056
+ readonly frame: TurnedFrame;
2057
+ readonly angle: number;
2058
+ } | {
2059
+ readonly kind: "selection";
2060
+ readonly roots: readonly T[];
2061
+ readonly box: Rect;
2062
+ };
2063
+ /** The handle target of the view's selection, or `undefined` when it has no handles. */
2064
+ export declare function handleTarget<T extends CanvasElement>(view: ToolView<T>): HandleTarget<T> | undefined;
2065
+ /** The world points of a target's handles, in hit-test order. */
2066
+ export declare function handlePoints<T extends CanvasElement>(target: HandleTarget<T>, scale: number): ReadonlyArray<readonly [ResizeHandle, Point]>;
2067
+ /** The handle within `radius` of `point`, closest first, or `undefined`. */
2068
+ export declare function handleUnder<T extends CanvasElement>(target: HandleTarget<T>, point: Point, radius: number, scale: number): ResizeHandle | undefined;
2069
+ /** A guide line, in world units: vertical when `axis` is "x", horizontal when "y". */
2070
+ interface SnapGuide {
2071
+ readonly axis: "x" | "y";
2072
+ /** The line's position on its axis. */
2073
+ readonly at: number;
2074
+ /** Where the line starts and ends on the other axis. */
2075
+ readonly from: number;
2076
+ readonly to: number;
2077
+ }
2078
+ /** The corrected offset and the guides to draw. */
2079
+ interface SnapResult {
2080
+ readonly dx: number;
2081
+ readonly dy: number;
2082
+ readonly guides: readonly SnapGuide[];
2083
+ }
2084
+ /** What snapping considers beyond the targets' edges and centres. */
2085
+ interface SnapOptions {
2086
+ /** A grid spacing in world units: the box's left and top edges also snap to multiples of it. */
2087
+ readonly grid?: number | undefined;
2088
+ /** Snap a box between two neighbours so the gaps on both sides are equal. */
2089
+ readonly spacing?: boolean | undefined;
2090
+ }
2091
+ /**
2092
+ * Snaps a box being moved by (`dx`, `dy`) from `origin`: its edges and centre to the nearest target
2093
+ * lines, and with `options`, to equal spacing between neighbours and to a grid. On each axis the
2094
+ * smallest correction within `threshold` wins.
2095
+ *
2096
+ * `threshold` is in world units (the screen threshold divided by the camera scale).
2097
+ */
2098
+ export declare function snapOffset(origin: Rect, dx: number, dy: number, targets: readonly Rect[], threshold: number, options?: SnapOptions): SnapResult;
2099
+ /**
2100
+ * Snaps one edge coordinate being resized: to the nearest target edge or centre on that axis, or to
2101
+ * the grid. Returns the corrected value and the line it snapped to (no line for the grid).
2102
+ */
2103
+ export declare function snapEdge(value: number, axis: "x" | "y", targets: readonly Rect[], threshold: number, options?: SnapOptions): {
2104
+ readonly value: number;
2105
+ readonly line: number | undefined;
2106
+ };
2107
+ /** The guide for an edge snapped to `line`, spanning the resized box and the targets on that line. */
2108
+ export declare function edgeGuide(axis: "x" | "y", line: number, box: Rect, targets: readonly Rect[]): SnapGuide;
2109
+ /** What {@link deriveConnectors} takes. */
2110
+ interface DeriveConnectorsOptions<T extends CanvasElement> {
2111
+ /** The document to view. The view reads it and passes writes on, except connector geometry. */
2112
+ readonly document: CanvasEditableDocument<T>;
2113
+ /** The host's connector predicate. Pass the same instance given to `createCanvasSession`. */
2114
+ readonly isConnector: ConnectorPredicate<T>;
2115
+ /**
2116
+ * Which elements an `elbow-avoid` connector routes around. Connectors and the connector's own two
2117
+ * endpoints never are. Defaults to every other element.
2118
+ */
2119
+ readonly isObstacle?: (element: T) => boolean;
2120
+ }
2121
+ /** A document view with derived connector bounds. */
2122
+ interface DerivedConnectors<T extends CanvasElement> {
2123
+ readonly document: CanvasEditableDocument<T>;
2124
+ /**
2125
+ * The route, label box and bounds a connector is drawn and hit by, from the same solve as its
2126
+ * derived bounds. `undefined` for an id that is not a connector, or one with no route.
2127
+ */
2128
+ geometry(id: string): ConnectorGeometry | undefined;
2129
+ /** Stops listening to the underlying document. Terminal. */
2130
+ destroy(): void;
2131
+ }
2132
+ /** Creates a view over a document in which connectors' bounds are derived from their endpoints. */
2133
+ export declare function deriveConnectors<T extends CanvasElement>(options: DeriveConnectorsOptions<T>): DerivedConnectors<T>;
2134
+ /** The four field names that write one component of `bounds`. */
2135
+ export declare const GEOMETRY_FIELDS: readonly ["x", "y", "width", "height"];
2136
+ /** One of {@link GEOMETRY_FIELDS}. */
2137
+ type GeometryField = (typeof GEOMETRY_FIELDS)[number];
2138
+ /** Whether a field name writes a component of `bounds`. */
2139
+ export declare function isGeometryField(field: string): field is GeometryField;
2140
+ /** The current value of a field, reading geometry fields from `bounds`. */
2141
+ export declare function readField<T extends CanvasElement>(element: T, field: string): unknown;
2142
+ /**
2143
+ * The element with one field written: a geometry field replaces that component of `bounds`, and
2144
+ * any other field replaces the property of the same name. Returns the same object when the value
2145
+ * is already stored, so a caller can tell a no-op from a change by identity.
2146
+ */
2147
+ export declare function withField<T extends CanvasElement>(element: T, field: string, value: unknown): T;
2148
+ /**
2149
+ * A gesture in progress, by element id: the fields it has written so far.
2150
+ *
2151
+ * A `Map` is what `onPending` hands out; a plain record is what survives a JSON round trip on a
2152
+ * presence channel. Both are accepted, and both are read in insertion order.
2153
+ */
2154
+ type PresencePending = ReadonlyMap<string, DraftFields> | Readonly<Record<string, Readonly<Record<string, unknown>>>>;
2155
+ /** O(1) affine drag/scale delta broadcast for multi-element presence previews. */
2156
+ interface PresenceTransform {
2157
+ readonly dx: number;
2158
+ readonly dy: number;
2159
+ readonly scaleX?: number | undefined;
2160
+ readonly scaleY?: number | undefined;
2161
+ readonly origin?: Point | undefined;
2162
+ }
2163
+ /** One remote collaborator, as the host last heard of them. */
2164
+ interface PresencePeer {
2165
+ /** Stable per peer; two entries with one id are drawn once, the most recently seen. */
2166
+ readonly id: string;
2167
+ /** The words on the cursor's tag. */
2168
+ readonly name: string;
2169
+ /** Any CSS colour. The cursor, the tag, the outlines and the ghosts are painted in it. */
2170
+ readonly colour: string;
2171
+ /** The pointer, in world units. Absent when their pointer is off the canvas. */
2172
+ readonly cursor?: Point;
2173
+ /** The ids they have selected. Ids that do not resolve here are skipped. */
2174
+ readonly selection?: readonly string[];
2175
+ /** Their gesture in progress, as `onPending` reports it. */
2176
+ readonly pending?: PresencePending;
2177
+ /** Uniform drag/scale preview over `selection`, alternative to per-element `pending`. */
2178
+ readonly transform?: PresenceTransform | undefined;
2179
+ /** Active page/sub-surface identifier for peer filtering. */
2180
+ readonly pageId?: string | undefined;
2181
+ /** Collaborator's current camera viewport for follow mode. */
2182
+ readonly camera?: Camera | undefined;
2183
+ /** Whether this collaborator is actively presenting. */
2184
+ readonly presenter?: boolean | undefined;
2185
+ /** When the host last heard from them, on the clock `now` reads. */
2186
+ readonly seen: number;
2187
+ /** Whether the peer is a human user or an autonomous agent. */
2188
+ readonly actorType?: "human" | "agent" | undefined;
2189
+ /** Optional status summary for agent/collaborator activity indicators. */
2190
+ readonly status?: string | undefined;
2191
+ }
2192
+ /** What {@link createPresenceLayer} takes. Every member is read when the layer paints or claims, never stored. */
2193
+ interface PresenceOptions<T extends CanvasElement> {
2194
+ /** The peers as they stand. */
2195
+ readonly peers: () => readonly PresencePeer[];
2196
+ /** Optional predicate to filter live peers (for example by active `pageId`). */
2197
+ readonly filter?: ((peer: PresencePeer) => boolean) | undefined;
2198
+ /** Collapse transform ghosts to a single union outline above this count. Defaults to 256. */
2199
+ readonly maxGhostBoxes?: number | undefined;
2200
+ /** The document a peer's selection and pending fields are read against: `session.document` for a session host. */
2201
+ readonly document: () => CanvasDocument<T>;
2202
+ /** The camera the engine paints with, so the claim can size screen-constant marks. */
2203
+ readonly camera: () => Camera;
2204
+ /** The clock `seen` is on. Defaults to `Date.now`. */
2205
+ readonly now?: () => number;
2206
+ /** How long a peer stays live after it was last seen. Defaults to {@link PRESENCE_EXPIRE_MS}. */
2207
+ readonly expireAfterMs?: number;
2208
+ /**
2209
+ * The width of a name in CSS pixels at {@link PRESENCE_FONT}. The tag is sized from it, and the
2210
+ * text is squeezed into the tag if the guess was short, so nothing paints outside the claim.
2211
+ * Defaults to a per-character estimate.
2212
+ */
2213
+ readonly measureText?: (text: string) => number;
2214
+ }
2215
+ /** A presence layer: what to paint, and where it paints. */
2216
+ interface PresenceLayer {
2217
+ /** Paints every live peer, in world units, under the camera transform the engine applied. */
2218
+ draw(ctx: CanvasRenderingContext2D, camera: Camera): void;
2219
+ /** The world rect the live peers cover now. Zero-size when there is nothing to paint. */
2220
+ area(): Rect;
2221
+ /**
2222
+ * The area for this frame's paint, recorded as what is on screen once it is painted. The renderer
2223
+ * from {@link withPresence} calls it from `overlayBounds`; a host painting the layer itself calls
2224
+ * it once per frame before `draw`.
2225
+ */
2226
+ claim(): Rect;
2227
+ /** What was last claimed together with what is covered now: the rect a host invalidates after the peers change. */
2228
+ dirtyArea(): Rect;
2229
+ /** The peers that are live now, one per id. */
2230
+ live(): readonly PresencePeer[];
2231
+ /** When the next live peer goes stale, on the `now` clock, or `undefined` when none is live. */
2232
+ nextExpiry(): number | undefined;
2233
+ }
2234
+ /** The pending fields as `[id, [field, value][]]` pairs, from either shape a host may hold. */
2235
+ export declare function pendingEntries(pending: PresencePending): Array<readonly [string, ReadonlyArray<readonly [string, unknown]>]>;
2236
+ /** The pending fields as a plain record, ready to put on a presence channel as JSON. */
2237
+ export declare function pendingToRecord(pending: ReadonlyMap<string, DraftFields>): Record<string, Record<string, unknown>>;
2238
+ /** Applies a presence affine transform to a world box. */
2239
+ export declare function applyPresenceTransform(box: Rect, transform: PresenceTransform): Rect;
2240
+ /** Reduces uniform translate-only `pending` fields into a single transform, or `undefined` when non-uniform. */
2241
+ export declare function pendingToTransform<T extends CanvasElement>(document: CanvasDocument<T>, pending: PresencePending, tolerance?: number): PresenceTransform | undefined;
2242
+ /** The element with a peer's pending fields applied, by the same rule the draft applies its own. */
2243
+ export declare function previewElement<T extends CanvasElement>(element: T, fields: Iterable<readonly [string, unknown]>): T;
2244
+ /** The peers that are live at `now`, one per id: the most recently seen entry wins. */
2245
+ export declare function livePeers(peers: readonly PresencePeer[], now: number, expireAfterMs?: number): PresencePeer[];
2246
+ /**
2247
+ * Creates a presence layer. Wrap a renderer with it through {@link withPresence}, or paint it from a
2248
+ * host's own `drawOverlay` and union {@link PresenceLayer.claim} into the host's `overlayBounds`.
2249
+ */
2250
+ export declare function createPresenceLayer<T extends CanvasElement>(options: PresenceOptions<T>): PresenceLayer;
2251
+ /**
2252
+ * The host's renderer with a presence layer painted above its own overlay.
2253
+ *
2254
+ * The claim is the host's claim and the layer's together. A host with an overlay but no
2255
+ * `overlayBounds` claims the whole window, and so does the result.
2256
+ */
2257
+ export declare function withPresence<T extends CanvasElement>(host: CanvasRenderer<T>, layer: PresenceLayer): CanvasRenderer<T>;
2258
+ type CanvasProposalKind = "add" | "modify" | "remove";
2259
+ type CanvasProposalStatus = "pending" | "accepted" | "rejected";
2260
+ interface CanvasProposalItem {
2261
+ readonly id: string;
2262
+ readonly groupId?: string | undefined;
2263
+ readonly kind: CanvasProposalKind;
2264
+ readonly status?: CanvasProposalStatus | undefined;
2265
+ readonly bounds: Rect;
2266
+ readonly beforeBounds?: Rect | undefined;
2267
+ readonly label?: string | undefined;
2268
+ readonly colour?: string | undefined;
2269
+ }
2270
+ interface ProposalLayerOptions {
2271
+ readonly items: () => readonly CanvasProposalItem[];
2272
+ readonly camera: () => Camera;
2273
+ readonly colors?: Partial<Record<CanvasProposalKind, string>> | undefined;
2274
+ }
2275
+ interface ProposalLayer {
2276
+ draw(ctx: CanvasRenderingContext2D, camera: Camera): void;
2277
+ area(): Rect;
2278
+ claim(): Rect;
2279
+ dirtyArea(): Rect;
2280
+ hitItem(world: Point): CanvasProposalItem | undefined;
2281
+ hitGroup(world: Point): string | undefined;
2282
+ }
2283
+ /** Creates a ghost diff overlay layer over pending/accepted proposal items. */
2284
+ export declare function createProposalLayer(options: ProposalLayerOptions): ProposalLayer;
2285
+ /** Composes a host renderer with a proposal ghost overlay drawn above host overlays. */
2286
+ export declare function withProposal<T extends CanvasElement>(host: CanvasRenderer<T>, layer: ProposalLayer): CanvasRenderer<T>;
2287
+ /** How a fit is framed. */
2288
+ interface FitCameraOptions {
2289
+ /** Screen pixels of room on every side. Defaults to 0. */
2290
+ readonly padding?: number;
2291
+ /** The furthest out the fit may zoom. Defaults to 0.1. */
2292
+ readonly minScale?: number;
2293
+ /** The furthest in the fit may zoom. Defaults to 1, so a fit never magnifies unless asked to. */
2294
+ readonly maxScale?: number;
2295
+ }
2296
+ /** The union of the boxes, or `undefined` when there are none with area. */
2297
+ export declare function boundsOfElements(elements: Iterable<{
2298
+ readonly bounds: Rect;
2299
+ }>): Rect | undefined;
2300
+ /**
2301
+ * The box every element of a document covers, or `undefined` for an empty document.
2302
+ *
2303
+ * Reads `list(window)`, so a host whose document lives inside a known region can pass it; the
2304
+ * default is the same wide window the session reads its order keys over.
2305
+ */
2306
+ export declare function documentBounds<T extends CanvasElement>(document: CanvasDocument<T>, window?: Rect): Rect | undefined;
2307
+ /**
2308
+ * The camera that shows `bounds` whole and centred in a surface of `viewport` CSS pixels, or
2309
+ * `undefined` when there is nothing to fit or nowhere to fit it.
2310
+ */
2311
+ export declare function fitCamera(bounds: Rect | undefined, viewport: Size, options?: FitCameraOptions): Camera | undefined;
2312
+ /** How the overview maps world units into its own CSS pixels. */
2313
+ interface MinimapLayout {
2314
+ /** The overview's camera: world to overview pixels. */
2315
+ readonly camera: Camera;
2316
+ /** The world box the overview frames: the document's box and the window together. */
2317
+ readonly world: Rect;
2318
+ /** The overview's size in CSS pixels. */
2319
+ readonly size: Size;
2320
+ }
2321
+ /** What {@link drawMinimap} paints with. */
2322
+ interface MinimapStyle {
2323
+ /** The background, or `undefined` to leave the overview transparent. */
2324
+ readonly background?: string;
2325
+ /** One element's fill. Defaults to a light grey. */
2326
+ readonly fill?: string | ((element: CanvasElement) => string);
2327
+ /** The window rectangle's stroke. */
2328
+ readonly window?: string;
2329
+ }
2330
+ /**
2331
+ * The layout that fits the document's box and the main window into an overview of `size` pixels, or
2332
+ * `undefined` for an overview with no area.
2333
+ */
2334
+ export declare function minimapLayout(documentBox: Rect | undefined, window: Rect, size: Size): MinimapLayout | undefined;
2335
+ /**
2336
+ * Paints the overview: the background, one box per element and the window outlined.
2337
+ *
2338
+ * `ctx` is the overview's context with its device pixel ratio already applied, so one unit is one
2339
+ * CSS pixel of the overview. The context's state is restored afterwards.
2340
+ */
2341
+ export declare function drawMinimap<T extends CanvasElement>(ctx: CanvasRenderingContext2D, layout: MinimapLayout, elements: Iterable<T>, window: Rect, style?: MinimapStyle): void;
2342
+ /**
2343
+ * The main-view camera that centres the world point under `point` on the overview, keeping the
2344
+ * main view's scale. `viewport` is the main view's size in CSS pixels.
2345
+ */
2346
+ export declare function minimapCamera(layout: MinimapLayout, point: Point, main: Camera, viewport: Size): Camera;
2347
+ /**
2348
+ * What the memory adapter stores: the engine's three fields, plus whatever the host authored.
2349
+ *
2350
+ * Deliberately a plain intersection with an index signature, and deliberately *not* the
2351
+ * constraint the adapter is declared with: an interface with three named fields cannot
2352
+ * satisfy an index signature, so requiring one would keep a host from declaring its own
2353
+ * element type. The adapter is generic over `CanvasElement`; writing a field adds it.
2354
+ */
2355
+ type MemoryElement = CanvasElement & {
2356
+ readonly [field: string]: unknown;
2357
+ };
2358
+ /** What {@link memoryDocument} takes. */
2359
+ interface MemoryDocumentOptions<T extends CanvasElement> {
2360
+ /** The elements to start with, in any order. */
2361
+ readonly elements?: readonly T[];
2362
+ /**
2363
+ * Whether changes are queued until {@link MemoryDocument.flush} instead of delivering
2364
+ * in the write.
2365
+ *
2366
+ * The default (`false`) notifies synchronously, which is what a local write does. A
2367
+ * remote change in a real document arrives on its own schedule, so a test that models
2368
+ * one turns this on and flushes when it wants the change to land.
2369
+ */
2370
+ readonly deferred?: boolean;
2371
+ }
2372
+ /**
2373
+ * The memory adapter, with the seams a canvas suite needs beyond the port.
2374
+ *
2375
+ * It is a {@link CanvasEditableDocument}: `insert` and `delete` come from there. They are not
2376
+ * on the read port because creating an element is an application action with its own id
2377
+ * policy, and the engine never learns they exist.
2378
+ */
2379
+ interface MemoryDocument<T extends CanvasElement> extends CanvasEditableDocument<T> {
2380
+ /** Delivers every change queued while `deferred` is on. */
2381
+ flush(): void;
2382
+ /** The ids currently stored, ascending by `order` — for assertions, not for the engine. */
2383
+ ids(): readonly string[];
2384
+ /** How many times `list` has been called — the culling cost, as a number. */
2385
+ readonly listCalls: number;
2386
+ }
2387
+ /**
2388
+ * A canvas document backed by a Map.
2389
+ *
2390
+ * `order` is compared with `<` on the stored strings, which is position order for
2391
+ * fractional-index keys and the reason this adapter never parses one. `list` returns a
2392
+ * new array each call; the `readonly` on its return type says a caller must not mutate
2393
+ * it, and the sort is on the fresh array rather than on stored state.
2394
+ */
2395
+ export declare function memoryDocument<T extends CanvasElement>(options?: MemoryDocumentOptions<T>): MemoryDocument<T>;
2396
+ /**
2397
+ * Builds the bitmap target: a canvas of the given pixel size and its 2D context.
2398
+ *
2399
+ * The default touches `globalThis.document`, so a caller without a DOM must supply its own —
2400
+ * a test, a worker, a host that composites several canvases into one buffer.
2401
+ */
2402
+ type BitmapCanvasFactory = (width: number, height: number) => {
2403
+ readonly canvas: HTMLCanvasElement;
2404
+ readonly context: CanvasRenderingContext2D;
2405
+ };
2406
+ /** What {@link renderToBitmap} takes. */
2407
+ interface RenderToBitmapOptions<T extends CanvasElement> {
2408
+ /** The document to render. Read-only: the export never writes. */
2409
+ readonly document: CanvasDocument<T>;
2410
+ /** The host's own paint, one element at a time. The overlay is not drawn. */
2411
+ readonly renderer: CanvasRenderer<T>;
2412
+ /** The world rect to render. Defaults to the union of every element's bounds; an empty or zero-area union throws (pass an explicit rect to draw a blank bitmap). */
2413
+ readonly bounds?: Rect;
2414
+ /** World units of margin round the bounds; 0 by default. */
2415
+ readonly padding?: number;
2416
+ /** Bitmap pixels per world unit; 1 by default. A 2× export is `scale: 2` — the engine's per-axis device-pixel-ratio logic is not part of this path. */
2417
+ readonly scale?: number;
2418
+ /** A CSS colour for the background, painted before any element. `null` (the default) leaves the bitmap transparent. */
2419
+ readonly background?: string | null;
2420
+ /** Builds the canvas and context. Defaults to a fresh `document.createElement("canvas")`. */
2421
+ readonly canvasFactory?: BitmapCanvasFactory;
2422
+ }
2423
+ /** What {@link renderToBitmap} produced. */
2424
+ interface RenderedBitmap {
2425
+ /** A PNG data URL of the whole bitmap. */
2426
+ readonly dataUrl: string;
2427
+ /** The canvas the renderer drew into. */
2428
+ readonly canvas: HTMLCanvasElement;
2429
+ /** The bitmap's width in pixels: `ceil((bounds.width + 2·padding) · scale)`. */
2430
+ readonly width: number;
2431
+ /** The bitmap's height in pixels. */
2432
+ readonly height: number;
2433
+ /**
2434
+ * The camera the renderer was given, and the one the transform encodes:
2435
+ * `bitmap = scale · world + offset`, with the offset placing the bounds' top-left corner at
2436
+ * the padding's edge. A bounds far from the world origin lands on the bitmap all the same.
2437
+ */
2438
+ readonly camera: Camera;
2439
+ }
2440
+ /**
2441
+ * Renders a document to a standalone bitmap and returns its PNG data URL.
2442
+ *
2443
+ * The elements are the document's, drawn in ascending order straight through the host's
2444
+ * renderer — the same `draw` a frame uses, with the camera this function declares, so what an
2445
+ * export shows is what the canvas would have painted at scale 1 over that rect.
2446
+ *
2447
+ * Throws, with the reason named, when the padding or scale is not a usable number, when there
2448
+ * are no bounds with area to draw (an empty document, or a rect that was passed empty), or
2449
+ * when the bitmap would exceed {@link MAX_BACKING_SIDE} on a side — a canvas the browser would
2450
+ * refuse anyway, and failing here beats silently squashing the export to fit.
2451
+ */
2452
+ export declare function renderToBitmap<T extends CanvasElement>(options: RenderToBitmapOptions<T>): RenderedBitmap;
2453
+ /** What {@link renderToSvg} takes. */
2454
+ interface RenderToSvgOptions<T extends CanvasElement> {
2455
+ /** The document to render. Read-only: the export never writes. */
2456
+ readonly document: CanvasDocument<T>;
2457
+ /** The host's own paint, one element at a time, given the SVG context. The overlay is not drawn. */
2458
+ readonly renderer: CanvasRenderer<T>;
2459
+ /** The world rect to render, defaulting and validated as for {@link renderToBitmap}. */
2460
+ readonly bounds?: Rect;
2461
+ /** World units of margin round the bounds; 0 by default. */
2462
+ readonly padding?: number;
2463
+ /** SVG units per world unit; 1 by default. */
2464
+ readonly scale?: number;
2465
+ /** A CSS colour for a background rect under every element. `null` (the default) leaves it transparent. */
2466
+ readonly background?: string | null;
2467
+ /** Answers the context's `measureText`; see {@link SvgContextOptions.measure}. */
2468
+ readonly measure?: MeasureText;
2469
+ /** The URL a drawn image points at; see {@link SvgContextOptions.imageHref}. */
2470
+ readonly imageHref?: (source: CanvasImageSource) => string;
2471
+ /** Prefixes the SVG's ids; see {@link SvgContextOptions.idPrefix}. */
2472
+ readonly idPrefix?: string;
2473
+ }
2474
+ /** What {@link renderToSvg} produced. */
2475
+ interface RenderedSvg {
2476
+ /** The SVG document as markup, with a `0 0 width height` viewBox. */
2477
+ readonly svg: string;
2478
+ /** The SVG's width: the same number {@link renderToBitmap} gives the bitmap for the same options. */
2479
+ readonly width: number;
2480
+ /** The SVG's height. */
2481
+ readonly height: number;
2482
+ /** The camera the renderer was given, as for {@link RenderedBitmap.camera}. */
2483
+ readonly camera: Camera;
2484
+ }
2485
+ /**
2486
+ * Renders a document to a standalone SVG, through the same renderer a frame and the bitmap use.
2487
+ *
2488
+ * The renderer draws into {@link createSvgContext}'s recording context, so each shape has one paint path
2489
+ * for every target. The bounds, padding, scale and background follow {@link renderToBitmap}'s rules, and
2490
+ * the size is the bitmap's, so the two exports of one board line up. There is no side limit, since no
2491
+ * bitmap is allocated. A renderer that reaches for a context member the SVG context does not implement
2492
+ * throws that member's name.
2493
+ */
2494
+ export declare function renderToSvg<T extends CanvasElement>(options: RenderToSvgOptions<T>): RenderedSvg;
2495
+ /** What {@link createSvgContext} takes. */
2496
+ interface SvgContextOptions {
2497
+ /** The SVG's width, in its own units. A shadow's filter region covers the whole picture. */
2498
+ readonly width: number;
2499
+ /** The SVG's height, in its own units. */
2500
+ readonly height: number;
2501
+ /**
2502
+ * Answers `ctx.measureText`. Defaults to a scratch canvas's own `measureText` in the context's font,
2503
+ * which needs a DOM; a caller without one must supply this or a renderer that measures throws.
2504
+ */
2505
+ readonly measure?: MeasureText;
2506
+ /**
2507
+ * The URL an `<image>` points at for a drawn source. Defaults to a PNG data URL of the source (read
2508
+ * through a scratch canvas), so the SVG stands alone; an image the scratch canvas cannot read back
2509
+ * (cross-origin) falls back to its own `src`, which a viewer showing the SVG as an image will not load.
2510
+ */
2511
+ readonly imageHref?: (source: CanvasImageSource) => string;
2512
+ /** Prefixes every `id` in the SVG, so two exports inlined in one page cannot collide. `"canvas-"` by default. */
2513
+ readonly idPrefix?: string;
2514
+ }
2515
+ /** A recording SVG target: the context to draw into, and the SVG drawn so far. */
2516
+ interface SvgCanvas {
2517
+ /** The context to paint through. Only the implemented members exist; any other throws. */
2518
+ readonly context: CanvasRenderingContext2D;
2519
+ readonly width: number;
2520
+ readonly height: number;
2521
+ /** The whole document drawn so far: an `<svg>` root with its size and a `0 0 width height` viewBox. */
2522
+ toSvg(): string;
2523
+ }
2524
+ /**
2525
+ * Creates a recording SVG target of the given size.
2526
+ *
2527
+ * Paint through `context` exactly as through a canvas's 2D context, then read the document with
2528
+ * `toSvg()`. Reading does not end the recording: more paint can follow, and the next `toSvg()` has it.
2529
+ */
2530
+ export declare function createSvgContext(options: SvgContextOptions): SvgCanvas;
2531
+ /** How the image is requested. */
2532
+ interface LoadImageOptions {
2533
+ /**
2534
+ * The CORS mode of the request. Defaults to `anonymous`, and the default is the point of the
2535
+ * option. A cross-origin image drawn without CORS taints the canvas, and the next `toDataURL`
2536
+ * then throws a SecurityError, which breaks an export with no visible failure. With `anonymous`
2537
+ * a server that sends no CORS headers fails to load instead: the placeholder stays, the promise
2538
+ * resolves `undefined`, and the export still works. The cost is that such third-party images are
2539
+ * unavailable, so a host needs a local-file entry point. `data:` URLs are unaffected.
2540
+ *
2541
+ * There is no option to skip CORS. A request that would taint the canvas is not offered.
2542
+ */
2543
+ readonly crossOrigin?: "anonymous" | "use-credentials";
2544
+ }
2545
+ /**
2546
+ * Decodes an image URL into an `ImageBitmap`, or resolves `undefined` when it cannot.
2547
+ *
2548
+ * The bitmap is the decoded pixels, which is what a canvas draws and exports. The function resolves
2549
+ * `undefined`, and never rejects, when any of these holds: the request fails (`onerror`), decoding
2550
+ * fails, the bitmap cannot be created, or the environment has no `Image`, no `createImageBitmap`, or
2551
+ * an `Image` without `decode` (jsdom and Node have none of these). Resolving rather than rejecting is
2552
+ * deliberate: the host draws its placeholder for an absent bitmap, so a failure is a state, not an error.
2553
+ *
2554
+ * The CORS mode is set before `src`, because setting `src` starts the request and the mode is part of
2555
+ * it. See {@link LoadImageOptions.crossOrigin} for why it defaults to `anonymous`.
2556
+ */
2557
+ export declare function loadImageBitmap(src: string, options?: LoadImageOptions): Promise<ImageBitmap | undefined>;
2558
+ interface CanvasLease {
2559
+ readonly actorId: string;
2560
+ readonly expiresAt: number;
2561
+ }
2562
+ type CanvasCollabOp<T extends CanvasElement = CanvasElement> = {
2563
+ readonly op: "insert";
2564
+ readonly element: T;
2565
+ } | {
2566
+ readonly op: "set";
2567
+ readonly id: string;
2568
+ readonly field: string;
2569
+ readonly value: unknown;
2570
+ readonly expected?: unknown;
2571
+ } | {
2572
+ readonly op: "delete";
2573
+ readonly id: string;
2574
+ };
2575
+ interface CanvasCollabConflict {
2576
+ readonly id: string;
2577
+ readonly holder: string;
2578
+ readonly field?: string | undefined;
2579
+ readonly reason?: "lease" | "stale" | undefined;
2580
+ }
2581
+ interface CanvasLeaseResult {
2582
+ readonly ok: boolean;
2583
+ readonly leased: readonly string[];
2584
+ readonly conflicts: readonly CanvasCollabConflict[];
2585
+ }
2586
+ interface CanvasCollabTxOptions {
2587
+ readonly bypassLease?: boolean | undefined;
2588
+ }
2589
+ interface CanvasCollabTxResult {
2590
+ readonly ok: boolean;
2591
+ readonly applied: number;
2592
+ readonly conflicts: readonly CanvasCollabConflict[];
2593
+ readonly notifiedHolders?: readonly string[] | undefined;
2594
+ }
2595
+ interface CanvasSelectiveUndoResult {
2596
+ readonly ok: boolean;
2597
+ readonly reverted: number;
2598
+ readonly skipped: readonly {
2599
+ readonly id: string;
2600
+ readonly field?: string | undefined;
2601
+ }[];
2602
+ }
2603
+ interface CanvasRegionQueryOptions<T extends CanvasElement = CanvasElement> {
2604
+ readonly limit?: number | undefined;
2605
+ readonly filter?: ((element: T) => boolean) | undefined;
2606
+ }
2607
+ interface CanvasRegionQueryResult {
2608
+ readonly total: number;
2609
+ readonly truncated: boolean;
2610
+ readonly items: readonly {
2611
+ readonly id: string;
2612
+ readonly bounds: Rect;
2613
+ readonly order: string;
2614
+ readonly label?: string | undefined;
2615
+ }[];
2616
+ }
2617
+ interface CanvasCollabHubOptions<T extends CanvasElement = CanvasElement> {
2618
+ readonly document: CanvasEditableDocument<T>;
2619
+ readonly now?: (() => number) | undefined;
2620
+ readonly defaultLeaseMs?: number | undefined;
2621
+ readonly describe?: ((element: T) => string) | undefined;
2622
+ }
2623
+ interface CanvasCollabHub<T extends CanvasElement = CanvasElement> {
2624
+ acquireLease(actorId: string, ids: readonly string[], ttlMs?: number): CanvasLeaseResult;
2625
+ releaseLease(actorId: string, ids?: readonly string[]): void;
2626
+ leaseOf(id: string): CanvasLease | undefined;
2627
+ activeLeases(): ReadonlyMap<string, CanvasLease>;
2628
+ transact(actorId: string, ops: readonly CanvasCollabOp<T>[], options?: CanvasCollabTxOptions): CanvasCollabTxResult;
2629
+ undo(actorId: string): boolean;
2630
+ selectiveUndo(actorId: string): CanvasSelectiveUndoResult;
2631
+ redo(actorId: string): boolean;
2632
+ queryRegion(rect: Rect, options?: CanvasRegionQueryOptions<T>): CanvasRegionQueryResult;
2633
+ }
2634
+ /** Creates a multi-actor coordination hub over a canvas document. */
2635
+ export declare function createCanvasCollabHub<T extends CanvasElement = CanvasElement>(options: CanvasCollabHubOptions<T>): CanvasCollabHub<T>;
2636
+ /**
2637
+ * One agent tool: core's `AgentToolSpec`, declared structurally so a host passes
2638
+ * these straight to `createAgent().registerTools` without this package importing core.
2639
+ */
2640
+ interface CanvasAgentTool {
2641
+ readonly name: string;
2642
+ readonly description: string;
2643
+ readonly inputSchema: Record<string, unknown>;
2644
+ readonly annotations?: Record<string, boolean>;
2645
+ readonly execute?: (input: Record<string, unknown>, context?: {
2646
+ readonly signal?: AbortSignal;
2647
+ }) => unknown;
2648
+ }
2649
+ /** Creates WebMCP-compatible agent tool descriptors bound to a canvas session and optional collaboration hub. */
2650
+ export declare function canvasAgentTools<T extends CanvasElement>(session: CanvasSession<T>, collab?: {
2651
+ readonly hub: CanvasCollabHub<T>;
2652
+ readonly actorId: string;
2653
+ }): readonly CanvasAgentTool[];
2654
+ export type { AccessibleNode, AlignMode, ArrangeMode, BitmapCanvasFactory, Camera, CameraChange, CameraReason, CanvasAgentTool, CanvasAsyncEngineOptions, CanvasAtlasRegion, CanvasBackendAttempt, CanvasBackendInfo, CanvasBackendKind, CanvasBackendOptions, CanvasBackendPreference, CanvasChange, CanvasClipboard, CanvasCollabConflict, CanvasCollabHub, CanvasCollabHubOptions, CanvasCollabOp, CanvasCollabTxOptions, CanvasCollabTxResult, CanvasConnectorFields, CanvasDocument, CanvasEditableDocument, CanvasElement, CanvasEngine, CanvasEngineOptions, CanvasFrame, CanvasGpuAtlas, CanvasGpuBatch, CanvasGpuColor, CanvasGpuEncoder, CanvasImageCrop, CanvasImageFilter, CanvasImageMask, CanvasImageStyle, CanvasKeyEvent, CanvasLease, CanvasLeaseResult, CanvasPointerEvent, CanvasProposalItem, CanvasProposalKind, CanvasProposalStatus, CanvasRegionQueryOptions, CanvasRegionQueryResult, CanvasRenderBackend, CanvasRenderFrame, CanvasRenderer, CanvasRotation, CanvasSelectiveUndoResult, CanvasSession, CanvasSessionOptions, CanvasShadow, CanvasSizing, CanvasSizingOptions, CanvasStructure, CanvasStyle, CanvasSync, CanvasTextEditor, CanvasTextEditorOptions, CanvasTextStyle, CanvasTool, CanvasToolCore, CanvasToolRegistry, ClampCameraOptions, ClipboardReferences, ConnectorAnchor, ConnectorAnchors, ConnectorArrow, ConnectorGeometry, ConnectorPort, ConnectorPredicate, ConnectorRouting, ContainerKind, DefaultToolRegistration, DeriveConnectorsOptions, DerivedConnectors, DirtyBatch, DirtyOptions, DraftDocument, DraftDocumentOptions, DraftFields, ElbowAvoidBudget, ElementTraits, FitCameraOptions, FitOptions, GeometryField, GestureConfig, HandleTarget, HitTarget, ImageFit, InkOutline, InkPoint, InkStyle, KeyInput, LoadImageOptions, MeasureText, MemoryDocument, MemoryDocumentOptions, MemoryElement, MinimapLayout, MinimapStyle, PanMode, PinchReading, Placement, Point, PointerLike, PortSnap, PresenceLayer, PresenceOptions, PresencePeer, PresencePending, PresenceTransform, ProposalLayer, ProposalLayerOptions, Rect, RenderToBitmapOptions, RenderToSvgOptions, RenderedBitmap, RenderedSvg, ResizeHandle, ResizeOptions, RotationView, SelectionView, Size, SnapGuide, SnapOptions, SnapResult, SnapView, StackEntry, StrokeOutlineOptions, StructureOptions, StructureView, SurfaceBox, SurfaceSize, SvgCanvas, SvgContextOptions, TextFitMode, TextFitOptions, TextFitResult, TextLayoutOptions, TextLine, ToolContext, ToolEngine, ToolFactory, ToolIntent, ToolRegistration, ToolView, TurnedFrame, WheelInput };