@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
76 lines (75 loc) • 2.77 kB
JavaScript
"use client";
import { useCallback, useContext, useRef } from 'react';
import pointer from '../utils/json-pointer';
import DataContext from '../DataContext/Context';
import IterateItemContext from '../Iterate/IterateItemContext';
import usePath from './usePath';
export default function useDataValue(pathProp, value) {
const dataContextRef = useRef();
dataContextRef.current = useContext(DataContext);
const iterateItemContext = useContext(IterateItemContext);
const {
makePath,
makeIteratePath
} = usePath();
const get = useCallback(function (selector) {
var _dataContextRef$curre, _dataContextRef$curre2;
let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_dataContextRef$curre = dataContextRef.current) === null || _dataContextRef$curre === void 0 ? void 0 : (_dataContextRef$curre2 = _dataContextRef$curre.internalDataRef) === null || _dataContextRef$curre2 === void 0 ? void 0 : _dataContextRef$curre2.current;
if (selector === '/') {
return data;
}
return pointer.has(data, selector) ? pointer.get(data, selector) : undefined;
}, []);
const getValueByPath = useCallback(function (path) {
let data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
if (isPath(path)) {
return get(makePath(path), data);
}
}, [get, makePath]);
const getValueByIteratePath = useCallback(path => {
if (isPath(path)) {
return get(makeIteratePath(path));
}
}, [get, makeIteratePath]);
const moveValueToPath = useCallback(function (path, value) {
let object = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (path !== '/' && isPath(path)) {
pointer.set(object, path, value);
return object;
}
return value;
}, []);
const getData = useCallback((path, options) => {
if (isPath(path)) {
const value = getValueByPath(path);
if (options !== null && options !== void 0 && options.includeCurrentPath && path !== '/') {
return moveValueToPath(path, value);
}
return value;
}
}, [getValueByPath, moveValueToPath]);
const getSourceValue = useCallback(source => {
if (typeof source === 'string' && isPath(source)) {
if (iterateItemContext) {
return getValueByIteratePath(source);
}
return getValueByPath(source);
}
return source;
}, [getValueByIteratePath, getValueByPath, iterateItemContext]);
if (pathProp) {
value = getSourceValue(pathProp);
}
return {
getSourceValue,
getValueByPath,
getValueByIteratePath,
moveValueToPath,
getData,
value
};
}
function isPath(path) {
return typeof path === 'string' && path.startsWith('/');
}
//# sourceMappingURL=useDataValue.js.map