mirror of
https://github.com/rive-app/rive-react.git
synced 2026-03-13 08:22:30 +08:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a968ec266 | ||
|
|
b5f00e5c97 | ||
|
|
22e6dd3494 | ||
|
|
08b9f9a2aa | ||
|
|
a24b910096 | ||
|
|
33760042d1 | ||
|
|
2c82fa04e7 | ||
|
|
2b249494d5 | ||
|
|
b56c17d48c | ||
|
|
a6fe08ced9 | ||
|
|
cd1e1410f4 | ||
|
|
353fbf8e9d | ||
|
|
ae05ad4375 | ||
|
|
ff8bbb084c | ||
|
|
89a6802fa0 | ||
|
|
91025e6772 | ||
|
|
d3bc913bcf | ||
|
|
ce56321e1d | ||
|
|
4b6f5410fd | ||
|
|
6544874d3d | ||
|
|
ed90c7f7c9 | ||
|
|
e06fdd1c8b | ||
|
|
b8ffb6b53c | ||
|
|
2dc925ef70 | ||
|
|
639de79c9e | ||
|
|
a9961c821a | ||
|
|
fc082d1a03 | ||
|
|
87fa1ae2a5 | ||
|
|
62490a50f9 | ||
|
|
fcc1a16df4 | ||
|
|
29e0ceb797 | ||
|
|
3e6a951ca1 | ||
|
|
04910f78f1 | ||
|
|
c2977c705c | ||
|
|
4e2137422b | ||
|
|
0696417926 | ||
|
|
f11a433365 | ||
|
|
48a4726d1f | ||
|
|
c927f24b5a | ||
|
|
3cbbf99fec | ||
|
|
03f05f57b7 | ||
|
|
8b483b807b | ||
|
|
816fcfcdbc | ||
|
|
6c28a8795e | ||
|
|
6a57630ae6 | ||
|
|
acba24c4ed | ||
|
|
1e6eb5ec92 | ||
|
|
6871a81ebd | ||
|
|
33053b3b7f | ||
|
|
4040083d5a | ||
|
|
2153b81e6b | ||
|
|
6b1500e681 |
26
.github/workflows/add_to_project.yml
vendored
Normal file
26
.github/workflows/add_to_project.yml
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
name: Adds all new issues to project board
|
||||
|
||||
on:
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
|
||||
jobs:
|
||||
add-to-project:
|
||||
name: Add issue to project
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/add-to-project@v0.5.0
|
||||
with:
|
||||
project-url: https://github.com/orgs/rive-app/projects/12/views/1
|
||||
github-token: ${{ secrets.ADD_TO_PROJECT_ACTION }}
|
||||
|
||||
- uses: actions/github-script@v6
|
||||
with:
|
||||
script: |
|
||||
github.rest.issues.addLabels({
|
||||
issue_number: context.issue.number,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
labels: ["triage"]
|
||||
})
|
||||
71
CHANGELOG.md
71
CHANGELOG.md
@@ -4,8 +4,79 @@ All notable changes to this project will be documented in this file. Dates are d
|
||||
|
||||
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
|
||||
|
||||
#### [v3.0.52](https://github.com/rive-app/rive-react/compare/v3.0.38...v3.0.52)
|
||||
|
||||
- fix: bump WASM to fix iterator over animatables [`b5f00e5`](https://github.com/rive-app/rive-react/commit/b5f00e5c97146573474ab73773fe189b1bcc5d43)
|
||||
|
||||
#### [v3.0.38](https://github.com/rive-app/rive-react/compare/v3.0.37...v3.0.38)
|
||||
|
||||
> 3 March 2023
|
||||
|
||||
- chore: release 3.0.38 [`04910f7`](https://github.com/rive-app/rive-react/commit/04910f78f1779242626db0dfb74ab27ae95c75fa)
|
||||
- maint: bump wasm dependency for more speed on state updates [`c2977c7`](https://github.com/rive-app/rive-react/commit/c2977c705c5572480be3f253b7237bdc2d3eea35)
|
||||
|
||||
#### [v3.0.37](https://github.com/rive-app/rive-react/compare/v3.0.36...v3.0.37)
|
||||
|
||||
> 1 March 2023
|
||||
|
||||
- chore: release 3.0.37 [`4e21374`](https://github.com/rive-app/rive-react/commit/4e2137422b8c1d135a6501add3f2cc68140f1817)
|
||||
- maint: bump wasm dependency for more speed on state updates [`0696417`](https://github.com/rive-app/rive-react/commit/06964179262d4b79114f3609d79cc6560c30ef94)
|
||||
|
||||
#### [v3.0.36](https://github.com/rive-app/rive-react/compare/v3.0.35...v3.0.36)
|
||||
|
||||
> 22 February 2023
|
||||
|
||||
- chore: release 3.0.36 [`f11a433`](https://github.com/rive-app/rive-react/commit/f11a433365c34818976798106fc03a264e6ceaea)
|
||||
- Fix: matchMedia add event listener for safari 13 and older versions [`3cbbf99`](https://github.com/rive-app/rive-react/commit/3cbbf99fec90f58cdf410df861f272115a7704e6)
|
||||
- maint: bump wasm to support speed on states feature [`48a4726`](https://github.com/rive-app/rive-react/commit/48a4726d1f7a01088959d47580082e5ddfed1492)
|
||||
|
||||
#### [v3.0.35](https://github.com/rive-app/rive-react/compare/v3.0.34...v3.0.35)
|
||||
|
||||
> 17 January 2023
|
||||
|
||||
- chore: release 3.0.35 [`03f05f5`](https://github.com/rive-app/rive-react/commit/03f05f57b7f277d7d90701954b5ca09842bcaab6)
|
||||
- fix: update rive-wasm to try patching slow burn memory leak [`8b483b8`](https://github.com/rive-app/rive-react/commit/8b483b807b8207fe12c864e19f64592c0bedac46)
|
||||
|
||||
#### [v3.0.34](https://github.com/rive-app/rive-react/compare/v3.0.33...v3.0.34)
|
||||
|
||||
> 16 December 2022
|
||||
|
||||
- chore: release 3.0.34 [`816fcfc`](https://github.com/rive-app/rive-react/commit/816fcfcdbcb9f2d8f83cc7887f43aae011dee3be)
|
||||
- Bumping rive-app/canvas & webgl versions. [`6c28a87`](https://github.com/rive-app/rive-react/commit/6c28a8795eeabc10aa8bdcee99ee9754d924d0ae)
|
||||
|
||||
#### [v3.0.33](https://github.com/rive-app/rive-react/compare/v3.0.32...v3.0.33)
|
||||
|
||||
> 8 November 2022
|
||||
|
||||
- maint: bump wasm runtime and replace old skills rive file example [`acba24c`](https://github.com/rive-app/rive-react/commit/acba24c4ed4f703303615819678c7273c385286f)
|
||||
- chore: release 3.0.33 [`6a57630`](https://github.com/rive-app/rive-react/commit/6a57630ae67df057472a6d40f354fcfe53cb5521)
|
||||
|
||||
#### [v3.0.32](https://github.com/rive-app/rive-react/compare/v3.0.31...v3.0.32)
|
||||
|
||||
> 21 October 2022
|
||||
|
||||
- chore: release 3.0.32 [`1e6eb5e`](https://github.com/rive-app/rive-react/commit/1e6eb5ec927aa0bb10ee1e7659c4824c64702f58)
|
||||
- Bumping to latest Rive WASM to fix https://2dimensions.slack.com/archives/CLLCU09T6/p1666370141425879 [`6871a81`](https://github.com/rive-app/rive-react/commit/6871a81ebd17038426e7089ed836379d02a9c5fd)
|
||||
|
||||
#### [v3.0.31](https://github.com/rive-app/rive-react/compare/v3.0.30...v3.0.31)
|
||||
|
||||
> 21 October 2022
|
||||
|
||||
- chore: release 3.0.31 [`33053b3`](https://github.com/rive-app/rive-react/commit/33053b3b7f0ff6d99ce4383ecea1f031ccb587e0)
|
||||
- bump runtimes to incorporate speed fix for state machines [`4040083`](https://github.com/rive-app/rive-react/commit/4040083d5a89510356e45433e5026664baf92a49)
|
||||
|
||||
#### [v3.0.30](https://github.com/rive-app/rive-react/compare/v3.0.29...v3.0.30)
|
||||
|
||||
> 20 October 2022
|
||||
|
||||
- chore: release 3.0.30 [`2153b81`](https://github.com/rive-app/rive-react/commit/2153b81e6b74d33d1e2f709291fad338dcbb85da)
|
||||
- Bump dependencies to fix call to runtime cleanup [`6b1500e`](https://github.com/rive-app/rive-react/commit/6b1500e681ba8984d786eec4d414c4c8ad4b0268)
|
||||
|
||||
#### [v3.0.29](https://github.com/rive-app/rive-react/compare/v3.0.28...v3.0.29)
|
||||
|
||||
> 20 October 2022
|
||||
|
||||
- chore: release 3.0.29 [`503702c`](https://github.com/rive-app/rive-react/commit/503702cf1f963204e3519b9b3dbfea1bfa271d0a)
|
||||
- Call cleanup on unmount [`7be20b0`](https://github.com/rive-app/rive-react/commit/7be20b0a874afab7f6a29122521f42c71a22aa51)
|
||||
|
||||
#### [v3.0.28](https://github.com/rive-app/rive-react/compare/v3.0.27...v3.0.28)
|
||||
|
||||
@@ -50,7 +50,7 @@ Check out our Storybook instance that shows how to use the library in small exam
|
||||
- [Example page](https://rive-app.github.io/rive-react)
|
||||
- [Login screen w/ input tracking](https://rive-app.github.io/rive-use-cases/?path=/story/example-loginformcomponent--primary)
|
||||
- [Mouse tracking](https://codesandbox.io/s/rive-mouse-track-test-t0y965?file=/src/App.js)
|
||||
- [Accessibility concerns](https://blog.rive.app/accessible-web-animations-aria-live-regions/)
|
||||
- [Accessibility concerns](https://rive.app/blog/accesible-web-animations-aria-live-regions)
|
||||
|
||||
## Migration Guides
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import { useState } from 'react';
|
||||
|
||||
import { Canvas, Meta, Story, ArgsTable } from '@storybook/addon-docs';
|
||||
|
||||
import RiveComponent, {useRive, useStateMachineInput} from '../../src';
|
||||
import {Button} from './components/Button';
|
||||
import RiveComponent, { useRive, useStateMachineInput } from '../../src';
|
||||
import { Button } from './components/Button';
|
||||
import './rive-overview.css';
|
||||
|
||||
<Meta title="React Runtime/Overview" />
|
||||
@@ -31,6 +31,7 @@ There's multiple ways to render Rive using the React runtime. See the associated
|
||||
```tsx
|
||||
import RiveComponent from '@rive-app/react-canvas';
|
||||
```
|
||||
|
||||
The React runtime exports a default React component you can insert as JSX. Under the hood, it renders a `<canvas>` element that runs the animation, and a wrapping `<div>` element that handles sizing of the canvas based on the parent that wraps the component.
|
||||
|
||||
**When to use this**: Use this for simple rendering cases where you don't need to control playback or setup state machine inputs to advance state machines. It will simply autoplay the first animation it finds in the `.riv`, the animation name you provide it, or the state machine name if you provide one.
|
||||
@@ -56,12 +57,13 @@ In addition to the props laid out below, the component accepts other props that
|
||||
### useRive Hook
|
||||
|
||||
```tsx
|
||||
import {useRive} from '@rive-app/react-canvas';
|
||||
import { useRive } from '@rive-app/react-canvas';
|
||||
```
|
||||
|
||||
The runtime also exports a named `useRive` hook that allows for more control at Rive instantiation, since it passes back a `rive` object you can use to manipulate state machines, control playback, and more.
|
||||
|
||||
**When to use this:** When you need to control your Rive animation in any aspect, such as controlling playback, using state machine inputs to advance state machines, add adding callbacks on certain Rive-specific events such as `onStateChange`, `onPause`, etc.
|
||||
|
||||
<Canvas withSource="open">
|
||||
<Story name="useRive Hook">
|
||||
{() => {
|
||||
@@ -69,7 +71,7 @@ The runtime also exports a named `useRive` hook that allows for more control at
|
||||
const [animationText, setAnimationText] = useState('');
|
||||
const { rive, RiveComponent: RiveComponentPlayback } = useRive({
|
||||
src: 'truck.riv',
|
||||
stateMachines: "drive",
|
||||
stateMachines: 'drive',
|
||||
artboard: 'Truck',
|
||||
autoplay: true,
|
||||
onPause: () => {
|
||||
@@ -88,15 +90,19 @@ The runtime also exports a named `useRive` hook that allows for more control at
|
||||
setIsPlaying(true);
|
||||
}
|
||||
};
|
||||
return ((
|
||||
return (
|
||||
<>
|
||||
<div className="center">
|
||||
<RiveComponentPlayback className="base-canvas-size" />
|
||||
<RiveComponentPlayback className="base-canvas-size">
|
||||
<p>Animation that can be paused and played by clicking on it</p>
|
||||
</RiveComponentPlayback>
|
||||
<p>{animationText}</p>
|
||||
<Button onClick={togglePlaying}>{isPlaying ? 'Pause' : 'Play'}</Button>
|
||||
<Button onClick={togglePlaying}>
|
||||
{isPlaying ? 'Pause' : 'Play'}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
));
|
||||
);
|
||||
}}
|
||||
</Story>
|
||||
</Canvas>
|
||||
|
||||
@@ -4,8 +4,8 @@ import { useState } from 'react';
|
||||
|
||||
import { Canvas, Meta, Story, ArgsTable } from '@storybook/addon-docs';
|
||||
|
||||
import RiveComponent, {useRive, useStateMachineInput} from '../../src';
|
||||
import {Button} from './components/Button';
|
||||
import RiveComponent, { useRive, useStateMachineInput } from '../../src';
|
||||
import { Button } from './components/Button';
|
||||
import './rive-overview.css';
|
||||
|
||||
<Meta title="React Runtime/State Machines" />
|
||||
@@ -15,6 +15,7 @@ import './rive-overview.css';
|
||||
Not familiar with Rive State Machines? Check out our [help docs](https://help.rive.app/editor/state-machine) on what these are first!
|
||||
|
||||
The `useStateMachineInput` hook is a helper that makes grabbing references to state machine inputs easier to setup. This hook should be used along with the `useRive` hook, as you need to pass in the `rive` instance returned from `useRive`. See each of the examples below to see usage of the hook creating instance of three types of inputs:
|
||||
|
||||
- Booleans
|
||||
- Numbers
|
||||
- Triggers
|
||||
@@ -90,8 +91,8 @@ Once you grab a reference to the state machine input, you can get/set the value
|
||||
<Canvas withSource="open">
|
||||
<Story name="Number input">
|
||||
{() => {
|
||||
const STATE_MACHINE_NAME = 'State Machine ';
|
||||
const INPUT_NAME = 'Level';
|
||||
const STATE_MACHINE_NAME = 'skill-controller';
|
||||
const INPUT_NAME = 'level';
|
||||
const { rive, RiveComponent: RiveComponentTouch } = useRive({
|
||||
src: 'skills.riv',
|
||||
stateMachines: STATE_MACHINE_NAME,
|
||||
@@ -101,7 +102,11 @@ Once you grab a reference to the state machine input, you can get/set the value
|
||||
// levelInput is a number state machine input. To transition the state machine,
|
||||
// we need to set the value to a number. For this state machine input, we need
|
||||
// to set to 0, 1 or 2 for a state transition to occur.
|
||||
const levelInput = useStateMachineInput(rive, STATE_MACHINE_NAME, INPUT_NAME);
|
||||
const levelInput = useStateMachineInput(
|
||||
rive,
|
||||
STATE_MACHINE_NAME,
|
||||
INPUT_NAME
|
||||
);
|
||||
return (
|
||||
// The animation will fit to the parent element, so we set a large height
|
||||
// and width for this example.
|
||||
|
||||
Binary file not shown.
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rive-react",
|
||||
"version": "3.0.29",
|
||||
"version": "3.0.52",
|
||||
"description": "React wrapper around the rive-js library",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/types/index.d.ts",
|
||||
@@ -29,8 +29,8 @@
|
||||
},
|
||||
"homepage": "https://github.com/rive-app/rive-react#readme",
|
||||
"dependencies": {
|
||||
"@rive-app/canvas": "1.0.90",
|
||||
"@rive-app/webgl": "1.0.86"
|
||||
"@rive-app/canvas": "1.1.10",
|
||||
"@rive-app/webgl": "1.1.10"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
||||
|
||||
@@ -28,7 +28,15 @@ export interface RiveProps {
|
||||
* For `@rive-app/react-webgl`, sets this property to maintain a single WebGL context for multiple canvases. **We recommend to keep the default value** when rendering multiple Rive instances on a page.
|
||||
*/
|
||||
useOffscreenRenderer?: boolean;
|
||||
};
|
||||
/**
|
||||
* Specify whether to disable Rive listeners on the canvas, thus preventing any event listeners to be attached to the canvas element
|
||||
*/
|
||||
shouldDisableRiveListeners?: boolean;
|
||||
/**
|
||||
* Specify whether to resize the canvas to its container automatically
|
||||
*/
|
||||
shouldResizeCanvasToContainer?: boolean;
|
||||
}
|
||||
|
||||
const Rive = ({
|
||||
src,
|
||||
@@ -37,6 +45,9 @@ const Rive = ({
|
||||
stateMachines,
|
||||
layout,
|
||||
useOffscreenRenderer = true,
|
||||
shouldDisableRiveListeners = false,
|
||||
shouldResizeCanvasToContainer = true,
|
||||
children,
|
||||
...rest
|
||||
}: RiveProps & ComponentProps<'canvas'>) => {
|
||||
const params = {
|
||||
@@ -46,14 +57,16 @@ const Rive = ({
|
||||
layout,
|
||||
stateMachines,
|
||||
autoplay: true,
|
||||
shouldDisableRiveListeners,
|
||||
};
|
||||
|
||||
const options = {
|
||||
useOffscreenRenderer,
|
||||
shouldResizeCanvasToContainer,
|
||||
};
|
||||
|
||||
const { RiveComponent } = useRive(params, options);
|
||||
return <RiveComponent {...rest} />;
|
||||
return <RiveComponent {...rest}>{children}</RiveComponent>;
|
||||
};
|
||||
|
||||
export default Rive;
|
||||
|
||||
94
src/hooks/useContainerSize.ts
Normal file
94
src/hooks/useContainerSize.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Dimensions } from '../types';
|
||||
|
||||
// There are polyfills for this, but they add hundreds of lines of code
|
||||
class FakeResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
function throttle(f: Function, delay: number) {
|
||||
let timer = 0;
|
||||
return function (this: Function, ...args: any) {
|
||||
clearTimeout(timer);
|
||||
timer = window.setTimeout(() => f.apply(this, args), delay);
|
||||
};
|
||||
}
|
||||
|
||||
const MyResizeObserver = globalThis.ResizeObserver || FakeResizeObserver;
|
||||
const hasResizeObserver = globalThis.ResizeObserver !== undefined;
|
||||
|
||||
const useResizeObserver = hasResizeObserver;
|
||||
const useWindowListener = !useResizeObserver;
|
||||
|
||||
/**
|
||||
* Hook to listen for a ref element's resize events being triggered. When resized,
|
||||
* it sets state to an object of {width: number, height: number} indicating the contentRect
|
||||
* size of the element at the new resize.
|
||||
*
|
||||
* @param containerRef - Ref element to listen for resize events on
|
||||
* @returns - Size object with width and height attributes
|
||||
*/
|
||||
export default function useSize(
|
||||
containerRef: React.MutableRefObject<HTMLElement | null>,
|
||||
shouldResizeCanvasToContainer = true
|
||||
) {
|
||||
const [size, setSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
});
|
||||
|
||||
// internet explorer does not support ResizeObservers.
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined' && shouldResizeCanvasToContainer) {
|
||||
const handleResize = () => {
|
||||
setSize({
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight,
|
||||
});
|
||||
};
|
||||
|
||||
if (useWindowListener) {
|
||||
// only pay attention to window size changes when we do not have the resizeObserver (IE only)
|
||||
handleResize();
|
||||
window.addEventListener('resize', handleResize);
|
||||
}
|
||||
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}
|
||||
}, []);
|
||||
const observer = useRef(
|
||||
new MyResizeObserver(
|
||||
throttle((entries: any) => {
|
||||
if (useResizeObserver) {
|
||||
setSize({
|
||||
width: entries[entries.length - 1].contentRect.width,
|
||||
height: entries[entries.length - 1].contentRect.height,
|
||||
});
|
||||
}
|
||||
}, 0)
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const currentObserver = observer.current;
|
||||
if (!shouldResizeCanvasToContainer) {
|
||||
currentObserver.disconnect();
|
||||
return;
|
||||
}
|
||||
const containerEl = containerRef.current;
|
||||
if (containerRef.current && useResizeObserver) {
|
||||
currentObserver.observe(containerRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
currentObserver.disconnect();
|
||||
if (containerEl && useResizeObserver) {
|
||||
currentObserver.unobserve(containerEl);
|
||||
}
|
||||
};
|
||||
}, [containerRef, observer]);
|
||||
|
||||
return size;
|
||||
}
|
||||
49
src/hooks/useDevicePixelRatio.ts
Normal file
49
src/hooks/useDevicePixelRatio.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
/**
|
||||
* Listen for devicePixelRatio changes and set the new value accordingly. This could
|
||||
* happen for reasons such as:
|
||||
* - User moves window from retina screen display to a separate monitor
|
||||
* - User controls zoom settings on the browser
|
||||
*
|
||||
* Source: https://github.com/rexxars/use-device-pixel-ratio/blob/main/index.ts
|
||||
*
|
||||
* @returns dpr: Number - Device pixel ratio; ratio of physical px to resolution in CSS pixels for current device
|
||||
*/
|
||||
export default function useDevicePixelRatio() {
|
||||
const dpr = getDevicePixelRatio();
|
||||
const [currentDpr, setCurrentDpr] = useState(dpr);
|
||||
|
||||
useEffect(() => {
|
||||
const canListen = typeof window !== 'undefined' && 'matchMedia' in window;
|
||||
if (!canListen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateDpr = () => {
|
||||
const newDpr = getDevicePixelRatio();
|
||||
setCurrentDpr(newDpr);
|
||||
};
|
||||
const mediaMatcher = window.matchMedia(
|
||||
`screen and (resolution: ${currentDpr}dppx)`
|
||||
);
|
||||
mediaMatcher.hasOwnProperty('addEventListener')
|
||||
? mediaMatcher.addEventListener('change', updateDpr)
|
||||
: mediaMatcher.addListener(updateDpr);
|
||||
|
||||
return () => {
|
||||
mediaMatcher.hasOwnProperty('removeEventListener')
|
||||
? mediaMatcher.removeEventListener('change', updateDpr)
|
||||
: mediaMatcher.removeListener(updateDpr);
|
||||
};
|
||||
}, [currentDpr]);
|
||||
|
||||
return currentDpr;
|
||||
}
|
||||
|
||||
function getDevicePixelRatio(): number {
|
||||
const hasDprProp =
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.devicePixelRatio === 'number';
|
||||
const dpr = hasDprProp ? window.devicePixelRatio : 1;
|
||||
return Math.min(Math.max(1, dpr), 3);
|
||||
}
|
||||
186
src/hooks/useResizeCanvas.ts
Normal file
186
src/hooks/useResizeCanvas.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import { useEffect, useState, MutableRefObject, useCallback } from 'react';
|
||||
import { Bounds } from '@rive-app/canvas';
|
||||
import { Dimensions, UseRiveOptions } from '../types';
|
||||
import useDevicePixelRatio from './useDevicePixelRatio';
|
||||
import useContainerSize from './useContainerSize';
|
||||
import { getOptions } from '../utils';
|
||||
|
||||
interface UseResizeCanvasProps {
|
||||
/**
|
||||
* Whether or not Rive is loaded and renderer is associated with the canvas
|
||||
*/
|
||||
riveLoaded: boolean;
|
||||
/**
|
||||
* Ref to the canvas element
|
||||
*/
|
||||
canvasRef: MutableRefObject<HTMLCanvasElement | null>;
|
||||
/**
|
||||
* Ref to the container element of the canvas
|
||||
*/
|
||||
containerRef: MutableRefObject<HTMLElement | null>;
|
||||
/**
|
||||
* (Optional) Callback to be invoked after the canvas has been resized due to a resize
|
||||
* of its parent container. This is where you would want to reset the layout
|
||||
* dimensions for the Rive renderer to dictate the new min/max bounds of the
|
||||
* canvas.
|
||||
*
|
||||
* Using the high-level JS runtime, this might be a simple call to `rive.resizeToCanvas()`
|
||||
* Using the low-level JSruntime, this might be invoking the renderer's `.align()` method
|
||||
* with the Layout and min/max X/Y values of the canvas.
|
||||
*
|
||||
* @returns void
|
||||
*/
|
||||
onCanvasHasResized?: () => void;
|
||||
/**
|
||||
* (Optional) Options passed to the useRive hook, including the shouldResizeCanvasToContainer option
|
||||
* which prevents the canvas element from resizing to its parent container
|
||||
*/
|
||||
options?: Partial<UseRiveOptions>;
|
||||
/**
|
||||
* (Optional) AABB bounds of the artboard. If provided, the canvas will be sized to the artboard
|
||||
* height if the fitCanvasToArtboardHeight option is true.
|
||||
*/
|
||||
artboardBounds?: Bounds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper hook to listen for changes in the <canvas> parent container size and size the <canvas>
|
||||
* to match. If a resize event has occurred, a supplied callback (onCanvasHasResized)
|
||||
* will be inokved to allow for any re-calculation needed (i.e. Rive layout on the canvas).
|
||||
*
|
||||
* This hook is useful if you are not intending to use the `useRive` hook yourself, but still
|
||||
* want to use the auto-sizing logic on the canvas/container.
|
||||
*
|
||||
* @param props - Object to supply necessary props to the hook
|
||||
*/
|
||||
export default function useResizeCanvas({
|
||||
riveLoaded = false,
|
||||
canvasRef,
|
||||
containerRef,
|
||||
options = {},
|
||||
onCanvasHasResized,
|
||||
artboardBounds,
|
||||
}: UseResizeCanvasProps) {
|
||||
const presetOptions = getOptions(options);
|
||||
const [
|
||||
{ height: lastContainerHeight, width: lastContainerWidth },
|
||||
setLastContainerDimensions,
|
||||
] = useState<Dimensions>({
|
||||
height: 0,
|
||||
width: 0,
|
||||
});
|
||||
const [
|
||||
{ height: lastCanvasHeight, width: lastCanvasWidth },
|
||||
setLastCanvasSize,
|
||||
] = useState<Dimensions>({
|
||||
height: 0,
|
||||
width: 0,
|
||||
});
|
||||
|
||||
const [isFirstSizing, setIsFirstSizing] = useState(true);
|
||||
|
||||
const {
|
||||
fitCanvasToArtboardHeight,
|
||||
shouldResizeCanvasToContainer,
|
||||
useDevicePixelRatio: shouldUseDevicePixelRatio,
|
||||
} = presetOptions;
|
||||
|
||||
const containerSize = useContainerSize(
|
||||
containerRef,
|
||||
shouldResizeCanvasToContainer
|
||||
);
|
||||
const currentDevicePixelRatio = useDevicePixelRatio();
|
||||
|
||||
const { maxX, maxY } = artboardBounds ?? {};
|
||||
|
||||
const getContainerDimensions = useCallback(() => {
|
||||
const width = containerRef.current?.clientWidth ?? 0;
|
||||
const height = containerRef.current?.clientHeight ?? 0;
|
||||
if (fitCanvasToArtboardHeight && artboardBounds) {
|
||||
const { maxY, maxX } = artboardBounds;
|
||||
return { width, height: width * (maxY / maxX) };
|
||||
}
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}, [containerRef, fitCanvasToArtboardHeight, maxX, maxY]);
|
||||
|
||||
useEffect(() => {
|
||||
// If Rive is not ready, the container is not ready, or the user supplies a flag
|
||||
// to not resize the canvas to the container, then return early
|
||||
if (
|
||||
!shouldResizeCanvasToContainer ||
|
||||
!containerRef.current ||
|
||||
!riveLoaded
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { width, height } = getContainerDimensions();
|
||||
let hasResized = false;
|
||||
if (canvasRef.current) {
|
||||
// Check if the canvas parent container bounds have changed and set
|
||||
// new values accordingly
|
||||
const boundsChanged =
|
||||
width !== lastContainerWidth || height !== lastContainerHeight;
|
||||
if (presetOptions.fitCanvasToArtboardHeight && boundsChanged) {
|
||||
containerRef.current.style.height = height + 'px';
|
||||
hasResized = true;
|
||||
}
|
||||
if (presetOptions.useDevicePixelRatio) {
|
||||
// Check if devicePixelRatio may have changed and get new canvas
|
||||
// width/height values to set the size
|
||||
const canvasSizeChanged =
|
||||
width * currentDevicePixelRatio !== lastCanvasWidth ||
|
||||
height * currentDevicePixelRatio !== lastCanvasHeight;
|
||||
if (boundsChanged || canvasSizeChanged) {
|
||||
const newCanvasWidthProp = currentDevicePixelRatio * width;
|
||||
const newCanvasHeightProp = currentDevicePixelRatio * height;
|
||||
canvasRef.current.width = newCanvasWidthProp;
|
||||
canvasRef.current.height = newCanvasHeightProp;
|
||||
canvasRef.current.style.width = width + 'px';
|
||||
canvasRef.current.style.height = height + 'px';
|
||||
setLastCanvasSize({
|
||||
width: newCanvasWidthProp,
|
||||
height: newCanvasHeightProp,
|
||||
});
|
||||
hasResized = true;
|
||||
}
|
||||
} else if (boundsChanged) {
|
||||
canvasRef.current.width = width;
|
||||
canvasRef.current.height = height;
|
||||
setLastCanvasSize({
|
||||
width: width,
|
||||
height: height,
|
||||
});
|
||||
hasResized = true;
|
||||
}
|
||||
setLastContainerDimensions({ width, height });
|
||||
}
|
||||
|
||||
// Callback to perform any Rive-related actions after resizing the canvas
|
||||
// (i.e., reset the Rive layout in the render loop)
|
||||
if (onCanvasHasResized && (isFirstSizing || hasResized)) {
|
||||
onCanvasHasResized && onCanvasHasResized();
|
||||
}
|
||||
isFirstSizing && setIsFirstSizing(false);
|
||||
}, [
|
||||
canvasRef,
|
||||
containerRef,
|
||||
containerSize,
|
||||
currentDevicePixelRatio,
|
||||
getContainerDimensions,
|
||||
isFirstSizing,
|
||||
setIsFirstSizing,
|
||||
lastCanvasHeight,
|
||||
lastCanvasWidth,
|
||||
lastContainerHeight,
|
||||
lastContainerWidth,
|
||||
onCanvasHasResized,
|
||||
shouldResizeCanvasToContainer,
|
||||
fitCanvasToArtboardHeight,
|
||||
shouldUseDevicePixelRatio,
|
||||
riveLoaded,
|
||||
]);
|
||||
}
|
||||
@@ -7,13 +7,9 @@ import React, {
|
||||
RefCallback,
|
||||
} from 'react';
|
||||
import { Rive, EventType } from '@rive-app/canvas';
|
||||
import {
|
||||
UseRiveParameters,
|
||||
UseRiveOptions,
|
||||
RiveState,
|
||||
Dimensions,
|
||||
} from '../types';
|
||||
import { useSize, useDevicePixelRatio } from '../utils';
|
||||
import { UseRiveParameters, UseRiveOptions, RiveState } from '../types';
|
||||
import useResizeCanvas from './useResizeCanvas';
|
||||
import { getOptions } from '../utils';
|
||||
|
||||
type RiveComponentProps = {
|
||||
setContainerRef: RefCallback<HTMLElement>;
|
||||
@@ -25,6 +21,7 @@ function RiveComponent({
|
||||
setCanvasRef,
|
||||
className = '',
|
||||
style,
|
||||
children,
|
||||
...rest
|
||||
}: RiveComponentProps & ComponentProps<'canvas'>) {
|
||||
const containerStyle = {
|
||||
@@ -43,27 +40,13 @@ function RiveComponent({
|
||||
ref={setCanvasRef}
|
||||
style={{ verticalAlign: 'top', width: 0, height: 0 }}
|
||||
{...rest}
|
||||
/>
|
||||
>
|
||||
{children}
|
||||
</canvas>
|
||||
</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.
|
||||
*
|
||||
@@ -86,117 +69,30 @@ export default function useRive(
|
||||
const containerRef = useRef<HTMLElement | null>(null);
|
||||
|
||||
const [rive, setRive] = useState<Rive | null>(null);
|
||||
const [lastContainerDimensions, setLastContainerDimensions] =
|
||||
useState<Dimensions>({
|
||||
height: 0,
|
||||
width: 0,
|
||||
});
|
||||
const [lastCanvasSize, setLastCanvasSize] = 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 currentDevicePixelRatio = useDevicePixelRatio();
|
||||
|
||||
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.
|
||||
* When the canvas/parent container resize, reset the Rive layout to match the
|
||||
* new (0, 0, canvas.width, canvas.height) bounds in the render loop
|
||||
*/
|
||||
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();
|
||||
if (canvasRef.current && rive) {
|
||||
// Check if the canvas parent container bounds have changed and set
|
||||
// new values accordingly
|
||||
const boundsChanged =
|
||||
width !== lastContainerDimensions.width ||
|
||||
height !== lastContainerDimensions.height;
|
||||
if (options.fitCanvasToArtboardHeight && boundsChanged) {
|
||||
containerRef.current.style.height = height + 'px';
|
||||
}
|
||||
if (options.useDevicePixelRatio) {
|
||||
// Check if devicePixelRatio may have changed and get new canvas
|
||||
// width/height values to set the size
|
||||
const canvasSizeChanged =
|
||||
width * currentDevicePixelRatio !== lastCanvasSize.width ||
|
||||
height * currentDevicePixelRatio !== lastCanvasSize.height;
|
||||
if (boundsChanged || canvasSizeChanged) {
|
||||
const newCanvasWidthProp = currentDevicePixelRatio * width;
|
||||
const newCanvasHeightProp = currentDevicePixelRatio * height;
|
||||
canvasRef.current.width = newCanvasWidthProp;
|
||||
canvasRef.current.height = newCanvasHeightProp;
|
||||
canvasRef.current.style.width = width + 'px';
|
||||
canvasRef.current.style.height = height + 'px';
|
||||
setLastCanvasSize({
|
||||
width: newCanvasWidthProp,
|
||||
height: newCanvasHeightProp,
|
||||
});
|
||||
}
|
||||
} else if (boundsChanged) {
|
||||
canvasRef.current.width = width;
|
||||
canvasRef.current.height = height;
|
||||
setLastCanvasSize({
|
||||
width: width,
|
||||
height: height,
|
||||
});
|
||||
}
|
||||
setLastContainerDimensions({ 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
|
||||
const onCanvasHasResized = useCallback(() => {
|
||||
if (rive) {
|
||||
rive.startRendering();
|
||||
rive.resizeToCanvas();
|
||||
}
|
||||
}
|
||||
}, [rive]);
|
||||
|
||||
/**
|
||||
* 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, currentDevicePixelRatio]);
|
||||
// Watch the canvas parent container resize and size the canvas to match
|
||||
useResizeCanvas({
|
||||
riveLoaded: !!rive,
|
||||
canvasRef,
|
||||
containerRef,
|
||||
options,
|
||||
onCanvasHasResized,
|
||||
artboardBounds: rive?.bounds,
|
||||
});
|
||||
|
||||
/**
|
||||
* Ref callback called when the canvas element mounts and unmounts.
|
||||
@@ -298,11 +194,12 @@ export default function useRive(
|
||||
/>
|
||||
);
|
||||
},
|
||||
[]
|
||||
[setCanvasRef, setContainerRef]
|
||||
);
|
||||
|
||||
return {
|
||||
canvas: canvasRef.current,
|
||||
container: containerRef.current,
|
||||
setCanvasRef,
|
||||
setContainerRef,
|
||||
rive,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import Rive from './components/Rive';
|
||||
import useRive from './hooks/useRive';
|
||||
import useStateMachineInput from './hooks/useStateMachineInput';
|
||||
import useResizeCanvas from './hooks/useResizeCanvas';
|
||||
|
||||
export default Rive;
|
||||
export { useRive, useStateMachineInput };
|
||||
export { useRive, useStateMachineInput, useResizeCanvas };
|
||||
export { RiveState, UseRiveParameters, UseRiveOptions } from './types';
|
||||
export * from '@rive-app/canvas';
|
||||
|
||||
@@ -7,6 +7,7 @@ export type UseRiveOptions = {
|
||||
useDevicePixelRatio: boolean;
|
||||
fitCanvasToArtboardHeight: boolean;
|
||||
useOffscreenRenderer: boolean;
|
||||
shouldResizeCanvasToContainer: boolean;
|
||||
};
|
||||
|
||||
export type Dimensions = {
|
||||
@@ -17,6 +18,7 @@ export type Dimensions = {
|
||||
/**
|
||||
* @typedef RiveState
|
||||
* @property canvas - Canvas element the Rive Animation is attached to.
|
||||
* @property container - Container element of the canvas.
|
||||
* @property setCanvasRef - Ref callback to be passed to the canvas element.
|
||||
* @property setContainerRef - Ref callback to be passed to the container element
|
||||
* of the canvas. This is optional, however if not used then the hook will
|
||||
@@ -26,6 +28,7 @@ export type Dimensions = {
|
||||
*/
|
||||
export type RiveState = {
|
||||
canvas: HTMLCanvasElement | null;
|
||||
container: HTMLElement | null;
|
||||
setCanvasRef: RefCallback<HTMLCanvasElement>;
|
||||
setContainerRef: RefCallback<HTMLElement>;
|
||||
rive: Rive | null;
|
||||
|
||||
133
src/utils.ts
133
src/utils.ts
@@ -1,125 +1,12 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Dimensions } from './types';
|
||||
import { UseRiveOptions } from './types';
|
||||
|
||||
// There are polyfills for this, but they add hundreds of lines of code
|
||||
class FakeResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
|
||||
function throttle(f: Function, delay: number) {
|
||||
let timer = 0;
|
||||
return function (this: Function, ...args: any) {
|
||||
clearTimeout(timer);
|
||||
timer = window.setTimeout(() => f.apply(this, args), delay);
|
||||
};
|
||||
}
|
||||
|
||||
const MyResizeObserver = globalThis.ResizeObserver || FakeResizeObserver;
|
||||
const hasResizeObserver = globalThis.ResizeObserver !== undefined;
|
||||
|
||||
const useResizeObserver = hasResizeObserver;
|
||||
const useWindowListener = !useResizeObserver;
|
||||
|
||||
export function useSize(
|
||||
containerRef: React.MutableRefObject<HTMLElement | null>
|
||||
) {
|
||||
const [size, setSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
});
|
||||
|
||||
// internet explorer does not support ResizeObservers.
|
||||
useEffect(() => {
|
||||
if (typeof window !== 'undefined') {
|
||||
const handleResize = () => {
|
||||
setSize({
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight,
|
||||
});
|
||||
};
|
||||
|
||||
if (useWindowListener) {
|
||||
// only pay attention to window size changes when we do not have the resizeObserver (IE only)
|
||||
handleResize();
|
||||
window.addEventListener('resize', handleResize);
|
||||
}
|
||||
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}
|
||||
}, []);
|
||||
const observer = useRef(
|
||||
new MyResizeObserver(
|
||||
throttle((entries: any) => {
|
||||
if (useResizeObserver) {
|
||||
setSize({
|
||||
width: entries[entries.length - 1].contentRect.width,
|
||||
height: entries[entries.length - 1].contentRect.height,
|
||||
});
|
||||
}
|
||||
}, 0)
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const current = observer.current;
|
||||
if (containerRef.current && useResizeObserver) {
|
||||
current.observe(containerRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
current.disconnect();
|
||||
if (containerRef.current && useResizeObserver) {
|
||||
current.unobserve(containerRef.current);
|
||||
}
|
||||
};
|
||||
}, [containerRef, observer]);
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for devicePixelRatio changes and set the new value accordingly. This could
|
||||
* happen for reasons such as:
|
||||
* - User moves window from retina screen display to a separate monitor
|
||||
* - User controls zoom settings on the browser
|
||||
*
|
||||
* Source: https://github.com/rexxars/use-device-pixel-ratio/blob/main/index.ts
|
||||
*
|
||||
* @returns dpr: Number - Device pixel ratio; ratio of physical px to resolution in CSS pixels for current device
|
||||
*/
|
||||
export function useDevicePixelRatio() {
|
||||
const dpr = getDevicePixelRatio();
|
||||
const [currentDpr, setCurrentDpr] = useState(dpr);
|
||||
|
||||
useEffect(() => {
|
||||
const canListen = typeof window !== 'undefined' && 'matchMedia' in window;
|
||||
if (!canListen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateDpr = () => {
|
||||
const newDpr = getDevicePixelRatio();
|
||||
setCurrentDpr(newDpr);
|
||||
};
|
||||
const mediaMatcher = window.matchMedia(
|
||||
`screen and (resolution: ${currentDpr}dppx)`
|
||||
);
|
||||
mediaMatcher.addEventListener('change', updateDpr);
|
||||
|
||||
return () => {
|
||||
mediaMatcher.removeEventListener('change', updateDpr);
|
||||
};
|
||||
}, [currentDpr]);
|
||||
|
||||
return currentDpr;
|
||||
}
|
||||
|
||||
export function getDevicePixelRatio(): number {
|
||||
const hasDprProp =
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.devicePixelRatio === 'number';
|
||||
const dpr = hasDprProp ? window.devicePixelRatio : 1;
|
||||
return Math.min(Math.max(1, dpr), 3);
|
||||
const defaultOptions = {
|
||||
useDevicePixelRatio: true,
|
||||
fitCanvasToArtboardHeight: false,
|
||||
useOffscreenRenderer: true,
|
||||
shouldResizeCanvasToContainer: true,
|
||||
};
|
||||
|
||||
export function getOptions(opts: Partial<UseRiveOptions>) {
|
||||
return Object.assign({}, defaultOptions, opts);
|
||||
}
|
||||
|
||||
@@ -36,4 +36,19 @@ describe('Rive Component', () => {
|
||||
expect(container.firstChild).toHaveClass('container-styles');
|
||||
expect(getByLabelText('Foo label').tagName).toEqual('CANVAS');
|
||||
});
|
||||
|
||||
it('allows children to render in the canvas body', () => {
|
||||
const accessibleFallbackText = 'An animated test';
|
||||
const { getByText } = render(
|
||||
<RiveComponent
|
||||
src="foo.riv"
|
||||
className="container-styles"
|
||||
aria-label="Foo label"
|
||||
>
|
||||
<p>{accessibleFallbackText}</p>
|
||||
</RiveComponent>
|
||||
);
|
||||
|
||||
expect(getByText(accessibleFallbackText)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -94,6 +94,9 @@ describe('useRive', () => {
|
||||
result.current.setCanvasRef(canvasSpy);
|
||||
result.current.setContainerRef(containerSpy);
|
||||
controlledRiveloadCb();
|
||||
jest.spyOn(containerSpy, 'clientWidth', 'get').mockReturnValue(500);
|
||||
jest.spyOn(containerSpy, 'clientHeight', 'get').mockReturnValue(500);
|
||||
containerSpy.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
|
||||
expect(result.current.rive).toBe(riveMock);
|
||||
@@ -192,7 +195,7 @@ describe('useRive', () => {
|
||||
expect(canvasSpy).toHaveAttribute('width', '100');
|
||||
});
|
||||
|
||||
it('uses artbound height to set bounds if fitCanvasToArtboardHeight is true', async () => {
|
||||
it('uses artboard height to set bounds if fitCanvasToArtboardHeight is true', async () => {
|
||||
const params = {
|
||||
src: 'file-src',
|
||||
};
|
||||
@@ -446,9 +449,45 @@ describe('useRive', () => {
|
||||
result.current.setCanvasRef(canvasSpy);
|
||||
result.current.setContainerRef(containerSpy);
|
||||
controlledRiveloadCb();
|
||||
jest.spyOn(containerSpy, 'clientWidth', 'get').mockReturnValue(200);
|
||||
jest.spyOn(containerSpy, 'clientHeight', 'get').mockReturnValue(200);
|
||||
containerSpy.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
|
||||
expect(canvasSpy).toHaveAttribute('width', '200');
|
||||
expect(canvasSpy).toHaveAttribute('height', '200');
|
||||
expect(canvasSpy).toHaveAttribute('width', '400');
|
||||
expect(canvasSpy).toHaveAttribute('height', '400');
|
||||
});
|
||||
|
||||
it('prevents resizing if shouldResizeCanvasToContainer option is false', async () => {
|
||||
const params = {
|
||||
src: 'file-src',
|
||||
};
|
||||
const options = {
|
||||
shouldResizeCanvasToContainer: false,
|
||||
};
|
||||
|
||||
window.devicePixelRatio = 2;
|
||||
|
||||
// @ts-ignore
|
||||
mocked(rive.Rive).mockImplementation(() => baseRiveMock);
|
||||
|
||||
const canvasSpy = document.createElement('canvas');
|
||||
canvasSpy.width = 200;
|
||||
canvasSpy.height = 200;
|
||||
const containerSpy = document.createElement('div');
|
||||
|
||||
const { result } = renderHook(() => useRive(params, options));
|
||||
|
||||
await act(async () => {
|
||||
result.current.setCanvasRef(canvasSpy);
|
||||
result.current.setContainerRef(containerSpy);
|
||||
controlledRiveloadCb();
|
||||
jest.spyOn(containerSpy, 'clientWidth', 'get').mockReturnValue(500);
|
||||
jest.spyOn(containerSpy, 'clientHeight', 'get').mockReturnValue(500);
|
||||
containerSpy.dispatchEvent(new Event('resize'));
|
||||
});
|
||||
|
||||
expect(canvasSpy.width).toBe(200);
|
||||
expect(canvasSpy.height).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user