-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathuseViewModelInstanceProperty.ts
More file actions
99 lines (90 loc) · 2.59 KB
/
Copy pathuseViewModelInstanceProperty.ts
File metadata and controls
99 lines (90 loc) · 2.59 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
import { useState, useEffect, useRef } from 'react';
import {
EventType,
ViewModelInstance,
} from '@rive-app/canvas';
import { UseViewModelInstanceValueParameters } from '../types';
const defaultParams: UseViewModelInstanceValueParameters = {
viewModelInstance: null,
};
const equal = (
path: string[],
params: UseViewModelInstanceValueParameters | null,
to: HookArguments | null
): boolean => {
if (!params || !to) {
return false;
}
if (
params.rive !== to.parameters.rive ||
params.viewModelInstance !== to.parameters.viewModelInstance ||
path.join('') !== to.path.join('')
) {
return false;
}
return true;
};
type HookArguments = {
path: string[],
parameters: UseViewModelInstanceValueParameters,
}
/**
* Custom hook for fetching a view model instance value.
*
* @param name - name of the propery
* @param path - Path to reach the required property
* @param userParameters - Parameters to load view model instance number
* @returns
*/
export default function useViewModelInstanceProperty(
path: string[] = [],
userParameters?: UseViewModelInstanceValueParameters
): ViewModelInstance | null {
const [viewModelInstance, setViewModelValue] =
useState<ViewModelInstance | null>(null);
const currentArguments = useRef<HookArguments | null>(
null
);
useEffect(() => {
const parameters = {
...defaultParams,
...userParameters,
};
function getInstanceValue(): ViewModelInstance | null {
let viewModelInstance: ViewModelInstance | null = null;
if (userParameters?.viewModelInstance) {
viewModelInstance = userParameters?.viewModelInstance;
} else if (userParameters?.rive) {
viewModelInstance = userParameters?.rive?.viewModelInstance;
}
if (viewModelInstance) {
let index = 0;
while (index < path?.length) {
if(!viewModelInstance) {
return null;
}
viewModelInstance = viewModelInstance?.viewModel(path[index]);
index++;
}
return viewModelInstance;
}
return null;
}
function searchViewModelInstance() {
const instanceValue = getInstanceValue();
setViewModelValue(instanceValue);
currentArguments.current = {
parameters,
path,
};
}
if (!equal(path, parameters, currentArguments.current)) {
parameters.rive?.on(EventType.Load, searchViewModelInstance);
searchViewModelInstance();
}
return () => {
parameters.rive?.off(EventType.Load, searchViewModelInstance);
};
}, [path, userParameters]);
return viewModelInstance;
}