-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathuseRive.tsx
More file actions
296 lines (270 loc) · 7.61 KB
/
useRive.tsx
File metadata and controls
296 lines (270 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import React, {
useCallback,
useEffect,
useRef,
useState,
ComponentProps,
RefCallback,
} from 'react';
import { Rive, EventType } from '@rive-app/canvas';
import {
UseRiveParameters,
UseRiveOptions,
RiveState,
Dimensions,
} from '../types';
import { useSize } from '../utils';
type RiveComponentProps = {
setContainerRef: RefCallback<HTMLElement>;
setCanvasRef: RefCallback<HTMLCanvasElement>;
};
function RiveComponent({
setContainerRef,
setCanvasRef,
className = '',
style,
width,
height,
...rest
}: RiveComponentProps & ComponentProps<'canvas'>) {
const containerStyle = {
width: '100%',
height: '100%',
...style,
};
return (
<div
ref={setContainerRef}
className={className}
{...(!className && { style: containerStyle })}
>
<canvas
ref={setCanvasRef}
style={{ verticalAlign: 'top' }}
{...(width !== undefined && {width, 'data-rive-width-prop': width})}
{...(height !== undefined && {height, 'data-rive-height-prop': height})}
{...rest}
/>
</div>
);
}
const defaultOptions = {
useDevicePixelRatio: true,
fitCanvasToArtboardHeight: false,
useOffscreenRenderer: true,
};
/**
* Returns options, with defaults set.
*
* @param opts
* @returns
*/
function getOptions(opts: Partial<UseRiveOptions>) {
return Object.assign({}, defaultOptions, opts);
}
/**
* Custom Hook for loading a Rive file.
*
* Waits until the load event has fired before returning it.
* We can then listen for changes to this animation in other hooks to detect
* when it has loaded.
*
* @param riveParams - Object containing parameters accepted by the Rive object
* in the rive-js runtime, with the exception of Canvas as that is attached
* via the ref callback `setCanvasRef`.
*
* @param opts - Optional list of options that are specific for this hook.
* @returns {RiveAnimationState}
*/
export default function useRive(
riveParams?: UseRiveParameters,
opts: Partial<UseRiveOptions> = {}
): RiveState {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const containerRef = useRef<HTMLElement | null>(null);
const [rive, setRive] = useState<Rive | null>(null);
const [dimensions, setDimensions] = useState<Dimensions>({
height: 0,
width: 0,
});
// Listen to changes in the window sizes and update the bounds when changes
// occur.
const size = useSize(containerRef);
const isParamsLoaded = Boolean(riveParams);
const options = getOptions(opts);
/**
* Gets the intended dimensions of the canvas element.
*
* The intended dimensions are those of the container element, unless the
* option `fitCanvasToArtboardHeight` is true, then they are adjusted to
* the height of the artboard.
*
* @returns Dimensions object.
*/
function getCanvasDimensions() {
// getBoundingClientRect returns the scaled width and height
// this will result in double scaling
// https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements
const width = containerRef.current?.clientWidth ?? 0;
const height = containerRef.current?.clientHeight ?? 0;
if (rive && options.fitCanvasToArtboardHeight) {
const { maxY, maxX } = rive.bounds;
return { width, height: width * (maxY / maxX) };
}
return { width, height };
}
/**
* Updates the width and height of the canvas.
*/
function updateBounds() {
if (!containerRef.current) {
return;
}
const { width, height } = getCanvasDimensions();
const boundsChanged =
width !== dimensions.width || height !== dimensions.height;
if (canvasRef.current && rive && boundsChanged) {
const widthProp = canvasRef.current.getAttribute('data-rive-width-prop');
const heightProp = canvasRef.current.getAttribute('data-rive-height-prop');
if (options.fitCanvasToArtboardHeight) {
containerRef.current.style.height = height + 'px';
}
if (options.useDevicePixelRatio) {
const dpr = window.devicePixelRatio || 1;
if (!widthProp) {
canvasRef.current.width = dpr * width;
}
if (!heightProp) {
canvasRef.current.height = dpr * height;
}
canvasRef.current.style.width = width + 'px';
canvasRef.current.style.height = height + 'px';
} else {
if (!widthProp) {
canvasRef.current.width = width;
}
if (!heightProp) {
canvasRef.current.height = height;
}
}
setDimensions({ width, height });
// Updating the canvas width or height will clear the canvas, so call
// startRendering() to redraw the current frame as the animation might
// be paused and not advancing.
rive.startRendering();
}
// Always resize to Canvas
if (rive) {
rive.resizeToCanvas();
}
}
/**
* Listen to changes on the windowSize and the rive file being loaded
* and update the canvas bounds as needed.
*
* ie does not support ResizeObservers, so we fallback to the window listener there
*/
useEffect(() => {
if (rive) {
updateBounds();
}
}, [rive, size]);
/**
* Ref callback called when the canvas element mounts and unmounts.
*/
const setCanvasRef: RefCallback<HTMLCanvasElement> = useCallback(
(canvas: HTMLCanvasElement | null) => {
if (canvas && riveParams && isParamsLoaded) {
const { useOffscreenRenderer } = options;
const r = new Rive({
useOffscreenRenderer,
...riveParams,
canvas,
});
r.on(EventType.Load, () => {
// Check if the component/canvas is mounted before setting state to avoid setState
// on an unmounted component in some rare cases
if (canvasRef.current) {
setRive(r);
}
});
} else if (canvas === null && canvasRef.current) {
canvasRef.current.height = 0;
canvasRef.current.width = 0;
}
canvasRef.current = canvas;
},
[isParamsLoaded]
);
/**
* Ref callback called when the container element mounts
*/
const setContainerRef: RefCallback<HTMLElement> = useCallback(
(container: HTMLElement | null) => {
containerRef.current = container;
},
[]
);
/**
* Set up IntersectionObserver to stop rendering if the animation is not in
* view.
*/
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
entry.isIntersecting
? rive && rive.startRendering()
: rive && rive.stopRendering();
});
if (canvasRef.current) {
observer.observe(canvasRef.current);
}
return () => {
observer.disconnect();
};
}, [rive]);
/**
* On unmount, stop rive from rendering.
*/
useEffect(() => {
return () => {
if (rive) {
rive.stop();
setRive(null);
}
};
}, [rive]);
/**
* Listen for changes in the animations params
*/
const animations = riveParams?.animations;
useEffect(() => {
if (rive && animations) {
if (rive.isPlaying) {
rive.stop(rive.animationNames);
rive.play(animations);
} else if (rive.isPaused) {
rive.stop(rive.animationNames);
rive.pause(animations);
}
}
}, [animations, rive]);
const Component = useCallback(
(props: ComponentProps<'canvas'>): JSX.Element => {
return (
<RiveComponent
setContainerRef={setContainerRef}
setCanvasRef={setCanvasRef}
{...props}
/>
);
},
[]
);
return {
canvas: canvasRef.current,
setCanvasRef,
setContainerRef,
rive,
RiveComponent: Component,
};
}