UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

316 lines (315 loc) 15.2 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; require("core-js/modules/web.dom-collections.iterator.js"); var _react = _interopRequireWildcard(require("react")); var _classnames = _interopRequireDefault(require("classnames")); var _jsonPointer = _interopRequireDefault(require("../../utils/json-pointer")); var _hooks = require("../../hooks"); var _componentHelper = require("../../../../shared/component-helper"); var _components = require("../../../../components"); var _elements = require("../../../../elements"); var _utils = require("../../../../components/flex/utils"); var _useMountEffect = _interopRequireDefault(require("../../../../shared/helpers/useMountEffect")); var _useUpdateEffect = _interopRequireDefault(require("../../../../shared/helpers/useUpdateEffect")); var _Container = require("../../../../components/flex/Container"); var _IterateItemContext = _interopRequireDefault(require("../IterateItemContext")); var _SummaryListContext = _interopRequireDefault(require("../../Value/SummaryList/SummaryListContext")); var _ValueBlockContext = _interopRequireDefault(require("../../ValueBlock/ValueBlockContext")); var _FieldBoundaryProvider = _interopRequireDefault(require("../../DataContext/FieldBoundary/FieldBoundaryProvider")); var _Context = _interopRequireDefault(require("../../DataContext/Context")); var _useDataValue = _interopRequireDefault(require("../../hooks/useDataValue")); var _hooks2 = require("../hooks"); var _FieldBlock = require("../../FieldBlock"); var _structuredClone = _interopRequireDefault(require("@ungap/structured-clone")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function ArrayComponent(props) { var _props$value; const [salt, forceUpdate] = (0, _react.useReducer)(() => ({}), {}); const { path: pathProp, itemPath: itemPathProp, reverse, countPath, countPathTransform, countPathLimit = Infinity } = 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, _hooks2.useItemPath)(itemPathProp); const { setLimitProps, error: limitWarning } = (0, _hooks2.useArrayLimit)(pathProp || absolutePath); const { getValueByPath } = (0, _useDataValue.default)(); const getCountValue = (0, _react.useCallback)(() => { if (!countPath) { return -1; } let countValue = parseFloat(getValueByPath(countPath)); if (!(countValue >= 0)) { countValue = 0; } if (countValue > countPathLimit) { countValue = countPathLimit; } return countValue; }, [countPath, countPathLimit, getValueByPath]); const countValue = getCountValue(); const validateRequired = (0, _react.useCallback)((value, _ref) => { let { emptyValue, required, error } = _ref; if (required && (!value || (value === null || value === void 0 ? void 0 : value.length) === 0 || value === emptyValue)) { return error; } }, []); const preparedProps = (0, _react.useMemo)(() => { const shared = { required: false, validateRequired }; 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]; newValue.push(countPathTransform ? countPathTransform({ value, index: i }) : value); } return _objectSpread(_objectSpread(_objectSpread({}, shared), props), {}, { value: newValue }); } return _objectSpread(_objectSpread({}, shared), props); }, [countPath, countPathTransform, countValue, getValueByPath, pathProp, props, validateRequired]); const { path, itemPath, value: arrayValue, limit, error, withoutFlex, emptyValue, placeholder, containerMode, animate, handleChange, setChanged, onChange, validateValue, children } = (0, _hooks.useFieldProps)(preparedProps, { updateContextDataInSync: true, omitMultiplePathWarning: true, forceUpdateWhenContextDataIsSet: Boolean(countPath) }); 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]); (0, _react.useEffect)(() => { valueCountRef.current = arrayValue || []; }, [arrayValue]); const idsRef = (0, _react.useRef)([]); const isNewRef = (0, _react.useRef)({}); const modesRef = (0, _react.useRef)({}); const valueWhileClosingRef = (0, _react.useRef)(); const valueCountRef = (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, _hooks2.useSwitchContainerMode)(); const arrayItems = (0, _react.useMemo)(() => { var _ref2; const list = (_ref2 = valueWhileClosingRef.current || arrayValue) !== null && _ref2 !== void 0 ? _ref2 : []; 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]) { isNewRef.current[id] = hasNewItems; idsRef.current.push(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: function (mode) { var _isNewRef$current; let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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 ? true : delete _isNewRef$current[id]; if ((options === null || options === void 0 ? void 0 : options.preventUpdate) !== true) { forceUpdate(); } }, handleChange: (path, value) => { const newArrayValue = (0, _structuredClone.default)(arrayValue); newArrayValue[index] = _objectSpread({}, newArrayValue[index]); _jsonPointer.default.set(newArrayValue, path, value); handleChange(newArrayValue); }, handlePush: element => { hadPushRef.current = true; handleChange([...(arrayValue || []), element]); }, handleRemove: function () { let { keepItems = false } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (keepItems) { valueWhileClosingRef.current = arrayValue; } const newArrayValue = (0, _structuredClone.default)(arrayValue); newArrayValue.splice(index, 1); handleChange(newArrayValue); }, fulfillRemove: () => { var _modesRef$current, _isNewRef$current2; valueWhileClosingRef.current = null; (_modesRef$current = modesRef.current) === null || _modesRef$current === void 0 ? true : delete _modesRef$current[id]; (_isNewRef$current2 = isNewRef.current) === null || _isNewRef$current2 === void 0 ? true : delete _isNewRef$current2[id]; const findIndex = idsRef.current.indexOf(id); idsRef.current.splice(findIndex, 1); forceUpdate(); }, restoreOriginalValue: value => { if (value) { const newArrayValue = (0, _structuredClone.default)(arrayValue); 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 ? void 0 : onChange(arrayValue); } else { hadPushRef.current = false; } }, [arrayValue, arrayItems, onChange]); const flexProps = _objectSpread(_objectSpread(_objectSpread({ 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 = arrayValue === emptyValue || (props === null || props === void 0 ? void 0 : (_props$value = props.value) === null || _props$value === void 0 ? void 0 : _props$value.length) === 0 ? typeof placeholder === 'string' ? _react.default.createElement(_elements.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 = _objectSpread(_objectSpread({}, 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(_components.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(_components.Flex.Stack, flexProps, arrayElements); return _react.default.createElement(_react.default.Fragment, null, animate ? _react.default.createElement(_components.HeightAnimation, null, content) : content, _react.default.createElement(_components.FormStatus, { show: Boolean(error || limitWarning), state: !error && limitWarning ? 'warning' : undefined, shellSpace: { top: 0, bottom: 'medium' }, no_animation: false }, (0, _FieldBlock.getMessagesFromError)({ content: error || limitWarning })[0])); } ArrayComponent._supportsSpacingProps = true; var _default = exports.default = ArrayComponent; //# sourceMappingURL=Array.js.map