@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/index.tsx ADDED
@@ -0,0 +1,510 @@
1
+ import { activateHozoNavigation, useHozoNavigation } from '@hozo/engine/navigation'
2
+ import {
3
+ type CSSProperties,
4
+ type ReactNode,
5
+ type PointerEvent as ReactPointerEvent,
6
+ useEffect,
7
+ useLayoutEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ } from 'react'
12
+
13
+ import { type CanvasAccessibilityProps, canvasAccessibilityMode } from './accessibility.ts'
14
+ import {
15
+ type CanvasPoint,
16
+ type CanvasTextMetrics,
17
+ canvasNodePoint,
18
+ hitTestCanvas,
19
+ } from './hit-test.ts'
20
+ import { renderCanvas2D } from './render-canvas-2d.ts'
21
+ import {
22
+ BoundedCache,
23
+ Circle,
24
+ Clip,
25
+ canvasControls,
26
+ canvasPressEvent,
27
+ canvasUnreadableText,
28
+ cssFontShorthand,
29
+ Ellipse,
30
+ Group,
31
+ Line,
32
+ Path,
33
+ Rect,
34
+ RoundedRect,
35
+ reportUnreadableText,
36
+ Text,
37
+ type TextProps,
38
+ useCanvasScene,
39
+ } from './scene.tsx'
40
+ import { wrapText } from './wrap-text.ts'
41
+
42
+ export type { CanvasAccessibilityProps, CanvasAccessibleFallback } from './accessibility.ts'
43
+ export {
44
+ type CanvasHitTestResult,
45
+ type CanvasHitTestViewport,
46
+ type CanvasPathHitTest,
47
+ type CanvasPoint,
48
+ type CanvasRendererQueries,
49
+ type CanvasTextMeasure,
50
+ type CanvasTextMetrics,
51
+ hitTestCanvas,
52
+ } from './hit-test.ts'
53
+ export { type CanvasViewport, renderCanvas2D } from './render-canvas-2d.ts'
54
+ export type {
55
+ CanvasDestination,
56
+ CanvasInteractionProps,
57
+ CanvasPaintProps,
58
+ CanvasPressEvent,
59
+ CanvasScene,
60
+ CanvasSceneNode,
61
+ CanvasTransform,
62
+ CircleProps,
63
+ ClipProps,
64
+ EllipseProps,
65
+ GroupProps,
66
+ LineProps,
67
+ PathProps,
68
+ RectProps,
69
+ RoundedRectProps,
70
+ } from './scene.tsx'
71
+ export { CanvasSceneStore } from './scene.tsx'
72
+ // The rule on its own, for a caller with a measurement of its own --
73
+ // one that already knows its metrics, or is laying out for a font it
74
+ // will load later.
75
+ export { textLines, wrapText } from './wrap-text.ts'
76
+
77
+ /**
78
+ * A run of text, measured the way the renderer measures it.
79
+ *
80
+ * `actualBoundingBox*` rather than `fontBoundingBox*`: the ink, not the
81
+ * line box. A label sits where its glyphs are, and the font box of a
82
+ * run with no descenders reaches below anything on screen.
83
+ */
84
+ function measureWith(context: CanvasRenderingContext2D, props: TextProps): CanvasTextMetrics {
85
+ context.save()
86
+ context.font = cssFontShorthand(props)
87
+ const metrics = context.measureText(props.text)
88
+ context.restore()
89
+ return {
90
+ width: metrics.width,
91
+ ascent: metrics.actualBoundingBoxAscent ?? 0,
92
+ descent: metrics.actualBoundingBoxDescent ?? 0,
93
+ }
94
+ }
95
+
96
+ /**
97
+ * A context to measure with for a caller that is not inside a surface.
98
+ *
99
+ * Text metrics read nothing from a canvas but its `font`, so a caller
100
+ * laying out before anything has mounted gets the numbers the drawing
101
+ * context would have given. Made once and kept: an element per
102
+ * measurement would be the expensive part of this.
103
+ */
104
+ let measuringContext: CanvasRenderingContext2D | null | undefined
105
+ function sharedContext() {
106
+ if (measuringContext === undefined) {
107
+ measuringContext = globalThis.document?.createElement('canvas').getContext('2d') ?? null
108
+ }
109
+ return measuringContext
110
+ }
111
+
112
+ /**
113
+ * What a label will occupy, for a caller placing something against it.
114
+ *
115
+ * The measurement this package took internally and kept. Sizing a
116
+ * tooltip against a label, or deciding where a line has to break, meant
117
+ * guessing at metrics only Hozo could see.
118
+ *
119
+ * `undefined` where there is no renderer to ask -- a server, a test --
120
+ * which is the refusal a path hit test makes there for the same reason.
121
+ * A guess would be a layout that moves on hydration.
122
+ */
123
+ export function measureCanvasText(props: TextProps): CanvasTextMetrics | undefined {
124
+ const context = sharedContext()
125
+ return context ? measureWith(context, props) : undefined
126
+ }
127
+
128
+ /**
129
+ * The lines a label would be broken into at a given width.
130
+ *
131
+ * The same rule `maxWidth` follows, for a caller doing its own layout:
132
+ * sizing a card around a legend, deciding how tall a row has to be,
133
+ * placing something under the last line. Withholding it would leave
134
+ * those to a guess, which is what this package did with the
135
+ * measurement until it stopped.
136
+ *
137
+ * `undefined` where there is no renderer to measure with, as
138
+ * `measureCanvasText` is and for the same reason.
139
+ */
140
+ export function wrapCanvasText(props: TextProps, maxWidth: number): string[] | undefined {
141
+ const context = sharedContext()
142
+ if (!context) return undefined
143
+ return wrapText(
144
+ props.text,
145
+ maxWidth,
146
+ (run) => measureWith(context, { ...props, text: run }).width,
147
+ )
148
+ }
149
+
150
+ export type CanvasProps = CanvasAccessibilityProps & {
151
+ children?: ReactNode
152
+ className?: string
153
+ style?: CSSProperties
154
+ width?: number
155
+ height?: number
156
+ viewBox?: readonly [x: number, y: number, width: number, height: number]
157
+ fit?: 'contain' | 'stretch'
158
+ testID?: string
159
+ }
160
+
161
+ interface Size {
162
+ width: number
163
+ height: number
164
+ pixelRatio: number
165
+ }
166
+
167
+ const useIsoLayoutEffect = typeof document === 'undefined' ? useEffect : useLayoutEffect
168
+
169
+ function Root({
170
+ children,
171
+ className,
172
+ style,
173
+ width,
174
+ height,
175
+ viewBox,
176
+ fit = 'contain',
177
+ decorative,
178
+ accessibilityLabel,
179
+ accessibleFallback,
180
+ testID,
181
+ }: CanvasProps) {
182
+ const canvasRef = useRef<HTMLCanvasElement>(null)
183
+ const pressedTargets = useRef(new Map<number, string>())
184
+ const navigation = useHozoNavigation()
185
+ const { scene, collector, isInteractive, press, activate, interactions, interactionRevision } =
186
+ useCanvasScene(children)
187
+ const [size, setSize] = useState<Size>(() => ({
188
+ width: width ?? viewBox?.[2] ?? 300,
189
+ height: height ?? viewBox?.[3] ?? 150,
190
+ pixelRatio: 1,
191
+ }))
192
+
193
+ useIsoLayoutEffect(() => {
194
+ const canvas = canvasRef.current
195
+ if (!canvas) return
196
+ const measure = () => {
197
+ const bounds = canvas.getBoundingClientRect()
198
+ const next = {
199
+ width: width ?? (bounds.width || viewBox?.[2] || 300),
200
+ height: height ?? (bounds.height || viewBox?.[3] || 150),
201
+ pixelRatio: globalThis.devicePixelRatio || 1,
202
+ }
203
+ setSize((current) =>
204
+ current.width === next.width &&
205
+ current.height === next.height &&
206
+ current.pixelRatio === next.pixelRatio
207
+ ? current
208
+ : next,
209
+ )
210
+ }
211
+ measure()
212
+ if (typeof ResizeObserver === 'undefined') return
213
+ const observer = new ResizeObserver(measure)
214
+ observer.observe(canvas)
215
+ return () => observer.disconnect()
216
+ }, [width, height, viewBox])
217
+
218
+ useIsoLayoutEffect(() => {
219
+ const context = canvasRef.current?.getContext('2d')
220
+ if (!context) return
221
+ renderCanvas2D(context, scene, { ...size, viewBox, fit })
222
+ }, [scene, size, viewBox, fit])
223
+
224
+ const rootStyle: CSSProperties = {
225
+ ...style,
226
+ ...(width === undefined ? null : { width }),
227
+ ...(height === undefined ? null : { height }),
228
+ }
229
+ const accessibilityMode = canvasAccessibilityMode({ decorative, accessibleFallback })
230
+ const surfacePoint = (event: ReactPointerEvent<HTMLCanvasElement>): CanvasPoint => {
231
+ const bounds = event.currentTarget.getBoundingClientRect()
232
+ return {
233
+ x: ((event.clientX - bounds.left) * size.width) / (bounds.width || size.width || 1),
234
+ y: ((event.clientY - bounds.top) * size.height) / (bounds.height || size.height || 1),
235
+ }
236
+ }
237
+ /**
238
+ * Containment answered by the same engine that draws the path.
239
+ *
240
+ * `Path2D` objects are cached by their string: constructing one parses
241
+ * the path, and a pointer moving across a chart would otherwise reparse
242
+ * every path on every frame.
243
+ *
244
+ * The context is the offscreen one this surface already draws with, and
245
+ * `isPointInPath` reads no state from it beyond the path and the point.
246
+ */
247
+ const paths = useRef(new BoundedCache<Path2D>(256))
248
+ const pathHitTest = (path: string, fillRule: 'nonzero' | 'evenodd', point: CanvasPoint) => {
249
+ const context = canvasRef.current?.getContext('2d')
250
+ if (!context) return false
251
+ let path2d = paths.current.get(path)
252
+ if (!path2d) {
253
+ path2d = new Path2D(path)
254
+ paths.current.set(path, path2d)
255
+ }
256
+ // Reset first. `isPointInPath` reads the point in the context's
257
+ // *current* transform, and the point handed here is already in the
258
+ // path's own coordinates -- the hit test inverted the viewport and
259
+ // every ancestor to get it there. Relying on the render pass having
260
+ // left an identity transform behind would work today and break the
261
+ // first time something drew after it.
262
+ context.save()
263
+ context.setTransform(1, 0, 0, 1, 0, 0)
264
+ const inside = context.isPointInPath(path2d, point.x, point.y, fillRule)
265
+ context.restore()
266
+ return inside
267
+ }
268
+
269
+ /**
270
+ * A run measured by the context that will draw it.
271
+ *
272
+ * Falls back to the shared one before this surface has mounted, which
273
+ * agrees with it: text metrics read nothing from a canvas but its
274
+ * `font`.
275
+ */
276
+ const measureText = (props: TextProps): CanvasTextMetrics => {
277
+ const context = canvasRef.current?.getContext('2d')
278
+ if (context) return measureWith(context, props)
279
+ return measureCanvasText(props) ?? { width: 0, ascent: 0, descent: 0 }
280
+ }
281
+
282
+ const hitAt = (point: CanvasPoint) =>
283
+ hitTestCanvas(
284
+ scene,
285
+ point,
286
+ { width: size.width, height: size.height, viewBox, fit },
287
+ isInteractive,
288
+ { pathContains: pathHitTest, measureText },
289
+ )
290
+ const onPointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {
291
+ pressedTargets.current.delete(event.pointerId)
292
+ if (!event.isPrimary || (event.button !== 0 && event.button !== 1)) return
293
+ const hit = hitAt(surfacePoint(event))
294
+ if (!hit) return
295
+ if (event.button === 1 && interactions.destination(hit.id)) event.preventDefault()
296
+ pressedTargets.current.set(event.pointerId, hit.id)
297
+ if (event.pointerType === 'touch') {
298
+ activate(hit.id, canvasPressEvent(hit.point, surfacePoint(event)))
299
+ }
300
+ event.currentTarget.setPointerCapture?.(event.pointerId)
301
+ }
302
+ const onPointerUp = (event: ReactPointerEvent<HTMLCanvasElement>) => {
303
+ const startedTarget = pressedTargets.current.get(event.pointerId)
304
+ pressedTargets.current.delete(event.pointerId)
305
+ if (!startedTarget) return
306
+ const point = surfacePoint(event)
307
+ const hit = hitAt(point)
308
+ // The finger has gone, so it indicates nothing -- whether or not the
309
+ // release also counted as a press.
310
+ if (event.pointerType === 'touch') activate(undefined, undefined)
311
+ if (!hit || hit.id !== startedTarget) return
312
+ const pressEvent = canvasPressEvent(hit.point, point, event)
313
+ const destination = press(hit.id, pressEvent)
314
+ if (!destination) return
315
+
316
+ const newContext = event.button === 1 || event.ctrlKey || event.metaKey || event.shiftKey
317
+ if (newContext || destination.external) {
318
+ window.open(destination.href, '_blank', 'noopener,noreferrer')
319
+ return
320
+ }
321
+ void activateHozoNavigation(navigation, destination, (href) => window.location.assign(href))
322
+ }
323
+ const onPointerCancel = (event: ReactPointerEvent<HTMLCanvasElement>) => {
324
+ pressedTargets.current.delete(event.pointerId)
325
+ activate(undefined, undefined)
326
+ }
327
+ /**
328
+ * What a mouse or a pen indicates by being over it.
329
+ *
330
+ * `pointerType` decides whether this counts, and it has to: a finger
331
+ * emits `pointermove` too, but only while it is touching, so treating
332
+ * that as hover would make a tap indicate the shape it landed on and
333
+ * keep indicating it after the finger left. Touch indicates by holding
334
+ * instead, which is what the press handlers below do.
335
+ */
336
+ const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {
337
+ if (event.pointerType === 'touch') return
338
+ const point = surfacePoint(event)
339
+ const hit = hitAt(point)
340
+ activate(hit?.id, hit ? canvasPressEvent(hit.point, point) : undefined)
341
+ }
342
+ const onPointerLeave = () => activate(undefined, undefined)
343
+
344
+ // Warned always rather than in development only: this package has no
345
+ // build-time channel to say it in, and a control nobody can reach is
346
+ // not a development-only problem. `canvasControls` says it once per
347
+ // shape.
348
+ // Memoised on the scene, which is the only thing that can change the
349
+ // answer. Without this it walked every node on every render of the
350
+ // surface -- a second full traversal beside the snapshot and the
351
+ // redraw, for a list that changes only when a shape is added, removed
352
+ // or renamed.
353
+ //
354
+ // `interactions` is a stable store rather than a value, so it is not a
355
+ // dependency: a handler arriving or leaving mutates it without a new
356
+ // scene. That is why the list is rebuilt whenever the scene is, which
357
+ // is also when a shape's presence could have changed.
358
+ // Only in `label` mode, and that is the whole condition. A
359
+ // `decorative` surface has said it carries no information and a
360
+ // surface with an `accessibleFallback` has supplied it; second-guessing
361
+ // either would be arguing with an author who already answered. What is
362
+ // left is the one where a single name stands for a drawing, and the
363
+ // drawing has words the name does not.
364
+ if (accessibilityMode === 'label') {
365
+ reportUnreadableText(canvasUnreadableText(scene, accessibilityLabel), (message) =>
366
+ console.warn(`[hozo] ${message}`),
367
+ )
368
+ }
369
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the registry revision intentionally invalidates semantic controls without redrawing the scene
370
+ const controls = useMemo(
371
+ () => canvasControls(scene, interactions, (message) => console.warn(`[hozo] ${message}`)),
372
+ [scene, interactions, interactionRevision],
373
+ )
374
+ /**
375
+ * Where a keyboard "is" when it reaches a shape.
376
+ *
377
+ * Its centre in scene coordinates, and the same in surface coordinates
378
+ * only because there is nothing better: a keyboard has no cursor, and a
379
+ * tooltip still has to be told somewhere to appear. A chart that wants
380
+ * to place it from the datum rather than from the point already knows
381
+ * which shape it is.
382
+ */
383
+ const pointFor = (id: string) =>
384
+ canvasNodePoint(scene, id, { width: size.width, height: size.height, viewBox, fit }) ?? {
385
+ point: { x: 0, y: 0 },
386
+ surfacePoint: { x: 0, y: 0 },
387
+ }
388
+
389
+ return (
390
+ <>
391
+ <canvas
392
+ ref={canvasRef}
393
+ className={className}
394
+ style={rootStyle}
395
+ width={Math.max(1, Math.round(size.width * size.pixelRatio))}
396
+ height={Math.max(1, Math.round(size.height * size.pixelRatio))}
397
+ aria-hidden={accessibilityMode === 'label' ? undefined : true}
398
+ aria-label={accessibilityMode === 'label' ? accessibilityLabel : undefined}
399
+ role={accessibilityMode === 'label' ? 'img' : undefined}
400
+ data-testid={testID}
401
+ onPointerDown={onPointerDown}
402
+ onPointerUp={onPointerUp}
403
+ onPointerCancel={onPointerCancel}
404
+ onPointerMove={onPointerMove}
405
+ onPointerLeave={onPointerLeave}
406
+ onLostPointerCapture={onPointerCancel}
407
+ >
408
+ {collector}
409
+ </canvas>
410
+ {/*
411
+ A real control per named interactive shape.
412
+
413
+ The canvas is one element and the shapes in it are pixels, so a
414
+ keyboard has nothing to reach and a screen reader has nothing to
415
+ announce. Actions become buttons; destinations become anchors. Both
416
+ have real focus, native keyboard behaviour, and accessible names,
417
+ placed in the same visually-hidden layer the fallback already uses,
418
+ in scene order so the tab order is the reading order.
419
+
420
+ Focus moves the active target, which is what makes a tooltip
421
+ appear for a keyboard the same way hovering does for a mouse. The
422
+ surface point is the shape's own: a keyboard has no cursor, so
423
+ there is no other honest answer.
424
+
425
+ Rendered whenever there is a named control, not only in
426
+ `fallback` mode. A pressable shape is a control however the
427
+ surface chooses to describe itself.
428
+ */}
429
+ {controls.length > 0 ? (
430
+ <div style={accessibleOnlyStyle} data-hozo-canvas-controls="">
431
+ {controls.map((control) => {
432
+ const point = pointFor(control.id)
433
+ if (control.destination) {
434
+ return (
435
+ <a
436
+ key={control.id}
437
+ href={control.destination.href}
438
+ target={control.destination.external ? '_blank' : undefined}
439
+ rel={control.destination.external ? 'noreferrer noopener' : undefined}
440
+ data-hozo-navigation-replace={control.destination.replace ? '' : undefined}
441
+ onClick={(event) => {
442
+ const pressEvent = canvasPressEvent(point.point, point.surfacePoint, event)
443
+ press(control.id, pressEvent)
444
+ if (pressEvent.defaultPrevented) event.preventDefault()
445
+ }}
446
+ onFocus={() =>
447
+ activate(control.id, canvasPressEvent(point.point, point.surfacePoint))
448
+ }
449
+ onBlur={() => activate(undefined, undefined)}
450
+ >
451
+ {control.label}
452
+ </a>
453
+ )
454
+ }
455
+ return (
456
+ <button
457
+ key={control.id}
458
+ type="button"
459
+ onClick={() => press(control.id, canvasPressEvent(point.point, point.surfacePoint))}
460
+ onFocus={() =>
461
+ activate(control.id, canvasPressEvent(point.point, point.surfacePoint))
462
+ }
463
+ onBlur={() => activate(undefined, undefined)}
464
+ >
465
+ {control.label}
466
+ </button>
467
+ )
468
+ })}
469
+ </div>
470
+ ) : null}
471
+ {accessibilityMode === 'fallback' ? (
472
+ <div
473
+ style={accessibleOnlyStyle}
474
+ role={accessibilityLabel ? 'group' : undefined}
475
+ aria-label={accessibilityLabel}
476
+ data-hozo-canvas-fallback=""
477
+ >
478
+ {accessibleFallback}
479
+ </div>
480
+ ) : null}
481
+ </>
482
+ )
483
+ }
484
+
485
+ const accessibleOnlyStyle: CSSProperties = {
486
+ position: 'absolute',
487
+ width: 1,
488
+ height: 1,
489
+ padding: 0,
490
+ margin: -1,
491
+ overflow: 'hidden',
492
+ clip: 'rect(0, 0, 0, 0)',
493
+ clipPath: 'inset(50%)',
494
+ whiteSpace: 'nowrap',
495
+ border: 0,
496
+ }
497
+
498
+ /** Canvas root plus its platform-neutral scene vocabulary. */
499
+ export const Canvas = Object.assign(Root, {
500
+ Group,
501
+ Clip,
502
+ Text,
503
+ Rect,
504
+ RoundedRect,
505
+ Circle,
506
+ Ellipse,
507
+ Line,
508
+
509
+ Path,
510
+ })