@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
335 lines (334 loc) • 14.1 kB
JavaScript
"use strict";
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _push = _interopRequireDefault(require("core-js-pure/stable/instance/push.js"));
var _react = _interopRequireWildcard(require("react"));
var z = _interopRequireWildcard(require("zod"));
var _classnames = _interopRequireDefault(require("classnames"));
var _index = _interopRequireDefault(require("../../utils/json-pointer/index.js"));
var _index2 = require("../../hooks/index.js");
var _componentHelper = require("../../../../shared/component-helper.js");
var _index3 = require("../../../../components/index.js");
var _index4 = require("../../../../elements/index.js");
var _utils = require("../../../../components/flex/utils.js");
var _useMountEffect = _interopRequireDefault(require("../../../../shared/helpers/useMountEffect.js"));
var _useUpdateEffect = _interopRequireDefault(require("../../../../shared/helpers/useUpdateEffect.js"));
var _Container = require("../../../../components/flex/Container.js");
var _IterateItemContext = _interopRequireDefault(require("../IterateItemContext.js"));
var _SummaryListContext = _interopRequireDefault(require("../../Value/SummaryList/SummaryListContext.js"));
var _ValueBlockContext = _interopRequireDefault(require("../../ValueBlock/ValueBlockContext.js"));
var _FieldBoundaryProvider = _interopRequireDefault(require("../../DataContext/FieldBoundary/FieldBoundaryProvider.js"));
var _Context = _interopRequireDefault(require("../../DataContext/Context.js"));
var _useDataValue = _interopRequireDefault(require("../../hooks/useDataValue.js"));
var _index5 = require("../hooks/index.js");
var _index6 = require("../../FieldBlock/index.js");
var _useFieldProps = require("../../hooks/useFieldProps.js");
var _structuredClone = require("../../../../shared/helpers/structuredClone.js");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function ArrayComponent(props) {
const [salt, forceUpdate] = (0, _react.useReducer)(() => ({}), {});
const {
path: pathProp,
itemPath: itemPathProp,
reverse,
countPath,
countPathTransform,
countPathLimit = Infinity,
omitSectionPath
} = props || {};
const dataContext = (0, _react.useContext)(_Context.default);
const summaryListContext = (0, _react.useContext)(_SummaryListContext.default);
const valueBlockContext = (0, _react.useContext)(_ValueBlockContext.default);
const {
absolutePath
} = (0, _index5.useItemPath)(itemPathProp);
const {
setLimitProps,
error: limitWarning
} = (0, _index5.useArrayLimit)(pathProp || absolutePath);
const {
getValueByPath
} = (0, _useDataValue.default)();
const countValue = (0, _react.useMemo)(() => {
if (!countPath) {
return -1;
}
let countValue = parseFloat(getValueByPath(countPath, dataContext.data));
if (!(countValue >= 0)) {
countValue = 0;
}
if (countValue > countPathLimit) {
countValue = countPathLimit;
}
return countValue;
}, [countPath, countPathLimit, getValueByPath, dataContext.data]);
const validateRequired = (0, _react.useCallback)((value, {
emptyValue,
required,
error
}) => {
if (required && (!value || (value === null || value === void 0 ? void 0 : value.length) === 0 || value === emptyValue)) {
return error;
}
}, []);
const preparedProps = (0, _react.useMemo)(() => {
const shared = {
schema: undefined,
emptyValue: undefined,
required: false,
validateRequired,
...props
};
if (typeof props.minItems === 'number' || typeof props.maxItems === 'number') {
shared.schema = p => {
let s = z.array(z.any());
if (typeof p.minItems === 'number') {
s = s.min(p.minItems, {
message: 'IterateArray.errorMinItems'
});
}
if (typeof p.maxItems === 'number') {
s = s.max(p.maxItems, {
message: 'IterateArray.errorMaxItems'
});
}
return s;
};
}
if (countPath) {
const arrayValue = getValueByPath(pathProp);
const newValue = [];
for (let i = 0, l = countValue; i < l; i++) {
const value = arrayValue === null || arrayValue === void 0 ? void 0 : arrayValue[i];
(0, _push.default)(newValue).call(newValue, countPathTransform ? countPathTransform({
value,
index: i
}) : value);
}
return {
...shared,
value: newValue
};
}
return {
...shared
};
}, [countPath, countPathTransform, countValue, getValueByPath, pathProp, props, validateRequired]);
const {
path,
itemPath,
value: arrayValue,
limit,
error,
withoutFlex,
placeholder,
containerMode,
animate,
handleChange,
setChanged,
onChange,
validateValue,
children
} = (0, _index2.useFieldProps)(preparedProps, {
updateContextDataInSync: true,
omitMultiplePathWarning: true,
forceUpdateWhenContextDataIsSet: Boolean(countPath),
omitSectionPath
});
const countValueRef = (0, _react.useRef)();
(0, _useUpdateEffect.default)(() => {
if (countPath) {
if (typeof countValueRef.current === 'number' && countValue !== countValueRef.current) {
window.requestAnimationFrame(() => {
dataContext.handlePathChange(path, getValueByPath(path));
});
}
countValueRef.current = countValue;
}
}, [countValue]);
const idsRef = (0, _react.useRef)([]);
const isNewRef = (0, _react.useRef)({});
const modesRef = (0, _react.useRef)({});
const valueCountRef = (0, _react.useRef)(arrayValue);
const arrayValueRef = (0, _react.useRef)(arrayValue);
const containerRef = (0, _react.useRef)();
const hadPushRef = (0, _react.useRef)();
const innerRefs = (0, _react.useRef)({});
const omitFlex = withoutFlex !== null && withoutFlex !== void 0 ? withoutFlex : summaryListContext || valueBlockContext;
const {
getNextContainerMode
} = (0, _index5.useSwitchContainerMode)();
(0, _react.useEffect)(() => {
valueCountRef.current = arrayValue || [];
arrayValueRef.current = arrayValue || [];
}, [arrayValue]);
const arrayItems = (0, _react.useMemo)(() => {
const list = Array.isArray(arrayValue) ? arrayValue : [];
const limitedList = typeof limit === 'number' ? list.slice(0, limit) : list;
const arrayItems = limitedList.map((value, index) => {
var _valueCountRef$curren, _modesRef$current$id;
const id = idsRef.current[index] || (0, _componentHelper.makeUniqueId)();
const hasNewItems = (arrayValue === null || arrayValue === void 0 ? void 0 : arrayValue.length) > ((_valueCountRef$curren = valueCountRef.current) === null || _valueCountRef$curren === void 0 ? void 0 : _valueCountRef$curren.length);
if (!idsRef.current[index]) {
var _context;
isNewRef.current[id] = hasNewItems;
(0, _push.default)(_context = idsRef.current).call(_context, id);
}
const isNew = isNewRef.current[id] || false;
if (!((_modesRef$current$id = modesRef.current[id]) !== null && _modesRef$current$id !== void 0 && _modesRef$current$id.current)) {
var _getNextContainerMode;
modesRef.current[id] = {
current: containerMode !== null && containerMode !== void 0 ? containerMode : isNew ? (_getNextContainerMode = getNextContainerMode()) !== null && _getNextContainerMode !== void 0 ? _getNextContainerMode : 'edit' : 'auto'
};
}
const itemContext = {
id,
path,
itemPath,
value,
index,
arrayValue,
containerRef,
isNew,
containerMode: modesRef.current[id].current,
previousContainerMode: modesRef.current[id].previous,
initialContainerMode: containerMode || 'auto',
modeOptions: modesRef.current[id].options,
nestedIteratePath: absolutePath,
switchContainerMode: (mode, options = {}) => {
var _isNewRef$current;
modesRef.current[id].previous = modesRef.current[id].current;
modesRef.current[id].current = mode;
modesRef.current[id].options = options;
(_isNewRef$current = isNewRef.current) === null || _isNewRef$current === void 0 || delete _isNewRef$current[id];
if ((options === null || options === void 0 ? void 0 : options.preventUpdate) !== true) {
forceUpdate();
}
},
handleChange: (path, value) => {
const newArrayValue = (0, _structuredClone.structuredClone)(arrayValueRef.current || []);
newArrayValue[index] = {
...newArrayValue[index]
};
_index.default.set(newArrayValue, path, value);
handleChange(newArrayValue);
},
handlePush: element => {
hadPushRef.current = true;
handleChange([...(arrayValueRef.current || []), element]);
},
handleRemove: ({
keepItems = false
} = {}) => {
if (keepItems) {
return;
}
itemContext.fulfillRemove();
},
fulfillRemove: () => {
var _modesRef$current, _isNewRef$current2;
const newArrayValue = (0, _structuredClone.structuredClone)(arrayValueRef.current || []);
newArrayValue.splice(index, 1);
handleChange(newArrayValue.length === 0 ? _useFieldProps.clearedArray : newArrayValue);
(_modesRef$current = modesRef.current) === null || _modesRef$current === void 0 || delete _modesRef$current[id];
(_isNewRef$current2 = isNewRef.current) === null || _isNewRef$current2 === void 0 || delete _isNewRef$current2[id];
const findIndex = idsRef.current.indexOf(id);
idsRef.current.splice(findIndex, 1);
forceUpdate();
},
restoreOriginalValue: value => {
if (value) {
const newArrayValue = (0, _structuredClone.structuredClone)(arrayValueRef.current || []);
newArrayValue[index] = value;
handleChange(newArrayValue);
}
}
};
return itemContext;
});
if (reverse) {
return arrayItems.reverse();
}
return arrayItems;
}, [salt, arrayValue, limit, path, itemPath, absolutePath, reverse, handleChange]);
const total = arrayItems.length;
(0, _react.useEffect)(() => {
if (limit) {
setLimitProps({
limit,
total
});
}
}, [total, limit, setLimitProps]);
(0, _useUpdateEffect.default)(() => {
validateValue();
}, [total, validateValue]);
(0, _useMountEffect.default)(() => {
setChanged(true);
});
(0, _react.useMemo)(() => {
const last = arrayItems === null || arrayItems === void 0 ? void 0 : arrayItems[arrayItems.length - 1];
if (last !== null && last !== void 0 && last.isNew && !hadPushRef.current) {
onChange === null || onChange === void 0 || onChange(arrayValue);
} else {
hadPushRef.current = false;
}
}, [arrayValue, arrayItems, onChange]);
const flexProps = {
className: (0, _classnames.default)("dnb-forms-iterate dnb-forms-section", props === null || props === void 0 ? void 0 : props.className),
...(0, _Container.pickFlexContainerProps)(props),
...(0, _utils.pickSpacingProps)(props),
innerRef: containerRef
};
const arrayElements = total === 0 ? typeof placeholder === 'string' ? _react.default.createElement(_index4.Span, {
size: "small"
}, placeholder) : placeholder : arrayItems.map(itemProps => {
const {
id,
value,
index
} = itemProps;
const elementRef = innerRefs.current[id] = innerRefs.current[id] || (0, _react.createRef)();
const renderChildren = elementChild => {
return typeof elementChild === 'function' ? elementChild(value, index, arrayItems) : elementChild;
};
const contextValue = {
...itemProps,
elementRef
};
const content = Array.isArray(children) ? children.map(child => renderChildren(child)) : renderChildren(children);
if (omitFlex) {
return _react.default.createElement(_IterateItemContext.default.Provider, {
key: `element-${id}`,
value: contextValue
}, _react.default.createElement(_FieldBoundaryProvider.default, null, content));
}
return _react.default.createElement(_index3.Flex.Item, {
className: "dnb-forms-iterate__element",
tabIndex: -1,
innerRef: elementRef,
key: `element-${id}`
}, _react.default.createElement(_IterateItemContext.default.Provider, {
value: contextValue
}, _react.default.createElement(_FieldBoundaryProvider.default, null, content)));
});
const content = omitFlex ? arrayElements : _react.default.createElement(_index3.Flex.Stack, flexProps, arrayElements);
return _react.default.createElement(_react.default.Fragment, null, animate ? _react.default.createElement(_index3.HeightAnimation, null, content) : content, _react.default.createElement(_index3.FormStatus, {
show: Boolean(error || limitWarning),
state: !error && limitWarning ? 'warning' : undefined,
shellSpace: {
top: 0,
bottom: 'medium'
},
no_animation: false
}, (0, _index6.getMessagesFromError)({
content: error || limitWarning
})[0]));
}
ArrayComponent._supportsSpacingProps = true;
var _default = exports.default = ArrayComponent;
//# sourceMappingURL=Array.js.map