@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,499 @@
1
+ import {
2
+ type CanvasScene,
3
+ type CanvasSceneNode,
4
+ type CanvasTransform,
5
+ type ClipProps,
6
+ type LineProps,
7
+ paintStrokes,
8
+ type TextProps,
9
+ unhandledShape,
10
+ } from './scene.tsx'
11
+ import { textLines } from './wrap-text.ts'
12
+
13
+ export interface CanvasPoint {
14
+ x: number
15
+ y: number
16
+ }
17
+
18
+ export interface CanvasHitTestViewport {
19
+ /** Logical surface width in CSS pixels or React Native points. */
20
+ width: number
21
+ /** Logical surface height in CSS pixels or React Native points. */
22
+ height: number
23
+ viewBox?: readonly [x: number, y: number, width: number, height: number]
24
+ fit?: 'contain' | 'stretch'
25
+ }
26
+
27
+ export interface CanvasHitTestResult {
28
+ id: string
29
+ /** Point in the root scene coordinate system, after the viewBox transform. */
30
+ point: CanvasPoint
31
+ /** Point after the target's ancestor transforms have also been inverted. */
32
+ localPoint: CanvasPoint
33
+ }
34
+
35
+ type Matrix = readonly [a: number, b: number, c: number, d: number, e: number, f: number]
36
+
37
+ const identity: Matrix = [1, 0, 0, 1, 0, 0]
38
+
39
+ function multiply(left: Matrix, right: Matrix): Matrix {
40
+ return [
41
+ left[0] * right[0] + left[2] * right[1],
42
+ left[1] * right[0] + left[3] * right[1],
43
+ left[0] * right[2] + left[2] * right[3],
44
+ left[1] * right[2] + left[3] * right[3],
45
+ left[0] * right[4] + left[2] * right[5] + left[4],
46
+ left[1] * right[4] + left[3] * right[5] + left[5],
47
+ ]
48
+ }
49
+
50
+ function translate(x: number, y: number): Matrix {
51
+ return [1, 0, 0, 1, x, y]
52
+ }
53
+
54
+ function scale(x: number, y: number): Matrix {
55
+ return [x, 0, 0, y, 0, 0]
56
+ }
57
+
58
+ function rotate(degrees: number): Matrix {
59
+ const radians = (degrees * Math.PI) / 180
60
+ const cosine = Math.cos(radians)
61
+ const sine = Math.sin(radians)
62
+ return [cosine, sine, -sine, cosine, 0, 0]
63
+ }
64
+
65
+ function invert(matrix: Matrix): Matrix | undefined {
66
+ const determinant = matrix[0] * matrix[3] - matrix[1] * matrix[2]
67
+ if (!Number.isFinite(determinant) || Math.abs(determinant) < Number.EPSILON) return undefined
68
+ return [
69
+ matrix[3] / determinant,
70
+ -matrix[1] / determinant,
71
+ -matrix[2] / determinant,
72
+ matrix[0] / determinant,
73
+ (matrix[2] * matrix[5] - matrix[3] * matrix[4]) / determinant,
74
+ (matrix[1] * matrix[4] - matrix[0] * matrix[5]) / determinant,
75
+ ]
76
+ }
77
+
78
+ function apply(matrix: Matrix, point: CanvasPoint): CanvasPoint {
79
+ return {
80
+ x: matrix[0] * point.x + matrix[2] * point.y + matrix[4],
81
+ y: matrix[1] * point.x + matrix[3] * point.y + matrix[5],
82
+ }
83
+ }
84
+
85
+ function groupMatrix(transform?: CanvasTransform): Matrix {
86
+ if (!transform) return identity
87
+ const originX = transform.originX ?? 0
88
+ const originY = transform.originY ?? 0
89
+ let result = translate(transform.translateX ?? 0, transform.translateY ?? 0)
90
+ if (originX !== 0 || originY !== 0) result = multiply(result, translate(originX, originY))
91
+ if (transform.rotate) result = multiply(result, rotate(transform.rotate))
92
+ result = multiply(result, scale(transform.scaleX ?? 1, transform.scaleY ?? 1))
93
+ if (originX !== 0 || originY !== 0) result = multiply(result, translate(-originX, -originY))
94
+ return result
95
+ }
96
+
97
+ function viewportMatrix(viewport: CanvasHitTestViewport): Matrix | undefined {
98
+ if (viewport.width <= 0 || viewport.height <= 0) return undefined
99
+ const viewBox = viewport.viewBox
100
+ if (!viewBox) return identity
101
+ if (viewBox[2] <= 0 || viewBox[3] <= 0) return undefined
102
+ const scaleX = viewport.width / viewBox[2]
103
+ const scaleY = viewport.height / viewBox[3]
104
+ if ((viewport.fit ?? 'contain') === 'stretch') {
105
+ return multiply(scale(scaleX, scaleY), translate(-viewBox[0], -viewBox[1]))
106
+ }
107
+ const uniformScale = Math.min(scaleX, scaleY)
108
+ const offsetX = (viewport.width - viewBox[2] * uniformScale) / 2
109
+ const offsetY = (viewport.height - viewBox[3] * uniformScale) / 2
110
+ return multiply(
111
+ multiply(translate(offsetX, offsetY), scale(uniformScale, uniformScale)),
112
+ translate(-viewBox[0], -viewBox[1]),
113
+ )
114
+ }
115
+
116
+ function normalRect(x: number, y: number, width: number, height: number) {
117
+ return {
118
+ x: width < 0 ? x + width : x,
119
+ y: height < 0 ? y + height : y,
120
+ width: Math.abs(width),
121
+ height: Math.abs(height),
122
+ }
123
+ }
124
+
125
+ function pointInRect(point: CanvasPoint, x: number, y: number, width: number, height: number) {
126
+ const rect = normalRect(x, y, width, height)
127
+ return (
128
+ rect.width > 0 &&
129
+ rect.height > 0 &&
130
+ point.x >= rect.x &&
131
+ point.x <= rect.x + rect.width &&
132
+ point.y >= rect.y &&
133
+ point.y <= rect.y + rect.height
134
+ )
135
+ }
136
+
137
+ function pointInRoundedRect(
138
+ point: CanvasPoint,
139
+ x: number,
140
+ y: number,
141
+ width: number,
142
+ height: number,
143
+ radius: number,
144
+ ) {
145
+ const rect = normalRect(x, y, width, height)
146
+ if (!pointInRect(point, rect.x, rect.y, rect.width, rect.height)) return false
147
+ const cornerRadius = Math.max(0, Math.min(Math.abs(radius), rect.width / 2, rect.height / 2))
148
+ if (cornerRadius === 0) return true
149
+ const centerX = Math.max(
150
+ rect.x + cornerRadius,
151
+ Math.min(point.x, rect.x + rect.width - cornerRadius),
152
+ )
153
+ const centerY = Math.max(
154
+ rect.y + cornerRadius,
155
+ Math.min(point.y, rect.y + rect.height - cornerRadius),
156
+ )
157
+ const dx = point.x - centerX
158
+ const dy = point.y - centerY
159
+ return dx * dx + dy * dy <= cornerRadius * cornerRadius
160
+ }
161
+
162
+ /**
163
+ * Whether a point lands on a line's stroke, as the stroke is painted.
164
+ *
165
+ * A line has no area, so the only honest region is the one the renderer
166
+ * draws: the band of `strokeWidth` around the segment, ended the way
167
+ * `lineCap` ends it. Anything wider would be a control nobody can see,
168
+ * which is the failure this issue's own wording warns about -- so a chart
169
+ * that wants a finger-sized target draws a wider transparent line, and
170
+ * says so in the scene rather than relying on a tolerance it cannot
171
+ * inspect.
172
+ *
173
+ * The three caps are three different shapes and are treated as such:
174
+ *
175
+ * - `butt` (the default in Canvas2D and Skia both) stops flat at the
176
+ * endpoints, so the region is exactly the rectangle;
177
+ * - `round` adds a half-disc at each end, which is what makes plain
178
+ * distance-to-segment the right test;
179
+ * - `square` extends the rectangle by half the width at each end.
180
+ */
181
+ function pointInLine(point: CanvasPoint, props: LineProps): boolean {
182
+ if (!paintStrokes(props)) return false
183
+ const half = (props.strokeWidth ?? 1) / 2
184
+ const dx = props.x2 - props.x1
185
+ const dy = props.y2 - props.y1
186
+ const lengthSquared = dx * dx + dy * dy
187
+
188
+ // A zero-length line, which the platforms disagree about the least when
189
+ // stated explicitly: `butt` paints nothing at all, and the other two
190
+ // paint the cap on its own -- a disc or a square of the stroke width.
191
+ if (lengthSquared === 0) {
192
+ const px = point.x - props.x1
193
+ const py = point.y - props.y1
194
+ if (props.lineCap === 'round') return px * px + py * py <= half * half
195
+ if (props.lineCap === 'square') return Math.abs(px) <= half && Math.abs(py) <= half
196
+ return false
197
+ }
198
+
199
+ // Where the point falls along the segment, 0 at one end and 1 at the
200
+ // other. The caps decide how far outside that range still counts.
201
+ const t = ((point.x - props.x1) * dx + (point.y - props.y1) * dy) / lengthSquared
202
+ if (props.lineCap === 'round') {
203
+ const clamped = Math.max(0, Math.min(1, t))
204
+ const nearestX = props.x1 + clamped * dx
205
+ const nearestY = props.y1 + clamped * dy
206
+ const offX = point.x - nearestX
207
+ const offY = point.y - nearestY
208
+ return offX * offX + offY * offY <= half * half
209
+ }
210
+ const overhang = props.lineCap === 'square' ? half / Math.sqrt(lengthSquared) : 0
211
+ if (t < -overhang || t > 1 + overhang) return false
212
+ // Distance to the infinite line, which inside that range is the
213
+ // distance to the stroke's centre.
214
+ const perpendicular = Math.abs((point.x - props.x1) * dy - (point.y - props.y1) * dx)
215
+ return perpendicular <= half * Math.sqrt(lengthSquared)
216
+ }
217
+
218
+ function pointInNode(node: CanvasSceneNode, point: CanvasPoint, queries?: CanvasRendererQueries) {
219
+ switch (node.kind) {
220
+ case 'rect':
221
+ return pointInRect(
222
+ point,
223
+ node.props.x ?? 0,
224
+ node.props.y ?? 0,
225
+ node.props.width,
226
+ node.props.height,
227
+ )
228
+ case 'rounded-rect':
229
+ return pointInRoundedRect(
230
+ point,
231
+ node.props.x ?? 0,
232
+ node.props.y ?? 0,
233
+ node.props.width,
234
+ node.props.height,
235
+ node.props.radius,
236
+ )
237
+ case 'circle': {
238
+ if (node.props.radius <= 0) return false
239
+ const dx = point.x - node.props.cx
240
+ const dy = point.y - node.props.cy
241
+ return dx * dx + dy * dy <= node.props.radius * node.props.radius
242
+ }
243
+ case 'ellipse': {
244
+ if (node.props.radiusX <= 0 || node.props.radiusY <= 0) return false
245
+ const dx = (point.x - node.props.cx) / node.props.radiusX
246
+ const dy = (point.y - node.props.cy) / node.props.radiusY
247
+ return dx * dx + dy * dy <= 1
248
+ }
249
+ case 'line':
250
+ return pointInLine(point, node.props)
251
+ case 'path':
252
+ // Asked of the renderer, for the reason `CanvasPathHitTest` gives.
253
+ return (
254
+ queries?.pathContains?.(node.props.path, node.props.fillRule ?? 'nonzero', point) ?? false
255
+ )
256
+ case 'text': {
257
+ const measure = queries?.measureText
258
+ if (!measure) return false
259
+ // Each line boxed on its own rather than one box around all of
260
+ // them: a short last line leaves a corner that looks pressable and
261
+ // is not, and a person who presses there gets nothing for a reason
262
+ // they cannot see.
263
+ const width = (run: string) => measure({ ...node.props, text: run }).width
264
+ return textLines(node.props, width).some((line) => {
265
+ const props = { ...node.props, text: line.text, y: line.y }
266
+ const box = textBox(props, measure(props))
267
+ return pointInRect(point, box.x, box.y, box.width, box.height)
268
+ })
269
+ }
270
+ case 'group':
271
+ case 'clip':
272
+ return false
273
+ default:
274
+ return unhandledShape(node, 'the hit test') ?? false
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Whether a point is inside an SVG path, answered by the renderer.
280
+ *
281
+ * Supplied by each surface rather than implemented here, which is the
282
+ * opposite of how every other shape works and is deliberate. A rectangle
283
+ * or a circle is the same geometry under Canvas2D and under Skia, so one
284
+ * shared predicate agrees with both. An arbitrary path is not: béziers,
285
+ * arcs and fill rules are where rasterisers differ, and a third
286
+ * implementation in TypeScript would agree with neither of the two that
287
+ * actually draw. Canvas2D's `isPointInPath` and Skia's `Path.contains`
288
+ * each agree with their own.
289
+ *
290
+ * The same reasoning `TextProps` gives for alignment: each renderer's
291
+ * measurement is its own, and only its own can match what it draws.
292
+ *
293
+ * Optional, and paths refuse without it. A caller that has no renderer to
294
+ * ask -- a test, a server -- gets the behaviour paths had before this
295
+ * existed rather than a guess.
296
+ */
297
+ export type CanvasPathHitTest = (
298
+ path: string,
299
+ fillRule: 'nonzero' | 'evenodd',
300
+ point: CanvasPoint,
301
+ ) => boolean
302
+
303
+ /**
304
+ * A run of text as the renderer that drew it measures it.
305
+ *
306
+ * Supplied per surface for the reason `CanvasPathHitTest` is: the only
307
+ * measurement that can agree with what is on screen is the one taken by
308
+ * the thing that put it there. Canvas2D answers with
309
+ * `actualBoundingBoxAscent` and `Descent`; Skia answers with a rect whose
310
+ * origin is the baseline. Both report the *ink*, not the font box.
311
+ *
312
+ * That last part is why this exists at all. Refusing to hit test text
313
+ * was argued from "a box is not where the ink is" -- true of a font box
314
+ * and false of this one, which both platforms have had all along. The
315
+ * refusal left a label a person can see and cannot press, with nothing
316
+ * said, which is the failure this package spends its time avoiding.
317
+ */
318
+ export interface CanvasTextMetrics {
319
+ width: number
320
+ /** Ink above the baseline, positive. */
321
+ ascent: number
322
+ /** Ink below the baseline, positive. */
323
+ descent: number
324
+ }
325
+
326
+ export type CanvasTextMeasure = (props: TextProps) => CanvasTextMetrics
327
+
328
+ /**
329
+ * What a surface can answer that the shared hit test cannot.
330
+ *
331
+ * One object rather than a growing tail of optional callbacks. Each is
332
+ * a question only a renderer can answer, and each is absent for a caller
333
+ * that has no renderer to ask -- a test, a server -- which refuses the
334
+ * shapes that need it rather than guessing at them.
335
+ */
336
+ export interface CanvasRendererQueries {
337
+ pathContains?: CanvasPathHitTest
338
+ measureText?: CanvasTextMeasure
339
+ }
340
+
341
+ /**
342
+ * The box a run of text occupies, in the text's own coordinates.
343
+ *
344
+ * `x` is the left edge and `y` the baseline, as `TextProps` says, so the
345
+ * box runs from the baseline up by the ascent and down by the descent.
346
+ * `textAlign` moves the run rather than the anchor, which is what it
347
+ * does on the screen.
348
+ */
349
+ function textBox(props: TextProps, metrics: CanvasTextMetrics) {
350
+ const align = props.textAlign ?? 'left'
351
+ const left =
352
+ align === 'left'
353
+ ? props.x
354
+ : align === 'center'
355
+ ? props.x - metrics.width / 2
356
+ : props.x - metrics.width
357
+ return {
358
+ x: left,
359
+ y: props.y - metrics.ascent,
360
+ width: metrics.width,
361
+ height: metrics.ascent + metrics.descent,
362
+ }
363
+ }
364
+
365
+ function pointInClip(
366
+ point: CanvasPoint,
367
+ props: Omit<ClipProps, 'children'>,
368
+ queries?: CanvasRendererQueries,
369
+ ) {
370
+ if (props.path !== undefined) {
371
+ // A clip has no fill rule of its own; both renderers clip a path by
372
+ // its default, which is nonzero on each.
373
+ return queries?.pathContains?.(props.path, 'nonzero', point) ?? false
374
+ }
375
+ return pointInRect(point, props.x ?? 0, props.y ?? 0, props.width ?? 0, props.height ?? 0)
376
+ }
377
+
378
+ /** A shape's own middle, in its own coordinates. */
379
+ function localCentre(node: CanvasSceneNode): CanvasPoint | undefined {
380
+ switch (node.kind) {
381
+ case 'rect':
382
+ case 'rounded-rect': {
383
+ const rect = normalRect(
384
+ node.props.x ?? 0,
385
+ node.props.y ?? 0,
386
+ node.props.width,
387
+ node.props.height,
388
+ )
389
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
390
+ }
391
+ case 'circle':
392
+ case 'ellipse':
393
+ return { x: node.props.cx, y: node.props.cy }
394
+ case 'line':
395
+ return { x: (node.props.x1 + node.props.x2) / 2, y: (node.props.y1 + node.props.y2) / 2 }
396
+ case 'text':
397
+ return { x: node.props.x, y: node.props.y }
398
+ default:
399
+ return undefined
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Where a shape is, for something that arrives without a pointer.
405
+ *
406
+ * A keyboard reaching a shape has no cursor, and `CanvasPressEvent` still
407
+ * has to say where. Its middle is the honest answer, and it is computed
408
+ * through the same matrices the hit test walks so that focusing a shape
409
+ * and clicking it report the same place.
410
+ */
411
+ export function canvasNodePoint(
412
+ scene: CanvasScene,
413
+ id: string,
414
+ viewport: CanvasHitTestViewport,
415
+ ): { point: CanvasPoint; surfacePoint: CanvasPoint } | undefined {
416
+ const rootMatrix = viewportMatrix(viewport)
417
+ if (!rootMatrix) return undefined
418
+
419
+ const visit = (
420
+ nodes: CanvasScene,
421
+ matrix: Matrix,
422
+ ): { point: CanvasPoint; surfacePoint: CanvasPoint } | undefined => {
423
+ for (const node of nodes) {
424
+ if (node.kind === 'group') {
425
+ const found = visit(node.children, multiply(matrix, groupMatrix(node.props.transform)))
426
+ if (found) return found
427
+ continue
428
+ }
429
+ if (node.kind === 'clip') {
430
+ const found = visit(node.children, matrix)
431
+ if (found) return found
432
+ continue
433
+ }
434
+ if (node.id !== id) continue
435
+ const centre = localCentre(node)
436
+ if (!centre) return undefined
437
+ // `matrix` already carries the viewport, so the ancestor transforms
438
+ // give the scene point and the whole thing gives the surface one.
439
+ const sceneMatrix = invert(rootMatrix)
440
+ const surfacePoint = apply(matrix, centre)
441
+ return {
442
+ point: sceneMatrix ? apply(sceneMatrix, surfacePoint) : centre,
443
+ surfacePoint,
444
+ }
445
+ }
446
+ return undefined
447
+ }
448
+ return visit(scene, rootMatrix)
449
+ }
450
+
451
+ /**
452
+ * Finds the topmost interactive geometry at a logical surface point.
453
+ *
454
+ * Rectangle clips, the four closed primitive shapes, and lines are
455
+ * portable today. Paths and path clips deliberately refuse hits until both
456
+ * renderers can implement the same contract.
457
+ */
458
+ export function hitTestCanvas(
459
+ scene: CanvasScene,
460
+ surfacePoint: CanvasPoint,
461
+ viewport: CanvasHitTestViewport,
462
+ isInteractive: (id: string) => boolean,
463
+ queries?: CanvasRendererQueries,
464
+ ): CanvasHitTestResult | undefined {
465
+ const rootMatrix = viewportMatrix(viewport)
466
+ if (!rootMatrix) return undefined
467
+ const rootInverse = invert(rootMatrix)
468
+ if (!rootInverse) return undefined
469
+ const scenePoint = apply(rootInverse, surfacePoint)
470
+
471
+ const visit = (nodes: CanvasScene, matrix: Matrix): CanvasHitTestResult | undefined => {
472
+ for (let index = nodes.length - 1; index >= 0; index -= 1) {
473
+ const node = nodes[index]
474
+ if (!node) continue
475
+ if (node.kind === 'group') {
476
+ const hit = visit(node.children, multiply(matrix, groupMatrix(node.props.transform)))
477
+ if (hit) return hit
478
+ continue
479
+ }
480
+ if (node.kind === 'clip') {
481
+ const inverse = invert(matrix)
482
+ if (!inverse || !pointInClip(apply(inverse, surfacePoint), node.props, queries)) continue
483
+ const hit = visit(node.children, matrix)
484
+ if (hit) return hit
485
+ continue
486
+ }
487
+ if (!node.id || !isInteractive(node.id)) continue
488
+ const inverse = invert(matrix)
489
+ if (!inverse) continue
490
+ const localPoint = apply(inverse, surfacePoint)
491
+ if (pointInNode(node, localPoint, queries)) {
492
+ return { id: node.id, point: scenePoint, localPoint }
493
+ }
494
+ }
495
+ return undefined
496
+ }
497
+
498
+ return visit(scene, rootMatrix)
499
+ }