@hozo/canvas 0.1.0 → 0.3.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.
@@ -2,27 +2,36 @@ import { activateHozoNavigation, useHozoNavigation } from '@hozo/engine/navigati
2
2
  import {
3
3
  type DrawingNodeProps,
4
4
  FillType,
5
+ FilterMode,
5
6
  matchFont,
6
7
  Skia,
7
8
  Canvas as SkiaCanvas,
8
9
  Circle as SkiaCircle,
10
+ ColorMatrix as SkiaColorMatrix,
9
11
  Group as SkiaGroup,
12
+ ImageShader as SkiaImageShader,
10
13
  Line as SkiaLine,
11
14
  LinearGradient as SkiaLinearGradient,
15
+ LinearToSRGBGamma as SkiaLinearToSRGBGamma,
12
16
  Oval as SkiaOval,
13
17
  Path as SkiaPath,
14
18
  RadialGradient as SkiaRadialGradient,
15
19
  Rect as SkiaRect,
16
20
  RoundedRect as SkiaRoundedRect,
21
+ SRGBToLinearGamma as SkiaSRGBToLinearGamma,
17
22
  Text as SkiaText,
23
+ Vertices as SkiaVertices,
18
24
  type Transforms3d,
25
+ useImage,
19
26
  } from '@shopify/react-native-skia'
