1+ import { useCallback } from 'react' ;
2+ import { ViewModelInstance , ViewModelInstanceList } from '@rive-app/canvas' ;
3+ import { UseViewModelInstanceListResult } from '../types' ;
4+ import { useViewModelInstanceProperty } from './useViewModelInstanceProperty' ;
5+
6+ /**
7+ * Hook for interacting with list properties of a ViewModelInstance.
8+ *
9+ * @param path - Path to the property (e.g. "items" or "nested/items")
10+ * @param viewModelInstance - The ViewModelInstance containing the list property
11+ * @returns An object with the list length and manipulation functions
12+ */
13+ export default function useViewModelInstanceList (
14+ path : string ,
15+ viewModelInstance ?: ViewModelInstance | null
16+ ) : UseViewModelInstanceListResult {
17+
18+ const result = useViewModelInstanceProperty < ViewModelInstanceList , number , Omit < UseViewModelInstanceListResult , 'length' > > (
19+ path ,
20+ viewModelInstance ,
21+ {
22+ getProperty : useCallback ( ( vm , p ) => vm . list ( p ) , [ ] ) ,
23+ getValue : useCallback ( ( prop ) => prop . length , [ ] ) ,
24+ defaultValue : 0 ,
25+ buildPropertyOperations : useCallback ( ( safePropertyAccess ) => ( {
26+ addInstance : ( instance : ViewModelInstance ) => {
27+ safePropertyAccess ( prop => prop . addInstance ( instance ) ) ;
28+ } ,
29+ addInstanceAt : ( instance : ViewModelInstance , index : number ) : boolean => {
30+ let result = false ;
31+ safePropertyAccess ( prop => {
32+ result = prop . addInstanceAt ( instance , index ) ;
33+ } ) ;
34+ return result ;
35+ } ,
36+ removeInstance : ( instance : ViewModelInstance ) => {
37+ safePropertyAccess ( prop => prop . removeInstance ( instance ) ) ;
38+ } ,
39+ removeInstanceAt : ( index : number ) => {
40+ safePropertyAccess ( prop => prop . removeInstanceAt ( index ) ) ;
41+ } ,
42+ getInstanceAt : ( index : number ) : ViewModelInstance | null => {
43+ let result : ViewModelInstance | null = null ;
44+ safePropertyAccess ( prop => {
45+ result = prop . instanceAt ( index ) ;
46+ } ) ;
47+ return result ;
48+ } ,
49+ swap : ( a : number , b : number ) => {
50+ safePropertyAccess ( prop => prop . swap ( a , b ) ) ;
51+ }
52+ } ) , [ ] )
53+ }
54+ ) ;
55+
56+ return {
57+ length : result . value ?? 0 ,
58+ addInstance : result . addInstance ,
59+ addInstanceAt : result . addInstanceAt ,
60+ removeInstance : result . removeInstance ,
61+ removeInstanceAt : result . removeInstanceAt ,
62+ getInstanceAt : result . getInstanceAt ,
63+ swap : result . swap
64+ } ;
65+ }
0 commit comments