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.
|
|
|
|
*/
|
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>>] {
|
|
|
|
const { $scope } = useIdeContext()
|
2021-06-16 05:32:38 -04:00
|
|
|
|
2022-05-25 03:57:57 -04:00
|
|
|
const [value, setValue] = useState<T>(() => _.get($scope, path))
|
2021-02-23 05:17:41 -05:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
return $scope.$watch(
|
|
|
|
path,
|
2022-05-27 08:32:27 -04:00
|
|
|
(newValue: T) => {
|
2021-10-08 06:09:41 -04:00
|
|
|
setValue(() => {
|
|
|
|
// NOTE: this is deliberately wrapped in a function,
|
|
|
|
// to avoid calling setValue directly with a value that's a function
|
|
|
|
return deep ? _.cloneDeep(newValue) : newValue
|
|
|
|
})
|
2021-02-23 05:17:41 -05:00
|
|
|
},
|
|
|
|
deep
|
|
|
|
)
|
|
|
|
}, [path, $scope, deep])
|
|
|
|
|
|
|
|
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
|
|
|
|
$scope.$applyAsync(() => _.set($scope, path, actualNewValue))
|
|
|
|
return actualNewValue
|
|
|
|
})
|
|
|
|
},
|
|
|
|
[path, $scope]
|
|
|
|
)
|
|
|
|
|
|
|
|
return [value, scopeSetter]
|
|
|
|
}
|