@hozo/canvas 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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -0
  3. package/dist/accessibility.d.ts +20 -0
  4. package/dist/accessibility.d.ts.map +1 -0
  5. package/dist/accessibility.js +9 -0
  6. package/dist/accessibility.js.map +1 -0
  7. package/dist/hit-test.d.ts +96 -0
  8. package/dist/hit-test.d.ts.map +1 -0
  9. package/dist/hit-test.js +354 -0
  10. package/dist/hit-test.js.map +1 -0
  11. package/dist/index.d.ts +80 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +317 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/index.native.d.ts +83 -0
  16. package/dist/index.native.d.ts.map +1 -0
  17. package/dist/index.native.js +435 -0
  18. package/dist/index.native.js.map +1 -0
  19. package/dist/render-canvas-2d.d.ts +6 -0
  20. package/dist/render-canvas-2d.d.ts.map +1 -0
  21. package/dist/render-canvas-2d.js +213 -0
  22. package/dist/render-canvas-2d.js.map +1 -0
  23. package/dist/scene.d.ts +495 -0
  24. package/dist/scene.d.ts.map +1 -0
  25. package/dist/scene.js +591 -0
  26. package/dist/scene.js.map +1 -0
  27. package/dist/viewport.d.ts +9 -0
  28. package/dist/viewport.d.ts.map +1 -0
  29. package/dist/viewport.js +2 -0
  30. package/dist/viewport.js.map +1 -0
  31. package/dist/wrap-text.d.ts +28 -0
  32. package/dist/wrap-text.d.ts.map +1 -0
  33. package/dist/wrap-text.js +148 -0
  34. package/dist/wrap-text.js.map +1 -0
  35. package/package.json +79 -0
  36. package/src/accessibility.ts +28 -0
  37. package/src/hit-test.ts +499 -0
  38. package/src/index.native.tsx +733 -0
  39. package/src/index.tsx +510 -0
  40. package/src/render-canvas-2d.ts +259 -0
  41. package/src/scene.tsx +1037 -0
  42. package/src/viewport.ts +8 -0
  43. package/src/wrap-text.ts +157 -0
