@hozo/canvas 0.1.0 → 0.2.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.
package/src/scene.tsx CHANGED
@@ -118,6 +118,15 @@ export interface CanvasInteractionProps {
118
118
  * says so in development rather than being silently pointer-only.
119
119
  */
120
120
  accessibilityLabel?: string
121
+ /**
122
+ * Groups several painted shapes into one semantic control.
123
+ *
124
+ * A data point or projected 3D object can be made from many paths while
125
+ * still being one thing to a keyboard or screen reader. Shapes sharing
126
+ * this id remain independently hit-testable, but produce one hidden
127
+ * button or link in scene order.
128
+ */
129
+ accessibilityControlId?: string
121
130
  disabled?: boolean
122
131
  }
123
132
 
@@ -374,6 +383,200 @@ export interface PathProps extends CanvasPaintProps, CanvasInteractionProps {
374
383
  fillRule?: 'nonzero' | 'evenodd'
375
384
  }
376
385
 
386
+ /**
387
+ * Indexed triangles in the Canvas coordinate system.
388
+ *
389
+ * This is deliberately triangles rather than a generic polygon mesh: Web
390
+ * Canvas 2D and Skia already agree on that topology, and Three.js can hand
391
+ * projected geometry across without serialising it into SVG path strings.
392
+ * An omitted index array means consecutive triples. Incomplete and invalid
393
+ * triples draw nothing as a unit, so the two renderers cannot disagree by
394
+ * repairing malformed geometry differently.
395
+ *
396
+ * Per-vertex colours are normalized sRGB channels. A numeric representation
397
+ * keeps interpolation independent of whichever CSS colour parser happens to
398
+ * be present, and lets a projected renderer pass colour data without turning
399
+ * every vertex into a string. Texture coordinates use normalized, top-left
400
+ * image space so neither backend leaks its decoded image dimensions into the
401
+ * retained scene.
402
+ */
403
+ export interface CanvasVertexColor {
404
+ /** Normalized sRGB red channel. Values outside 0..1 are clamped. */
405
+ r: number
406
+ /** Normalized sRGB green channel. Values outside 0..1 are clamped. */
407
+ g: number
408
+ /** Normalized sRGB blue channel. Values outside 0..1 are clamped. */
409
+ b: number
410
+ /** Optional normalized alpha channel. Values outside 0..1 are clamped. */
411
+ a?: number
412
+ }
413
+
414
+ export type CanvasTextureSource = string | number | { uri?: string; default?: string }
415
+ export type CanvasTextureWrap = 'clamp' | 'repeat' | 'mirror'
416
+
417
+ export interface CanvasMeshTexture {
418
+ source: CanvasTextureSource
419
+ /** One top-left coordinate per vertex. One unit is one image tile. */
420
+ coordinates: readonly CanvasPoint[]
421
+ filter?: 'linear' | 'nearest'
422
+ /** Linear RGB multiplier; alpha is unchanged. Defaults to 1. */
423
+ intensity?: number
424
+ /** Linear-sRGB multipliers, applied before encoding; alpha is unchanged. */
425
+ tint?: { r: number; g: number; b: number }
426
+ /** Default wrapping for both axes. */
427
+ wrap?: CanvasTextureWrap
428
+ /** Horizontal override, matching texture S/U coordinates. */
429
+ wrapX?: CanvasTextureWrap
430
+ /** Vertical override, matching texture T/V coordinates. */
431
+ wrapY?: CanvasTextureWrap
432
+ }
433
+
434
+ export interface TriangleMeshProps extends CanvasInteractionProps {
435
+ /** Compiler input. Runtime drawing uses the explicit fill below. */
436
+ className?: string
437
+ vertices: readonly CanvasPoint[]
438
+ indices?: readonly number[]
439
+ /** One colour per vertex. When present, these replace the uniform fill. */
440
+ colors?: readonly CanvasVertexColor[]
441
+ /** An affine image texture. Vertex colours and textures are not combined yet. */
442
+ texture?: CanvasMeshTexture
443
+ fill?: CanvasPaint
444
+ opacity?: number
445
+ }
446
+
447
+ /** Finite normalized channels, or no colour when a renderer must skip that face. */
448
+ export function triangleMeshColor(
449
+ color: CanvasVertexColor | undefined,
450
+ ): CanvasVertexColor | undefined {
451
+ if (
452
+ !color ||
453
+ ![color.r, color.g, color.b].every(Number.isFinite) ||
454
+ (color.a !== undefined && !Number.isFinite(color.a))
455
+ ) {
456
+ return undefined
457
+ }
458
+ return {
459
+ r: Math.max(0, Math.min(1, color.r)),
460
+ g: Math.max(0, Math.min(1, color.g)),
461
+ b: Math.max(0, Math.min(1, color.b)),
462
+ ...(color.a === undefined ? {} : { a: Math.max(0, Math.min(1, color.a)) }),
463
+ }
464
+ }
465
+
466
+ /** A normalized vertex colour in the syntax Canvas 2D and Skia both accept. */
467
+ export function triangleMeshColorCss(color: CanvasVertexColor, alpha = color.a ?? 1): string {
468
+ return `rgba(${Math.round(color.r * 255)}, ${Math.round(color.g * 255)}, ${Math.round(color.b * 255)}, ${alpha})`
469
+ }
470
+
471
+ /** A finite top-left texture coordinate, bounded to one tile when clamped. */
472
+ export function triangleMeshTextureCoordinate(
473
+ coordinate: CanvasPoint | undefined,
474
+ wrapX: CanvasTextureWrap = 'clamp',
475
+ wrapY: CanvasTextureWrap = wrapX,
476
+ ): CanvasPoint | undefined {
477
+ if (
478
+ !coordinate ||
479
+ !Number.isFinite(coordinate.x) ||
480
+ !Number.isFinite(coordinate.y) ||
481
+ (wrapX === 'clamp' && (coordinate.x < 0 || coordinate.x > 1)) ||
482
+ (wrapY === 'clamp' && (coordinate.y < 0 || coordinate.y > 1))
483
+ ) {
484
+ return undefined
485
+ }
486
+ return coordinate
487
+ }
488
+
489
+ /** The resolved per-axis wrapping used by both renderers. */
490
+ export function canvasMeshTextureWrap(
491
+ texture: CanvasMeshTexture,
492
+ ): readonly [CanvasTextureWrap, CanvasTextureWrap] {
493
+ return [texture.wrapX ?? texture.wrap ?? 'clamp', texture.wrapY ?? texture.wrap ?? 'clamp']
494
+ }
495
+
496
+ /** A finite RGB multiplier. Negative light is the same clamped black Three.js displays. */
497
+ export function canvasMeshTextureIntensity(texture: CanvasMeshTexture): number | undefined {
498
+ const intensity = texture.intensity ?? 1
499
+ return Number.isFinite(intensity) ? Math.max(0, intensity) : undefined
500
+ }
501
+
502
+ const identityTextureColor = Object.freeze({ r: 1, g: 1, b: 1 })
503
+
504
+ /** One finite linear-RGB contract for validation and both renderer hosts. */
505
+ export function canvasMeshTextureColor(
506
+ texture: CanvasMeshTexture,
507
+ ): { r: number; g: number; b: number } | undefined {
508
+ const intensity = canvasMeshTextureIntensity(texture)
509
+ if (intensity === 1 && !texture.tint) return identityTextureColor
510
+ const tint = texture.tint ?? { r: 1, g: 1, b: 1 }
511
+ if (intensity === undefined || ![tint.r, tint.g, tint.b].every(Number.isFinite)) return undefined
512
+ const color = {
513
+ r: Math.max(0, tint.r) * intensity,
514
+ g: Math.max(0, tint.g) * intensity,
515
+ b: Math.max(0, tint.b) * intensity,
516
+ }
517
+ return [color.r, color.g, color.b].every(Number.isFinite) ? color : undefined
518
+ }
519
+
520
+ /** The URI a browser can load, absent for a Native-only numeric asset ID. */
521
+ export function canvasTextureUri(source: CanvasTextureSource): string | undefined {
522
+ if (typeof source === 'string') return source
523
+ if (typeof source === 'number') return undefined
524
+ return typeof source.uri === 'string'
525
+ ? source.uri
526
+ : typeof source.default === 'string'
527
+ ? source.default
528
+ : undefined
529
+ }
530
+
531
+ /** The complete, valid triangle index stream shared by rendering and hit testing. */
532
+ export function triangleMeshIndices(props: TriangleMeshProps): number[] {
533
+ if (props.colors && props.texture) return []
534
+ if (props.texture && !canvasMeshTextureColor(props.texture)) return []
535
+ const source = props.indices ?? props.vertices.map((_, index) => index)
536
+ const result: number[] = []
537
+ for (let offset = 0; offset + 2 < source.length; offset += 3) {
538
+ const a = source[offset]
539
+ const b = source[offset + 1]
540
+ const c = source[offset + 2]
541
+ if (
542
+ a === undefined ||
543
+ b === undefined ||
544
+ c === undefined ||
545
+ !Number.isInteger(a) ||
546
+ !Number.isInteger(b) ||
547
+ !Number.isInteger(c) ||
548
+ a < 0 ||
549
+ b < 0 ||
550
+ c < 0 ||
551
+ a >= props.vertices.length ||
552
+ b >= props.vertices.length ||
553
+ c >= props.vertices.length
554
+ ) {
555
+ continue
556
+ }
557
+ if (
558
+ props.colors &&
559
+ (!triangleMeshColor(props.colors[a]) ||
560
+ !triangleMeshColor(props.colors[b]) ||
561
+ !triangleMeshColor(props.colors[c]))
562
+ ) {
563
+ continue
564
+ }
565
+ if (props.texture) {
566
+ const [wrapX, wrapY] = canvasMeshTextureWrap(props.texture)
567
+ if (
568
+ !triangleMeshTextureCoordinate(props.texture.coordinates[a], wrapX, wrapY) ||
569
+ !triangleMeshTextureCoordinate(props.texture.coordinates[b], wrapX, wrapY) ||
570
+ !triangleMeshTextureCoordinate(props.texture.coordinates[c], wrapX, wrapY)
571
+ ) {
572
+ continue
573
+ }
574
+ }
575
+ result.push(a, b, c)
576
+ }
577
+ return result
578
+ }
579
+
377
580
  export type ClipProps = (
378
581
  | { path: string; x?: never; y?: never; width?: never; height?: never }
379
582
  | { path?: never; x?: number; y?: number; width: number; height: number }
@@ -389,6 +592,7 @@ export type CanvasLeafNode =
389
592
  | { id?: string; kind: 'line'; props: SceneProps<LineProps> }
390
593
  | { id?: string; kind: 'text'; props: SceneProps<TextProps> }
391
594
  | { id?: string; kind: 'path'; props: SceneProps<PathProps> }
595
+ | { id?: string; kind: 'triangle-mesh'; props: SceneProps<TriangleMeshProps> }
392
596
 
393
597
  export type CanvasSceneNode =
394
598
  | CanvasLeafNode
@@ -423,6 +627,7 @@ class CanvasInteractionStore {
423
627
  readonly #handlers = new Map<string, (event: CanvasPressEvent) => void>()
424
628
  readonly #labels = new Map<string, string>()
425
629
  readonly #destinations = new Map<string, CanvasDestination>()
630
+ readonly #controlIds = new Map<string, string>()
426
631
  readonly #listeners = new Set<() => void>()
427
632
  #version = 0
428
633
 
@@ -442,22 +647,27 @@ class CanvasInteractionStore {
442
647
  handler: ((event: CanvasPressEvent) => void) | undefined,
443
648
  label: string | undefined,
444
649
  destination: CanvasDestination | undefined,
650
+ controlId: string | undefined,
445
651
  ) {
446
652
  const previousHas = this.has(id)
447
653
  const previousLabel = this.#labels.get(id)
448
654
  const previousDestination = this.#destinations.get(id)
655
+ const previousControlId = this.#controlIds.get(id)
449
656
  if (handler === undefined) this.#handlers.delete(id)
450
657
  else this.#handlers.set(id, handler)
451
658
  if (label === undefined) this.#labels.delete(id)
452
659
  else this.#labels.set(id, label)
453
660
  if (destination === undefined) this.#destinations.delete(id)
454
661
  else this.#destinations.set(id, destination)
662
+ if (controlId === undefined) this.#controlIds.delete(id)
663
+ else this.#controlIds.set(id, controlId)
455
664
  if (
456
665
  previousHas !== this.has(id) ||
457
666
  previousLabel !== label ||
458
667
  previousDestination?.href !== destination?.href ||
459
668
  previousDestination?.external !== destination?.external ||
460
- previousDestination?.replace !== destination?.replace
669
+ previousDestination?.replace !== destination?.replace ||
670
+ previousControlId !== controlId
461
671
  ) {
462
672
  this.#emit()
463
673
  }
@@ -467,11 +677,16 @@ class CanvasInteractionStore {
467
677
  return this.#labels.get(id)
468
678
  }
469
679
 
680
+ controlId(id: string) {
681
+ return this.#controlIds.get(id) ?? id
682
+ }
683
+
470
684
  remove(id: string) {
471
685
  const hadInteraction = this.has(id)
472
686
  this.#handlers.delete(id)
473
687
  this.#labels.delete(id)
474
688
  this.#destinations.delete(id)
689
+ this.#controlIds.delete(id)
475
690
  if (hadInteraction) this.#emit()
476
691
  }
477
692
 
@@ -503,14 +718,18 @@ class CanvasInteractionStore {
503
718
  */
504
719
  class CanvasActiveStore {
505
720
  readonly #handlers = new Map<string, (event: CanvasPressEvent | undefined) => void>()
721
+ readonly #controlIds = new Map<string, string>()
506
722
  #activeId: string | undefined
507
723
 
508
- set(id: string, handler: (event: CanvasPressEvent | undefined) => void) {
724
+ set(id: string, handler: (event: CanvasPressEvent | undefined) => void, controlId?: string) {
509
725
  this.#handlers.set(id, handler)
726
+ if (controlId === undefined) this.#controlIds.delete(id)
727
+ else this.#controlIds.set(id, controlId)
510
728
  }
511
729
 
512
730
  remove(id: string) {
513
731
  this.#handlers.delete(id)
732
+ this.#controlIds.delete(id)
514
733
  // A shape that unmounts while indicated leaves nothing to be
515
734
  // indicated, and the handler it would have been told through is the
516
735
  // one that just went away.
@@ -536,7 +755,14 @@ class CanvasActiveStore {
536
755
  activate(id: string | undefined, event: CanvasPressEvent | undefined) {
537
756
  if (this.#activeId === id) return
538
757
  const previous = this.#activeId
758
+ const previousControl =
759
+ previous === undefined ? undefined : (this.#controlIds.get(previous) ?? previous)
760
+ const nextControl = id === undefined ? undefined : (this.#controlIds.get(id) ?? id)
539
761
  this.#activeId = id
762
+ // The pointer crossed a paint boundary inside one semantic object. Keep
763
+ // the current handler aligned with the topmost shape, but do not report a
764
+ // leave and re-entry for a transition the user cannot perceive.
765
+ if (previousControl === nextControl) return
540
766
  if (previous !== undefined) this.#handlers.get(previous)?.(undefined)
541
767
  if (id !== undefined && event !== undefined) this.#handlers.get(id)?.(event)
542
768
  }
@@ -685,6 +911,7 @@ function interactiveLeaf<P extends CanvasInteractionProps>(
685
911
  onPress,
686
912
  onActiveChange,
687
913
  accessibilityLabel,
914
+ accessibilityControlId,
688
915
  disabled,
689
916
  href,
690
917
  external,
@@ -706,6 +933,7 @@ function interactiveLeaf<P extends CanvasInteractionProps>(
706
933
  onPress,
707
934
  accessibilityLabel,
708
935
  href === undefined ? undefined : { href, external, replace },
936
+ accessibilityControlId,
709
937
  )
710
938
  return () => context.interactions.remove(context.id)
711
939
  }, [
@@ -713,6 +941,7 @@ function interactiveLeaf<P extends CanvasInteractionProps>(
713
941
  context.id,
714
942
  onPress,
715
943
  accessibilityLabel,
944
+ accessibilityControlId,
716
945
  disabled,
717
946
  href,
718
947
  external,
@@ -723,9 +952,9 @@ function interactiveLeaf<P extends CanvasInteractionProps>(
723
952
  context.active.remove(context.id)
724
953
  return
725
954
  }
726
- context.active.set(context.id, onActiveChange)
955
+ context.active.set(context.id, onActiveChange, accessibilityControlId)
727
956
  return () => context.active.remove(context.id)
728
- }, [context.active, context.id, onActiveChange, disabled])
957
+ }, [context.active, context.id, onActiveChange, accessibilityControlId, disabled])
729
958
  return null
730
959
  }
731
960
  Component.displayName = `Canvas.${kind}`
@@ -742,6 +971,7 @@ export const Line = interactiveLeaf<LineProps>('line')
742
971
  // surface answers for its own -- see `CanvasPathHitTest`.
743
972
  export const Text = interactiveLeaf<TextProps>('text')
744
973
  export const Path = interactiveLeaf<PathProps>('path')
974
+ export const TriangleMesh = interactiveLeaf<TriangleMeshProps>('triangle-mesh')
745
975
 
746
976
  export function Group({ children, ...props }: GroupProps) {
747
977
  // A rest object is new on every render; see `interactiveLeaf`.
@@ -879,9 +1109,13 @@ export function canvasControls(
879
1109
  warn?: (message: string) => void,
880
1110
  ): CanvasControl[] {
881
1111
  const found: CanvasControl[] = []
1112
+ const represented = new Set<string>()
882
1113
  const walk = (nodes: CanvasScene) => {
883
1114
  for (const node of nodes) {
884
1115
  if (node.id !== undefined && interactions.has(node.id)) {
1116
+ const controlId = interactions.controlId(node.id)
1117
+ if (represented.has(controlId)) continue
1118
+ represented.add(controlId)
885
1119
  const label = interactions.label(node.id)
886
1120
  if (label === undefined) {
887
1121
  // Once per shape, not once per render: `useId` is stable for