@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
78 lines (77 loc) • 2.93 kB
JavaScript
;
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useDataValue;
var _react = require("react");
var _index = _interopRequireDefault(require("../utils/json-pointer/index.js"));
var _Context = _interopRequireDefault(require("../DataContext/Context.js"));
var _IterateItemContext = _interopRequireDefault(require("../Iterate/IterateItemContext.js"));
var _usePath = _interopRequireDefault(require("./usePath.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function useDataValue(pathProp, value) {
const dataContextRef = (0, _react.useRef)();
dataContextRef.current = (0, _react.useContext)(_Context.default);
const iterateItemContext = (0, _react.useContext)(_IterateItemContext.default);
const {
makePath,
makeIteratePath
} = (0, _usePath.default)();
const get = (0, _react.useCallback)((selector, data = (_dataContextRef$curre => (_dataContextRef$curre = dataContextRef.current) === null || _dataContextRef$curre === void 0 || (_dataContextRef$curre = _dataContextRef$curre.internalDataRef) === null || _dataContextRef$curre === void 0 ? void 0 : _dataContextRef$curre.current)()) => {
if (selector === '/') {
return data;
}
return _index.default.has(data, selector) ? _index.default.get(data, selector) : undefined;
}, []);
const getValueByPath = (0, _react.useCallback)((path, data = undefined) => {
if (isPath(path)) {
return get(makePath(path), data);
}
}, [get, makePath]);
const getValueByIteratePath = (0, _react.useCallback)(path => {
if (isPath(path)) {
return get(makeIteratePath(path));
}
}, [get, makeIteratePath]);
const moveValueToPath = (0, _react.useCallback)((path, value, object = {}) => {
if (path !== '/' && isPath(path)) {
_index.default.set(object, path, value);
return object;
}
return value;
}, []);
const getData = (0, _react.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 = (0, _react.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