package/src/scene.tsx ADDED
@@ -0,0 +1,1037 @@
1
+ import {
2
+ createContext,
3
+ type ReactNode,
4
+ useCallback,
5
+ useContext,
6
+ useEffect,
7
+ useId,
8
+ useLayoutEffect,
9
+ useMemo,
10
+ useRef,
11
+ useState,
12
+ } from 'react'
13
+
14
+ import type { CanvasPoint } from './hit-test.ts'
15
+
16
+ export interface CanvasPressEvent {
17
+ /** Position in the root Canvas scene coordinate system. */
18
+ point: CanvasPoint
19
+ /** Position in logical CSS pixels or React Native points. */
20
+ surfacePoint: CanvasPoint
21
+ /** Browser-style modifier state, also present (as false) on touch-only hosts. */
22
+ altKey: boolean
23
+ ctrlKey: boolean
24
+ metaKey: boolean
25
+ shiftKey: boolean
26
+ /** `0` for the primary button and `1` for a mouse-wheel press. */
27
+ button: number
28
+ /** Whether the authored handler kept this activation from following its destination. */
29
+ readonly defaultPrevented: boolean
30
+ /** Keep an href-bearing shape available for authored selection or another local interaction. */
31
+ preventDefault(): void
32
+ }
33
+
34
+ export interface CanvasDestination {
35
+ href: string
36
+ /** Bypass an installed application router and open the platform destination. */
37
+ external?: boolean
38
+ /** Replace the router history entry for an ordinary primary activation. */
39
+ replace?: boolean
40
+ }
41
+
42
+ interface CanvasPressModifiers {
43
+ altKey?: boolean
44
+ ctrlKey?: boolean
45
+ metaKey?: boolean
46
+ shiftKey?: boolean
47
+ button?: number
48
+ }
49
+
50
+ /** Builds the cancellable event shared by pointer, keyboard, and accessibility activation. */
51
+ export function canvasPressEvent(
52
+ point: CanvasPoint,
53
+ surfacePoint: CanvasPoint,
54
+ modifiers: CanvasPressModifiers = {},
55
+ ): CanvasPressEvent {
56
+ let defaultPrevented = false
57
+ const event = { point, surfacePoint }
58
+ // Keep the two historical coordinate fields as the enumerable payload.
59
+ // Consumers that log or spread an event do not suddenly acquire browser
60
+ // bookkeeping, while direct event access follows the familiar DOM shape.
61
+ Object.defineProperties(event, {
62
+ altKey: { value: modifiers.altKey ?? false, enumerable: false },
63
+ ctrlKey: { value: modifiers.ctrlKey ?? false, enumerable: false },
64
+ metaKey: { value: modifiers.metaKey ?? false, enumerable: false },
65
+ shiftKey: { value: modifiers.shiftKey ?? false, enumerable: false },
66
+ button: { value: modifiers.button ?? 0, enumerable: false },
67
+ defaultPrevented: { get: () => defaultPrevented, enumerable: false },
68
+ preventDefault: {
69
+ value: () => {
70
+ defaultPrevented = true
71
+ },
72
+ enumerable: false,
73
+ },
74
+ })
75
+ return event as CanvasPressEvent
76
+ }
77
+
78
+ export interface CanvasInteractionProps {
79
+ /** Portable discrete activation for closed Canvas geometry. */
80
+ onPress?: (event: CanvasPressEvent) => void
81
+ /** Turns this shape into a destination while leaving its pixels on the Canvas surface. */
82
+ href?: string
83
+ external?: boolean
84
+ replace?: boolean
85
+ /**
86
+ * The shape a person is currently indicating, by whatever means the
87
+ * device has. `undefined` when they stop indicating it.
88
+ *
89
+ * One notion rather than one per input, because a tooltip is one
90
+ * feature and a chart should not carry three implementations of it. A
91
+ * mouse or a pen indicates by hovering; a finger indicates by holding.
92
+ * Both arrive here, and the handler cannot tell which -- deliberately,
93
+ * since the answer never changes what a tooltip does.
94
+ *
95
+ * Hover is not a Web-only idea, which is worth stating because it is
96
+ * easy to assume: React Native's `View` declares the whole W3C pointer
97
+ * set and its payload carries `pointerType` and `offsetX`/`offsetY`,
98
+ * the same as the browser's. A tablet with a trackpad hovers.
99
+ *
100
+ * Keyboard is *not* a source yet, and that is the honest gap. Making
101
+ * one would mean deciding how a shape inside a canvas takes focus
102
+ * without inventing a control nobody can see, which is its own
103
+ * question -- see #26.
104
+ */
105
+ onActiveChange?: (event: CanvasPressEvent | undefined) => void
106
+ /**
107
+ * What this shape is called, which is what makes it reachable at all.
108
+ *
109
+ * An interactive shape is a control, and a control on a canvas is
110
+ * unreachable by every route except a pointer: there is one element,
111
+ * and the shapes inside it are pixels. So a named one is given a real
112
+ * semantic control in the surface's hidden layer -- a button for an
113
+ * action or an anchor for a destination -- and the canvas keeps the drawing.
114
+ *
115
+ * Required for that to happen, and deliberately: a button with no
116
+ * accessible name is announced as "button" and is exactly the invisible
117
+ * control this is meant to avoid. A shape with a handler and no name
118
+ * says so in development rather than being silently pointer-only.
119
+ */
120
+ accessibilityLabel?: string
121
+ disabled?: boolean
122
+ }
123
+
124
+ /** One colour at one position along a gradient, `0` to `1`. */
125
+ export interface CanvasGradientStop {
126
+ offset: number
127
+ color: string
128
+ }
129
+
130
+ /**
131
+ * A gradient, in the shape both platforms take.
132
+ *
133
+ * Canvas2D builds one from coordinates and `addColorStop`; Skia takes a
134
+ * `start`/`end` pair with parallel `colors` and `positions` arrays. The two
135
+ * are the same description written differently, so this is the
136
+ * description and each renderer writes it its own way.
137
+ *
138
+ * The coordinates are the shape's own, on both. That is not a choice
139
+ * either: Canvas2D reads them in the current transform, which is the
140
+ * one Hozo set for this node, and Skia reads them in the shape's space.
141
+ *
142
+ * A radial gradient here is one circle, not Canvas2D's two. `r0` and a
143
+ * second centre have no counterpart in Skia, and a portable contract
144
+ * cannot promise what one side cannot draw.
145
+ */
146
+ export interface CanvasLinearGradient {
147
+ kind: 'linear'
148
+ from: CanvasPoint
149
+ to: CanvasPoint
150
+ stops: readonly CanvasGradientStop[]
151
+ }
152
+
153
+ export interface CanvasRadialGradient {
154
+ kind: 'radial'
155
+ center: CanvasPoint
156
+ radius: number
157
+ stops: readonly CanvasGradientStop[]
158
+ }
159
+
160
+ /**
161
+ * What a shape can be painted with.
162
+ *
163
+ * A string is a colour, and `'none'` is the absence of paint -- the two
164
+ * meanings the paint props had before gradients existed, unchanged.
165
+ */
166
+ export type CanvasPaint = string | CanvasLinearGradient | CanvasRadialGradient
167
+
168
+ /** Whether a paint is a gradient rather than a colour. */
169
+ export function isGradient(
170
+ paint: CanvasPaint | undefined,
171
+ ): paint is CanvasLinearGradient | CanvasRadialGradient {
172
+ return typeof paint === 'object' && paint !== null
173
+ }
174
+
175
+ export interface CanvasPaintProps {
176
+ /** Compiler input. Runtime drawing uses the explicit paint props below. */
177
+ className?: string
178
+ fill?: CanvasPaint
179
+ stroke?: CanvasPaint
180
+ strokeWidth?: number
181
+ opacity?: number
182
+ lineCap?: 'butt' | 'round' | 'square'
183
+ lineJoin?: 'bevel' | 'round' | 'miter'
184
+ }
185
+
186
+ /**
187
+ * Whether this paint puts anything on the surface, per channel.
188
+ *
189
+ * Both renderers had these two conditions written out, identically and
190
+ * separately -- Canvas2D in `applyPaint`, Skia in `paintLayers`. Hit
191
+ * testing needs the same answer for a third time, and a hit test that
192
+ * disagrees with the paint is worse than one that refuses: it reports a
193
+ * press on something nobody can see. So the condition is written once and
194
+ * all three read it.
195
+ *
196
+ * The defaults are the platforms' own and agree: an unset `strokeWidth`
197
+ * is 1 in Canvas2D and in Skia, so `?? 1` is not a Hozo policy.
198
+ */
199
+ export function paintStrokes(paint: CanvasPaintProps): boolean {
200
+ return paint.stroke !== undefined && paint.stroke !== 'none' && (paint.strokeWidth ?? 1) > 0
201
+ }
202
+
203
+ export function paintFills(paint: CanvasPaintProps): boolean {
204
+ return paint.fill !== 'none' && (paint.fill !== undefined || paint.stroke === undefined)
205
+ }
206
+
207
+ /**
208
+ * The four fields both platforms take, defaulted once.
209
+ *
210
+ * Shared so a face cannot differ between the surfaces for a reason Hozo
211
+ * chose. What it cannot make equal is the face a *system* resolves these
212
+ * to, which is why `fontFamily` is passed through untouched rather than
213
+ * mapped to something clever.
214
+ */
215
+ export function textFontSpec(props: TextProps) {
216
+ return {
217
+ fontFamily: props.fontFamily ?? 'sans-serif',
218
+ fontSize: props.fontSize,
219
+ fontStyle: props.fontStyle ?? 'normal',
220
+ fontWeight: props.fontWeight ?? 'normal',
221
+ } as const
222
+ }
223
+
224
+ /** The same four as the CSS shorthand `CanvasRenderingContext2D.font` takes. */
225
+ export function cssFontShorthand(props: TextProps): string {
226
+ const font = textFontSpec(props)
227
+ return `${font.fontStyle} ${font.fontWeight} ${font.fontSize}px ${font.fontFamily}`
228
+ }
229
+
230
+ export interface CanvasTransform {
231
+ translateX?: number
232
+ translateY?: number
233
+ scaleX?: number
234
+ scaleY?: number
235
+ /** Clockwise degrees. */
236
+ rotate?: number
237
+ originX?: number
238
+ originY?: number
239
+ }
240
+
241
+ export interface GroupProps {
242
+ children?: ReactNode
243
+ opacity?: number
244
+ transform?: CanvasTransform
245
+ }
246
+
247
+ export interface RectProps extends CanvasPaintProps, CanvasInteractionProps {
248
+ x?: number
249
+ y?: number
250
+ width: number
251
+ height: number
252
+ }
253
+
254
+ export interface RoundedRectProps extends RectProps {
255
+ radius: number
256
+ }
257
+
258
+ export interface CircleProps extends CanvasPaintProps, CanvasInteractionProps {
259
+ cx: number
260
+ cy: number
261
+ radius: number
262
+ }
263
+
264
+ export interface EllipseProps extends CanvasPaintProps, CanvasInteractionProps {
265
+ cx: number
266
+ cy: number
267
+ radiusX: number
268
+ radiusY: number
269
+ }
270
+
271
+ export interface LineProps extends CanvasPaintProps, CanvasInteractionProps {
272
+ x1: number
273
+ y1: number
274
+ x2: number
275
+ y2: number
276
+ }
277
+
278
+ /**
279
+ * A single line of text, drawn at a baseline.
280
+ *
281
+ * One line, and no wrapping. Neither renderer breaks lines -- Canvas2D's
282
+ * `fillText` and Skia's `Text` both draw a run and stop -- so wrapping
283
+ * would be Hozo's own layout engine rather than a shared contract, and
284
+ * the labels a chart needs are one line each.
285
+ *
286
+ * `x` is the left edge and `y` the alphabetic baseline, which is not a
287
+ * choice so much as the one place the platforms already agreed: it is
288
+ * Skia's only model and Canvas2D's default.
289
+ *
290
+ * The font is named rather than supplied. Skia's `matchFont` resolves a
291
+ * system face from these four fields synchronously, and Canvas2D takes
292
+ * the same four as a CSS shorthand, so nothing has to ship a font file.
293
+ * The cost is that the two may not resolve to the same face: system fonts
294
+ * differ, and a chart that needs identical glyphs on both has to load
295
+ * one, which is outside this contract.
296
+ */
297
+ export interface TextProps extends CanvasPaintProps, CanvasInteractionProps {
298
+ text: string
299
+ x: number
300
+ y: number
301
+ /**
302
+ * Required, because the platforms disagree on a default and neither
303
+ * default is a good one -- Canvas2D starts at 10px, which is smaller
304
+ * than any label anybody wants.
305
+ */
306
+ fontSize: number
307
+ fontFamily?: string
308
+ fontStyle?: 'normal' | 'italic'
309
+ fontWeight?:
310
+ | 'normal'
311
+ | 'bold'
312
+ | '100'
313
+ | '200'
314
+ | '300'
315
+ | '400'
316
+ | '500'
317
+ | '600'
318
+ | '700'
319
+ | '800'
320
+ | '900'
321
+ /** Which part of the run sits at `x`. */
322
+ textAlign?: 'left' | 'center' | 'right'
323
+ /**
324
+ * The width to wrap within, in the scene’s own coordinates.
325
+ *
326
+ * Without it a label is one line however long it is, which is what
327
+ * every drawing API does and what nobody wants for a legend. The
328
+ * break opportunities are the shared ones -- spaces, the boundaries
329
+ * around CJK, and the two kinsoku classes -- and the widths are the
330
+ * renderer’s own, so where a line ends can differ between platforms
331
+ * while what is allowed to end it cannot.
332
+ */
333
+ maxWidth?: number
334
+ /**
335
+ * The distance between baselines, as a multiple of `fontSize`.
336
+ *
337
+ * A multiple rather than a length, so a label that changes size
338
+ * keeps its spacing. `y` stays the first baseline, which is where it
339
+ * is with no wrapping at all.
340
+ */
341
+ lineHeight?: number
342
+ /**
343
+ * That these words are decoration rather than information.
344
+ *
345
+ * Text drawn on a canvas is pixels: no screen reader will ever read it,
346
+ * whatever the surface calls itself. So a surface that draws words and
347
+ * offers only a name has lost them, and `canvasUnreadableText` says so.
348
+ *
349
+ * This is the answer for the case where nothing was lost, and there are
350
+ * two of those. The words may carry no information -- a watermark, a
351
+ * repeated glyph. Or their information may already be exposed
352
+ * elsewhere, which is the commoner one: a label reading "Revenue rose
353
+ * from 3,200 in January to 4,800 in March" covers the drawn "Jan" and
354
+ * "4800" without containing either string, and no test of the text
355
+ * could tell.
356
+ *
357
+ * Both are what "presentational" means in ARIA. The word is not "this
358
+ * is pretty" but "this needs no accessible representation of its own",
359
+ * and a thing already said elsewhere needs none. So marking a covered
360
+ * label `decorative` is the word used correctly rather than a warning
361
+ * suppressed, which is why it is spelled the way the surface's own
362
+ * `decorative` is: the two say the same thing at different scales.
363
+ *
364
+ * The containment check that runs alongside this only catches the
365
+ * literal case -- `accessibilityLabel="Unread: 42"` over a drawn `42`.
366
+ * It is a convenience, not the boundary; semantics are the author's to
367
+ * assert because nothing here can read them.
368
+ */
369
+ decorative?: boolean
370
+ }
371
+
372
+ export interface PathProps extends CanvasPaintProps, CanvasInteractionProps {
373
+ path: string
374
+ fillRule?: 'nonzero' | 'evenodd'
375
+ }
376
+
377
+ export type ClipProps = (
378
+ | { path: string; x?: never; y?: never; width?: never; height?: never }
379
+ | { path?: never; x?: number; y?: number; width: number; height: number }
380
+ ) & { children?: ReactNode }
381
+
382
+ type SceneProps<Props> = Omit<Props, keyof CanvasInteractionProps>
383
+
384
+ export type CanvasLeafNode =
385
+ | { id?: string; kind: 'rect'; props: SceneProps<RectProps> }
386
+ | { id?: string; kind: 'rounded-rect'; props: SceneProps<RoundedRectProps> }
387
+ | { id?: string; kind: 'circle'; props: SceneProps<CircleProps> }
388
+ | { id?: string; kind: 'ellipse'; props: SceneProps<EllipseProps> }
389
+ | { id?: string; kind: 'line'; props: SceneProps<LineProps> }
390
+ | { id?: string; kind: 'text'; props: SceneProps<TextProps> }
391
+ | { id?: string; kind: 'path'; props: SceneProps<PathProps> }
392
+
393
+ export type CanvasSceneNode =
394
+ | CanvasLeafNode
395
+ | {
396
+ id?: string
397
+ kind: 'group'
398
+ props: Omit<GroupProps, 'children'>
399
+ children: readonly CanvasSceneNode[]
400
+ }
401
+ | {
402
+ id?: string
403
+ kind: 'clip'
404
+ props: Omit<ClipProps, 'children'>
405
+ children: readonly CanvasSceneNode[]
406
+ }
407
+
408
+ export type CanvasScene = readonly CanvasSceneNode[]
409
+
410
+ type FlatNode =
411
+ | CanvasLeafNode
412
+ | { kind: 'group'; props: Omit<GroupProps, 'children'> }
413
+ | { kind: 'clip'; props: Omit<ClipProps, 'children'> }
414
+
415
+ interface StoredNode {
416
+ id: string
417
+ parentId?: string
418
+ order: number
419
+ node: FlatNode
420
+ }
421
+
422
+ class CanvasInteractionStore {
423
+ readonly #handlers = new Map<string, (event: CanvasPressEvent) => void>()
424
+ readonly #labels = new Map<string, string>()
425
+ readonly #destinations = new Map<string, CanvasDestination>()
426
+ readonly #listeners = new Set<() => void>()
427
+ #version = 0
428
+
429
+ get version() {
430
+ return this.#version
431
+ }
432
+
433
+ subscribe(listener: () => void) {
434
+ this.#listeners.add(listener)
435
+ return () => {
436
+ this.#listeners.delete(listener)
437
+ }
438
+ }
439
+
440
+ set(
441
+ id: string,
442
+ handler: ((event: CanvasPressEvent) => void) | undefined,
443
+ label: string | undefined,
444
+ destination: CanvasDestination | undefined,
445
+ ) {
446
+ const previousHas = this.has(id)
447
+ const previousLabel = this.#labels.get(id)
448
+ const previousDestination = this.#destinations.get(id)
449
+ if (handler === undefined) this.#handlers.delete(id)
450
+ else this.#handlers.set(id, handler)
451
+ if (label === undefined) this.#labels.delete(id)
452
+ else this.#labels.set(id, label)
453
+ if (destination === undefined) this.#destinations.delete(id)
454
+ else this.#destinations.set(id, destination)
455
+ if (
456
+ previousHas !== this.has(id) ||
457
+ previousLabel !== label ||
458
+ previousDestination?.href !== destination?.href ||
459
+ previousDestination?.external !== destination?.external ||
460
+ previousDestination?.replace !== destination?.replace
461
+ ) {
462
+ this.#emit()
463
+ }
464
+ }
465
+
466
+ label(id: string) {
467
+ return this.#labels.get(id)
468
+ }
469
+
470
+ remove(id: string) {
471
+ const hadInteraction = this.has(id)
472
+ this.#handlers.delete(id)
473
+ this.#labels.delete(id)
474
+ this.#destinations.delete(id)
475
+ if (hadInteraction) this.#emit()
476
+ }
477
+
478
+ has(id: string) {
479
+ return this.#handlers.has(id) || this.#destinations.has(id)
480
+ }
481
+
482
+ press(id: string, event: CanvasPressEvent) {
483
+ this.#handlers.get(id)?.(event)
484
+ }
485
+
486
+ destination(id: string) {
487
+ return this.#destinations.get(id)
488
+ }
489
+
490
+ #emit() {
491
+ this.#version += 1
492
+ for (const listener of this.#listeners) listener()
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Which shape is currently indicated, and who to tell when that changes.
498
+ *
499
+ * The active id lives here rather than in each surface because it is one
500
+ * fact about the scene: two pointers cannot indicate two different shapes
501
+ * and both be right, and a tooltip that believed otherwise would show
502
+ * two.
503
+ */
504
+ class CanvasActiveStore {
505
+ readonly #handlers = new Map<string, (event: CanvasPressEvent | undefined) => void>()
506
+ #activeId: string | undefined
507
+
508
+ set(id: string, handler: (event: CanvasPressEvent | undefined) => void) {
509
+ this.#handlers.set(id, handler)
510
+ }
511
+
512
+ remove(id: string) {
513
+ this.#handlers.delete(id)
514
+ // A shape that unmounts while indicated leaves nothing to be
515
+ // indicated, and the handler it would have been told through is the
516
+ // one that just went away.
517
+ if (this.#activeId === id) this.#activeId = undefined
518
+ }
519
+
520
+ has(id: string) {
521
+ return this.#handlers.has(id)
522
+ }
523
+
524
+ get activeId() {
525
+ return this.#activeId
526
+ }
527
+
528
+ /**
529
+ * Moves the indication, telling the shape that lost it and the one that
530
+ * gained it, in that order.
531
+ *
532
+ * Nothing happens when the target has not changed, so a pointer moving
533
+ * across one shape reports once rather than once per pixel -- which is
534
+ * what makes this usable from `onPointerMove` at all.
535
+ */
536
+ activate(id: string | undefined, event: CanvasPressEvent | undefined) {
537
+ if (this.#activeId === id) return
538
+ const previous = this.#activeId
539
+ this.#activeId = id
540
+ if (previous !== undefined) this.#handlers.get(previous)?.(undefined)
541
+ if (id !== undefined && event !== undefined) this.#handlers.get(id)?.(event)
542
+ }
543
+ }
544
+
545
+ function sceneValueEqual(left: unknown, right: unknown): boolean {
546
+ if (Object.is(left, right)) return true
547
+ if (!left || !right || typeof left !== 'object' || typeof right !== 'object') return false
548
+ if (Array.isArray(left) || Array.isArray(right)) {
549
+ return (
550
+ Array.isArray(left) &&
551
+ Array.isArray(right) &&
552
+ left.length === right.length &&
553
+ left.every((value, index) => sceneValueEqual(value, right[index]))
554
+ )
555
+ }
556
+ const leftRecord = left as Record<string, unknown>
557
+ const rightRecord = right as Record<string, unknown>
558
+ const leftKeys = Object.keys(leftRecord)
559
+ const rightKeys = Object.keys(rightRecord)
560
+ return (
561
+ leftKeys.length === rightKeys.length &&
562
+ leftKeys.every(
563
+ (key) => key in rightRecord && sceneValueEqual(leftRecord[key], rightRecord[key]),
564
+ )
565
+ )
566
+ }
567
+
568
+ function flatNodeEqual(left: FlatNode, right: FlatNode) {
569
+ return left.kind === right.kind && sceneValueEqual(left.props, right.props)
570
+ }
571
+
572
+ /** A small platform-neutral retained scene. It is deliberately not Hozo's semantic/SVG IR. */
573
+ export class CanvasSceneStore {
574
+ readonly #nodes = new Map<string, StoredNode>()
575
+ readonly #listeners = new Set<() => void>()
576
+ #nextOrder = 0
577
+ #version = 0
578
+
579
+ get version() {
580
+ return this.#version
581
+ }
582
+
583
+ subscribe(listener: () => void) {
584
+ this.#listeners.add(listener)
585
+ return () => {
586
+ this.#listeners.delete(listener)
587
+ }
588
+ }
589
+
590
+ upsert(id: string, parentId: string | undefined, node: FlatNode) {
591
+ const previous = this.#nodes.get(id)
592
+ if (previous && previous.parentId === parentId && flatNodeEqual(previous.node, node)) return
593
+ this.#nodes.set(id, {
594
+ id,
595
+ parentId,
596
+ order: previous?.order ?? this.#nextOrder++,
597
+ node,
598
+ })
599
+ this.#emit()
600
+ }
601
+
602
+ remove(id: string) {
603
+ if (!this.#nodes.delete(id)) return
604
+ this.#emit()
605
+ }
606
+
607
+ snapshot(): CanvasScene {
608
+ const childrenByParent = new Map<string | undefined, StoredNode[]>()
609
+ for (const stored of this.#nodes.values()) {
610
+ const siblings = childrenByParent.get(stored.parentId) ?? []
611
+ siblings.push(stored)
612
+ childrenByParent.set(stored.parentId, siblings)
613
+ }
614
+ for (const siblings of childrenByParent.values()) {
615
+ siblings.sort((a, b) => a.order - b.order)
616
+ }
617
+
618
+ const build = (parentId: string | undefined, ancestors: Set<string>): CanvasSceneNode[] => {
619
+ const result: CanvasSceneNode[] = []
620
+ for (const stored of childrenByParent.get(parentId) ?? []) {
621
+ // A malformed custom renderer cannot turn a parent cycle into an
622
+ // infinite traversal. The public marker components never create one.
623
+ if (ancestors.has(stored.id)) continue
624
+ if (stored.node.kind === 'group' || stored.node.kind === 'clip') {
625
+ const nextAncestors = new Set(ancestors).add(stored.id)
626
+ result.push({
627
+ ...stored.node,
628
+ id: stored.id,
629
+ children: build(stored.id, nextAncestors),
630
+ } as CanvasSceneNode)
631
+ } else {
632
+ result.push({ ...stored.node, id: stored.id })
633
+ }
634
+ }
635
+ return result
636
+ }
637
+
638
+ return build(undefined, new Set())
639
+ }
640
+
641
+ #emit() {
642
+ this.#version += 1
643
+ for (const listener of this.#listeners) listener()
644
+ }
645
+ }
646
+
647
+ interface SceneContextValue {
648
+ store: CanvasSceneStore
649
+ interactions: CanvasInteractionStore
650
+ active: CanvasActiveStore
651
+ parentId?: string
652
+ }
653
+
654
+ const SceneContext = createContext<SceneContextValue | undefined>(undefined)
655
+ const useIsoLayoutEffect = typeof document === 'undefined' ? useEffect : useLayoutEffect
656
+
657
+ function useSceneNode(node: FlatNode) {
658
+ const context = useContext(SceneContext)
659
+ const id = useId()
660
+ if (!context) {
661
+ throw new Error('Canvas shapes must be rendered inside <Canvas>.')
662
+ }
663
+
664
+ useIsoLayoutEffect(() => () => context.store.remove(id), [context.store, id])
665
+ useIsoLayoutEffect(() => {
666
+ context.store.upsert(id, context.parentId, node)
667
+ }, [context.store, context.parentId, id, node])
668
+ return {
669
+ store: context.store,
670
+ interactions: context.interactions,
671
+ active: context.active,
672
+ id,
673
+ }
674
+ }
675
+
676
+ function interactiveLeaf<P extends CanvasInteractionProps>(
677
+ // Every leaf kind, which it did not used to be. The list was spelled out
678
+ // while it meant something -- first the four closed shapes, then lines,
679
+ // then paths -- and the plain leaf beside it was for the shapes the hit
680
+ // test could not answer for. Text was the last of those, so the
681
+ // distinction and the plain `leaf` went with it.
682
+ kind: CanvasLeafNode['kind'],
683
+ ) {
684
+ const Component = ({
685
+ onPress,
686
+ onActiveChange,
687
+ accessibilityLabel,
688
+ disabled,
689
+ href,
690
+ external,
691
+ replace,
692
+ ...props
693
+ }: P) => {
694
+ // Not memoised. `props` is a rest object, new on every render, so a
695
+ // memo keyed on it recomputed every time -- the cost of a hook with
696
+ // none of the saving, on every shape in the scene.
697
+ const node = { kind, props } as unknown as FlatNode
698
+ const context = useSceneNode(node)
699
+ useIsoLayoutEffect(() => {
700
+ if ((!onPress && !href) || disabled) {
701
+ context.interactions.remove(context.id)
702
+ return
703
+ }
704
+ context.interactions.set(
705
+ context.id,
706
+ onPress,
707
+ accessibilityLabel,
708
+ href === undefined ? undefined : { href, external, replace },
709
+ )
710
+ return () => context.interactions.remove(context.id)
711
+ }, [
712
+ context.interactions,
713
+ context.id,
714
+ onPress,
715
+ accessibilityLabel,
716
+ disabled,
717
+ href,
718
+ external,
719
+ replace,
720
+ ])
721
+ useIsoLayoutEffect(() => {
722
+ if (!onActiveChange || disabled) {
723
+ context.active.remove(context.id)
724
+ return
725
+ }
726
+ context.active.set(context.id, onActiveChange)
727
+ return () => context.active.remove(context.id)
728
+ }, [context.active, context.id, onActiveChange, disabled])
729
+ return null
730
+ }
731
+ Component.displayName = `Canvas.${kind}`
732
+ return Component
733
+ }
734
+
735
+ export const Rect = interactiveLeaf<RectProps>('rect')
736
+ export const RoundedRect = interactiveLeaf<RoundedRectProps>('rounded-rect')
737
+ export const Circle = interactiveLeaf<CircleProps>('circle')
738
+ export const Ellipse = interactiveLeaf<EllipseProps>('ellipse')
739
+ export const Line = interactiveLeaf<LineProps>('line')
740
+ // Text is not interactive: its region is a run of glyphs, and neither
741
+ // renderer offers a containment test for one. `Path` is, now that each
742
+ // surface answers for its own -- see `CanvasPathHitTest`.
743
+ export const Text = interactiveLeaf<TextProps>('text')
744
+ export const Path = interactiveLeaf<PathProps>('path')
745
+
746
+ export function Group({ children, ...props }: GroupProps) {
747
+ // A rest object is new on every render; see `interactiveLeaf`.
748
+ const node = { kind: 'group' as const, props }
749
+ const context = useSceneNode(node)
750
+ return (
751
+ <SceneContext.Provider
752
+ value={{
753
+ store: context.store,
754
+ interactions: context.interactions,
755
+ active: context.active,
756
+ parentId: context.id,
757
+ }}
758
+ >
759
+ {children}
760
+ </SceneContext.Provider>
761
+ )
762
+ }
763
+
764
+ export function Clip({ children, ...props }: ClipProps) {
765
+ // A rest object is new on every render; see `interactiveLeaf`.
766
+ const node = { kind: 'clip' as const, props }
767
+ const context = useSceneNode(node)
768
+ return (
769
+ <SceneContext.Provider
770
+ value={{
771
+ store: context.store,
772
+ interactions: context.interactions,
773
+ active: context.active,
774
+ parentId: context.id,
775
+ }}
776
+ >
777
+ {children}
778
+ </SceneContext.Provider>
779
+ )
780
+ }
781
+
782
+ /**
783
+ * A cache that forgets, because the things it holds are not a fixed set.
784
+ *
785
+ * Fonts are: a chart uses a handful of specs and reuses them, so an
786
+ * unbounded map is fine there. Paths are not. A line chart that animates
787
+ * builds a new `d` string every frame, and each one parsed by `Path2D`
788
+ * or by `MakeFromSVGString` was kept for the life of the process -- the
789
+ * exact workload #154 describes as Canvas mode's reason to exist.
790
+ *
791
+ * Least-recently-used, by the oldest insertion, which a `Map` gives for
792
+ * free: its iteration order is insertion order, so the first key is the
793
+ * oldest. Re-inserting on a hit is what makes "oldest insertion" mean
794
+ * "least recently used".
795
+ *
796
+ * The bound is generous rather than tuned. A frame draws every path it
797
+ * has, so anything smaller than one frame's worth of paths would evict
798
+ * entries it is about to need; anything larger only delays the same
799
+ * behaviour.
800
+ */
801
+ export class BoundedCache<Value> {
802
+ readonly #entries = new Map<string, Value>()
803
+ readonly #limit: number
804
+
805
+ constructor(limit: number) {
806
+ this.#limit = limit
807
+ }
808
+
809
+ get size() {
810
+ return this.#entries.size
811
+ }
812
+
813
+ get(key: string): Value | undefined {
814
+ const value = this.#entries.get(key)
815
+ if (value === undefined) return undefined
816
+ this.#entries.delete(key)
817
+ this.#entries.set(key, value)
818
+ return value
819
+ }
820
+
821
+ set(key: string, value: Value) {
822
+ this.#entries.delete(key)
823
+ this.#entries.set(key, value)
824
+ while (this.#entries.size > this.#limit) {
825
+ const oldest = this.#entries.keys().next().value
826
+ if (oldest === undefined) break
827
+ this.#entries.delete(oldest)
828
+ }
829
+ }
830
+ }
831
+
832
+ /**
833
+ * The compiler's proof that every shape was handled.
834
+ *
835
+ * Three places switch on `kind` -- the two renderers and the hit test --
836
+ * and none of them was checked. Adding a kind to `CanvasLeafNode`
837
+ * produced no error in any of them, verified by adding one: zero
838
+ * diagnostics, because `drawNode` returns `void` so a missing case falls
839
+ * through, `renderNode` returns `ReactNode` and `undefined` is a valid
840
+ * one, and `pointInNode`'s caller takes its result as a condition. A
841
+ * shape whose renderer was forgotten drew nothing, refused every press,
842
+ * and said nothing about either.
843
+ *
844
+ * The parameter typed `never` is what fixes that: reaching it with a kind
845
+ * still in the union is a compile error naming the kind. At run time it
846
+ * warns rather than throws -- the type has already made this unreachable
847
+ * from TypeScript, and a hand-built scene from JavaScript should lose one
848
+ * shape rather than the whole chart.
849
+ */
850
+ export function unhandledShape(node: never, where: string): undefined {
851
+ const kind = (node as { kind?: unknown }).kind
852
+ console.warn(`[hozo] ${where} has no case for a Canvas ${String(kind)}, so it does nothing.`)
853
+ return undefined
854
+ }
855
+
856
+ export interface CanvasControl {
857
+ id: string
858
+ label: string
859
+ destination?: CanvasDestination
860
+ }
861
+
862
+ /**
863
+ * The named interactive shapes, in the order they were drawn.
864
+ *
865
+ * Scene order and not registration order, so the tab order a keyboard
866
+ * walks is the order an eye reads. The registry knows the handlers; only
867
+ * the scene knows where they sit.
868
+ *
869
+ * Unnamed ones are left out and reported instead. A `<button>` with no
870
+ * accessible name is announced as "button" and is the invisible control
871
+ * this whole route exists to avoid, so the shape stays pointer-only and
872
+ * says so rather than becoming one.
873
+ */
874
+ const warned = new Set<string>()
875
+
876
+ export function canvasControls(
877
+ scene: CanvasScene,
878
+ interactions: CanvasInteractionStore,
879
+ warn?: (message: string) => void,
880
+ ): CanvasControl[] {
881
+ const found: CanvasControl[] = []
882
+ const walk = (nodes: CanvasScene) => {
883
+ for (const node of nodes) {
884
+ if (node.id !== undefined && interactions.has(node.id)) {
885
+ const label = interactions.label(node.id)
886
+ if (label === undefined) {
887
+ // Once per shape, not once per render: `useId` is stable for
888
+ // the life of the component, and a redraw is not new news.
889
+ if (!warned.has(node.id)) {
890
+ warned.add(node.id)
891
+ warn?.(
892
+ `an interactive Canvas ${node.kind} has no accessibilityLabel, so it can only be ` +
893
+ 'reached with a pointer. Name it to give it a keyboard control.',
894
+ )
895
+ }
896
+ } else {
897
+ found.push({ id: node.id, label, destination: interactions.destination(node.id) })
898
+ }
899
+ }
900
+ if (node.kind === 'group' || node.kind === 'clip') walk(node.children)
901
+ }
902
+ }
903
+ walk(scene)
904
+ return found
905
+ }
906
+
907
+ const reportedLosses = new Set<string>()
908
+
909
+ /**
910
+ * The drawn words a person using a screen reader will never get.
911
+ *
912
+ * Canvas text is pixels. Unlike SVG, where the fix was a role that stops
913
+ * hiding the children, there is nothing here to expose -- so `role="img"`
914
+ * on a Canvas is right, and the defect is not the role but the silence.
915
+ *
916
+ * Four things mean nothing was lost, and each is the author saying
917
+ * something different rather than the same suppression spelled four ways:
918
+ *
919
+ * - an `accessibleFallback`: "the content is here". The fix, and the
920
+ * only one that supplies the data. Whether it really contains it is
921
+ * not checkable from here, and presence is the honest signal.
922
+ * - `decorative` on the surface: "this drawing carries no information".
923
+ * - `decorative` on the text: "these words are decoration".
924
+ * - the words being in the name already.
925
+ *
926
+ * Returns what is lost rather than a boolean, so a caller can say which
927
+ * words rather than that some exist.
928
+ */
929
+ export function canvasUnreadableText(scene: CanvasScene, accessibleName?: string): string[] {
930
+ const name = (accessibleName ?? '').toLowerCase()
931
+ const lost: string[] = []
932
+ const walk = (nodes: CanvasScene) => {
933
+ for (const node of nodes) {
934
+ if (node.kind === 'group' || node.kind === 'clip') {
935
+ walk(node.children)
936
+ continue
937
+ }
938
+ if (node.kind !== 'text' || node.props.decorative) continue
939
+ const text = node.props.text.trim()
940
+ if (text !== '' && !name.includes(text.toLowerCase())) lost.push(text)
941
+ }
942
+ }
943
+ walk(scene)
944
+ return lost
945
+ }
946
+
947
+ /**
948
+ * Says it once per surface per distinct loss.
949
+ *
950
+ * Not once ever: a chart whose labels change has lost different words and
951
+ * that is news. Not once per render either -- a redraw is not.
952
+ */
953
+ export function reportUnreadableText(lost: string[], warn: (message: string) => void) {
954
+ if (lost.length === 0) return
955
+ const key = lost.join('\u0000')
956
+ if (reportedLosses.has(key)) return
957
+ reportedLosses.add(key)
958
+ const shown = lost.slice(0, 3).join('", "')
959
+ const rest = lost.length > 3 ? ` and ${lost.length - 3} more` : ''
960
+ warn(
961
+ `this Canvas draws words no screen reader can read -- "${shown}"${rest}. Canvas text is ` +
962
+ 'pixels, and the accessibilityLabel on the surface does not contain them. Pass an ' +
963
+ 'accessibleFallback with the same information -- a table, a list, a paragraph -- or mark ' +
964
+ 'the text decorative if it carries none.',
965
+ )
966
+ }
967
+
968
+ /** Shared by the Web and Native roots; `collector` executes arbitrary React composition. */
969
+ export function useCanvasScene(children: ReactNode) {
970
+ const storeRef = useRef<CanvasSceneStore | null>(null)
971
+ if (!storeRef.current) storeRef.current = new CanvasSceneStore()
972
+ const store = storeRef.current
973
+ const interactionStoreRef = useRef<CanvasInteractionStore | null>(null)
974
+ if (!interactionStoreRef.current) interactionStoreRef.current = new CanvasInteractionStore()
975
+ const interactions = interactionStoreRef.current
976
+ const activeStoreRef = useRef<CanvasActiveStore | null>(null)
977
+ if (!activeStoreRef.current) activeStoreRef.current = new CanvasActiveStore()
978
+ const active = activeStoreRef.current
979
+ const [revision, setRevision] = useState(store.version)
980
+ const [interactionRevision, setInteractionRevision] = useState(interactions.version)
981
+
982
+ useIsoLayoutEffect(() => {
983
+ setRevision(store.version)
984
+ return store.subscribe(() => setRevision(store.version))
985
+ }, [store])
986
+ useIsoLayoutEffect(() => {
987
+ setInteractionRevision(interactions.version)
988
+ return interactions.subscribe(() => setInteractionRevision(interactions.version))
989
+ }, [interactions])
990
+
991
+ const rootContext = useMemo(
992
+ () => ({ store, interactions, active }),
993
+ [store, interactions, active],
994
+ )
995
+ const collector = useMemo(
996
+ () => <SceneContext.Provider value={rootContext}>{children}</SceneContext.Provider>,
997
+ [rootContext, children],
998
+ )
999
+
1000
+ // A shape is worth hit testing if either handler is on it. Without the
1001
+ // second half a hover-only shape would never be found, and `onActiveChange`
1002
+ // would be a prop that type-checks and never fires.
1003
+ const isInteractive = useCallback(
1004
+ (id: string) => interactions.has(id) || active.has(id),
1005
+ [interactions, active],
1006
+ )
1007
+ const press = useCallback(
1008
+ (id: string, event: CanvasPressEvent) => {
1009
+ interactions.press(id, event)
1010
+ return event.defaultPrevented ? undefined : interactions.destination(id)
1011
+ },
1012
+ [interactions],
1013
+ )
1014
+ const activate = useCallback(
1015
+ (id: string | undefined, event: CanvasPressEvent | undefined) => active.activate(id, event),
1016
+ [active],
1017
+ )
1018
+
1019
+ return {
1020
+ // `revision` is read by nothing, and that is the point of it: a
1021
+ // counter the store bumps, whose only job is to invalidate this
1022
+ // snapshot. `biome check --unsafe` removed it once, and every hover
1023
+ // and press test in this package failed with nothing under the
1024
+ // pointer, because the scene never refreshed.
1025
+ // biome-ignore lint/correctness/useExhaustiveDependencies: it is what invalidates the snapshot
1026
+ scene: useMemo(() => store.snapshot(), [store, revision]),
1027
+ // A scene revision redraws the platform surface, but must not rerender
1028
+ // every marker just because the root observed it. Stable provider value
1029
+ // and element identity keep large scenes from doing that second pass.
1030
+ collector,
1031
+ isInteractive,
1032
+ press,
1033
+ activate,
1034
+ interactions,
1035
+ interactionRevision,
1036
+ }
1037
+ }