2022-05-25 03:57:57 -04:00
|
|
|
import {
|
|
|
|
type Dispatch,
|
|
|
|
type SetStateAction,
|
|
|
|
useCallback,
|
|
|
|
useEffect,
|
|
|
|
useState,
|
|
|
|
} from 'react'
|
2021-02-23 05:17:41 -05:00
|
|
|
import _ from 'lodash'
|
2021-10-08 06:09:41 -04:00
|
|
|
import { useIdeContext } from '../context/ide-context'
|
2021-02-23 05:17:41 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Binds a property in an Angular scope making it accessible in a React
|
|
|
|
* component. The interface is compatible with React.useState(), including
|
|
|
|
* the option of passing a function to the setter.
|
2023-10-24 10:57:17 -04:00
|
|
|
*
|
|
|
|
* The generic type is not an actual guarantee because the value for a path is
|
|
|
|
* returned as undefined when there is nothing in the scope store for that path.
|
2021-02-23 05:17:41 -05:00
|
|
|
*/
|
2022-05-25 03:57:57 -04:00
|
|
|
export default function useScopeValue<T = any>(
|
|
|
|
path: string, // dot '.' path of a property in the Angular scope
|
|
|
|
deep = false
|
|
|
|
): [T, Dispatch<SetStateAction<T>>] {
|
2023-10-24 10:57:17 -04:00
|
|
|
const { scopeStore } = useIdeContext()
|
2021-06-16 05:32:38 -04:00
|
|
|
|
2023-10-24 10:57:17 -04:00
|
|
|
const [value, setValue] = useState<T>(() => scopeStore.get(path))
|
2021-02-23 05:17:41 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
2023-10-24 10:57:17 -04:00
|
|
|
return scopeStore.watch<T>(
|
2021-02-23 05:17:41 -05:00
|
|
|
path,
|
2022-05-27 08:32:27 -04:00
|
|
|
(newValue: T) => {
|
2023-10-24 10:57:17 -04:00
|
|
|
// NOTE: this is deliberately wrapped in a function,
|
|
|
|
// to avoid calling setValue directly with a value that's a function
|
|
|
|
setValue(() => newValue)
|
2021-02-23 05:17:41 -05:00
|
|
|
},
|
|
|
|
deep
|
|
|
|
)
|
2023-10-24 10:57:17 -04:00
|
|
|
}, [path, scopeStore, deep])
|
2021-02-23 05:17:41 -05:00
|
|
|
|
|
|
|
const scopeSetter = useCallback(
|
2022-05-25 03:57:57 -04:00
|
|
|
(newValue: SetStateAction<T>) => {
|
2021-02-23 05:17:41 -05:00
|
|
|
setValue(val => {
|
|
|
|
const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
|
2023-10-24 10:57:17 -04:00
|
|
|
scopeStore.set(path, actualNewValue)
|
2021-02-23 05:17:41 -05:00
|
|
|
return actualNewValue
|
|
|
|
})
|
|
|
|
},
|
2023-10-24 10:57:17 -04:00
|
|
|
[path, scopeStore]
|
2021-02-23 05:17:41 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
return [value, scopeSetter]
|
|
|
|
}
|