-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathuseStateMachineInputs.ts
More file actions
60 lines (56 loc) · 1.88 KB
/
useStateMachineInputs.ts
File metadata and controls
60 lines (56 loc) · 1.88 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
import { useState, useEffect } from 'react';
import { EventType, Rive, StateMachineInput } from '@rive-app/canvas';
/**
* Custom hook for fetching multiple stateMachine inputs from a rive file.
* Particularly useful for fetching multiple inputs from a variable number of input names.
*
* @param rive - Rive instance
* @param stateMachineName - Name of the state machine
* @param inputNames - Names of the inputs
* @returns StateMachineInput[] | null
*/
export default function useStateMachineInputs(
rive: Rive | null,
stateMachineName?: string,
inputNames?: {
name: string;
initialValue?: number | boolean;
}[]
) {
const [inputs, setInputs] = useState<StateMachineInput[] | null>(null);
useEffect(() => {
function setStateMachineInput() {
if (!rive || !stateMachineName || !inputNames) {
setInputs(null);
}
if (rive && stateMachineName && inputNames) {
const inputs = rive.stateMachineInputs(stateMachineName);
if (inputs) {
const selectedInputs = inputs.filter((input) =>
inputNames.some((inputName) => inputName.name === input.name)
);
if (selectedInputs) {
selectedInputs.forEach((input) => {
const targetInputName = inputNames.find(inputName => inputName.name === input.name);
if(targetInputName?.initialValue){
input.value = targetInputName.initialValue
}
});
}
setInputs(selectedInputs);
}
} else {
setInputs(null);
}
}
setStateMachineInput();
if (rive) {
rive.on(EventType.Load, () => {
// Check if the component/canvas is mounted before setting state to avoid setState
// on an unmounted component in some rare cases
setStateMachineInput();
});
}
}, [inputNames, rive, stateMachineName]);
return inputs;
}