@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
@@ -0,0 +1,733 @@
1
+ import { activateHozoNavigation, useHozoNavigation } from '@hozo/engine/navigation'
2
+ import {
3
+ type DrawingNodeProps,
4
+ FillType,
5
+ matchFont,
6
+ Skia,
7
+ Canvas as SkiaCanvas,
8
+ Circle as SkiaCircle,
9
+ Group as SkiaGroup,
10
+ Line as SkiaLine,
11
+ LinearGradient as SkiaLinearGradient,
12
+ Oval as SkiaOval,
13
+ Path as SkiaPath,
14
+ RadialGradient as SkiaRadialGradient,
15
+ Rect as SkiaRect,
16
+ RoundedRect as SkiaRoundedRect,
17
+ Text as SkiaText,
18
+ type Transforms3d,
19
+ } from '@shopify/react-native-skia'
20
+ import { type ComponentType, type ReactNode, useMemo, useRef, useState } from 'react'
21
+ import {
22
+ type GestureResponderEvent,
23
+ type LayoutChangeEvent,
24
+ Linking,
25
+ type PointerEvent,
26
+ type StyleProp,
27
+ StyleSheet,
28
+ Text,
29
+ View,
30
+ type ViewStyle,
31
+ } from 'react-native'
32
+
33
+ import { type CanvasAccessibilityProps, canvasAccessibilityMode } from './accessibility.ts'
34
+ import {
35
+ type CanvasPoint,
36
+ type CanvasTextMetrics,
37
+ canvasNodePoint,
38
+ hitTestCanvas,
39
+ } from './hit-test.ts'
40
+ import {
41
+ BoundedCache,
42
+ type CanvasPaint,
43
+ type CanvasPaintProps,
44
+ type CanvasScene,
45
+ type CanvasSceneNode,
46
+ Text as CanvasText,
47
+ type CanvasTransform,
48
+ Circle,
49
+ Clip,
50
+ type ClipProps,
51
+ canvasControls,
52
+ canvasPressEvent,
53
+ canvasUnreadableText,
54
+ Ellipse,
55
+ Group,
56
+ isGradient,
57
+ Line,
58
+ Path,
59
+ paintFills,
60
+ paintStrokes,
61
+ Rect,
62
+ RoundedRect,
63
+ reportUnreadableText,
64
+ type TextProps,
65
+ textFontSpec,
66
+ unhandledShape,
67
+ useCanvasScene,
68
+ } from './scene.tsx'
69
+ import { textLines, wrapText } from './wrap-text.ts'
70
+
71
+ export type { CanvasAccessibilityProps, CanvasAccessibleFallback } from './accessibility.ts'
72
+ export {
73
+ type CanvasHitTestResult,
74
+ type CanvasHitTestViewport,
75
+ type CanvasPathHitTest,
76
+ type CanvasPoint,
77
+ type CanvasRendererQueries,
78
+ type CanvasTextMeasure,
79
+ type CanvasTextMetrics,
80
+ hitTestCanvas,
81
+ } from './hit-test.ts'
82
+ export type {
83
+ CanvasDestination,
84
+ CanvasInteractionProps,
85
+ CanvasPaintProps,
86
+ CanvasPressEvent,
87
+ CanvasScene,
88
+ CanvasSceneNode,
89
+ CanvasTransform,
90
+ CircleProps,
91
+ ClipProps,
92
+ EllipseProps,
93
+ GroupProps,
94
+ LineProps,
95
+ PathProps,
96
+ RectProps,
97
+ RoundedRectProps,
98
+ } from './scene.tsx'
99
+ export { CanvasSceneStore } from './scene.tsx'
100
+ export type { CanvasViewport } from './viewport.ts'
101
+ // The rule on its own, for a caller with a measurement of its own --
102
+ // one that already knows its metrics, or is laying out for a font it
103
+ // will load later.
104
+ export { textLines, wrapText } from './wrap-text.ts'
105
+
106
+ export type CanvasProps = CanvasAccessibilityProps & {
107
+ children?: ReactNode
108
+ className?: string
109
+ style?: StyleProp<ViewStyle>
110
+ width?: number
111
+ height?: number
112
+ viewBox?: readonly [x: number, y: number, width: number, height: number]
113
+ fit?: 'contain' | 'stretch'
114
+ testID?: string
115
+ }
116
+
117
+ function transformFor(transform?: CanvasTransform): Transforms3d | undefined {
118
+ if (!transform) return undefined
119
+ // `Transforms3d` and not `Record<string, number>[]`: Skia's type is a
120
+ // union of one-key objects, and the loose annotation is what let this
121
+ // compile against a stub that checked nothing.
122
+ const result: Transforms3d = []
123
+ if (transform.translateX) result.push({ translateX: transform.translateX })
124
+ if (transform.translateY) result.push({ translateY: transform.translateY })
125
+ if (transform.rotate) result.push({ rotate: (transform.rotate * Math.PI) / 180 })
126
+ if (transform.scaleX !== undefined) result.push({ scaleX: transform.scaleX })
127
+ if (transform.scaleY !== undefined) result.push({ scaleY: transform.scaleY })
128
+ return result
129
+ }
130
+
131
+ /**
132
+ * One Skia element per painted channel, since Skia paints one at a time.
133
+ *
134
+ * Generic over the shape rather than typed `typeof SkiaRect` with the
135
+ * geometry as `Record<string, unknown>`. That signature erased every
136
+ * geometry prop, so nothing checked that a `Circle` was handed `cx`/`cy`
137
+ * or a `Line` its two points -- and the hand-written module stub this
138
+ * package used to carry declared every component as
139
+ * `ComponentType<Record<string, unknown>>`, so nothing checked the paint
140
+ * props either. Against Skia's own types, with the geometry kept, both are
141
+ * checked.
142
+ */
143
+ /**
144
+ * Containment answered by the same engine that draws the path.
145
+ *
146
+ * Skia parses an SVG path string into an `SkPath`, so the result is
147
+ * cached by that string and by the fill rule -- a pointer moving across a
148
+ * chart would otherwise reparse every path on every frame, and
149
+ * `setFillType` mutates the path rather than returning a new one, so the
150
+ * two rules cannot share an entry.
151
+ *
152
+ * Module level rather than per surface, like `fonts`: a path string means
153
+ * the same shape wherever it is drawn.
154
+ */
155
+ const parsedPaths = new BoundedCache<ReturnType<typeof Skia.Path.MakeFromSVGString>>(256)
156
+ const pathHitTest = (path: string, fillRule: 'nonzero' | 'evenodd', point: CanvasPoint) => {
157
+ const key = `${fillRule}:${path}`
158
+ let parsed = parsedPaths.get(key)
159
+ if (parsed === undefined) {
160
+ parsed = Skia.Path.MakeFromSVGString(path)
161
+ parsed?.setFillType(fillRule === 'evenodd' ? FillType.EvenOdd : FillType.Winding)
162
+ parsedPaths.set(key, parsed)
163
+ }
164
+ // A path Skia could not parse contains nothing, which is the same
165
+ // answer the Web surface gives for one `Path2D` rejects.
166
+ return parsed?.contains(point.x, point.y) ?? false
167
+ }
168
+
169
+ /**
170
+ * The system face for a font spec, resolved once per spec.
171
+ *
172
+ * `matchFont` walks the platform's font manager, so calling it per text
173
+ * node per frame would put that walk on every redraw. Keyed by the four
174
+ * fields rather than by object identity, since the spec is rebuilt each
175
+ * render.
176
+ */
177
+ const fonts = new Map<string, ReturnType<typeof matchFont>>()
178
+ function fontFor(props: TextProps) {
179
+ const spec = textFontSpec(props)
180
+ const key = `${spec.fontStyle} ${spec.fontWeight} ${spec.fontSize} ${spec.fontFamily}`
181
+ let font = fonts.get(key)
182
+ if (!font) {
183
+ font = matchFont(spec)
184
+ fonts.set(key, font)
185
+ }
186
+ return font
187
+ }
188
+
189
+ /**
190
+ * Where the run starts, given which part of it sits at `x`.
191
+ *
192
+ * Skia's `Text` draws from the left and has no alignment of its own, so
193
+ * this measures. Canvas2D does not measure here -- it is told
194
+ * `textAlign` and aligns against its own metrics, which is the only
195
+ * measurement that can agree with what it rasterises. Two mechanisms for
196
+ * one contract, because each renderer's metrics are its own.
197
+ */
198
+ function alignedX(props: TextProps, font: ReturnType<typeof matchFont>) {
199
+ const align = props.textAlign ?? 'left'
200
+ if (align === 'left') return props.x
201
+ const width = font.measureText(props.text).width
202
+ return align === 'center' ? props.x - width / 2 : props.x - width
203
+ }
204
+
205
+ /**
206
+ * A gradient as Skia takes it: a shader element inside the shape.
207
+ *
208
+ * The other half of the same description Canvas2D builds with
209
+ * `createLinearGradient`. Skia wants two parallel arrays where the
210
+ * browser wants a call per stop, so the stops are unzipped here and
211
+ * nowhere else.
212
+ */
213
+ function gradientShader(paint: CanvasPaint) {
214
+ if (!isGradient(paint)) return null
215
+ const colors = paint.stops.map((stop) => stop.color)
216
+ const positions = paint.stops.map((stop) => stop.offset)
217
+ return paint.kind === 'linear' ? (
218
+ <SkiaLinearGradient start={paint.from} end={paint.to} colors={colors} positions={positions} />
219
+ ) : (
220
+ <SkiaRadialGradient c={paint.center} r={paint.radius} colors={colors} positions={positions} />
221
+ )
222
+ }
223
+
224
+ /** The colour Skia is given when the paint is a gradient instead. */
225
+ function colorFor(paint: CanvasPaint | undefined, fallback?: string) {
226
+ // A shape carrying a shader ignores its colour, but the prop is
227
+ // required, so it gets one that says nothing rather than one that
228
+ // would show if the shader ever failed to attach.
229
+ if (isGradient(paint)) return 'black'
230
+ return paint ?? fallback
231
+ }
232
+ /**
233
+ * The lines a label would be broken into at a given width.
234
+ *
235
+ * The same rule `maxWidth` follows, for a caller doing its own layout:
236
+ * sizing a card around a legend, deciding how tall a row has to be,
237
+ * placing something under the last line. Withholding it would leave
238
+ * those to a guess, which is what this package did with the
239
+ * measurement until it stopped.
240
+ *
241
+ * `undefined` where there is no renderer to measure with, as
242
+ * `measureCanvasText` is and for the same reason.
243
+ */
244
+ export function wrapCanvasText(props: TextProps, maxWidth: number): string[] | undefined {
245
+ const font = fontFor(props)
246
+ return wrapText(props.text, maxWidth, (run) => font.measureText(run).width)
247
+ }
248
+
249
+ /**
250
+ * What a label will occupy, for a caller placing something against it.
251
+ *
252
+ * Skia's `measureText` returns a rect whose origin is the baseline, so
253
+ * its `y` is the ascent negated and `y + height` is the descent. Ink
254
+ * again, and the same font object the renderer draws with -- a second
255
+ * face resolved separately could measure a different width.
256
+ *
257
+ * Optional to match the Web signature, where there may be no DOM to
258
+ * measure with. Native always has a font manager, so this side always
259
+ * answers; one shape for one API rather than two a caller has to know
260
+ * apart.
261
+ */
262
+ export function measureCanvasText(props: TextProps): CanvasTextMetrics | undefined {
263
+ const bounds = fontFor(props).measureText(props.text)
264
+ return { width: bounds.width, ascent: -bounds.y, descent: bounds.y + bounds.height }
265
+ }
266
+
267
+ /** Always defined here, and the hit test wants a total function. */
268
+ const measureText = (props: TextProps): CanvasTextMetrics =>
269
+ measureCanvasText(props) ?? { width: 0, ascent: 0, descent: 0 }
270
+ function paintLayers<Geometry extends object>(
271
+ key: string,
272
+ Shape: ComponentType<Geometry & DrawingNodeProps>,
273
+ geometry: Geometry,
274
+ paint: CanvasPaintProps,
275
+ ) {
276
+ const layers: ReactNode[] = []
277
+ const hasFill = paintFills(paint)
278
+ const hasStroke = paintStrokes(paint)
279
+ if (hasFill) {
280
+ layers.push(
281
+ <Shape
282
+ key={`${key}:fill`}
283
+ {...geometry}
284
+ color={colorFor(paint.fill, 'black')}
285
+ opacity={paint.opacity}
286
+ style="fill"
287
+ >
288
+ {gradientShader(paint.fill as CanvasPaint)}
289
+ </Shape>,
290
+ )
291
+ }
292
+ if (hasStroke) {
293
+ layers.push(
294
+ <Shape
295
+ key={`${key}:stroke`}
296
+ {...geometry}
297
+ color={colorFor(paint.stroke)}
298
+ opacity={paint.opacity}
299
+ style="stroke"
300
+ strokeWidth={paint.strokeWidth ?? 1}
301
+ strokeCap={paint.lineCap}
302
+ strokeJoin={paint.lineJoin}
303
+ >
304
+ {gradientShader(paint.stroke as CanvasPaint)}
305
+ </Shape>,
306
+ )
307
+ }
308
+ return layers
309
+ }
310
+
311
+ function renderNode(node: CanvasSceneNode, key: string): ReactNode {
312
+ switch (node.kind) {
313
+ case 'group':
314
+ return (
315
+ <SkiaGroup
316
+ key={key}
317
+ opacity={node.props.opacity}
318
+ transform={transformFor(node.props.transform)}
319
+ origin={
320
+ node.props.transform
321
+ ? { x: node.props.transform.originX ?? 0, y: node.props.transform.originY ?? 0 }
322
+ : undefined
323
+ }
324
+ >
325
+ {node.children.map((child, index) => renderNode(child, `${key}.${index}`))}
326
+ </SkiaGroup>
327
+ )
328
+ case 'clip': {
329
+ const props = node.props as Omit<ClipProps, 'children'>
330
+ const clip =
331
+ props.path !== undefined
332
+ ? props.path
333
+ : // `?? 0` on all four, as `pointInClip` and the Canvas2D renderer
334
+ // already do. The union says a rectangle clip has a width, but
335
+ // the scene node is reached through a cast, so nothing enforces
336
+ // it -- and Skia given `undefined` clips to nothing in silence.
337
+ {
338
+ x: props.x ?? 0,
339
+ y: props.y ?? 0,
340
+ width: props.width ?? 0,
341
+ height: props.height ?? 0,
342
+ }
343
+ return (
344
+ <SkiaGroup key={key} clip={clip}>
345
+ {node.children.map((child, index) => renderNode(child, `${key}.${index}`))}
346
+ </SkiaGroup>
347
+ )
348
+ }
349
+ case 'rect':
350
+ return paintLayers(
351
+ key,
352
+ SkiaRect,
353
+ {
354
+ x: node.props.x ?? 0,
355
+ y: node.props.y ?? 0,
356
+ width: node.props.width,
357
+ height: node.props.height,
358
+ },
359
+ node.props,
360
+ )
361
+ case 'rounded-rect':
362
+ return paintLayers(
363
+ key,
364
+ SkiaRoundedRect,
365
+ {
366
+ x: node.props.x ?? 0,
367
+ y: node.props.y ?? 0,
368
+ width: node.props.width,
369
+ height: node.props.height,
370
+ r: node.props.radius,
371
+ },
372
+ node.props,
373
+ )
374
+ case 'circle':
375
+ return paintLayers(
376
+ key,
377
+ SkiaCircle,
378
+ {
379
+ cx: node.props.cx,
380
+ cy: node.props.cy,
381
+ r: node.props.radius,
382
+ },
383
+ node.props,
384
+ )
385
+ case 'ellipse':
386
+ return paintLayers(
387
+ key,
388
+ SkiaOval,
389
+ {
390
+ rect: {
391
+ x: node.props.cx - node.props.radiusX,
392
+ y: node.props.cy - node.props.radiusY,
393
+ width: node.props.radiusX * 2,
394
+ height: node.props.radiusY * 2,
395
+ },
396
+ },
397
+ node.props,
398
+ )
399
+ case 'line':
400
+ return paintLayers(
401
+ key,
402
+ SkiaLine,
403
+ {
404
+ p1: { x: node.props.x1, y: node.props.y1 },
405
+ p2: { x: node.props.x2, y: node.props.y2 },
406
+ },
407
+ { ...node.props, fill: 'none', stroke: node.props.stroke ?? 'black' },
408
+ )
409
+ case 'text': {
410
+ const font = fontFor(node.props)
411
+ // One Skia element per line. Skia draws a run rather than a
412
+ // paragraph, so the breaking is the shared rule the Web renderer
413
+ // follows and the widths are this font's -- the one about to draw
414
+ // them.
415
+ const lines = textLines(node.props, (run) => font.measureText(run).width)
416
+ return lines.map((line, index) =>
417
+ paintLayers(
418
+ `${key}:${index}`,
419
+ SkiaText,
420
+ {
421
+ font,
422
+ text: line.text,
423
+ x: alignedX({ ...node.props, text: line.text }, font),
424
+ y: line.y,
425
+ },
426
+ node.props,
427
+ ),
428
+ )
429
+ }
430
+ case 'path':
431
+ return paintLayers(
432
+ key,
433
+ SkiaPath,
434
+ {
435
+ path: node.props.path,
436
+ // `as const` so this stays the enum Skia names rather than
437
+ // widening to `string`. The mapping itself was already right;
438
+ // nothing was checking it.
439
+ fillType: node.props.fillRule === 'evenodd' ? ('evenOdd' as const) : ('winding' as const),
440
+ },
441
+ node.props,
442
+ )
443
+ default:
444
+ return unhandledShape(node, 'the Skia renderer')
445
+ }
446
+ }
447
+
448
+ function viewportTransform(
449
+ viewBox: CanvasProps['viewBox'],
450
+ width: number,
451
+ height: number,
452
+ fit: CanvasProps['fit'],
453
+ ): Transforms3d | undefined {
454
+ if (!viewBox || width <= 0 || height <= 0 || viewBox[2] <= 0 || viewBox[3] <= 0) return undefined
455
+ const scaleX = width / viewBox[2]
456
+ const scaleY = height / viewBox[3]
457
+ if ((fit ?? 'contain') === 'stretch') {
458
+ const result: Transforms3d = []
459
+ result.push({ scaleX })
460
+ result.push({ scaleY })
461
+ result.push({ translateX: -viewBox[0] })
462
+ result.push({ translateY: -viewBox[1] })
463
+ return result
464
+ }
465
+ const scale = Math.min(scaleX, scaleY)
466
+ const result: Transforms3d = []
467
+ result.push({ translateX: (width - viewBox[2] * scale) / 2 })
468
+ result.push({ translateY: (height - viewBox[3] * scale) / 2 })
469
+ result.push({ scale })
470
+ result.push({ translateX: -viewBox[0] })
471
+ result.push({ translateY: -viewBox[1] })
472
+ return result
473
+ }
474
+
475
+ function Scene({ scene, transform }: { scene: CanvasScene; transform?: Transforms3d }) {
476
+ const nodes = scene.map((node, index) => renderNode(node, `root.${index}`))
477
+ return transform ? <SkiaGroup transform={transform}>{nodes}</SkiaGroup> : nodes
478
+ }
479
+
480
+ function Root({
481
+ children,
482
+ className,
483
+ style,
484
+ width,
485
+ height,
486
+ viewBox,
487
+ fit = 'contain',
488
+ decorative,
489
+ accessibilityLabel,
490
+ accessibleFallback,
491
+ testID,
492
+ }: CanvasProps) {
493
+ const pressedTarget = useRef<{ id: string; touchId: number } | undefined>(undefined)
494
+ const navigation = useHozoNavigation()
495
+ const { scene, collector, isInteractive, press, activate, interactions, interactionRevision } =
496
+ useCanvasScene(children)
497
+ const [layout, setLayout] = useState({
498
+ width: width ?? viewBox?.[2] ?? 0,
499
+ height: height ?? viewBox?.[3] ?? 0,
500
+ })
501
+ const onLayout = (event: LayoutChangeEvent) => {
502
+ const next = event.nativeEvent.layout
503
+ setLayout((current) =>
504
+ current.width === next.width && current.height === next.height
505
+ ? current
506
+ : { width: next.width, height: next.height },
507
+ )
508
+ }
509
+ const transform = useMemo(
510
+ () => viewportTransform(viewBox, layout.width, layout.height, fit),
511
+ [viewBox, layout, fit],
512
+ )
513
+ const hasValidViewport =
514
+ !viewBox || (layout.width > 0 && layout.height > 0 && viewBox[2] > 0 && viewBox[3] > 0)
515
+ const nativeClass = { className } as Record<string, unknown>
516
+ const accessibilityMode = canvasAccessibilityMode({ decorative, accessibleFallback })
517
+ const fallbackContent =
518
+ typeof accessibleFallback === 'string' ||
519
+ typeof accessibleFallback === 'number' ||
520
+ typeof accessibleFallback === 'bigint' ? (
521
+ <Text>{String(accessibleFallback)}</Text>
522
+ ) : (
523
+ accessibleFallback
524
+ )
525
+ const surfacePoint = (event: GestureResponderEvent): CanvasPoint => ({
526
+ x: event.nativeEvent.locationX,
527
+ y: event.nativeEvent.locationY,
528
+ })
529
+ const hitAt = (point: CanvasPoint) =>
530
+ hitTestCanvas(
531
+ scene,
532
+ point,
533
+ { width: layout.width, height: layout.height, viewBox, fit },
534
+ isInteractive,
535
+ { pathContains: pathHitTest, measureText },
536
+ )
537
+ const onStartShouldSetResponder = (event: GestureResponderEvent) => {
538
+ pressedTarget.current = undefined
539
+ if (event.nativeEvent.touches.length !== 1) return false
540
+ const hit = hitAt(surfacePoint(event))
541
+ if (hit) {
542
+ pressedTarget.current = { id: hit.id, touchId: event.nativeEvent.identifier }
543
+ activate(hit.id, canvasPressEvent(hit.point, surfacePoint(event)))
544
+ }
545
+ return hit !== undefined
546
+ }
547
+ const onResponderRelease = (event: GestureResponderEvent) => {
548
+ const startedTarget = pressedTarget.current
549
+ pressedTarget.current = undefined
550
+ if (
551
+ !startedTarget ||
552
+ event.nativeEvent.touches.length > 0 ||
553
+ event.nativeEvent.identifier !== startedTarget.touchId
554
+ )
555
+ return
556
+ const point = surfacePoint(event)
557
+ const hit = hitAt(point)
558
+ activate(undefined, undefined)
559
+ if (!hit || hit.id !== startedTarget.id) return
560
+ const destination = press(hit.id, canvasPressEvent(hit.point, point))
561
+ if (destination) {
562
+ void activateHozoNavigation(navigation, destination, Linking.openURL)
563
+ }
564
+ }
565
+ const onResponderTerminate = () => {
566
+ pressedTarget.current = undefined
567
+ activate(undefined, undefined)
568
+ }
569
+
570
+ /**
571
+ * The same hover as the Web surface, from the same event.
572
+ *
573
+ * React Native's `View` declares the whole W3C pointer set and its
574
+ * payload carries `pointerType` and `offsetX`/`offsetY`, so this is the
575
+ * browser's handler with a different import. A tablet with a trackpad
576
+ * and a phone with a mouse both reach it; a finger does not, and is
577
+ * excluded by `pointerType` for the reason the Web side gives.
578
+ *
579
+ * Not verified on a device. The types and the prop declarations are as
580
+ * far as this repository can check from here, and #26 asks for device
581
+ * validation as an item of its own.
582
+ */
583
+ const pointerPoint = (event: PointerEvent): CanvasPoint => ({
584
+ x: event.nativeEvent.offsetX,
585
+ y: event.nativeEvent.offsetY,
586
+ })
587
+ const onPointerMove = (event: PointerEvent) => {
588
+ if (event.nativeEvent.pointerType === 'touch') return
589
+ const point = pointerPoint(event)
590
+ const hit = hitAt(point)
591
+ activate(hit?.id, hit ? canvasPressEvent(hit.point, point) : undefined)
592
+ }
593
+ const onPointerLeave = () => activate(undefined, undefined)
594
+
595
+ // Memoised on the scene, which is the only thing that can change the
596
+ // answer. Without this it walked every node on every render of the
597
+ // surface -- a second full traversal beside the snapshot and the
598
+ // redraw, for a list that changes only when a shape is added, removed
599
+ // or renamed.
600
+ //
601
+ // `interactions` is a stable store rather than a value, so it is not a
602
+ // dependency: a handler arriving or leaving mutates it without a new
603
+ // scene. That is why the list is rebuilt whenever the scene is, which
604
+ // is also when a shape's presence could have changed.
605
+ // Only in `label` mode, and that is the whole condition. A
606
+ // `decorative` surface has said it carries no information and a
607
+ // surface with an `accessibleFallback` has supplied it; second-guessing
608
+ // either would be arguing with an author who already answered. What is
609
+ // left is the one where a single name stands for a drawing, and the
610
+ // drawing has words the name does not.
611
+ if (accessibilityMode === 'label') {
612
+ reportUnreadableText(canvasUnreadableText(scene, accessibilityLabel), (message) =>
613
+ console.warn(`[hozo] ${message}`),
614
+ )
615
+ }
616
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the registry revision intentionally invalidates semantic controls without redrawing the scene
617
+ const controls = useMemo(
618
+ () => canvasControls(scene, interactions, (message) => console.warn(`[hozo] ${message}`)),
619
+ [scene, interactions, interactionRevision],
620
+ )
621
+ const pointFor = (id: string) =>
622
+ canvasNodePoint(scene, id, {
623
+ width: layout.width,
624
+ height: layout.height,
625
+ viewBox,
626
+ fit,
627
+ }) ?? { point: { x: 0, y: 0 }, surfacePoint: { x: 0, y: 0 } }
628
+
629
+ return (
630
+ <View
631
+ {...nativeClass}
632
+ style={[
633
+ styles.root,
634
+ width === undefined ? null : { width },
635
+ height === undefined ? null : { height },
636
+ style,
637
+ ]}
638
+ onLayout={onLayout}
639
+ accessible={accessibilityMode === 'label'}
640
+ accessibilityRole={accessibilityMode === 'label' ? 'image' : undefined}
641
+ accessibilityLabel={accessibilityMode === 'label' ? accessibilityLabel : undefined}
642
+ testID={testID}
643
+ onStartShouldSetResponder={onStartShouldSetResponder}
644
+ onResponderRelease={onResponderRelease}
645
+ onResponderTerminate={onResponderTerminate}
646
+ onPointerMove={onPointerMove}
647
+ onPointerLeave={onPointerLeave}
648
+ >
649
+ {collector}
650
+ <View
651
+ style={StyleSheet.absoluteFill}
652
+ accessible={false}
653
+ accessibilityElementsHidden
654
+ importantForAccessibility="no-hide-descendants"
655
+ pointerEvents="none"
656
+ >
657
+ <SkiaCanvas style={StyleSheet.absoluteFill}>
658
+ {hasValidViewport ? <Scene scene={scene} transform={transform} /> : null}
659
+ </SkiaCanvas>
660
+ </View>
661
+ {/*
662
+ The same real controls the Web surface renders, in the shape this
663
+ platform reads: an accessibility element per named interactive
664
+ shape, with the destination/action role and the shape's name.
665
+
666
+ A screen reader focusing one activates it the way keyboard focus
667
+ does on the Web, so a tooltip driven by `onActiveChange` appears
668
+ for VoiceOver and TalkBack too. `onAccessibilityTap` is the
669
+ double-tap that follows.
670
+
671
+ Zero-sized and clipped rather than `display: none`: an element
672
+ with no size is still an accessibility element, and one that is
673
+ hidden is not.
674
+ */}
675
+ {controls.length > 0 ? (
676
+ <View style={styles.accessibleFallback}>
677
+ {controls.map((control) => (
678
+ <View
679
+ key={control.id}
680
+ accessible
681
+ accessibilityRole={control.destination ? 'link' : 'button'}
682
+ accessibilityLabel={control.label}
683
+ onAccessibilityTap={() => {
684
+ const point = pointFor(control.id)
685
+ const destination = press(
686
+ control.id,
687
+ canvasPressEvent(point.point, point.surfacePoint),
688
+ )
689
+ if (destination) {
690
+ void activateHozoNavigation(navigation, destination, Linking.openURL)
691
+ }
692
+ }}
693
+ onAccessibilityEscape={() => activate(undefined, undefined)}
694
+ />
695
+ ))}
696
+ </View>
697
+ ) : null}
698
+ {accessibilityMode === 'fallback' ? (
699
+ <View style={styles.accessibleFallback} accessible={false} pointerEvents="none">
700
+ {accessibilityLabel ? <Text>{accessibilityLabel}</Text> : null}
701
+ {fallbackContent}
702
+ </View>
703
+ ) : null}
704
+ </View>
705
+ )
706
+ }
707
+
708
+ const styles = StyleSheet.create({
709
+ root: { position: 'relative', overflow: 'hidden' },
710
+ accessibleFallback: {
711
+ position: 'absolute',
712
+ width: 1,
713
+ height: 1,
714
+ padding: 0,
715
+ margin: -1,
716
+ overflow: 'hidden',
717
+ },
718
+ })
719
+
720
+ /** Canvas root plus the same scene vocabulary exported on Web. */
721
+ export const Canvas = Object.assign(Root, {
722
+ Group,
723
+ Clip,
724
+ // Under a local alias only because React Native's own `Text` is in
725
+ // scope in this module; the public name is the same on both surfaces.
726
+ Text: CanvasText,
727
+ Rect,
728
+ RoundedRect,
729
+ Circle,
730
+ Ellipse,
731
+ Line,
732
+ Path,
733
+ })