@rive-app/canvas-single 2.39.0 → 2.39.1

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.
@@ -0,0 +1,217 @@
1
+ import type * as rc from "../rive_advanced.mjs";
2
+ import type { SemanticTreeModel } from "./semanticTreeModel";
3
+ import { SemanticActionType, RiveSemanticsOptions } from "./types";
4
+ export interface AccessibilityOverlayOptions {
5
+ canvas: HTMLCanvasElement;
6
+ /** Unique string per Rive instance (used for prefixed IDs). */
7
+ instanceId: string;
8
+ /** Optional options for controlling semantic tree behavior and rendering */
9
+ semanticsOptions: RiveSemanticsOptions;
10
+ /** Callback to fire a semantic action back into the state machine. */
11
+ fireAction: (nodeId: number, actionType: SemanticActionType) => void;
12
+ /** Callback when AT focuses a semantic node (routes to SemanticManager::requestFocus). */
13
+ requestFocus: (nodeId: number) => void;
14
+ /** Callback when AT focus leaves a semantic node. */
15
+ clearFocus: () => void;
16
+ /**
17
+ * When false (default), the overlay only moves focus while focus is already
18
+ * inside Rive (overlay or canvas); when true it may also pull focus from outside Rive.
19
+ */
20
+ allowFocusInterrupt?: boolean;
21
+ }
22
+ /**
23
+ * Indication of what changed since the last overlay update.
24
+ *
25
+ * - `semanticChanged` — semantic tree content/structure changed; attributes,
26
+ * DOM order, and stale removal need reconciling.
27
+ * - `nodeGeometryChanged` — node bounds changed in the tree model.
28
+ * - `layoutChanged` — canvas size/position changed (or the transform container
29
+ * hasn't been created yet); the artboard→canvas transform must be recomputed.
30
+ */
31
+ export interface OverlayChange {
32
+ semanticChanged: boolean;
33
+ nodeGeometryChanged: boolean;
34
+ layoutChanged: boolean;
35
+ }
36
+ /**
37
+ * Creates and manages an invisible DOM tree overlaying a Rive canvas. This is for
38
+ * screen readers to discover and interact with the Rive content.
39
+ *
40
+ * Each semantic node in the {@link SemanticTreeModel} gets a corresponding
41
+ * DOM element with appropriate ARIA role, states, and action handlers so
42
+ * assistive technologies (i.e. screen readers) can discover
43
+ * and interact with the Rive content.
44
+ *
45
+ * Each node receives a prefixed ID (`id=rive-{instanceId}-sem-{nodeId}`) to avoid host-page ID collisions.
46
+ * The nodeID is Rive's semantic node ID from core runtime.
47
+ * Each node is styled with `pointer-events: none`. Interactive nodes can receive
48
+ * programmatic focus and keydown events without entering the browser Tab order.
49
+ */
50
+ export declare class AccessibilityOverlay {
51
+ private container;
52
+ private canvas;
53
+ private semanticsOptions;
54
+ private elements;
55
+ /** Visually-hidden description spans keyed by node ID, referenced by aria-describedby. */
56
+ private descElements;
57
+ private instanceId;
58
+ private fireAction;
59
+ private requestFocus;
60
+ private clearFocus;
61
+ private lastSemanticVersion;
62
+ private lastGeometryVersion;
63
+ /** Text elements whose fit-scale needs recomputing, batched per update (see flushTextGeometry). */
64
+ private pendingTextGeometry;
65
+ /** Last measured box-size|text key per text element, to skip redundant re-measures. */
66
+ private textGeometryKeys;
67
+ private lastCanvasPositioning;
68
+ /**
69
+ * Set when a ResizeObserver/window-resize signals the canvas geometry may have
70
+ * changed, cleared once the transform is re-synced. Lets {@link needsUpdate}
71
+ * report geometry changes without a per-frame `getBoundingClientRect()` reflow.
72
+ * Starts true so the first update computes the transform.
73
+ */
74
+ private _geometryDirty;
75
+ /** True while reconciling the DOM (reserved for future focus-sync guards). */
76
+ private isUpdating;
77
+ /** See {@link AccessibilityOverlayOptions.allowFocusInterrupt}. */
78
+ private allowFocusInterrupt;
79
+ /**
80
+ * Single child div of the overlay container that carries the artboard→CSS
81
+ * transform. All semantic node elements are children of this div and express
82
+ * their positions in raw artboard-space coordinates. The CSS transform on
83
+ * this container maps artboard units to CSS pixels in one GPU pass — no
84
+ * per-node matrix multiplication required.
85
+ */
86
+ private transformContainer;
87
+ private _artboardBounds;
88
+ private repositionTimer;
89
+ private canvasResizeObserver;
90
+ private parentResizeObserver;
91
+ /**
92
+ * Detects canvas *position* drift. See {@link observePosition}.
93
+ */
94
+ private positionObserver;
95
+ private readonly _onWindowResize;
96
+ constructor(options: AccessibilityOverlayOptions);
97
+ getSemanticOverlayContainer(): HTMLDivElement;
98
+ private attachPositionObservers;
99
+ /**
100
+ * Arms an IntersectionObserver whose root box is bounded to the canvas, so it
101
+ * fires when the canvas moves relative to the viewport — position drift that
102
+ * no ResizeObserver reports. Lets us re-sync the overlay container on a move
103
+ * instead of recalculating the canvas bounding box every frame.
104
+ */
105
+ private observePosition;
106
+ private scheduleReposition;
107
+ private syncContainerGeometry;
108
+ private createContainer;
109
+ /**
110
+ * Returns what changed since the last update, or null if nothing changed.
111
+ *
112
+ * Callers use this to avoid recomputing the (relatively expensive)
113
+ * artboard→canvas transform on frames where only node bounds changed in the
114
+ * tree: the transform only needs recomputing when `layoutChanged` is true.
115
+ */
116
+ needsUpdate(tree: SemanticTreeModel): OverlayChange | null;
117
+ /**
118
+ * Update the overlay DOM to reflect the current state of the semantic tree.
119
+ * Call once per frame after `applyDiff` when {@link needsUpdate} reports a
120
+ * change, when layout/transform inputs are dirty, or when a fresh
121
+ * `forwardMat` is supplied (even if the tree versions are unchanged).
122
+ *
123
+ * @param tree The in-memory semantic tree model
124
+ * @param forwardMat Artboard→canvas-pixel transform from `computeAlignment`,
125
+ * or null to reuse the existing CSS transform on the
126
+ * transform container
127
+ * @param dpr Device pixel ratio used for the canvas backing store
128
+ * @param artboardBounds The artboard's own bounding rectangle
129
+ */
130
+ update(tree: SemanticTreeModel, forwardMat: rc.Mat2D | null, dpr: number, artboardBounds: rc.AABB, change?: OverlayChange | null): void;
131
+ private performUpdate;
132
+ /** Remove the overlay from the DOM entirely. */
133
+ destroy(): void;
134
+ /**
135
+ * Reconcile a parent DOM element's children with an ordered list of
136
+ * semantic node IDs. Creates, updates, and reorders elements as needed.
137
+ *
138
+ * Node positions are expressed in artboard-space coordinates. The CSS
139
+ * transform on the transform container maps artboard units to CSS pixels,
140
+ * so no per-node matrix multiplication is required here.
141
+ *
142
+ * @param parentArtboardLeft Absolute artboard minX of the parent node (0 for roots)
143
+ * @param parentArtboardTop Absolute artboard minY of the parent node (0 for roots)
144
+ */
145
+ private rebuildChildren;
146
+ /**
147
+ * Reposition only the subtrees whose bounds changed in the latest diff.
148
+ * Descendants are included because node CSS positions are parent-relative.
149
+ */
150
+ private updateGeometryForChangedNodes;
151
+ private updateNodeGeometrySubtree;
152
+ /**
153
+ * Whether the overlay may move focus now. Following focus already inside this
154
+ * instance is always allowed; pulling it in from the host page is gated behind
155
+ * allowFocusInterrupt (from the Rive class).
156
+ */
157
+ private canMoveFocus;
158
+ /**
159
+ * Move focus into a newly appeared modal/alert dialog so screen readers
160
+ * announce and read its content (web ATs don't auto-enter a freshly mounted
161
+ * dialog). Skips when focus can't move (see canMoveFocus) or a descendant
162
+ * already holds it. The dialog's aria-modal keeps focus trapped inside.
163
+ */
164
+ private autoFocusDialogOnAppear;
165
+ /**
166
+ * Resolve the element assistive technologies (AT) should focus on appearance. Walks the subtree
167
+ * depth-first and returns the first focusable node's host element, else the
168
+ * inner <span> of the first labeled leaf. Container and unlabeled nodes are
169
+ * descended into but never focused. Returns null if nothing qualifies.
170
+ */
171
+ private routeDefaultFocusTarget;
172
+ /** Shared `id` prefix for all semantic node elements of this instance. */
173
+ private get nodeIdPrefix();
174
+ /** Recover the semantic node ID from an overlay element, or null. */
175
+ private nodeIdFromElement;
176
+ private createElement;
177
+ /**
178
+ * Wire arrow-key roving focus for a group member (tab, radio). Arrow keys
179
+ * move focus to the next/previous member (wrapping), optionally Home/End jump
180
+ * to first/last, and the newly focused member receives a tap action.
181
+ */
182
+ private attachRovingNav;
183
+ private attachActionHandlers;
184
+ private applyAttributes;
185
+ /**
186
+ * Positions an element in artboard-space coordinates relative to its parent.
187
+ *
188
+ * Node bounds stay in raw artboard units — the CSS `transform: matrix(...)`
189
+ * on the transform container maps artboard units to CSS pixels in one GPU
190
+ * pass. No per-node forwardMat multiplication or DPR division needed here.
191
+ *
192
+ * Round to whole artboard units before comparing to avoid triggering AX
193
+ * layout notifications from sub-unit floating-point animation jitter.
194
+ */
195
+ private applyPosition;
196
+ /**
197
+ * Scale each queued text span to fit its layout box, batched so a frame
198
+ * pays at most one synchronous layout: all measurement-reset writes first,
199
+ * then all rect reads, then all transform writes. Interleaving
200
+ * write→read→write per node would force a reflow per text node instead.
201
+ *
202
+ * Nodes whose box size and text are unchanged since the last pass are
203
+ * skipped entirely (their existing transform is still correct — the scale
204
+ * is a ratio of two rects, so ancestor transform changes cancel out).
205
+ */
206
+ private flushTextGeometry;
207
+ /**
208
+ * Creates (on first call) and updates the artboard-space transform container.
209
+ *
210
+ * The container is sized to the artboard dimensions and carries a CSS
211
+ * `transform: matrix(...)` equivalent to `forwardMat / dpr`. All semantic
212
+ * node elements are children of this container and use raw artboard
213
+ * coordinates as their CSS `left/top/width/height`, so the CSS compositor
214
+ * applies the artboard→screen mapping in one pass.
215
+ */
216
+ private syncTransformContainer;
217
+ }
@@ -0,0 +1,5 @@
1
+ export { SemanticTreeModel } from "./semanticTreeModel";
2
+ export { AccessibilityOverlay } from "./accessibilityOverlay";
3
+ export type { AccessibilityOverlayOptions } from "./accessibilityOverlay";
4
+ export { SemanticRole, SemanticState, SemanticTrait, SemanticActionType, SemanticMode, hasState, hasTrait, roleName, stateNames, traitNames, } from "./types";
5
+ export type { SemanticsDiffNode, SemanticsDiff, SemanticNodeData, RiveSemanticsOptions, } from "./types";
@@ -0,0 +1,64 @@
1
+ import type { SemanticsDiff, SemanticNodeData } from "./types";
2
+ /**
3
+ * Maintains an in-memory semantic tree built from incremental
4
+ * {@link SemanticsDiff} updates received each frame from the WASM runtime.
5
+ *
6
+ * Processing order within {@link applyDiff} follows the contract defined in
7
+ * `semantic_snapshot.hpp`: removed → added → moved → childrenUpdated →
8
+ * updatedSemantic → updatedGeometry.
9
+ */
10
+ export declare class SemanticTreeModel {
11
+ private _nodesById;
12
+ private _roots;
13
+ private _semanticVersion;
14
+ private _geometryVersion;
15
+ private _geometryChangedIds;
16
+ private _semanticChangedIds;
17
+ get nodeCount(): number;
18
+ /** Bumped when semantic content or tree structure changes. */
19
+ get semanticVersion(): number;
20
+ /** Bumped when node bounds change without a semantic/structural change. */
21
+ get geometryVersion(): number;
22
+ /** Node IDs whose bounds changed in the most recent {@link applyDiff}. */
23
+ get geometryChangedIds(): ReadonlySet<number>;
24
+ /**
25
+ * Node IDs whose semantic fields (role/label/value/hint/flags/headingLevel)
26
+ * changed in the most recent {@link applyDiff}. Structural changes (moves,
27
+ * child reorders, removals) bump {@link semanticVersion} but don't mark
28
+ * nodes here — element attributes don't depend on tree position.
29
+ */
30
+ get semanticChangedIds(): ReadonlySet<number>;
31
+ /** Root node IDs in sibling order. */
32
+ get roots(): readonly number[];
33
+ /** Look up a node by its ID, or undefined if not in the tree. */
34
+ nodeById(id: number): SemanticNodeData | undefined;
35
+ /** Current index of a node among its siblings (or roots), or -1 if absent. */
36
+ private siblingIndexOf;
37
+ /** Detach a node from its current parent (or from roots). */
38
+ private detach;
39
+ /** Attach a node under a parent at a given sibling index (or as root). */
40
+ private attach;
41
+ /** Recursively remove a node and all descendants. */
42
+ private removeSubtree;
43
+ /**
44
+ * Apply an incremental diff to the tree. Bumps version counters and notifies
45
+ * listeners only when the tree actually changed.
46
+ *
47
+ * No-op diffs (field values identical to current model) do not bump
48
+ * versions — the native side guards against emitting these, but applyDiff
49
+ * defends its subscribers regardless.
50
+ */
51
+ applyDiff(diff: SemanticsDiff): void;
52
+ private _debug;
53
+ /** Enable/disable debug logging of diffs to the console. */
54
+ set debug(enabled: boolean);
55
+ private logDiff;
56
+ /**
57
+ * Returns every node in depth-first order, paired with its depth level.
58
+ * Useful for debug logging / rendering a flat list.
59
+ */
60
+ flattened(): Array<{
61
+ depth: number;
62
+ node: SemanticNodeData;
63
+ }>;
64
+ }
@@ -0,0 +1,94 @@
1
+ import type { SemanticsDiffNode, SemanticsDiff } from "../rive_advanced.mjs";
2
+ export type { SemanticsDiffNode, SemanticsDiff, };
3
+ export declare const SemanticRole: {
4
+ readonly none: 0;
5
+ readonly button: 1;
6
+ readonly link: 2;
7
+ readonly checkbox: 3;
8
+ readonly switchControl: 4;
9
+ readonly slider: 5;
10
+ readonly textField: 6;
11
+ readonly text: 7;
12
+ readonly image: 8;
13
+ readonly group: 9;
14
+ readonly list: 10;
15
+ readonly listItem: 11;
16
+ readonly tab: 12;
17
+ readonly tabList: 13;
18
+ readonly dialog: 14;
19
+ readonly alertDialog: 15;
20
+ readonly radioGroup: 16;
21
+ readonly radioButton: 17;
22
+ };
23
+ export type SemanticRole = (typeof SemanticRole)[keyof typeof SemanticRole];
24
+ export declare const SemanticState: {
25
+ readonly None: 0;
26
+ readonly Expanded: number;
27
+ readonly Selected: number;
28
+ readonly Checked: number;
29
+ readonly Mixed: number;
30
+ readonly Toggled: number;
31
+ readonly Required: number;
32
+ readonly Disabled: number;
33
+ readonly Focused: number;
34
+ readonly Hidden: number;
35
+ readonly LiveRegion: number;
36
+ readonly ReadOnly: number;
37
+ readonly Modal: number;
38
+ readonly Obscured: number;
39
+ readonly Multiline: number;
40
+ };
41
+ export declare function hasState(flags: number, state: number): boolean;
42
+ /**
43
+ * Controls when the instance builds semantic trees and accessibility overlays.
44
+ *
45
+ * - `disabled`: no semantics work.
46
+ * - `enabled`: semantics and overlay are active immediately after load.
47
+ */
48
+ export declare const SemanticMode: {
49
+ readonly Disabled: "disabled";
50
+ readonly Enabled: "enabled";
51
+ };
52
+ export type SemanticMode = (typeof SemanticMode)[keyof typeof SemanticMode];
53
+ export interface RiveSemanticsOptions {
54
+ /**
55
+ * aria-label for the semantic DOM container element
56
+ */
57
+ riveCanvasLabel?: string;
58
+ }
59
+ export declare const SemanticTrait: {
60
+ readonly None: 0;
61
+ readonly Expandable: number;
62
+ readonly Selectable: number;
63
+ readonly Checkable: number;
64
+ readonly Toggleable: number;
65
+ readonly Requirable: number;
66
+ readonly Enablable: number;
67
+ readonly Focusable: number;
68
+ };
69
+ export declare function hasTrait(flags: number, trait: number): boolean;
70
+ export declare const SemanticActionType: {
71
+ readonly tap: 0;
72
+ readonly increase: 1;
73
+ readonly decrease: 2;
74
+ };
75
+ export type SemanticActionType = (typeof SemanticActionType)[keyof typeof SemanticActionType];
76
+ export interface SemanticNodeData {
77
+ readonly id: number;
78
+ parentId: number;
79
+ role: number;
80
+ label: string;
81
+ value: string;
82
+ hint: string;
83
+ stateFlags: number;
84
+ traitFlags: number;
85
+ headingLevel: number;
86
+ minX: number;
87
+ minY: number;
88
+ maxX: number;
89
+ maxY: number;
90
+ children: number[];
91
+ }
92
+ export declare function roleName(role: number): string;
93
+ export declare function stateNames(flags: number): string;
94
+ export declare function traitNames(flags: number): string;