@tioniq/sceniq 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,1627 @@
1
+ import { S as Scene, a as Surface, A as AnimationInterpolator, F as FrameScheduler } from './scene-Dd7ExNOl.cjs';
2
+ export { B as BounceInterpolator, C as Camera, b as CameraAnimationOptions, c as CameraOptions, d as CameraPadding, e as CameraZoomAnimationOptions, f as CreateLayerOptions, E as EaseInInterpolator, g as EaseInOutInterpolator, h as EaseOutInterpolator, i as FitBoundsOptions, j as FrameInfo, k as FrameLayerInfo, l as FrameSchedulerOptions, m as FrameSurfaceInfo, K as KeyboardObserveEvent, n as KeyboardObserver, L as Layer, o as LayerOptions, p as LinearInterpolator, O as OvershootInterpolator, q as SceneExportOptions, r as SceneOptions, s as SurfaceCreateOptions, t as SurfaceOptions, Z as ZoomData, u as ZoomInterceptor, v as animationInterpolators, w as createMinMaxZoomInterceptor, x as defaultScheduler } from './scene-Dd7ExNOl.cjs';
3
+ import { IDisposable, Disposiq } from '@tioniq/disposiq';
4
+ import { Var, VarOrVal, IVary, EventObserver } from '@tioniq/eventiq';
5
+ import { P as Point, a as PointerObserveEvent, W as WheelObserveEvent, V as View, b as ViewOptions, c as ViewBox, R as RectBounds, D as DrawState, H as HitTestContext, S as Size, d as SubscribedResult, L as LayoutContext, e as PointerActionEvent, f as Layout, g as DrawableContent, h as Padding, i as LayoutOptions, j as Drawable } from './rect-bounds-Bd7-7ERA.cjs';
6
+ export { A as AddExternalElementOptions, k as Align, I as Indent, l as IndentOptions, m as LiveObject, n as PointerActionEventType, o as PointerActionTarget, p as PointerKind, q as PointerObserver, r as PointerObserverOptions, s as ShouldDrawContext, t as SizeLike, u as SymmetricIndent, v as ViewClickEvent, w as ViewSize, x as createPointerActionEvent, y as inverseRotateScale, z as retargetDrawState, B as updateOptions } from './rect-bounds-Bd7-7ERA.cjs';
7
+ import { C as Color } from './color-IY199Sua.cjs';
8
+
9
+ /**
10
+ * Lays every view out again and repaints every layer on the next frame, and makes text views measure
11
+ * again. Every {@link Scene} calls it when the document finishes loading fonts; call it yourself after
12
+ * changing anything else layouts depend on without a variable.
13
+ */
14
+ declare function relayoutAllViews(): void;
15
+
16
+ /** Frame statistics over a recent window; see {@link FrameStatsMonitor}. */
17
+ interface FrameStats {
18
+ /** Frames drawn per second over the window; 0 while the scene is idle. */
19
+ readonly fps: number;
20
+ /** The average time a frame took to draw, in milliseconds (0 with no frames). */
21
+ readonly frameMs: number;
22
+ /** The longest frame in the window, in milliseconds. */
23
+ readonly maxFrameMs: number;
24
+ /** Frames drawn since the monitor started. */
25
+ readonly frames: number;
26
+ /** The layers drawn again in the window, by name, most often first. */
27
+ readonly redrawnLayers: readonly string[];
28
+ }
29
+ interface FrameStatsOptions {
30
+ /** How often {@link FrameStatsMonitor.stats} is updated, in milliseconds. Default 500. */
31
+ readonly interval?: number;
32
+ /** The window the figures cover, in milliseconds. Default 1000. */
33
+ readonly window?: number;
34
+ /** The clock. Default `performance.now`. */
35
+ readonly now?: () => number;
36
+ /** Starts the timer. Default `setInterval`; tests pass their own. */
37
+ readonly setInterval?: (callback: () => void, ms: number) => unknown;
38
+ readonly clearInterval?: (handle: unknown) => void;
39
+ }
40
+ /**
41
+ * Collects a scene's {@link Scene.onFrame} into figures for a readout: frames per second, frame time,
42
+ * the slowest frame and which layers redrew. {@link stats} is a variable updated on a timer, not per
43
+ * frame, so it can be shown anywhere (in the page, or in the scene itself) without making frames of its
44
+ * own: an idle scene stays at 0 fps and the variable stops changing.
45
+ *
46
+ * ```ts
47
+ * const monitor = new FrameStatsMonitor(scene)
48
+ * monitor.stats.subscribe(s => (readout.textContent = `${s.fps} fps · ${s.frameMs.toFixed(1)} ms · ${s.redrawnLayers.join(", ")}`))
49
+ * // later: monitor.dispose()
50
+ * ```
51
+ */
52
+ declare class FrameStatsMonitor implements IDisposable {
53
+ private readonly _stats;
54
+ private readonly _frames;
55
+ private readonly _now;
56
+ private readonly _window;
57
+ private readonly _subscription;
58
+ private readonly _timer;
59
+ private readonly _clearInterval;
60
+ private _count;
61
+ constructor(scene: Scene, options?: FrameStatsOptions);
62
+ /** The latest figures; changes at most once per interval, and only when a figure changed. */
63
+ get stats(): Var<FrameStats>;
64
+ /** Recomputes {@link stats} now (the timer calls this). */
65
+ update(): void;
66
+ dispose(): void;
67
+ private _record;
68
+ }
69
+
70
+ interface TimeSlicedQueueOptions {
71
+ /** Longest stretch of queued work run without yielding to the browser. */
72
+ budgetMs?: number;
73
+ now?: () => number;
74
+ schedule?: (callback: () => void) => void;
75
+ /** While true the queue drains in one go: there is no frame to keep responsive. */
76
+ isHidden?: () => boolean;
77
+ }
78
+ /**
79
+ * Runs view-building tasks so that one synchronous burst never blocks the main thread for longer
80
+ * than `budgetMs`. A task runs immediately while the current burst is within budget (small updates
81
+ * look exactly as before); once the budget is spent, the rest of the burst is queued and drained in
82
+ * budget-sized slices on later tasks, in FIFO order.
83
+ */
84
+ declare class TimeSlicedQueue implements IDisposable {
85
+ private readonly _budgetMs;
86
+ private readonly _now;
87
+ private readonly _schedule;
88
+ private readonly _isHidden;
89
+ private _pending;
90
+ private _head;
91
+ private _burstStart;
92
+ private _drainScheduled;
93
+ private _disposed;
94
+ constructor(options?: TimeSlicedQueueOptions);
95
+ get pendingCount(): number;
96
+ run(task: () => IDisposable): Disposiq;
97
+ dispose(): void;
98
+ private _withinBurstBudget;
99
+ private _scheduleDrain;
100
+ private _drain;
101
+ private _execute;
102
+ }
103
+
104
+ /** How two pointers moved between two moments, as a zoom about a point plus a pan. */
105
+ interface PinchStep {
106
+ /** The factor the distance between the pointers changed by. 1 when it did not, or cannot be told. */
107
+ readonly scale: number;
108
+ /** The midpoint of the pointers before the step: the point that stays put while zooming. */
109
+ readonly anchor: Point;
110
+ /** How far the midpoint moved. */
111
+ readonly translation: Point;
112
+ }
113
+ /**
114
+ * The zoom and pan that carry the pair of points `(fromA, fromB)` onto `(toA, toB)`: zooming by
115
+ * `scale` about `anchor`, then panning by `translation`, keeps the content under both pointers.
116
+ * All points are in the same (screen) coordinates.
117
+ */
118
+ declare function pinchStep(fromA: Point, fromB: Point, toA: Point, toB: Point): PinchStep;
119
+ interface WheelZoomOptions {
120
+ /** Zoom per pixel of wheel delta, as a power of two: the zoom is `2^(-deltaY * speed)`. Default 0.002. */
121
+ readonly speed?: number;
122
+ /**
123
+ * The multiplier applied to trackpad pinches. Browsers report a pinch as a Ctrl+wheel with small,
124
+ * fractional pixel deltas, much smaller than a mouse wheel's notches. Default 10.
125
+ */
126
+ readonly pinchBoost?: number;
127
+ }
128
+ /** A wheel delta in pixels, whatever its `deltaMode`. */
129
+ declare function wheelDeltaPixels(delta: number, deltaMode: number): number;
130
+ /**
131
+ * Whether a wheel event looks like a trackpad pinch: Ctrl held, pixel deltas, and a fractional
132
+ * delta, which a mouse wheel does not produce.
133
+ */
134
+ declare function isTrackpadPinch(event: {
135
+ ctrlKey: boolean;
136
+ deltaMode: number;
137
+ delta: Point;
138
+ }): boolean;
139
+ /** The zoom factor for a wheel event: above 1 zooms in (wheel up), below 1 zooms out. */
140
+ declare function wheelZoomFactor(event: {
141
+ ctrlKey: boolean;
142
+ deltaMode: number;
143
+ delta: Point;
144
+ }, options?: WheelZoomOptions): number;
145
+
146
+ type WheelAction = "pan" | "zoom" | "none";
147
+ interface ZoomPanOptions {
148
+ /** Whether dragging pans. Default true. */
149
+ readonly pan?: boolean;
150
+ /** Return false to leave a press to someone else (for example, a press on a draggable node). */
151
+ readonly shouldPanStart?: (event: PointerObserveEvent) => boolean;
152
+ /** What the plain wheel does. Default `"pan"` (Shift swaps the axes); `"zoom"` zooms about the pointer. */
153
+ readonly wheel?: WheelAction;
154
+ /** What the wheel does with Ctrl or Meta held, which is also how browsers report trackpad pinches. Default `"zoom"`. */
155
+ readonly ctrlWheel?: WheelAction;
156
+ /** Fine-tunes wheel zooming. */
157
+ readonly wheelZoom?: WheelZoomOptions;
158
+ /** False leaves a wheel event to someone else, e.g. a minimap scrolled under the pointer. */
159
+ readonly shouldHandleWheel?: (event: WheelObserveEvent) => boolean;
160
+ /** Whether two pointers pinch-zoom and pan. Default true. */
161
+ readonly pinch?: boolean;
162
+ /** Whether `+`/`=` and `-`/`_` zoom in and out about the centre. Default true. */
163
+ readonly keys?: boolean;
164
+ /** The smallest zoom the controls (and anything else zooming the camera) may reach. */
165
+ readonly minZoom?: number;
166
+ /** The largest zoom the controls (and anything else zooming the camera) may reach. */
167
+ readonly maxZoom?: number;
168
+ /**
169
+ * Kinetic panning: a drag released while moving glides on and slows down. True for the defaults, or
170
+ * `timeConstant` (ms for the speed to fall to about a third, default 325) and `minSpeed` (CSS pixels
171
+ * per millisecond below which a release does not glide, default 0.1). Default off.
172
+ */
173
+ readonly inertia?: boolean | {
174
+ readonly timeConstant?: number;
175
+ readonly minSpeed?: number;
176
+ };
177
+ /**
178
+ * Double-click or double-tap zooms in about the pointer, animated; with Shift it zooms out. True for
179
+ * a factor of 2, or `factor` and `duration` (ms, default 250). Default off.
180
+ *
181
+ * While it is on, the scene holds views' clicks back for a moment (see `Scene.clickDelay`) so that a
182
+ * double-click only zooms and does not also click what is under the pointer twice. `suppressClicks:
183
+ * false` delivers clicks at once instead.
184
+ */
185
+ readonly doubleClickZoom?: boolean | {
186
+ readonly factor?: number;
187
+ readonly duration?: number;
188
+ readonly suppressClicks?: boolean;
189
+ };
190
+ /** The clock, in milliseconds. Default `performance.now`; tests pass their own. */
191
+ readonly now?: () => number;
192
+ }
193
+ /**
194
+ * Wires a scene's input to pan and zoom a surface's camera: drag to pan (continuing outside the
195
+ * canvas, thanks to pointer capture), two-finger pinch to zoom and pan, the wheel to pan or zoom, and
196
+ * the `+`/`-` keys; optionally kinetic panning (`inertia`) and double-click zoom (`doubleClickZoom`).
197
+ * The wheel and keys are marked handled (`preventDefault`) only when they act. Touching the view stops
198
+ * a camera animation or a glide. Disposing the result removes it all.
199
+ */
200
+ declare function attachZoomPan(scene: Scene, surface: Surface, options?: ZoomPanOptions): IDisposable;
201
+
202
+ type FontStyle = "" | "normal" | "italic" | FontStyleOblique;
203
+ type FontStyleOblique = "oblique" | `oblique ${number}${"deg" | "grad" | "rad" | "turn"}`;
204
+ type FontWeight = "" | FontWeightThin | FontWeightExtraLight | FontWeightLight | FontWeightNormal | FontWeightMedium | FontWeightSemiBold | FontWeightBold | FontWeightExtraBold | FontWeightBlack | "bolder" | "lighter";
205
+ type FontWeightThin = 100;
206
+ type FontWeightExtraLight = 200;
207
+ type FontWeightLight = 300;
208
+ type FontWeightNormal = "normal" | 400;
209
+ type FontWeightMedium = 500;
210
+ type FontWeightSemiBold = 600;
211
+ type FontWeightBold = "bold" | 700;
212
+ type FontWeightExtraBold = 800;
213
+ type FontWeightBlack = 900;
214
+ type FontSizeAbsolute = "xx-small" | "x-small" | "small" | "medium" | "large" | "x-large" | "xx-large" | "xxx-large";
215
+ type FontSizeRelative = "smaller" | "larger";
216
+ type FontSizeLength = `${number}px` | `${number}em` | `${number}ex` | `${number}ch` | `${number}rem` | `${number}vw` | `${number}vh` | `${number}vmin` | `${number}vmax`;
217
+ type FontSizePercent = `${number}%`;
218
+ type FontSizeNumber = number;
219
+ type FontSize = FontSizeAbsolute | FontSizeRelative | FontSizeLength | FontSizePercent | FontSizeNumber;
220
+ type FontLineHeightNormal = "normal";
221
+ /** Unitless values: use this number multiplied by the element's font size */
222
+ type FontLineHeightUnitless = number;
223
+ type FontLineHeightLength = `${number}em` | `${number}ex` | `${number}ch` | `${number}rem` | `${number}vw` | `${number}vh` | `${number}vmin` | `${number}vmax`;
224
+ type FontLineHeightPercent = `${number}%`;
225
+ type FontLineHeight = FontLineHeightNormal | FontLineHeightUnitless | FontLineHeightLength | FontLineHeightPercent;
226
+ type FontFamilyGeneric = "serif" | "sans-serif" | "monospace" | "cursive" | "fantasy" | "system-ui" | "ui-serif" | "ui-sans-serif" | "ui-monospace" | "ui-rounded" | "emoji" | "math" | "fangsong";
227
+ type FontFamilyValue = FontFamilyGeneric | string;
228
+ type FontFamily = FontFamilyValue | FontFamilyValue[];
229
+ interface TextFont {
230
+ family?: FontFamily;
231
+ size?: FontSize;
232
+ style?: FontStyle;
233
+ weight?: FontWeight;
234
+ lineHeight?: number;
235
+ stretch?: CanvasFontStretch;
236
+ variantCaps?: CanvasFontVariantCaps;
237
+ kerning?: CanvasFontKerning;
238
+ }
239
+ interface TextFontOptions {
240
+ family?: VarOrVal<FontFamily | undefined | null>;
241
+ size?: VarOrVal<FontSize | undefined | null>;
242
+ style?: VarOrVal<FontStyle | undefined | null>;
243
+ weight?: VarOrVal<FontWeight | undefined | null>;
244
+ lineHeight?: VarOrVal<number | undefined | null>;
245
+ stretch?: VarOrVal<CanvasFontStretch | undefined | null>;
246
+ variantCaps?: VarOrVal<CanvasFontVariantCaps | undefined | null>;
247
+ kerning?: VarOrVal<CanvasFontKerning | undefined | null>;
248
+ }
249
+
250
+ /** Measures the advance width of a string in the current font. */
251
+ type MeasureText = (text: string) => number;
252
+ interface TextLine {
253
+ /** The line's text, without the spaces it was broken at. */
254
+ readonly text: string;
255
+ /** Its width as measured when wrapping. */
256
+ readonly width: number;
257
+ }
258
+ interface WrapTextOptions {
259
+ /** Breaks a word wider than the line between its characters instead of letting it overflow. Default true. */
260
+ readonly breakLongWords?: boolean;
261
+ /** Lines past this many are dropped, and the last kept line ends in `ellipsis`. */
262
+ readonly maxLines?: number | null;
263
+ /**
264
+ * Appended where text is cut: after the last of `maxLines`, and to a line that still does not fit
265
+ * (a single character wider than the line, or any long word with `breakLongWords` off). Null cuts
266
+ * nothing and lets such lines overflow. Default `"…"`.
267
+ */
268
+ readonly ellipsis?: string | null;
269
+ /** The locale word boundaries are found for. Default: the runtime's. */
270
+ readonly locale?: string;
271
+ /** Use `Intl.Segmenter` where available (default). False forces the whitespace fallback. */
272
+ readonly useSegmenter?: boolean;
273
+ }
274
+ interface WrappedText {
275
+ readonly lines: TextLine[];
276
+ /** The widest line. */
277
+ readonly width: number;
278
+ /** Whether anything was cut off or ellipsized. */
279
+ readonly truncated: boolean;
280
+ }
281
+ /**
282
+ * Splits `text` into lines no wider than `maxWidth`. Lines break at `\n` and between words: word
283
+ * boundaries come from `Intl.Segmenter`, so text without spaces (Chinese, Japanese, Thai) wraps too;
284
+ * without it, at whitespace and between CJK characters. A word wider than a line is broken between
285
+ * graphemes, and text cut off by `maxLines` ends in an ellipsis.
286
+ */
287
+ declare function wrapText(text: string, maxWidth: number, measure: MeasureText, options?: WrapTextOptions): WrappedText;
288
+ /**
289
+ * `text` cut to fit `maxWidth` with `ellipsis` at its end. With `endsInEllipsis`, `text` already ends
290
+ * in the ellipsis, which is kept.
291
+ */
292
+ declare function truncateText(text: string, maxWidth: number, measure: MeasureText, ellipsis: string, endsInEllipsis?: boolean): string;
293
+ /** The user-perceived characters of `text`, so an emoji or an accented letter is never split. */
294
+ declare function splitGraphemes(text: string): string[];
295
+
296
+ /** `start` and `end` follow `direction`: `start` is the left in left-to-right text and the right in right-to-left. */
297
+ type TextAlignment = "left" | "center" | "right" | "start" | "end";
298
+ type TextDirection = "ltr" | "rtl" | "inherit";
299
+ interface TextViewOptions extends ViewOptions {
300
+ readonly text: VarOrVal<string>;
301
+ readonly font?: TextFontOptions;
302
+ /** The fill colour. Default black. */
303
+ readonly color?: VarOrVal<string | Color | null>;
304
+ readonly align?: VarOrVal<TextAlignment>;
305
+ /**
306
+ * The base direction for bidirectional text: `"rtl"` for Hebrew or Arabic paragraphs. `"inherit"`
307
+ * takes the canvas element's CSS direction. Default `"inherit"`.
308
+ */
309
+ readonly direction?: VarOrVal<TextDirection>;
310
+ /** Lines past this many are dropped and the last one ends in the ellipsis. */
311
+ readonly maxLines?: VarOrVal<number | null>;
312
+ /**
313
+ * What marks text cut off by `maxLines` or too wide for its line: a string, `true` for "…"
314
+ * (default), or `false` to cut nothing and let it overflow. Text is never squashed to fit.
315
+ */
316
+ readonly ellipsis?: VarOrVal<string | boolean>;
317
+ /** Breaks a word wider than the line between its characters. Default true. */
318
+ readonly breakLongWords?: boolean;
319
+ /** The locale for finding word boundaries. Default: the runtime's. */
320
+ readonly locale?: string;
321
+ }
322
+ /**
323
+ * Text that wraps to the width it is given. Lines break between words (found with
324
+ * `Intl.Segmenter`, so scripts without spaces wrap too), long words break between characters, and
325
+ * text that does not fit ends in an ellipsis. Layouts are cached per text, font and width.
326
+ */
327
+ declare class TextView extends View {
328
+ private readonly _text;
329
+ private readonly _font;
330
+ private readonly _color;
331
+ private readonly _align;
332
+ private readonly _direction;
333
+ private readonly _maxLines;
334
+ private readonly _ellipsis;
335
+ private readonly _breakLongWords;
336
+ private readonly _locale;
337
+ /** The last two layouts: one for the width the view is measured at, one for the width it is drawn at. */
338
+ private _layouts;
339
+ constructor(options: TextViewOptions);
340
+ get font(): TextFont;
341
+ set font(value: TextFont);
342
+ get color(): Var<string | null>;
343
+ set color(value: string | Color | null | undefined);
344
+ get text(): Var<string>;
345
+ set text(value: string);
346
+ get align(): IVary<TextAlignment>;
347
+ set align(value: TextAlignment);
348
+ get direction(): IVary<TextDirection>;
349
+ set direction(value: TextDirection);
350
+ get maxLines(): IVary<number | null>;
351
+ set maxLines(value: number | null);
352
+ /** The lines the text is laid out in at `maxWidth`, measured as when drawn. */
353
+ measureLines(maxWidth?: number): ReadonlyArray<TextLine>;
354
+ protected doGetDrawBounds(measuredBox: ViewBox): RectBounds;
355
+ /**
356
+ * The text split into lines at `maxWidth`, measured once per text, font and width rather than on
357
+ * every frame.
358
+ */
359
+ private _layout;
360
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
361
+ protected hitTest(_context: HitTestContext): boolean;
362
+ }
363
+
364
+ type StrokeAlignment = "inner" | "center" | "outer";
365
+ interface RoundedRectangleDrawableOptions extends ViewOptions {
366
+ readonly radius?: VarOrVal<RectRadius>;
367
+ readonly lineWidth?: number;
368
+ readonly strokeColor?: VarOrVal<string | Color | null>;
369
+ readonly fillColor?: VarOrVal<string | Color | null>;
370
+ readonly strokeAlignment?: StrokeAlignment;
371
+ readonly lineCap?: CanvasLineCap;
372
+ readonly lineJoin?: CanvasLineJoin;
373
+ readonly lineDash?: number[];
374
+ readonly lineDashOffset?: number;
375
+ /**
376
+ * Whether the pointer hits the shape (inside its rounded corners), so it gets hover, the hover scale
377
+ * and the hover cursor, and clicks. Default: true when `onClick` or `hoverCursor` is given, otherwise
378
+ * false, so a rectangle used as a background leaves the pointer to the layout it is in.
379
+ */
380
+ readonly interactive?: boolean;
381
+ }
382
+ type RectRadius = number | Partial<RectRadiusCorners>;
383
+ interface RectRadiusCorners {
384
+ readonly topLeft: number;
385
+ readonly topRight: number;
386
+ readonly bottomLeft: number;
387
+ readonly bottomRight: number;
388
+ }
389
+ /**
390
+ * A rectangle with optionally rounded corners, filled and/or stroked; a circle when the radius is
391
+ * half its size. Colours and the radius may be variables. As a layout's background it leaves the
392
+ * pointer alone; with `onClick`, `hoverCursor` or `interactive` it takes hover and clicks inside its
393
+ * rounded shape.
394
+ */
395
+ declare class RoundedRectangleView extends View {
396
+ private readonly _fillColor;
397
+ private readonly _strokeColor;
398
+ private _lineWidth?;
399
+ private _lineCap?;
400
+ private _lineJoin?;
401
+ private _lineDash?;
402
+ private _lineDashOffset?;
403
+ private _strokeAlignment?;
404
+ private readonly _radius;
405
+ private readonly _interactive;
406
+ constructor(options?: RoundedRectangleDrawableOptions);
407
+ set bounds(value: RectBounds);
408
+ get radius(): Var<RectRadiusCorners>;
409
+ set radius(value: RectRadius);
410
+ get lineWidth(): number | undefined;
411
+ set lineWidth(value: number | undefined);
412
+ get strokeColor(): Var<string | null>;
413
+ set strokeColor(value: string | undefined);
414
+ get fillColor(): Var<string | null>;
415
+ set fillColor(value: string | null);
416
+ get strokeAlignment(): StrokeAlignment | undefined;
417
+ set strokeAlignment(value: StrokeAlignment | undefined);
418
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
419
+ protected hitTest(context: HitTestContext): boolean;
420
+ }
421
+ declare function getRadius(radius?: RectRadius): RectRadiusCorners;
422
+ /** Whether `(x, y)` lies inside a `width`×`height` rectangle at the origin with rounded corners. */
423
+ declare function insideRoundedRect(x: number, y: number, width: number, height: number, radius: RectRadiusCorners): boolean;
424
+
425
+ /**
426
+ * An image addressed by what it is rather than by where it currently lives.
427
+ *
428
+ * <p>The URL of a stored image is temporary — it is signed, it expires, and it is signed again —
429
+ * while the pixels behind it do not change. Views therefore hold a source, whose {@link key} is
430
+ * stable for as long as the image is, and the decode cache is keyed by that.
431
+ */
432
+ interface ImageSource {
433
+ /** Identity: two sources with the same key are the same pixels. */
434
+ readonly key: string;
435
+ /** URLs to try, in order. The first that loads wins; an empty list means the image is gone. */
436
+ urls(): Promise<(string | null)[]>;
437
+ /** Drops the current URLs, so the next {@link urls} call produces fresh ones. */
438
+ invalidate(): void;
439
+ /**
440
+ * Whether a failed load means the URLs went stale (an expired signature), so fresh ones from
441
+ * {@link urls} after {@link invalidate} are worth one more try. Defaults to {@link isUrlRejection}:
442
+ * HTTP 400, 401 and 403.
443
+ */
444
+ shouldRefresh?(error: unknown): boolean;
445
+ /** Downloads one of the URLs; defaults to the view's `fetch` option, or `fetch` itself. */
446
+ fetch?(url: string, init: {
447
+ signal?: AbortSignal;
448
+ cache: RequestCache;
449
+ }): Promise<Blob>;
450
+ }
451
+ declare function isImageSource(value: unknown): value is ImageSource;
452
+ /** An image that is already a URL, which is its own identity: a new URL is a new image. */
453
+ declare function staticImageSource(url: string, fallbackUrl?: string | null): ImageSource;
454
+
455
+ type ImageFallbacks = (string | null)[];
456
+ /** What an {@link ImageView} can draw as it is: an image element, a bitmap, a canvas or a video frame. */
457
+ type DrawableImage = HTMLImageElement | ImageBitmap | HTMLCanvasElement | OffscreenCanvas | HTMLVideoElement;
458
+ /**
459
+ * What an {@link ImageView} shows: a URL, URLs to try in turn, an {@link ImageSource}, or a drawable
460
+ * image. An image element still loading is shown once it has loaded.
461
+ */
462
+ type ImageContent = string | null | DrawableImage | ImageFallbacks | ImageSource;
463
+ type ImageFit = "cover" | "contain" | "fill" | "none" | "scale-down";
464
+ interface ImageViewOptions extends ViewOptions {
465
+ readonly image?: VarOrVal<ImageContent>;
466
+ /**
467
+ * Corner radius. Accepts a single number (all four corners) or per-corner radii
468
+ * (`{ topLeft, topRight, bottomLeft, bottomRight }`).
469
+ */
470
+ readonly radius?: VarOrVal<RectRadius>;
471
+ readonly fit?: ImageFit;
472
+ readonly onImageLoaded?: (image: ImageBitmap, view: ImageView) => void;
473
+ readonly onImageLoadFailed?: (error: unknown) => void;
474
+ /** Images loaded from a URL are downscaled on decode to fit this size; the aspect ratio is kept. */
475
+ readonly maxDecodeSize?: Size;
476
+ /**
477
+ * Lower downloads sooner. The download waits for one of a few shared slots, which go to the
478
+ * lowest value first, so the images in view are fetched before the rest; it is read again as slots
479
+ * free up, a few times a second, so it can follow the camera. Without it the image is fetched at once.
480
+ */
481
+ readonly loadPriority?: () => number;
482
+ /**
483
+ * Downloads an image URL (for example, to add headers or go through a service worker). Defaults to
484
+ * `fetch(url, { mode: "cors" })`. An {@link ImageSource} with its own `fetch` uses that instead.
485
+ */
486
+ readonly fetch?: ImageFetcher;
487
+ }
488
+ /** Downloads an image; throw an {@link ImageFetchError} for an HTTP failure so its status can be judged. */
489
+ type ImageFetcher = (url: string, init: {
490
+ signal?: AbortSignal;
491
+ cache: RequestCache;
492
+ }) => Promise<Blob>;
493
+ /**
494
+ * An image from a URL, an {@link ImageSource}, a bitmap or an element, drawn to fit its box (`fit`)
495
+ * with optional rounded corners. Downloads go through a shared priority queue that favours images
496
+ * near the middle of the screen, are shared between views of the same URL, are aborted when no view
497
+ * needs them, and are decoded no larger than `maxDecodeSize`.
498
+ */
499
+ declare class ImageView extends View {
500
+ private readonly _image;
501
+ private readonly _imageLoadedCallback?;
502
+ private readonly _imageLoadFailedCallback?;
503
+ private readonly _imageVar;
504
+ private readonly _radius;
505
+ private readonly _fit;
506
+ private readonly _maxDecodeSize;
507
+ private readonly _loadPriority;
508
+ private readonly _fetch;
509
+ constructor(options?: ImageViewOptions);
510
+ protected handleSubscribed(): SubscribedResult;
511
+ /** Shows an image element, a canvas or a video; an image or video still loading once it has loaded. */
512
+ private _showElement;
513
+ private _loadImage;
514
+ private _loadImageSource;
515
+ private _loadImageWithFallbacks;
516
+ get radius(): Var<RectRadiusCorners>;
517
+ /** Like every bound view property, a value set here holds until a bound radius variable changes. */
518
+ set radius(value: RectRadius);
519
+ get fit(): Var<ImageFit>;
520
+ set fit(value: ImageFit);
521
+ /** What the view shows, as given: a URL, URLs, an image source or a drawable image. */
522
+ get image(): Var<ImageContent>;
523
+ /** Shows something else; loaded like the `image` option, and kept when the view is shown again. */
524
+ set image(value: ImageContent);
525
+ /** The image ready to draw: null until it has loaded. */
526
+ get loadedImage(): Var<DrawableImage | null>;
527
+ get imageSize(): Size;
528
+ protected doGetDrawBounds(measuredBox: ViewBox): RectBounds;
529
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
530
+ }
531
+ /**
532
+ * The default {@link ImageSource.shouldRefresh}: an HTTP 400, 401 or 403, which is how a signed URL
533
+ * that expired is refused (S3, for one, answers an expired session token with 400). Fresh URLs may
534
+ * load; a 404 or a server fault would not change, so it is not retried.
535
+ */
536
+ declare function isUrlRejection(error: unknown): boolean;
537
+ /** The HTTP status behind a failed image load, so a caller can tell "expired" from "gone". */
538
+ declare class ImageFetchError extends Error {
539
+ readonly status: number;
540
+ constructor(status: number, url: string);
541
+ }
542
+
543
+ /**
544
+ * One load per key however many callers ask for it. Each caller passes its own signal, and the load
545
+ * itself is aborted only once every caller still waiting for it has aborted, so a view that goes
546
+ * away does not take the picture from another view showing the same image.
547
+ */
548
+ declare class SharedLoads<T> {
549
+ private readonly _pending;
550
+ /** Loads under way. */
551
+ get size(): number;
552
+ /**
553
+ * The load for `key`, started with `start` unless one is already under way. An abort of `signal`
554
+ * rejects this caller with the signal's reason.
555
+ *
556
+ * `priority` (lower sooner, see ImageViewOptions.loadPriority) is this caller's. `start` gets the
557
+ * load's: the lowest of the callers still waiting, and lower than any once a caller with none (one
558
+ * that wants it at once) joins; null when the caller that started it had none, so it runs at once.
559
+ */
560
+ load(key: string, signal: AbortSignal | undefined, priority: (() => number) | null, start: (signal: AbortSignal, priority: (() => number) | null) => Promise<T>): Promise<T>;
561
+ }
562
+
563
+ interface StrokeRectangleViewOptions extends ViewOptions {
564
+ readonly color?: string;
565
+ readonly lineWidth?: number;
566
+ }
567
+ /** The outline of its box. */
568
+ declare class StrokeRectangleView extends View {
569
+ private readonly _color;
570
+ private readonly _lineWidth;
571
+ constructor(options: StrokeRectangleViewOptions);
572
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
573
+ }
574
+
575
+ interface LineViewOptions extends ViewOptions {
576
+ readonly from: VarOrVal<Point>;
577
+ readonly to: VarOrVal<Point>;
578
+ readonly width?: number;
579
+ readonly color?: VarOrVal<string | Color | null>;
580
+ readonly cap?: CanvasLineCap | null;
581
+ }
582
+ /** A straight line from `from` to `to`, both of which may be variables. See {@link PathView} for curves. */
583
+ declare class LineView extends View {
584
+ private readonly _color;
585
+ private readonly _width;
586
+ private readonly _cap;
587
+ private readonly _from;
588
+ private readonly _to;
589
+ constructor(options: LineViewOptions);
590
+ get from(): Var<Point>;
591
+ set from(value: Point);
592
+ get to(): Var<Point>;
593
+ set to(value: Point);
594
+ get color(): Var<string | null>;
595
+ set color(value: Color | string | null);
596
+ get width(): Var<number>;
597
+ set width(value: number);
598
+ get cap(): Var<CanvasLineCap | null>;
599
+ set cap(value: CanvasLineCap | null);
600
+ protected doGetDrawBounds(_measuredBox: ViewBox): RectBounds;
601
+ protected doDraw(context: CanvasRenderingContext2D, _state: DrawState): void;
602
+ }
603
+
604
+ /**
605
+ * One step of a path, as in SVG and the canvas API: `M` starts a subpath, `L` draws a straight line,
606
+ * `Q` a quadratic Bézier with one control point, `C` a cubic Bézier with two, and `Z` closes the
607
+ * subpath. Coordinates are absolute.
608
+ */
609
+ type PathCommand = {
610
+ readonly type: "M";
611
+ readonly to: Point;
612
+ } | {
613
+ readonly type: "L";
614
+ readonly to: Point;
615
+ } | {
616
+ readonly type: "Q";
617
+ readonly control: Point;
618
+ readonly to: Point;
619
+ } | {
620
+ readonly type: "C";
621
+ readonly control1: Point;
622
+ readonly control2: Point;
623
+ readonly to: Point;
624
+ } | {
625
+ readonly type: "Z";
626
+ };
627
+ /** A path through `points` in straight lines. */
628
+ declare function polylinePath(points: ReadonlyArray<Point>, closed?: boolean): PathCommand[];
629
+ /** A quadratic Bézier curve from `from` to `to`, pulled towards `control`. */
630
+ declare function quadraticPath(from: Point, control: Point, to: Point): PathCommand[];
631
+ /** A cubic Bézier curve from `from` to `to`, leaving towards `control1` and arriving from `control2`. */
632
+ declare function cubicPath(from: Point, control1: Point, control2: Point, to: Point): PathCommand[];
633
+ /** Traces `path` on a canvas context (after `beginPath`). */
634
+ declare function tracePath(context: CanvasRenderingContext2D | Path2D | OffscreenCanvasRenderingContext2D, path: ReadonlyArray<PathCommand>): void;
635
+ /**
636
+ * The path as polylines, one per subpath: curves are replaced by `segments` straight pieces each.
637
+ */
638
+ declare function flattenPath(path: ReadonlyArray<PathCommand>, segments?: number): Point[][];
639
+ /** The point at `t` (0 to 1) along a quadratic Bézier. */
640
+ declare function quadraticPoint(p0: Point, p1: Point, p2: Point, t: number): Point;
641
+ /** The point at `t` (0 to 1) along a cubic Bézier. */
642
+ declare function cubicPoint(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point;
643
+ /** The distance from `point` to the segment from `a` to `b`. */
644
+ declare function distanceToSegment(point: Point, a: Point, b: Point): number;
645
+ /** The shortest distance from `point` to the stroke of the flattened path: its centre line. */
646
+ declare function distanceToPolylines(point: Point, polylines: ReadonlyArray<ReadonlyArray<Point>>): number;
647
+ /** The smallest rectangle around the flattened path; zero when the path is empty. */
648
+ declare function polylinesBounds(polylines: ReadonlyArray<ReadonlyArray<Point>>): RectBounds;
649
+ /** Where the path ends and the direction it arrives in (a unit vector); null for a path without length. */
650
+ declare function pathEnd(path: ReadonlyArray<PathCommand>): {
651
+ point: Point;
652
+ direction: Point;
653
+ } | null;
654
+ /** Where the path starts and the direction it leaves in, pointing back out of it (a unit vector). */
655
+ declare function pathStart(path: ReadonlyArray<PathCommand>): {
656
+ point: Point;
657
+ direction: Point;
658
+ } | null;
659
+
660
+ interface ArrowHead {
661
+ /** Length of the head along the path. Default 10 (in the same units as the line width). */
662
+ readonly size?: number;
663
+ /** Half the opening angle, in radians. Default π/7. */
664
+ readonly angle?: number;
665
+ /** A filled triangle (default) or two open strokes. */
666
+ readonly filled?: boolean;
667
+ }
668
+ interface PathViewOptions extends ViewOptions {
669
+ /** The path, in the view's own coordinates (offset by `location`). See {@link polylinePath}, {@link cubicPath}. */
670
+ readonly path: VarOrVal<ReadonlyArray<PathCommand>>;
671
+ readonly strokeColor?: VarOrVal<string | Color | null>;
672
+ /** Fills the path's closed area too. */
673
+ readonly fillColor?: VarOrVal<string | Color | null>;
674
+ /** Stroke width. Default 1. */
675
+ readonly lineWidth?: VarOrVal<number>;
676
+ /** A dash pattern, as for `setLineDash`; null or empty for a solid line. */
677
+ readonly lineDash?: VarOrVal<ReadonlyArray<number> | null>;
678
+ readonly lineDashOffset?: VarOrVal<number>;
679
+ readonly lineCap?: CanvasLineCap;
680
+ readonly lineJoin?: CanvasLineJoin;
681
+ /**
682
+ * Keeps the line width, dashes and arrowheads the same size on screen whatever the zoom: they are
683
+ * then in CSS pixels instead of view units. Default false.
684
+ */
685
+ readonly constantScreenWidth?: boolean;
686
+ /** An arrowhead where the path starts; `true` for the default head. */
687
+ readonly startArrow?: VarOrVal<ArrowHead | boolean | null>;
688
+ /** An arrowhead where the path ends; `true` for the default head. */
689
+ readonly endArrow?: VarOrVal<ArrowHead | boolean | null>;
690
+ /**
691
+ * How far from the stroke's edge a pointer still hits it, in CSS pixels. Default 4. Hit testing
692
+ * measures the distance to the curve, so thin lines are easy to hover and click.
693
+ */
694
+ readonly hitTolerance?: number;
695
+ }
696
+ /**
697
+ * A stroked (and optionally filled) path: polylines and quadratic or cubic Bézier curves, with
698
+ * optional arrowheads and dashes. Its pointer hit area follows the stroke, not the bounding box.
699
+ */
700
+ declare class PathView extends View {
701
+ private readonly _path;
702
+ private readonly _strokeColor;
703
+ private readonly _fillColor;
704
+ private readonly _lineWidth;
705
+ private readonly _lineDash;
706
+ private readonly _lineDashOffset;
707
+ private readonly _startArrow;
708
+ private readonly _endArrow;
709
+ private readonly _lineCap;
710
+ private readonly _lineJoin;
711
+ private readonly _constantScreenWidth;
712
+ private readonly _hitTolerance;
713
+ private _flattened;
714
+ /** World units per CSS pixel at the last layout, for sizes kept constant on screen. */
715
+ private _unitsPerPixel;
716
+ constructor(options: PathViewOptions);
717
+ get path(): Var<ReadonlyArray<PathCommand>>;
718
+ set path(value: ReadonlyArray<PathCommand>);
719
+ get strokeColor(): Var<string | null>;
720
+ set strokeColor(value: string | Color | null);
721
+ get lineWidth(): Var<number>;
722
+ set lineWidth(value: number);
723
+ /** The flattened centre line of the path, as polylines (curves split into straight pieces). */
724
+ get polylines(): ReadonlyArray<ReadonlyArray<Point>>;
725
+ /** Whether `point` (in the view's own coordinates) is within the stroke plus `tolerance` units. */
726
+ isPointOnStroke(point: Point, tolerance?: number): boolean;
727
+ getDrawState(context: LayoutContext): DrawState | null;
728
+ protected doGetDrawBounds(_measuredBox: ViewBox): RectBounds;
729
+ protected doDraw(context: CanvasRenderingContext2D, _state: DrawState): void;
730
+ protected hitSlop(action: PointerActionEvent): number;
731
+ protected hitTest(context: HitTestContext): boolean;
732
+ private _drawArrow;
733
+ private _arrowSize;
734
+ private _effectiveLineWidth;
735
+ private _flatten;
736
+ }
737
+ /** The same class as {@link PathView}, for those who look for curves. */
738
+ declare const CurveView: typeof PathView;
739
+ type CurveView = PathView;
740
+ type CurveViewOptions = PathViewOptions;
741
+
742
+ interface HexagonViewOptions extends ViewOptions {
743
+ readonly fillColor?: VarOrVal<string | Color | null>;
744
+ readonly strokeColor?: VarOrVal<string | Color | null>;
745
+ readonly lineWidth?: number;
746
+ readonly lineJoin?: CanvasLineJoin;
747
+ readonly lineCap?: CanvasLineCap;
748
+ readonly lineDash?: number[];
749
+ readonly cornerRadius?: number;
750
+ readonly orientation?: "flat" | "pointy";
751
+ }
752
+ /** A regular hexagon filling its box, flat- or pointy-topped, with optional rounded corners. */
753
+ declare class HexagonView extends View {
754
+ private readonly _fillColor;
755
+ private readonly _strokeColor;
756
+ private readonly _lineWidth?;
757
+ private readonly _lineJoin?;
758
+ private readonly _lineCap?;
759
+ private readonly _lineDash?;
760
+ private readonly _cornerRadius;
761
+ private readonly _orientation;
762
+ constructor(options: HexagonViewOptions);
763
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
764
+ }
765
+
766
+ interface TriangleViewOptions extends ViewOptions {
767
+ readonly direction: TriangleDirection;
768
+ readonly lineWidth?: number;
769
+ readonly strokeColor?: VarOrVal<string | Color | null>;
770
+ readonly fillColor?: VarOrVal<string | Color | null>;
771
+ readonly strokeAlignment?: StrokeAlignment;
772
+ readonly lineCap?: CanvasLineCap;
773
+ readonly lineJoin?: CanvasLineJoin;
774
+ readonly lineDash?: number[];
775
+ }
776
+ type TriangleDirection = "up" | "down" | "left" | "right";
777
+ /** An isosceles triangle filling its box, pointing up, down, left or right. */
778
+ declare class TriangleView extends View {
779
+ private readonly _fillColor;
780
+ private readonly _direction;
781
+ private readonly _strokeColor;
782
+ private readonly _lineWidth?;
783
+ private readonly _lineCap?;
784
+ private readonly _lineJoin?;
785
+ private readonly _lineDash?;
786
+ constructor(options: TriangleViewOptions);
787
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
788
+ }
789
+
790
+ interface ArrowViewOptions extends ViewOptions {
791
+ from: Point;
792
+ to: Point;
793
+ color?: string;
794
+ lineWidth?: number;
795
+ }
796
+ declare class ArrowView extends View {
797
+ private readonly _from;
798
+ private readonly _to;
799
+ private readonly _color;
800
+ private readonly _lineWidth;
801
+ constructor(options: ArrowViewOptions);
802
+ get from(): Var<Point>;
803
+ set from(value: Point);
804
+ get to(): Var<Point>;
805
+ set to(value: Point);
806
+ protected doGetDrawBounds(_viewBox: ViewBox): RectBounds;
807
+ protected doDraw(context: CanvasRenderingContext2D, _state: DrawState): void;
808
+ }
809
+
810
+ interface ButtonViewOptions extends Pick<ViewOptions, "visible" | "enabled" | "onClick" | "location" | "viewBox" | "size" | "alpha"> {
811
+ /** What the button shows: a view, or a plain drawable with a size. */
812
+ readonly content: View | DrawableContent;
813
+ readonly padding?: Padding;
814
+ /** Background while idle. Default transparent. */
815
+ readonly color?: VarOrVal<string | Color>;
816
+ /** Background while hovered. Default a faint black wash, `rgba(0, 0, 0, 0.06)`. */
817
+ readonly hoverColor?: VarOrVal<string | Color>;
818
+ /** Background while pressed. Default `rgba(0, 0, 0, 0.12)`. */
819
+ readonly pressedColor?: VarOrVal<string | Color>;
820
+ /** Corner radius of the background. Default 4. */
821
+ readonly radius?: VarOrVal<RectRadius>;
822
+ /** Cursor while hovered. Default `"pointer"`. */
823
+ readonly cursor?: VarOrVal<string | null>;
824
+ }
825
+ /**
826
+ * A clickable view: its content on a rounded background that changes colour when hovered and
827
+ * pressed. Listen with `onClick`.
828
+ */
829
+ declare class ButtonView extends Layout {
830
+ constructor(options: ButtonViewOptions);
831
+ }
832
+
833
+ interface BackgroundBlurOptions extends ViewOptions {
834
+ readonly size: Size;
835
+ readonly sourceContext: CanvasRenderingContext2D;
836
+ readonly cameraPosition: Var<Point>;
837
+ readonly cameraZoom: Var<number>;
838
+ readonly dpr: Var<number>;
839
+ readonly radius?: number;
840
+ }
841
+ declare class BackgroundBlur extends View {
842
+ private readonly _sourceContext;
843
+ private readonly _cameraPosition;
844
+ private readonly _cameraZoom;
845
+ private readonly _radius;
846
+ private readonly _dpr;
847
+ constructor(options: BackgroundBlurOptions);
848
+ get radius(): number;
849
+ set radius(value: number);
850
+ protected doGetDrawBounds(viewBox: ViewBox): RectBounds;
851
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
852
+ /** A blur of what `canvas` shows behind the view. It follows the camera only while it is in a layer. */
853
+ static fromCanvas(canvas: Surface, size: Size, radius?: number): BackgroundBlur;
854
+ }
855
+
856
+ interface AsyncViewOptions extends ViewOptions {
857
+ view: Promise<View>;
858
+ placeholder?: View;
859
+ }
860
+ /**
861
+ * Shows a placeholder until a promised view arrives, then that view. It stands in for them: the view
862
+ * shown is laid out, drawn and hit-tested as if it were in the AsyncView's place, with its own location,
863
+ * size and transform. Of the AsyncView's own options only `visible` and `alpha` apply.
864
+ */
865
+ declare class AsyncView extends View {
866
+ private _view;
867
+ /** The view the last layout was made for; a state from another view is not handed to the new one. */
868
+ private _laidOut;
869
+ constructor(options: AsyncViewOptions);
870
+ /** The view shown now: the placeholder, the loaded view, or null. */
871
+ get current(): View | null;
872
+ getDrawState(context: LayoutContext): DrawState | null;
873
+ protected doGetDrawBounds(measuredBox: ViewBox): RectBounds;
874
+ draw(context: CanvasRenderingContext2D, state: DrawState): void;
875
+ handleMouseAction(action: PointerActionEvent, state: DrawState): boolean;
876
+ }
877
+
878
+ interface BlurredViewOptions extends ViewOptions {
879
+ readonly child: View;
880
+ readonly radius: VarOrVal<number>;
881
+ }
882
+ /** Draws its child through a blur filter of `radius` CSS pixels. */
883
+ declare class BlurredView extends View {
884
+ private readonly _view;
885
+ private readonly _radius;
886
+ constructor(options: BlurredViewOptions);
887
+ get radius(): Var<number>;
888
+ set radius(value: number);
889
+ getDrawState(context: LayoutContext): DrawState | null;
890
+ draw(context: CanvasRenderingContext2D, state: DrawState): void;
891
+ }
892
+
893
+ interface CachedViewOptions extends ViewOptions {
894
+ child: View;
895
+ /**
896
+ * A fixed bitmap size, in pixels, for the cache. Without it (the default) the cache follows the
897
+ * pixels the view covers on screen: the device pixel ratio and the camera's zoom.
898
+ */
899
+ cacheSize?: Size | null | ((child: View) => Size);
900
+ /**
901
+ * The largest side of the cache bitmap, in pixels, when it follows the screen. Zoomed in past it the
902
+ * cache stops getting sharper rather than growing without limit. Default 4096.
903
+ */
904
+ maxCacheSide?: number;
905
+ }
906
+ /**
907
+ * Draws its child once into a bitmap and then draws the bitmap, until the child changes. Useful for a
908
+ * complicated view (many paths, an SVG, long text) that moves or is drawn often but rarely changes.
909
+ *
910
+ * The bitmap is drawn at the resolution the view is shown at: device pixels per unit, read from the
911
+ * transform it is drawn with, so it stays sharp on hi-DPI screens and when the camera zooms in. The
912
+ * resolution moves in steps of √2, so a zoom redraws the cache now and then, not every frame.
913
+ */
914
+ declare class CachedView extends View {
915
+ private readonly _child;
916
+ private readonly _cacheSize;
917
+ private readonly _maxCacheSide;
918
+ private _cache;
919
+ private _cacheBounds;
920
+ /** Bitmap pixels per unit of the cache, or 0 when it has a fixed size. */
921
+ private _cacheScale;
922
+ /** The child's layout the cache was drawn from, at the origin: pointer input goes to the child through it. */
923
+ private _childState;
924
+ constructor(options: CachedViewOptions);
925
+ /** The child this view draws. */
926
+ get child(): View;
927
+ /** The current cache bitmap, or null before the first draw or after a change. For inspection and tests. */
928
+ get cacheCanvas(): HTMLCanvasElement | null;
929
+ protected doGetDrawBounds(_measuredBox: ViewBox): RectBounds;
930
+ protected doDraw(context: CanvasRenderingContext2D, state: DrawState): void;
931
+ /**
932
+ * Pointer input goes to the child as if it were drawn here, so a cached button still clicks; what
933
+ * the child does not take, this view handles as any view does.
934
+ */
935
+ handleMouseAction(action: PointerActionEvent, state: DrawState): boolean;
936
+ private _reset;
937
+ private _measureChild;
938
+ /** Draws the child into a new bitmap at `scale` pixels per unit, or at the fixed cache size when `scale` is 0. */
939
+ private _cacheIt;
940
+ }
941
+ /** The cache scale for a screen scale: the next step of √2 at or above it, so the cache is never blurrier than the screen. */
942
+ declare function cacheScaleFor(screenScale: number): number;
943
+
944
+ interface LevelOfDetailViewOptions extends ViewOptions {
945
+ /** Always built; drawn whenever it has enough pixels, and while `high` is loading. */
946
+ readonly low: View;
947
+ /** Built on demand as `low` approaches magnification, and dropped again when zoomed back out. */
948
+ readonly createHigh: () => DetailedView;
949
+ /** On-screen width, in device pixels, up to which `low` is sharp enough. */
950
+ readonly lowResolutionWidth: number;
951
+ /**
952
+ * Caps how many detailed views are alive at once. Defaults to {@link defaultLevelOfDetailRegistry},
953
+ * shared by every view on the page; give a scene its own to cap it separately.
954
+ */
955
+ readonly registry?: LevelOfDetailRegistry;
956
+ }
957
+ interface DetailedView {
958
+ readonly view: View;
959
+ /** Whether `view` has what it needs to draw (for example, its image has loaded). */
960
+ isReady(): boolean;
961
+ }
962
+ /**
963
+ * The live detailed views of the {@link LevelOfDetailView}s that share it, capped at `capacity`: past
964
+ * it, the least recently drawn are released, except those drawn in the last half second (on screen).
965
+ */
966
+ declare class LevelOfDetailRegistry {
967
+ readonly capacity: number;
968
+ constructor(capacity?: number);
969
+ /** How many detailed views are alive now. */
970
+ get size(): number;
971
+ /** Releases every detailed view, for example under memory pressure. */
972
+ releaseAll(): void;
973
+ }
974
+ /** The registry level-of-detail views use unless given another. */
975
+ declare const defaultLevelOfDetailRegistry: LevelOfDetailRegistry;
976
+ /**
977
+ * Draws a cheap `low` view and swaps in a detailed `high` view only while it is on screen at a
978
+ * size `low` cannot resolve. Layout and hit-testing always follow `low`, so both must have the
979
+ * same bounds.
980
+ */
981
+ declare class LevelOfDetailView extends View {
982
+ private readonly _low;
983
+ private readonly _createHigh;
984
+ private readonly _lowResolutionWidth;
985
+ private _high;
986
+ private _highSubscription;
987
+ private readonly _registry;
988
+ constructor(options: LevelOfDetailViewOptions);
989
+ getDrawState(context: LayoutContext): DrawState | null;
990
+ draw(context: CanvasRenderingContext2D, state: DrawState): void;
991
+ releaseHigh(): void;
992
+ protected handleUnsubscribed(): void;
993
+ private _acquireHigh;
994
+ }
995
+
996
+ /** Of the view options, `visible` and `onMounted` apply; the view shown keeps its own location and look. */
997
+ interface ZoomLevelViewOptions extends ViewOptions {
998
+ /** Laid out and drawn while `referenceWidth` is large enough on screen. */
999
+ readonly detailed: View;
1000
+ /** Laid out and drawn instead of `detailed` when zoomed out; must have the same bounds. */
1001
+ readonly simplified: View;
1002
+ /** Width, in view units, whose on-screen size picks the level. */
1003
+ readonly referenceWidth: number;
1004
+ /** Device-pixel width of `referenceWidth` below which `simplified` is used. */
1005
+ readonly simplifiedBelow: number;
1006
+ }
1007
+ /** The level picked last, per reference width and threshold. */
1008
+ type ZoomLevels = Map<string, boolean>;
1009
+ /**
1010
+ * Makes the zoom-level views drawn into `target` (a layer's canvas) share their picks with every
1011
+ * other target given the same `levels`, such as the layers of one scene canvas. A view laid out
1012
+ * again after a while off screen then takes the level its neighbours went through, rather than the
1013
+ * one it last had itself.
1014
+ */
1015
+ declare function shareZoomLevels(target: object, levels: ZoomLevels): void;
1016
+ /**
1017
+ * Picks one of two views by zoom. Only the picked view is measured, drawn and hit-tested: this
1018
+ * view returns the picked child's draw state as its own, so the other subtree costs nothing per
1019
+ * frame. Both stay subscribed, so switching needs no reload. The pick, with its hysteresis, is kept
1020
+ * per canvas (see {@link shareZoomLevels}), so views of the same size always agree.
1021
+ */
1022
+ declare class ZoomLevelView extends View {
1023
+ private readonly _detailed;
1024
+ private readonly _simplified;
1025
+ private readonly _referenceWidth;
1026
+ private readonly _simplifiedBelow;
1027
+ private readonly _levelKey;
1028
+ private _isSimplified;
1029
+ constructor(options: ZoomLevelViewOptions);
1030
+ get isSimplified(): boolean;
1031
+ getDrawState(context: LayoutContext): DrawState | null;
1032
+ draw(context: CanvasRenderingContext2D, state: DrawState): void;
1033
+ handleMouseAction(action: PointerActionEvent, state: DrawState): boolean;
1034
+ }
1035
+
1036
+ declare function drawArrow(context: CanvasRenderingContext2D, fromX: number, fromY: number, toX: number, toY: number, arrowWidth?: number | null, color?: string | null): void;
1037
+
1038
+ declare function drawLine(context: CanvasRenderingContext2D, fromX: number, fromY: number, toX: number, toY: number): void;
1039
+
1040
+ type LinearLayoutOrientation = "vertical" | "horizontal";
1041
+ interface LinearLayoutOptions extends LayoutOptions {
1042
+ gap?: VarOrVal<number>;
1043
+ orientation?: LinearLayoutOrientation;
1044
+ reverseDrawOrder?: boolean;
1045
+ }
1046
+ /**
1047
+ * Lays its children out in a column (`orientation: "vertical"`, the default) or a row, `gap` apart.
1048
+ * Children with a `"max"` size on the main axis share the space left by the others; `verticalAlign`
1049
+ * and `horizontalAlign` place the children on the cross axis and the whole run on the main axis.
1050
+ *
1051
+ * ```ts
1052
+ * new LinearLayout({
1053
+ * orientation: "horizontal",
1054
+ * gap: 8,
1055
+ * verticalAlign: "center",
1056
+ * children: [icon, new TextView({ text: "Settings" })],
1057
+ * })
1058
+ * ```
1059
+ */
1060
+ declare class LinearLayout extends Layout {
1061
+ private readonly _gap;
1062
+ private readonly _orientation;
1063
+ private readonly _reverseDrawOrder;
1064
+ constructor(options?: LinearLayoutOptions);
1065
+ get orientation(): LinearLayoutOrientation;
1066
+ get reverseDrawOrder(): boolean;
1067
+ getDrawState(context: LayoutContext): DrawState | null;
1068
+ /** Lays the children out in `measuredBox` to measure: the size {@link getDrawState} would give. */
1069
+ protected doGetDrawBounds(measuredBox: ViewBox): RectBounds;
1070
+ }
1071
+
1072
+ type HorizontalLayoutOptions = Omit<LinearLayoutOptions, "orientation">;
1073
+ /** A {@link LinearLayout} that lays its children out in a row. */
1074
+ declare class HorizontalLayout extends LinearLayout {
1075
+ constructor(options?: HorizontalLayoutOptions);
1076
+ }
1077
+
1078
+ type VerticalLayoutOptions = Omit<LinearLayoutOptions, "orientation">;
1079
+ /** A {@link LinearLayout} that lays its children out in a column. */
1080
+ declare class VerticalLayout extends LinearLayout {
1081
+ constructor(options?: VerticalLayoutOptions);
1082
+ }
1083
+
1084
+ interface ContainerOptions extends LayoutOptions {
1085
+ child: View;
1086
+ }
1087
+ /**
1088
+ * A {@link Layout} around one `child`, often to give it a `background`: the background covers the
1089
+ * child, so give the child its own padding to have the background reach beyond its content.
1090
+ */
1091
+ declare class Container extends Layout {
1092
+ constructor(options?: ContainerOptions);
1093
+ }
1094
+
1095
+ interface ViewContainerOptions extends ViewOptions {
1096
+ content: Drawable | DrawableContent;
1097
+ }
1098
+ /** Wraps a {@link Drawable} or {@link DrawableContent} so a layout can place it. */
1099
+ declare class ViewContainer extends View {
1100
+ private readonly _content;
1101
+ constructor(options: ViewContainerOptions);
1102
+ doGetDrawBounds(_viewBox: ViewBox): RectBounds;
1103
+ protected doDraw(context: CanvasRenderingContext2D, _state: DrawState): void;
1104
+ }
1105
+
1106
+ declare class Line {
1107
+ readonly x1: number;
1108
+ readonly y1: number;
1109
+ readonly x2: number;
1110
+ readonly y2: number;
1111
+ constructor(x1: number, y1: number, x2: number, y2: number);
1112
+ get point1(): Point;
1113
+ get point2(): Point;
1114
+ get length(): number;
1115
+ get angle(): number;
1116
+ contains(point: Point): boolean;
1117
+ getIntersectionLengthWith(line: Line): number;
1118
+ private _getIntersectionLengthWith;
1119
+ intersectsMoreThanOnceWith(line: Line): boolean;
1120
+ getIntersectionWith(line: Line): Point | null;
1121
+ static fromPoints(p1: Point, p2: Point): Line;
1122
+ static readonly zero: Line;
1123
+ }
1124
+
1125
+ declare function getAverageColor(context: CanvasRenderingContext2D, width: number, height: number, blockSize?: number): Color;
1126
+ declare function getDominantColor(context: CanvasRenderingContext2D, imageSource: CanvasImageSource): Color;
1127
+ declare function getColors(imageSource: CanvasImageSource, block?: number): Color[];
1128
+
1129
+ /** `value` limited to `[min, max]`. */
1130
+ declare function clamp(value: number, min: number, max: number): number;
1131
+
1132
+ /** Anything with a writable `value`: an eventiq `Vary`, a view property's variable, or a plain object. */
1133
+ interface TweenTarget<T> {
1134
+ value: T;
1135
+ }
1136
+ /** An easing: an {@link AnimationInterpolator} or a function from linear progress (0 to 1) to eased progress. */
1137
+ type Easing = AnimationInterpolator | ((progress: number) => number);
1138
+ interface TweenOptions<T> {
1139
+ /** Milliseconds. Default 300. */
1140
+ readonly duration?: number;
1141
+ /** Default linear. Overshooting easings (bounce, overshoot) may take the value past `to` and back. */
1142
+ readonly easing?: Easing;
1143
+ /** Where to start. Default: the target's value when the tween starts. */
1144
+ readonly from?: T;
1145
+ /**
1146
+ * How to blend two values. Numbers, {@link Point}s and {@link Color}s are blended without one; any
1147
+ * other type needs it.
1148
+ */
1149
+ readonly lerp?: (from: T, to: T, progress: number) => T;
1150
+ /** The frame loop to run on. Default {@link defaultScheduler}; pass the scene's when it has its own. */
1151
+ readonly scheduler?: FrameScheduler;
1152
+ /** Called once the target holds `to`; not called when the tween is stopped or replaced early. */
1153
+ readonly onFinished?: () => void;
1154
+ /**
1155
+ * Animates even when the user prefers reduced motion. By default such a user gets `to` at once,
1156
+ * so use this for changes that are not motion (a progress value, a colour fade that carries meaning).
1157
+ */
1158
+ readonly ignoreReducedMotion?: boolean;
1159
+ }
1160
+ /** A running tween. Disposing it stops the value where it is. */
1161
+ interface Tween extends IDisposable {
1162
+ /** Whether it is still running. */
1163
+ readonly running: boolean;
1164
+ /** Stops it and sets the target to its end value at once. */
1165
+ finish(): void;
1166
+ }
1167
+ /**
1168
+ * Animates `target.value` to `to` over `duration` milliseconds, one step per frame on the scheduler.
1169
+ *
1170
+ * Because views take eventiq variables for their properties, tweening the variable animates every
1171
+ * view bound to it, and each frame redraws only the layers those views are in. A new tween of the
1172
+ * same target replaces the one running, so a hover that ends halfway turns back smoothly from where
1173
+ * the value is.
1174
+ *
1175
+ * ```ts
1176
+ * const size = createVar(10)
1177
+ * layer.add(new RoundedRectangleView({ size: size.map(s => new Size(s, s)) }))
1178
+ * tween(size, 40, { duration: 500, easing: animationInterpolators.overshoot })
1179
+ * ```
1180
+ */
1181
+ declare function tween<T>(target: TweenTarget<T>, to: T, options?: TweenOptions<T>): Tween;
1182
+ /** Linear interpolation of numbers. */
1183
+ declare function lerpNumber(from: number, to: number, progress: number): number;
1184
+ /** Linear interpolation of points. */
1185
+ declare function lerpPoint(from: Point, to: Point, progress: number): Point;
1186
+ /** Linear interpolation of colours, channel by channel, alpha included. Progress outside 0 to 1 is clamped. */
1187
+ declare function lerpColor(from: Color, to: Color, progress: number): Color;
1188
+
1189
+ /**
1190
+ * Whether the user asked the system for less motion (`prefers-reduced-motion: reduce`). Tweens and
1191
+ * camera animations then jump to their end instead of moving, unless told to ignore it.
1192
+ */
1193
+ declare function prefersReducedMotion(): boolean;
1194
+
1195
+ /** The shapes a {@link ShapeBatch} draws. Each fills its item's box. */
1196
+ type ShapeKind = "rect" | "roundRect" | "circle" | "diamond" | "triangle" | "hexagon";
1197
+ /** The numeric codes of {@link ShapeKind}, for the `kind` array of {@link ShapeArrays}. */
1198
+ declare const shapeKinds: Readonly<Record<ShapeKind, number>>;
1199
+ /** A colour, gradient or pattern; or a style index from {@link ShapeBatch.style}; null for none. */
1200
+ type ShapeStyle = string | CanvasGradient | CanvasPattern | number | null;
1201
+ /** One item of a {@link ShapeBatch}, as plain data. Coordinates are in the batch's own units. */
1202
+ interface ShapeRecord {
1203
+ readonly x: number;
1204
+ readonly y: number;
1205
+ readonly width: number;
1206
+ readonly height: number;
1207
+ /** Default `"rect"`. */
1208
+ readonly kind?: ShapeKind;
1209
+ /** Default: the batch's `fill`. Null draws no fill. */
1210
+ readonly fill?: ShapeStyle;
1211
+ /** Default: the batch's `stroke` (none unless given). */
1212
+ readonly stroke?: ShapeStyle;
1213
+ /** In the batch's units. Default: the batch's `strokeWidth`. */
1214
+ readonly strokeWidth?: number;
1215
+ /** Text drawn centred in the item when it is big enough on screen. */
1216
+ readonly label?: string | null;
1217
+ /** A hidden item is neither drawn nor hit. */
1218
+ readonly hidden?: boolean;
1219
+ }
1220
+ /**
1221
+ * Items as parallel arrays (typed arrays or plain), item `i` being element `i` of each. `kind` holds
1222
+ * {@link shapeKinds} codes; `fill` and `stroke` hold style indices from {@link ShapeBatch.style}
1223
+ * (0 for none). Missing arrays take the batch's defaults.
1224
+ */
1225
+ interface ShapeArrays {
1226
+ readonly x: ArrayLike<number>;
1227
+ readonly y: ArrayLike<number>;
1228
+ readonly width: ArrayLike<number>;
1229
+ readonly height: ArrayLike<number>;
1230
+ readonly kind?: ArrayLike<number>;
1231
+ readonly fill?: ArrayLike<number>;
1232
+ readonly stroke?: ArrayLike<number>;
1233
+ readonly strokeWidth?: ArrayLike<number>;
1234
+ readonly labels?: ArrayLike<string | null | undefined>;
1235
+ }
1236
+ /**
1237
+ * When items get cheaper to draw, by their size on screen in device pixels (the larger side).
1238
+ */
1239
+ interface ShapeBatchLevelOfDetail {
1240
+ /** Items smaller than this are not drawn. Default 0: every item is drawn. */
1241
+ readonly hideBelow?: number;
1242
+ /** Items smaller than this are drawn as plain filled rectangles, whatever their kind. Default 4. */
1243
+ readonly simplifyBelow?: number;
1244
+ /** Items smaller than this are not stroked. Default 4. */
1245
+ readonly strokeBelow?: number;
1246
+ /** `drawDetail` is called for items at least this big. Default 16. */
1247
+ readonly detailAbove?: number;
1248
+ /**
1249
+ * While the average item is smaller than this on screen, the batch is drawn once into a bitmap (at
1250
+ * the zoom rounded to a step of √2) and the bitmap is reused until an item changes or the zoom moves
1251
+ * a step: zoomed out, panning costs one image. 0 turns it off. Default 4.
1252
+ */
1253
+ readonly cacheBelow?: number;
1254
+ }
1255
+ interface ShapeBatchLabelOptions {
1256
+ /** Default `"system-ui, sans-serif"`. */
1257
+ readonly family?: string;
1258
+ /** Default 500. */
1259
+ readonly weight?: number | string;
1260
+ /** The font size in the batch's units; default 0.3 of the item's height. */
1261
+ readonly size?: number;
1262
+ /** Default `"#111"`. */
1263
+ readonly color?: string;
1264
+ /** Labels whose text would be smaller than this many device pixels are not drawn. Default 8. */
1265
+ readonly minScreenSize?: number;
1266
+ }
1267
+ /** What `drawDetail` gets: one item, valid only during the call (the object is reused). */
1268
+ interface ShapeBatchItem {
1269
+ index: number;
1270
+ x: number;
1271
+ y: number;
1272
+ width: number;
1273
+ height: number;
1274
+ kind: ShapeKind;
1275
+ /** The item's size on screen in device pixels (the larger side). */
1276
+ pixelSize: number;
1277
+ }
1278
+ /** A pointer event on one item of a batch. */
1279
+ interface ShapeBatchItemEvent {
1280
+ readonly batch: ShapeBatch;
1281
+ readonly index: number;
1282
+ /** Where the pointer is, in the batch's units. */
1283
+ readonly localPosition: Point;
1284
+ /** Where the pointer is on the surface, in device pixels. */
1285
+ readonly viewportPosition: Point;
1286
+ }
1287
+ interface ShapeBatchOptions extends Omit<ViewOptions, "viewBox" | "size" | "onClick"> {
1288
+ /** Items to start with. */
1289
+ readonly items?: Iterable<ShapeRecord>;
1290
+ /** Items to start with, as arrays. */
1291
+ readonly arrays?: ShapeArrays;
1292
+ /** Room for this many items before the arrays grow. */
1293
+ readonly capacity?: number;
1294
+ /**
1295
+ * The side of a cell of the spatial index, in the batch's units. Default: twice the larger side of the
1296
+ * average starting item (64 with none). Items larger than a cell still work, but every query reads them.
1297
+ */
1298
+ readonly cellSize?: number;
1299
+ /** The default fill. Default `"#8a94a6"`. */
1300
+ readonly fill?: string | CanvasGradient | CanvasPattern | null;
1301
+ /** The default stroke. Default none. */
1302
+ readonly stroke?: string | CanvasGradient | CanvasPattern | null;
1303
+ /** The default stroke width in the batch's units. Default 1. */
1304
+ readonly strokeWidth?: number;
1305
+ /** The corner radius of `"roundRect"` items, in the batch's units. Default 4. */
1306
+ readonly radius?: number;
1307
+ readonly lod?: ShapeBatchLevelOfDetail;
1308
+ readonly labels?: ShapeBatchLabelOptions;
1309
+ /**
1310
+ * Draws in the index order of the items. By default items are grouped by fill, which is much faster
1311
+ * but puts overlapping items of different fills in the order of their styles.
1312
+ */
1313
+ readonly preserveOrder?: boolean;
1314
+ /** Draws extra detail over items that are big on screen (see `lod.detailAbove`). */
1315
+ readonly drawDetail?: (context: CanvasRenderingContext2D, item: ShapeBatchItem) => void;
1316
+ readonly onItemClick?: (event: ShapeBatchItemEvent) => void;
1317
+ }
1318
+ /**
1319
+ * Tens or hundreds of thousands of simple shapes in one view, without a View per shape (a View costs
1320
+ * kilobytes). Items are rows of typed arrays: about 46 bytes each, plus the label text if any.
1321
+ *
1322
+ * - **Drawing** reads only the items in view, through a spatial grid, grouped by fill so a frame sets
1323
+ * each colour once. Small items become plain rectangles, then lose their strokes, then (optionally)
1324
+ * disappear, by their size on screen (`lod`); labels show when they fit; `drawDetail` adds detail
1325
+ * to items that are big on screen.
1326
+ * - **Input** goes through the same grid: {@link hoveredIndex} follows the item under the pointer and
1327
+ * {@link onItemClick} reports clicks, both by item index. Hovering does not redraw the batch; draw a
1328
+ * highlight with {@link createHighlight} in a layer of its own.
1329
+ * - **Updates** are per item: {@link set} rewrites one item, re-indexes it if it moved, and the layer
1330
+ * repaints on the next frame. Indices stay stable; {@link remove} frees an index for a later
1331
+ * {@link add}.
1332
+ *
1333
+ * ```ts
1334
+ * const batch = new ShapeBatch({ fill: "#4c8bf5", lod: { simplifyBelow: 6 } })
1335
+ * for (let i = 0; i < 50_000; i++) {
1336
+ * batch.add({ x: (i % 250) * 24, y: Math.floor(i / 250) * 24, width: 22, height: 22, kind: "roundRect" })
1337
+ * }
1338
+ * batch.onItemClick.subscribe(({ index }) => batch.set(index, { fill: "#f5a04c" }))
1339
+ * layer.add(batch)
1340
+ * overlay.add(batch.createHighlight({ stroke: "#fff", strokeWidth: 2 }))
1341
+ * ```
1342
+ *
1343
+ * The batch is one view: its location, alpha, visibility and `hittable` apply to all items. Keep it
1344
+ * unscaled and unrotated if you want hit testing to stay exact.
1345
+ */
1346
+ declare class ShapeBatch extends View {
1347
+ private readonly _store;
1348
+ private readonly _grid;
1349
+ private readonly _styles;
1350
+ private readonly _styleIndex;
1351
+ private readonly _freeList;
1352
+ private _count;
1353
+ private _liveCount;
1354
+ private readonly _defaultFill;
1355
+ private readonly _defaultStroke;
1356
+ private readonly _defaultStrokeWidth;
1357
+ private readonly _radius;
1358
+ private readonly _hideBelow;
1359
+ private readonly _simplifyBelow;
1360
+ private readonly _strokeBelow;
1361
+ private readonly _detailAbove;
1362
+ private readonly _cacheBelow;
1363
+ private _cache;
1364
+ private _version;
1365
+ private _sizeSum;
1366
+ private readonly _labelFamily;
1367
+ private readonly _labelWeight;
1368
+ private readonly _labelSize;
1369
+ private readonly _labelColor;
1370
+ private readonly _labelMinScreen;
1371
+ private readonly _preserveOrder;
1372
+ private readonly _drawDetail;
1373
+ private readonly _hoveredIndex;
1374
+ private readonly _onItemClick;
1375
+ private readonly _onItemsChanged;
1376
+ private _bounds;
1377
+ private _minX;
1378
+ private _minY;
1379
+ private _maxX;
1380
+ private _maxY;
1381
+ private _query;
1382
+ private _visibleIds;
1383
+ private _sorted;
1384
+ private _bucketCounts;
1385
+ private _labelWidths;
1386
+ private _labelEpoch;
1387
+ private readonly _item;
1388
+ private _downViewport;
1389
+ private _downIndex;
1390
+ private _lastStats;
1391
+ constructor(options?: ShapeBatchOptions);
1392
+ /** How many indices are in use, removed ones included: valid indices are `0 … count - 1`. */
1393
+ get count(): number;
1394
+ /** How many items there are (removed ones excluded). */
1395
+ get size(): number;
1396
+ /** The item under the pointer, or -1. Hovering does not redraw the batch. */
1397
+ get hoveredIndex(): Var<number>;
1398
+ get onItemClick(): EventObserver<ShapeBatchItemEvent>;
1399
+ /** Raised after items were added, changed or removed. */
1400
+ get onItemsChanged(): EventObserver<void>;
1401
+ /** What the last frame drew: items read from the index, drawn, labels and details. */
1402
+ get lastDrawStats(): Readonly<ShapeBatchDrawStats>;
1403
+ /** The side of a cell of the spatial index. */
1404
+ get cellSize(): number;
1405
+ /**
1406
+ * The index of a fill or stroke style, for {@link ShapeArrays} and {@link set}. The same colour
1407
+ * string always gives the same index. Index 0 is "none".
1408
+ */
1409
+ style(value: string | CanvasGradient | CanvasPattern): number;
1410
+ /** The style at an index from {@link style}; null for 0 or an unknown index. */
1411
+ styleAt(index: number): string | CanvasGradient | CanvasPattern | null;
1412
+ /** Adds an item and returns its index (a freed index when there is one). */
1413
+ add(record: ShapeRecord): number;
1414
+ /** Adds items at the end and returns the index of the first; they take consecutive indices. */
1415
+ addMany(records: Iterable<ShapeRecord>): number;
1416
+ /** Adds items from parallel arrays at the end and returns the index of the first. */
1417
+ addArrays(arrays: ShapeArrays): number;
1418
+ /**
1419
+ * Changes an item: only the fields given. Moving or resizing it re-indexes that item alone, and the
1420
+ * batch redraws on the next frame.
1421
+ */
1422
+ set(index: number, patch: Partial<ShapeRecord>): void;
1423
+ /** Moves an item; the same as `set(index, { x, y })`. */
1424
+ move(index: number, x: number, y: number): void;
1425
+ /** Whether `index` is a current item. */
1426
+ has(index: number): boolean;
1427
+ /** The item at `index` as a record, or null when there is none. */
1428
+ get(index: number): ShapeRecord | null;
1429
+ /** Removes an item; its index may be given to a later {@link add}. */
1430
+ remove(index: number): void;
1431
+ /** Removes every item. */
1432
+ clear(): void;
1433
+ /**
1434
+ * The items overlapping a rectangle in the batch's units (hidden ones excluded), in no particular
1435
+ * order.
1436
+ */
1437
+ query(rect: RectBounds): number[];
1438
+ /** The topmost item whose shape contains a point in the batch's units, or -1. */
1439
+ indexAt(point: Point): number;
1440
+ /** An item's box in the batch's units, or null when there is no such item. */
1441
+ itemBounds(index: number): RectBounds | null;
1442
+ /**
1443
+ * A view that draws one item of this batch, over it: put it in a layer above the batch's, with the
1444
+ * same camera, so a hover highlight repaints that small layer and not the whole batch. It follows
1445
+ * `index` (default: {@link hoveredIndex}) and the item's changes.
1446
+ */
1447
+ createHighlight(options?: ShapeBatchHighlightOptions): View;
1448
+ protected doGetDrawBounds(_measuredBox: ViewBox): RectBounds;
1449
+ /**
1450
+ * Hit-tests the items through the index: sets {@link hoveredIndex}, raises {@link onItemClick} when
1451
+ * the pointer goes down and up on the same item without moving more than the scene's `clickSlop`, and takes the
1452
+ * event only over an item. The view's own `hovered`, `pressed` and `onClick` stay unused, so moving
1453
+ * over the batch does not redraw it.
1454
+ */
1455
+ handleMouseAction(action: PointerActionEvent, state: DrawState): boolean;
1456
+ handleMouseLeave(): void;
1457
+ private _release;
1458
+ protected doDraw(context: CanvasRenderingContext2D, _state: DrawState): void;
1459
+ /** Draws the batch from a bitmap of all its items, made again when stale. False when it cannot. */
1460
+ private _drawCached;
1461
+ /** Draws the items in the part of the batch `context` shows. */
1462
+ private _render;
1463
+ /** The visible items in drawing order: index order, or grouped by fill (stable within a group). */
1464
+ private _order;
1465
+ private _drawShapes;
1466
+ private _drawDetails;
1467
+ private _drawLabels;
1468
+ private _trace;
1469
+ /** Whether a point lies inside an item's shape. */
1470
+ private _contains;
1471
+ private _write;
1472
+ private _styleOf;
1473
+ private _setLabel;
1474
+ private _pushStyle;
1475
+ /** Takes `n` new indices at the end, growing the arrays as needed; returns the first. */
1476
+ private _allocate;
1477
+ /** Sizes the grid for a block of new items before they are inserted one by one. */
1478
+ private _reserveGrid;
1479
+ private _growBounds;
1480
+ /** Called before an item moves or goes: when it touched the edge, the bounds must be recomputed. */
1481
+ private _touchBounds;
1482
+ private _recomputeBounds;
1483
+ private _changed;
1484
+ }
1485
+ interface ShapeBatchDrawStats {
1486
+ /** Items the spatial index offered for the visible area. */
1487
+ candidates: number;
1488
+ /** Items drawn. */
1489
+ drawn: number;
1490
+ labels: number;
1491
+ details: number;
1492
+ /** Drawn from the bitmap of the whole batch (`lod.cacheBelow`). */
1493
+ cached: boolean;
1494
+ }
1495
+ interface ShapeBatchHighlightOptions {
1496
+ /** The item to draw; default the batch's {@link ShapeBatch.hoveredIndex}. -1 draws nothing. */
1497
+ readonly index?: Var<number>;
1498
+ readonly fill?: string | CanvasGradient | CanvasPattern | null;
1499
+ /** Default `"#ffffff"`. */
1500
+ readonly stroke?: string | CanvasGradient | CanvasPattern | null;
1501
+ /** In device pixels, whatever the zoom. Default 2. */
1502
+ readonly strokeWidth?: number;
1503
+ /** How far outside the item the outline lies, in device pixels. Default 1. */
1504
+ readonly inset?: number;
1505
+ }
1506
+
1507
+ /**
1508
+ * Label placement for zoomable scenes: each frame, labels go only where they have room, the most
1509
+ * important first, and never over another item's mark. Work in screen space (CSS or device pixels),
1510
+ * after the camera: a label that fits at one zoom may not fit at the next, and the answer is cheap to
1511
+ * compute again.
1512
+ *
1513
+ * ```ts
1514
+ * const placer = new LabelPlacer()
1515
+ * // every frame, for the items on screen:
1516
+ * const placed = placer.place(
1517
+ * items.map(item => ({
1518
+ * x: item.screenX + item.radius, y: item.screenY, // the anchor
1519
+ * width: textWidth(item.name), height: 14,
1520
+ * tier: item.id === selected ? "selected" : item.id === hovered ? "hovered" : item.hub ? "important" : "normal",
1521
+ * rank: item.degree, // within a tier, higher first
1522
+ * id: item.id, // its own mark does not block it
1523
+ * })),
1524
+ * { obstacles: items.map(item => ({ ...circleBox(item), id: item.id })), bounds: { x0: 0, y0: 0, x1: width, y1: height } },
1525
+ * )
1526
+ * for (const label of placed) drawLabel(items[label.index], label.x, label.y)
1527
+ * ```
1528
+ *
1529
+ * It is the greedy method of most map renderers: candidates sorted by tier and rank, each tried at its
1530
+ * placements in order, kept when its box overlaps nothing kept before and no obstacle. A uniform grid of
1531
+ * screen cells keeps each test to the boxes nearby, so a few thousand candidates take well under a
1532
+ * millisecond, and the placer reuses its buffers from frame to frame.
1533
+ */
1534
+ /** How much a label matters: selected before hovered before important before the rest. */
1535
+ type LabelTier = "selected" | "hovered" | "important" | "normal";
1536
+ /** Where a label sits relative to its anchor point. */
1537
+ type LabelPlacement = "right" | "left" | "top" | "bottom" | "center";
1538
+ /** An axis-aligned box in screen units: `x0 ≤ x1`, `y0 ≤ y1`. */
1539
+ interface LabelBox {
1540
+ readonly x0: number;
1541
+ readonly y0: number;
1542
+ readonly x1: number;
1543
+ readonly y1: number;
1544
+ }
1545
+ /** Something labels may not cover: a mark, an icon, a control. */
1546
+ interface LabelObstacle extends LabelBox {
1547
+ /** A label with the same `id` may cover it (an item's own mark). */
1548
+ readonly id?: unknown;
1549
+ }
1550
+ interface LabelCandidate {
1551
+ /** The anchor point: the label is placed relative to it. */
1552
+ readonly x: number;
1553
+ readonly y: number;
1554
+ /** The label's size. */
1555
+ readonly width: number;
1556
+ readonly height: number;
1557
+ /** Default `"normal"`. */
1558
+ readonly tier?: LabelTier;
1559
+ /** Within a tier, a higher rank is placed first. Ties keep the order of the input. */
1560
+ readonly rank?: number;
1561
+ /** The placements to try, in order. Default `["right"]`. */
1562
+ readonly placements?: readonly LabelPlacement[];
1563
+ /** The distance between the anchor and the label. Default: the options' `gap`. */
1564
+ readonly gap?: number;
1565
+ /** Matches an obstacle's `id`: the label may cover that obstacle. */
1566
+ readonly id?: unknown;
1567
+ /**
1568
+ * Placed even where it collides (at its first placement), and kept as an obstacle for the rest.
1569
+ * Default: true for the tiers in the options' `forceTiers`.
1570
+ */
1571
+ readonly force?: boolean;
1572
+ }
1573
+ interface PlaceLabelsOptions {
1574
+ /** Boxes no label may cover, except a label whose `id` matches. */
1575
+ readonly obstacles?: Iterable<LabelObstacle>;
1576
+ /** Labels must lie inside this box (forced ones excepted). Default: anywhere. */
1577
+ readonly bounds?: LabelBox;
1578
+ /** Room kept around each label, in screen units. Default 2. */
1579
+ readonly padding?: number;
1580
+ /** The default distance between an anchor and its label. Default 4. */
1581
+ readonly gap?: number;
1582
+ /** Tiers placed whatever they cover. Default `["selected", "hovered"]`. */
1583
+ readonly forceTiers?: readonly LabelTier[];
1584
+ /** The side of a grid cell, in screen units. Default 64. */
1585
+ readonly cellSize?: number;
1586
+ /** Stop after placing this many labels. Default: no limit. */
1587
+ readonly maxLabels?: number;
1588
+ }
1589
+ /** A label that found room. */
1590
+ interface PlacedLabel {
1591
+ /** The candidate's index in the input. */
1592
+ readonly index: number;
1593
+ /** The label's top-left corner. */
1594
+ readonly x: number;
1595
+ readonly y: number;
1596
+ readonly width: number;
1597
+ readonly height: number;
1598
+ readonly placement: LabelPlacement;
1599
+ }
1600
+ /**
1601
+ * Places labels frame after frame, reusing its grid and buffers. See the module comment for the method;
1602
+ * {@link placeLabels} is the same for a single call.
1603
+ */
1604
+ declare class LabelPlacer {
1605
+ private _cellSize;
1606
+ private _x0;
1607
+ private _y0;
1608
+ private _x1;
1609
+ private _y1;
1610
+ private _ids;
1611
+ private _count;
1612
+ private readonly _cells;
1613
+ private readonly _usedCells;
1614
+ private _order;
1615
+ private _keys;
1616
+ /** Places `candidates` and returns those that found room, in the order they were placed. */
1617
+ place(candidates: readonly LabelCandidate[], options?: PlaceLabelsOptions): PlacedLabel[];
1618
+ private _reset;
1619
+ private _add;
1620
+ private _cell;
1621
+ private _isFree;
1622
+ private _isFreeIn;
1623
+ }
1624
+ /** Places labels once; see {@link LabelPlacer} to reuse buffers frame after frame. */
1625
+ declare function placeLabels(candidates: readonly LabelCandidate[], options?: PlaceLabelsOptions): PlacedLabel[];
1626
+
1627
+ export { AnimationInterpolator, type ArrowHead, ArrowView, type ArrowViewOptions, AsyncView, type AsyncViewOptions, BackgroundBlur, type BackgroundBlurOptions, BlurredView, type BlurredViewOptions, ButtonView, type ButtonViewOptions, CachedView, type CachedViewOptions, Color, Container, type ContainerOptions, CurveView, type CurveViewOptions, type DetailedView, DrawState, Drawable, DrawableContent, type DrawableImage, type Easing, type FontFamily, type FontLineHeight, type FontSize, type FontStyle, type FontWeight, FrameScheduler, type FrameStats, FrameStatsMonitor, type FrameStatsOptions, HexagonView, type HexagonViewOptions, HitTestContext, HorizontalLayout, type HorizontalLayoutOptions, type ImageContent, type ImageFallbacks, ImageFetchError, type ImageFetcher, type ImageFit, type ImageSource, ImageView, type ImageViewOptions, type LabelBox, type LabelCandidate, type LabelObstacle, type LabelPlacement, LabelPlacer, type LabelTier, Layout, LayoutContext, LayoutOptions, LevelOfDetailRegistry, LevelOfDetailView, type LevelOfDetailViewOptions, Line, LineView, type LineViewOptions, LinearLayout, type LinearLayoutOptions, type LinearLayoutOrientation, type MeasureText, Padding, type PathCommand, PathView, type PathViewOptions, type PinchStep, type PlaceLabelsOptions, type PlacedLabel, Point, PointerActionEvent, PointerObserveEvent, RectBounds, type RectRadius, type RectRadiusCorners, type RoundedRectangleDrawableOptions, RoundedRectangleView, Scene, type ShapeArrays, ShapeBatch, type ShapeBatchDrawStats, type ShapeBatchHighlightOptions, type ShapeBatchItem, type ShapeBatchItemEvent, type ShapeBatchLabelOptions, type ShapeBatchLevelOfDetail, type ShapeBatchOptions, type ShapeKind, type ShapeRecord, type ShapeStyle, SharedLoads, Size, type StrokeAlignment, StrokeRectangleView, type StrokeRectangleViewOptions, Surface, type TextAlignment, type TextDirection, type TextFont, type TextFontOptions, type TextLine, TextView, type TextViewOptions, TimeSlicedQueue, type TimeSlicedQueueOptions, type TriangleDirection, TriangleView, type TriangleViewOptions, type Tween, type TweenOptions, type TweenTarget, VerticalLayout, type VerticalLayoutOptions, View, ViewBox, ViewContainer, type ViewContainerOptions, ViewOptions, type WheelAction, WheelObserveEvent, type WheelZoomOptions, type WrapTextOptions, type WrappedText, ZoomLevelView, type ZoomLevelViewOptions, type ZoomLevels, type ZoomPanOptions, attachZoomPan, cacheScaleFor, clamp, cubicPath, cubicPoint, defaultLevelOfDetailRegistry, distanceToPolylines, distanceToSegment, drawArrow, drawLine, flattenPath, getAverageColor, getColors, getDominantColor, getRadius, insideRoundedRect, isImageSource, isTrackpadPinch, isUrlRejection, lerpColor, lerpNumber, lerpPoint, pathEnd, pathStart, pinchStep, placeLabels, polylinePath, polylinesBounds, prefersReducedMotion, quadraticPath, quadraticPoint, relayoutAllViews, shapeKinds, shareZoomLevels, splitGraphemes, staticImageSource, tracePath, truncateText, tween, wheelDeltaPixels, wheelZoomFactor, wrapText };