2021-02-23 05:17:41 -05:00
|
|
|
import { useCallback, useEffect, useState } from 'react'
|
2021-06-16 05:32:38 -04:00
|
|
|
import PropTypes from 'prop-types'
|
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.
|
|
|
|
*
|
2021-06-16 05:32:38 -04:00
|
|
|
* @param {string} path - dot '.' path of a property in the Angular scope.
|
2021-03-31 06:44:20 -04:00
|
|
|
* @param {boolean} deep
|
2021-02-23 05:17:41 -05:00
|
|
|
* @returns {[any, function]} - Binded value and setter function tuple.
|
|
|
|
*/
|
2021-06-16 05:32:38 -04:00
|
|
|
export default function useScopeValue(path, deep = false) {
|
|
|
|
const { $scope } = useIdeContext({
|
|
|
|
$scope: PropTypes.object.isRequired,
|
|
|
|
})
|
|
|
|
|
2021-02-23 05:17:41 -05:00
|
|
|
const [value, setValue] = useState(() => _.get($scope, path))
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
return $scope.$watch(
|
|
|
|
path,
|
|
|
|
newValue => {
|
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(
|
|
|
|
newValue => {
|
|
|
|
setValue(val => {
|
|
|
|
const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
|
|
|
|
$scope.$applyAsync(() => _.set($scope, path, actualNewValue))
|
|
|
|
return actualNewValue
|
|
|
|
})
|
|
|
|
},
|
|
|
|
[path, $scope]
|
|
|
|
)
|
|
|
|
|
|
|
|
return [value, scopeSetter]
|
|
|
|
}
|