2022-05-25 03:57:57 -04:00
|
|
|
import {
|
|
|
|
type Dispatch,
|
|
|
|
type SetStateAction,
|
|
|
|
useCallback,
|
|
|
|
useState,
|
|
|
|
} from 'react'
|
2021-11-03 10:30:41 -04:00
|
|
|
import { useIdeContext } from '../context/ide-context'
|
|
|
|
import _ from 'lodash'
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Similar to `useScopeValue`, but instead of creating a two-way binding, only
|
|
|
|
* changes in react-> angular direction are propagated, with `value` remaining
|
|
|
|
* local and independent of its value in the Angular scope.
|
|
|
|
*
|
|
|
|
* 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 useScopeValueSetterOnly<T = any>(
|
|
|
|
path: string, // dot '.' path of a property in the Angular scope.
|
|
|
|
defaultValue?: T
|
2022-05-27 08:32:27 -04:00
|
|
|
): [T | undefined, Dispatch<SetStateAction<T | undefined>>] {
|
2024-01-03 06:13:13 -05:00
|
|
|
const { scopeStore } = useIdeContext()
|
2021-11-03 10:30:41 -04:00
|
|
|
|
2022-05-27 08:32:27 -04:00
|
|
|
const [value, setValue] = useState<T | undefined>(defaultValue)
|
2021-11-03 10:30:41 -04:00
|
|
|
|
|
|
|
const scopeSetter = useCallback(
|
2022-05-27 08:32:27 -04:00
|
|
|
(newValue: SetStateAction<T | undefined>) => {
|
2021-11-03 10:30:41 -04:00
|
|
|
setValue(val => {
|
|
|
|
const actualNewValue = _.isFunction(newValue) ? newValue(val) : newValue
|
2024-01-03 06:13:13 -05:00
|
|
|
scopeStore.set(path, actualNewValue)
|
2021-11-03 10:30:41 -04:00
|
|
|
return actualNewValue
|
|
|
|
})
|
|
|
|
},
|
2024-01-03 06:13:13 -05:00
|
|
|
[path, scopeStore]
|
2021-11-03 10:30:41 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
return [value, scopeSetter]
|
|
|
|
}
|