@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
82 lines (81 loc) • 3.08 kB
JavaScript
;
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = usePath;
require("core-js/modules/es.string.replace.js");
var _react = require("react");
var _useId = _interopRequireDefault(require("../../../shared/helpers/useId"));
var _SectionContext = _interopRequireDefault(require("../Form/Section/SectionContext"));
var _IterateItemContext = _interopRequireDefault(require("../Iterate/IterateItemContext"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function usePath() {
var _useContext, _useContext2;
let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
const {
path: pathProp,
itemPath: itemPathProp
} = props;
const id = (0, _useId.default)(props.id);
const {
path: sectionPath
} = (_useContext = (0, _react.useContext)(_SectionContext.default)) !== null && _useContext !== void 0 ? _useContext : {};
const {
path: iteratePathProp,
index: iterateElementIndex
} = (_useContext2 = (0, _react.useContext)(_IterateItemContext.default)) !== null && _useContext2 !== void 0 ? _useContext2 : {};
if (pathProp && !pathProp.startsWith('/')) {
throw new Error(`path="${pathProp}" must start with a slash`);
}
if (itemPathProp && !itemPathProp.startsWith('/')) {
throw new Error(`itemPath="${itemPathProp}" must start with a slash`);
}
const joinPath = (0, _react.useCallback)(paths => {
return cleanPath(paths.reduce((acc, cur) => cur ? `${acc}/${cur}` : acc, '/'));
}, []);
const makeSectionPath = (0, _react.useCallback)(path => {
return cleanPath(`${sectionPath && sectionPath !== '/' ? sectionPath : ''}${path}`);
}, [sectionPath]);
const makeIteratePath = (0, _react.useCallback)(function () {
let itemPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : itemPathProp;
let iteratePath = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : iteratePathProp;
let root = '';
if (sectionPath) {
root = makeSectionPath('');
}
return cleanPath(`${root}${iteratePath || ''}/${iterateElementIndex}${itemPath || ''}`);
}, [itemPathProp, iteratePathProp, sectionPath, iterateElementIndex, makeSectionPath]);
const itemPath = (0, _react.useMemo)(() => {
if (itemPathProp) {
return makeIteratePath();
}
}, [itemPathProp, makeIteratePath]);
const makePath = (0, _react.useCallback)(path => {
if (itemPathProp) {
return itemPath;
}
if (sectionPath) {
return makeSectionPath(path);
}
return path;
}, [itemPathProp, sectionPath, itemPath, makeSectionPath]);
const path = (0, _react.useMemo)(() => {
return makePath(pathProp);
}, [makePath, pathProp]);
const identifier = path !== null && path !== void 0 ? path : id;
return {
identifier,
path,
itemPath,
joinPath,
makePath,
makeIteratePath,
makeSectionPath,
cleanPath
};
}
function cleanPath(path) {
return path.replace(/\/+$|\/(\/)+/g, '$1');
}
//# sourceMappingURL=usePath.js.map