20
- import { type ComponentType, type ReactNode, useMemo, useRef, useState } from 'react'
27
+ import { type ComponentType, type ReactNode, useEffect, useMemo, useRef, useState } from 'react'
21
28
  import {
22
29
  type GestureResponderEvent,
23
30
  type LayoutChangeEvent,
24
31
  Linking,
32
+ PixelRatio,
25
33
  type PointerEvent,
34
+ Pressable,
26
35
  type StyleProp,
27
36
  StyleSheet,
28
37
  Text,
@@ -44,11 +53,14 @@ import {
44
53
  type CanvasScene,
45
54
  type CanvasSceneNode,
46
55
  Text as CanvasText,
56
+ type CanvasTextureWrap,
47
57
  type CanvasTransform,
48
58
  Circle,
49
59
  Clip,
50
60
  type ClipProps,
51
61
  canvasControls,
62
+ canvasMeshTextureColor,
63
+ canvasMeshTextureWrap,
52
64
  canvasPressEvent,
53
65
  canvasUnreadableText,
54
66
  Ellipse,
@@ -62,7 +74,12 @@ import {
62
74
  RoundedRect,
63
75
  reportUnreadableText,
64
76
  type TextProps,
77
+ TriangleMesh,
65
78
  textFontSpec,
79
+ triangleMeshColor,
80
+ triangleMeshColorCss,
81
+ triangleMeshIndices,
82
+ triangleMeshTextureCoordinate,
66
83
  unhandledShape,
67
84
  useCanvasScene,
68
85
  } from './scene.tsx'
@@ -82,10 +99,13 @@ export {
82
99
  export type {
83
100
  CanvasDestination,
84
101
  CanvasInteractionProps,
102
+ CanvasMeshTexture,
85
103
  CanvasPaintProps,
86
104
  CanvasPressEvent,
87
105
  CanvasScene,
88
106
  CanvasSceneNode,
107
+ CanvasTextureSource,
108
+ CanvasTextureWrap,
89
109
  CanvasTransform,
90
110
  CircleProps,
91
111
  ClipProps,
@@ -95,6 +115,7 @@ export type {
95
115
  PathProps,
96
116
  RectProps,
97
117
  RoundedRectProps,
118
+ TriangleMeshProps,
98
119
  } from './scene.tsx'
99
120
  export { CanvasSceneStore } from './scene.tsx'
100
121
  export type { CanvasViewport } from './viewport.ts'
@@ -106,6 +127,7 @@ export { textLines, wrapText } from './wrap-text.ts'
106
127
  export type CanvasProps = CanvasAccessibilityProps & {
107
128
  children?: ReactNode
108
129
  className?: string
130
+ onSizeChange?: (size: CanvasSize) => void
109
131
  style?: StyleProp<ViewStyle>
110
132
  width?: number
111
133
  height?: number
@@ -114,6 +136,12 @@ export type CanvasProps = CanvasAccessibilityProps & {
114
136
  testID?: string
115
137
  }
116
138
 
139
+ export interface CanvasSize {
140
+ width: number
141
+ height: number
142
+ pixelRatio: number
143
+ }
144
+
117
145
  function transformFor(transform?: CanvasTransform): Transforms3d | undefined {
118
146
  if (!transform) return undefined
119
147
  // `Transforms3d` and not `Record<string, number>[]`: Skia's type is a
@@ -128,6 +156,102 @@ function transformFor(transform?: CanvasTransform): Transforms3d | undefined {
128
156
  return result
129
157
  }
130
158
 
159
+ type TriangleMeshNode = Extract<CanvasSceneNode, { kind: 'triangle-mesh' }>
160
+
161
+ function NativeTriangleMesh({ node }: { node: TriangleMeshNode }) {
162
+ const texture = node.props.texture
163
+ const [wrapX, wrapY]: readonly [CanvasTextureWrap, CanvasTextureWrap] = texture
164
+ ? canvasMeshTextureWrap(texture)
165
+ : ['clamp', 'clamp']
166
+ const source = texture?.source
167
+ const nativeSource =
168
+ typeof source === 'string' || typeof source === 'number'
169
+ ? source
170
+ : typeof source?.uri === 'string'
171
+ ? source.uri
172
+ : source?.default
173
+ const image = useImage(nativeSource)
174
+ const indices = triangleMeshIndices(node.props)
175
+ const tint = texture ? canvasMeshTextureColor(texture) : { r: 1, g: 1, b: 1 }
176
+ if (
177
+ indices.length === 0 ||
178
+ node.props.fill === 'none' ||
179
+ (texture && (!image || tint === undefined))
180
+ )
181
+ return null
182
+ const color = tint ?? { r: 1, g: 1, b: 1 }
183
+ const colors = node.props.colors?.map((color) => {
184
+ const normalized = triangleMeshColor(color)
185
+ return normalized ? triangleMeshColorCss(normalized) : 'rgba(0, 0, 0, 0)'
186
+ })
187
+ const textures =
188
+ texture && image
189
+ ? texture.coordinates.map((coordinate) => {
190
+ const normalized = triangleMeshTextureCoordinate(coordinate, wrapX, wrapY)
191
+ return normalized
192
+ ? { x: normalized.x * image.width(), y: normalized.y * image.height() }
193
+ : { x: 0, y: 0 }
194
+ })
195
+ : undefined
196
+ return (
197
+ <SkiaVertices
198
+ mode="triangles"
199
+ vertices={[...node.props.vertices]}
200
+ indices={indices}
201
+ textures={textures}
202
+ colors={colors}
203
+ color={colors || texture ? undefined : colorFor(node.props.fill, 'black')}
204
+ opacity={node.props.opacity}
205
+ >
206
+ {texture && image ? (
207
+ <>
208
+ <SkiaImageShader
209
+ image={image}
210
+ fit="none"
211
+ tx={wrapX}
212
+ ty={wrapY}
213
+ sampling={{
214
+ filter: texture.filter === 'nearest' ? FilterMode.Nearest : FilterMode.Linear,
215
+ }}
216
+ />
217
+ {color.r !== 1 || color.g !== 1 || color.b !== 1 ? (
218
+ <SkiaLinearToSRGBGamma>
219
+ <SkiaColorMatrix
220
+ matrix={[
221
+ color.r,
222
+ 0,
223
+ 0,
224
+ 0,
225
+ 0,
226
+ 0,
227
+ color.g,
228
+ 0,
229
+ 0,
230
+ 0,
231
+ 0,
232
+ 0,
233
+ color.b,
234
+ 0,
235
+ 0,
236
+ 0,
237
+ 0,
238
+ 0,
239
+ 1,
240
+ 0,
241
+ ]}
242
+ >
243
+ <SkiaSRGBToLinearGamma />
244
+ </SkiaColorMatrix>
245
+ </SkiaLinearToSRGBGamma>
246
+ ) : null}
247
+ </>
248
+ ) : colors ? null : (
249
+ gradientShader(node.props.fill as CanvasPaint)
250
+ )}
251
+ </SkiaVertices>
252
+ )
253
+ }
254
+
131
255
  /**
132
256
  * One Skia element per painted channel, since Skia paints one at a time.
133
257
  *
@@ -440,6 +564,9 @@ function renderNode(node: CanvasSceneNode, key: string): ReactNode {
440
564
  },
441
565
  node.props,
442
566
  )
567
+ case 'triangle-mesh': {
568
+ return <NativeTriangleMesh key={key} node={node} />
569
+ }
443
570
  default:
444
571
  return unhandledShape(node, 'the Skia renderer')
445
572
  }
@@ -488,6 +615,7 @@ function Root({
488
615
  decorative,
489
616
  accessibilityLabel,
490
617
  accessibleFallback,
618
+ onSizeChange,
491
619
  testID,
492
620
  }: CanvasProps) {
493
621
  const pressedTarget = useRef<{ id: string; touchId: number } | undefined>(undefined)
@@ -498,6 +626,8 @@ function Root({
498
626
  width: width ?? viewBox?.[2] ?? 0,
499
627
  height: height ?? viewBox?.[3] ?? 0,
500
628
  })
629
+ const sizeCallback = useRef(onSizeChange)
630
+ sizeCallback.current = onSizeChange
501
631
  const onLayout = (event: LayoutChangeEvent) => {
502
632
  const next = event.nativeEvent.layout
503
633
  setLayout((current) =>
@@ -506,6 +636,10 @@ function Root({
506
636
  : { width: next.width, height: next.height },
507
637
  )
508
638
  }
639
+ useEffect(() => {
640
+ if (layout.width <= 0 || layout.height <= 0) return
641
+ sizeCallback.current?.({ ...layout, pixelRatio: PixelRatio.get() })
642
+ }, [layout])
509
643
  const transform = useMemo(
510
644
  () => viewportTransform(viewBox, layout.width, layout.height, fit),
511
645
  [viewBox, layout, fit],
@@ -618,6 +752,7 @@ function Root({
618
752
  () => canvasControls(scene, interactions, (message) => console.warn(`[hozo] ${message}`)),
619
753
  [scene, interactions, interactionRevision],
620
754
  )
755
+ const hasControls = controls.length > 0
621
756
  const pointFor = (id: string) =>
622
757
  canvasNodePoint(scene, id, {
623
758
  width: layout.width,
@@ -625,6 +760,20 @@ function Root({
625
760
  viewBox,
626
761
  fit,
627
762
  }) ?? { point: { x: 0, y: 0 }, surfacePoint: { x: 0, y: 0 } }
763
+ const accessibilityControlStyle = (id: string): ViewStyle => {
764
+ const { surfacePoint } = pointFor(id)
765
+ return {
766
+ left: surfacePoint.x - 22,
767
+ top: surfacePoint.y - 22,
768
+ }
769
+ }
770
+ const activateControl = (id: string) => {
771
+ const point = pointFor(id)
772
+ const destination = press(id, canvasPressEvent(point.point, point.surfacePoint))
773
+ if (destination) {
774
+ void activateHozoNavigation(navigation, destination, Linking.openURL)
775
+ }
776
+ }
628
777
 
629
778
  return (
630
779
  <View
@@ -636,9 +785,11 @@ function Root({
636
785
  style,
637
786
  ]}
638
787
  onLayout={onLayout}
639
- accessible={accessibilityMode === 'label'}
640
- accessibilityRole={accessibilityMode === 'label' ? 'image' : undefined}
641
- accessibilityLabel={accessibilityMode === 'label' ? accessibilityLabel : undefined}
788
+ accessible={accessibilityMode === 'label' && !hasControls}
789
+ accessibilityRole={accessibilityMode === 'label' && !hasControls ? 'image' : undefined}
790
+ accessibilityLabel={
791
+ accessibilityMode === 'label' && !hasControls ? accessibilityLabel : undefined
792
+ }
642
793
  testID={testID}
643
794
  onStartShouldSetResponder={onStartShouldSetResponder}
644
795
  onResponderRelease={onResponderRelease}
@@ -663,33 +814,37 @@ function Root({
663
814
  platform reads: an accessibility element per named interactive
664
815
  shape, with the destination/action role and the shape's name.
665
816
 
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.
817
+ The controls have real, minimum-sized native bounds centred on their
818
+ shapes. Android omits clipped, empty descendants from its semantic
819
+ tree. The layer ignores pointer input so these larger accessibility
820
+ targets cannot change the Canvas hit-test contract; a screen-reader
821
+ activation reaches the standard native `activate` action instead.
674
822
  */}
675
- {controls.length > 0 ? (
676
- <View style={styles.accessibleFallback}>
677
- {controls.map((control) => (
823
+ {hasControls ? (
824
+ <View style={styles.accessibilityLayer} pointerEvents="box-none">
825
+ {/*
826
+ An accessible parent groups its descendants into one native
827
+ accessibility element. Keep a labelled interactive Canvas as a
828
+ non-accessible container, then expose its image description and
829
+ controls as siblings so TalkBack and VoiceOver can reach both.
830
+ */}
831
+ {accessibilityMode === 'label' ? (
678
832
  <View
833
+ style={styles.accessibilityDescription}
834
+ accessible
835
+ accessibilityRole="image"
836
+ accessibilityLabel={accessibilityLabel}
837
+ />
838
+ ) : null}
839
+ {controls.map((control) => (
840
+ <Pressable
679
841
  key={control.id}
842
+ style={[styles.accessibilityControl, accessibilityControlStyle(control.id)]}
843
+ pointerEvents="box-none"
680
844
  accessible
681
845
  accessibilityRole={control.destination ? 'link' : 'button'}
682
846
  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
- }}
847
+ onPress={() => activateControl(control.id)}
693
848
  onAccessibilityEscape={() => activate(undefined, undefined)}
694
849
  />
695
850
  ))}
@@ -707,6 +862,23 @@ function Root({
707
862
 
708
863
  const styles = StyleSheet.create({
709
864
  root: { position: 'relative', overflow: 'hidden' },
865
+ accessibilityLayer: {
866
+ position: 'absolute',
867
+ top: 0,
868
+ right: 0,
869
+ bottom: 0,
870
+ left: 0,
871
+ },
872
+ accessibilityDescription: {
873
+ position: 'absolute',
874
+ width: 1,
875
+ height: 1,
876
+ },
877
+ accessibilityControl: {
878
+ position: 'absolute',
879
+ width: 44,
880
+ height: 44,
881
+ },
710
882
  accessibleFallback: {
711
883
  position: 'absolute',
712
884
  width: 1,
@@ -730,4 +902,5 @@ export const Canvas = Object.assign(Root, {
730
902
  Ellipse,
731
903
  Line,
732
904
  Path,
905
+ TriangleMesh,
733
906
  })
package/src/index.tsx CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  type CSSProperties,
4
4
  type ReactNode,
5
5
  type PointerEvent as ReactPointerEvent,
6
+ useCallback,
6
7
  useEffect,
7
8
  useLayoutEffect,
8
9
  useMemo,
@@ -20,10 +21,13 @@ import {
20
21
  import { renderCanvas2D } from './render-canvas-2d.ts'
21
22
  import {
22
23
  BoundedCache,
24
+ type CanvasScene,
23
25
  Circle,
24
26
  Clip,
25
27
  canvasControls,
28
+ canvasMeshTextureColor,
26
29
  canvasPressEvent,
30
+ canvasTextureUri,
27
31
  canvasUnreadableText,
28
32
  cssFontShorthand,
29
33
  Ellipse,
@@ -35,6 +39,7 @@ import {
35
39
  reportUnreadableText,
36
40
  Text,
37
41
  type TextProps,
42
+ TriangleMesh,
38
43
  useCanvasScene,
39
44
  } from './scene.tsx'
40
45
  import { wrapText } from './wrap-text.ts'
@@ -54,10 +59,13 @@ export { type CanvasViewport, renderCanvas2D } from './render-canvas-2d.ts'
54
59
  export type {
55
60
  CanvasDestination,
56
61
  CanvasInteractionProps,
62
+ CanvasMeshTexture,
57
63
  CanvasPaintProps,
58
64
  CanvasPressEvent,
59
65
  CanvasScene,
60
66
  CanvasSceneNode,
67
+ CanvasTextureSource,
68
+ CanvasTextureWrap,
61
69
  CanvasTransform,
62
70
  CircleProps,
63
71
  ClipProps,
@@ -67,6 +75,7 @@ export type {
67
75
  PathProps,
68
76
  RectProps,
69
77
  RoundedRectProps,
78
+ TriangleMeshProps,
70
79
  } from './scene.tsx'
71
80
  export { CanvasSceneStore } from './scene.tsx'
72
81
  // The rule on its own, for a caller with a measurement of its own --
@@ -150,6 +159,7 @@ export function wrapCanvasText(props: TextProps, maxWidth: number): string[] | u
150
159
  export type CanvasProps = CanvasAccessibilityProps & {
151
160
  children?: ReactNode
152
161
  className?: string
162
+ onSizeChange?: (size: CanvasSize) => void
153
163
  style?: CSSProperties
154
164
  width?: number
155
165
  height?: number
@@ -158,7 +168,7 @@ export type CanvasProps = CanvasAccessibilityProps & {
158
168
  testID?: string
159
169
  }
160
170
 
161
- interface Size {
171
+ export interface CanvasSize {
162
172
  width: number
163
173
  height: number
164
174
  pixelRatio: number
@@ -177,6 +187,7 @@ function Root({
177
187
  decorative,
178
188
  accessibilityLabel,
179
189
  accessibleFallback,
190
+ onSizeChange,
180
191
  testID,
181
192
  }: CanvasProps) {
182
193
  const canvasRef = useRef<HTMLCanvasElement>(null)
@@ -184,11 +195,68 @@ function Root({
184
195
  const navigation = useHozoNavigation()
185
196
  const { scene, collector, isInteractive, press, activate, interactions, interactionRevision } =
186
197
  useCanvasScene(children)
187
- const [size, setSize] = useState<Size>(() => ({
198
+ const [size, setSize] = useState<CanvasSize>(() => ({
188
199
  width: width ?? viewBox?.[2] ?? 300,
189
200
  height: height ?? viewBox?.[3] ?? 150,
190
201
  pixelRatio: 1,
191
202
  }))
203
+ const sizeCallback = useRef(onSizeChange)
204
+ sizeCallback.current = onSizeChange
205
+ const textureImages = useRef(new Map<string, HTMLImageElement>())
206
+ const textureMounted = useRef(false)
207
+ const [textureRevision, setTextureRevision] = useState(0)
208
+
209
+ useEffect(() => {
210
+ textureMounted.current = true
211
+ return () => {
212
+ textureMounted.current = false
213
+ }
214
+ }, [])
215
+
216
+ useEffect(() => {
217
+ if (typeof Image === 'undefined') return
218
+ const visit = (nodes: CanvasScene) => {
219
+ for (const node of nodes) {
220
+ if (node.kind === 'triangle-mesh' && node.props.texture) {
221
+ const uri = canvasTextureUri(node.props.texture.source)
222
+ if (!uri) continue
223
+ const color = canvasMeshTextureColor(node.props.texture)
224
+ const readable = color && (color.r !== 1 || color.g !== 1 || color.b !== 1)
225
+ const cached = textureImages.current.get(uri)
226
+ if (cached && (!readable || cached.crossOrigin === 'anonymous')) continue
227
+ const image = new Image()
228
+ // Static RGB modulation reads pixels once. Request CORS only for
229
+ // that path; ordinary images must still draw without CORS support.
230
+ if (readable) image.crossOrigin = 'anonymous'
231
+ textureImages.current.set(uri, image)
232
+ image.onload = () => {
233
+ if (textureImages.current.get(uri) !== image) return
234
+ if (textureMounted.current) setTextureRevision((revision) => revision + 1)
235
+ }
236
+ image.onerror = () => {
237
+ if (textureImages.current.get(uri) !== image) return
238
+ textureImages.current.delete(uri)
239
+ if (readable)
240
+ console.warn(
241
+ '[hozo] Portable texture colour modulation could not load a readable image; external images need CORS support.',
242
+ )
243
+ if (textureMounted.current) setTextureRevision((revision) => revision + 1)
244
+ }
245
+ image.src = uri
246
+ } else if (node.kind === 'group' || node.kind === 'clip') {
247
+ visit(node.children)
248
+ }
249
+ }
250
+ }
251
+ visit(scene)
252
+ }, [scene])
253
+
254
+ const textureImage = useCallback((source: Parameters<typeof canvasTextureUri>[0]) => {
255
+ const uri = canvasTextureUri(source)
256
+ if (!uri) return undefined
257
+ const image = textureImages.current.get(uri)
258
+ return image?.complete && image.naturalWidth > 0 ? image : undefined
259
+ }, [])
192
260
 
193
261
  useIsoLayoutEffect(() => {
194
262
  const canvas = canvasRef.current
@@ -209,19 +277,33 @@ function Root({
209
277
  )
210
278
  }
211
279
  measure()
212
- if (typeof ResizeObserver === 'undefined') return
213
- const observer = new ResizeObserver(measure)
214
- observer.observe(canvas)
215
- return () => observer.disconnect()
280
+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure)
281
+ observer?.observe(canvas)
282
+ const browserWindow = globalThis.window
283
+ if (typeof browserWindow?.addEventListener === 'function') {
284
+ browserWindow.addEventListener('resize', measure)
285
+ }
286
+ return () => {
287
+ observer?.disconnect()
288
+ if (typeof browserWindow?.removeEventListener === 'function') {
289
+ browserWindow.removeEventListener('resize', measure)
290
+ }
291
+ }
216
292
  }, [width, height, viewBox])
217
293
 
294
+ useIsoLayoutEffect(() => {
295
+ sizeCallback.current?.(size)
296
+ }, [size])
297
+
218
298
  useIsoLayoutEffect(() => {
219
299
  const context = canvasRef.current?.getContext('2d')
220
300
  if (!context) return
221
- renderCanvas2D(context, scene, { ...size, viewBox, fit })
222
- }, [scene, size, viewBox, fit])
301
+ renderCanvas2D(context, scene, { ...size, viewBox, fit }, textureImage)
302
+ }, [scene, size, viewBox, fit, textureImage, textureRevision])
223
303
 
224
304
  const rootStyle: CSSProperties = {
305
+ width: width ?? style?.width ?? 300,
306
+ height: height ?? style?.height ?? 150,
225
307
  ...style,
226
308
  ...(width === undefined ? null : { width }),
227
309
  ...(height === undefined ? null : { height }),
@@ -454,6 +536,7 @@ function Root({
454
536
  }
455
537
  return (
456
538
  <button
539
+ data-hozo-pressable=""
457
540
  key={control.id}
458
541
  type="button"
459
542
  onClick={() => press(control.id, canvasPressEvent(point.point, point.surfacePoint))}
@@ -507,4 +590,5 @@ export const Canvas = Object.assign(Root, {
507
590
  Line,
508
591
 
509
592
  Path,
593
+ TriangleMesh,
510
594
  })