mirror of
https://github.com/overleaf/overleaf.git
synced 2024-12-26 05:41:43 +00:00
845b2fbc04
GitOrigin-RevId: b1a6a4e871af3b52fb3d100a83b479c834cb75ca
48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
import { useCallback, useEffect, useState } from 'react'
|
|
import PropTypes from 'prop-types'
|
|
import _ from 'lodash'
|
|
import { useIdeContext } from '../context/ide-context'
|
|
|
|
/**
|
|
* 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.
|
|
*
|
|
* @param {string} path - dot '.' path of a property in the Angular scope.
|
|
* @param {boolean} deep
|
|
* @returns {[any, function]} - Binded value and setter function tuple.
|
|
*/
|
|
export default function useScopeValue(path, deep = false) {
|
|
const { $scope } = useIdeContext({
|
|
$scope: PropTypes.object.isRequired,
|
|
})
|
|
|
|
const [value, setValue] = useState(() => _.get($scope, path))
|
|
|
|
useEffect(() => {
|
|
return $scope.$watch(
|
|
path,
|
|
newValue => {
|
|
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
|
|
})
|
|
},
|
|
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]
|
|
}
|