UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

397 lines (396 loc) 16 kB
"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 = require("react"); var z = _interopRequireWildcard(require("zod")); var _clsx = require("clsx"); 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"); var _withComponentMarkers = _interopRequireDefault(require("../../../../shared/helpers/withComponentMarkers.js")); var _jsxRuntime = require("react/jsx-runtime"); 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 { value: countPathValue, getValueByPath } = (0, _useDataValue.default)(countPath); const { value: contextArrayValue } = (0, _useDataValue.default)(countPath ? pathProp : undefined); const countValue = (0, _react.useMemo)(() => { if (!countPath) { return -1; } let countValue = parseFloat(countPathValue); if (!(countValue >= 0)) { countValue = 0; } if (countValue > countPathLimit) { countValue = countPathLimit; } return countValue; }, [countPath, countPathLimit, countPathValue]); const validateRequired = (0, _react.useCallback)((value, { emptyValue, required, error }) => { if (required && (!value || 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 = contextArrayValue; const newValue = []; for (let i = 0, l = countValue; i < l; i++) { const value = arrayValue?.[i]; (0, _push.default)(newValue).call(newValue, countPathTransform ? countPathTransform({ value, index: i }) : value); } return { ...shared, value: newValue }; } return { ...shared }; }, [contextArrayValue, countPath, countPathTransform, countValue, 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, getExternalValueSnapshot: getArrayShapeSnapshot }); (0, _useMountEffect.default)(() => { if (path && dataContext?.internalDataRef?.current && props.defaultValue !== undefined) { const currentValue = _index.default.has(dataContext.internalDataRef.current, path) ? _index.default.get(dataContext.internalDataRef.current, path) : undefined; if (!Array.isArray(currentValue)) { dataContext.updateDataValue?.(path, arrayValue); } } }); const countValueRef = (0, _react.useRef)(undefined); (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 restoreValueCountRef = (0, _react.useRef)({}); const valueCountRef = (0, _react.useRef)(arrayValue); const arrayValueRef = (0, _react.useRef)(arrayValue); const containerRef = (0, _react.useRef)(undefined); const hadPushRef = (0, _react.useRef)(undefined); const elementRefs = (0, _react.useRef)({}); const omitFlex = withoutFlex !== null && withoutFlex !== void 0 ? withoutFlex : Boolean(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) => { const id = idsRef.current[index] || (0, _componentHelper.makeUniqueId)(); const hasNewItems = arrayValue?.length > valueCountRef.current?.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]?.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, restoreValueCount: restoreValueCountRef.current[id] || 0, nestedIteratePath: absolutePath, switchContainerMode: (mode, options = {}) => { modesRef.current[id].previous = modesRef.current[id].current; modesRef.current[id].current = mode; modesRef.current[id].options = options; delete isNewRef.current?.[id]; if (options?.preventUpdate !== true) { forceUpdate(); } }, handleChange: (path, value) => { const newArrayValue = [...(arrayValueRef.current || [])]; const currentItemValue = newArrayValue[index]; newArrayValue[index] = currentItemValue && typeof currentItemValue === 'object' ? (0, _structuredClone.structuredClone)(currentItemValue) : {}; _index.default.set(newArrayValue, path, value); arrayValueRef.current = newArrayValue; handleChange(newArrayValue, undefined, { preventUpdate: true }); }, handlePush: element => { hadPushRef.current = true; handleChange([...(arrayValueRef.current || []), element]); }, handleRemove: ({ keepItems = false } = {}) => { if (keepItems) { return; } itemContext.fulfillRemove(); }, fulfillRemove: () => { const newArrayValue = (0, _structuredClone.structuredClone)(arrayValueRef.current || []); newArrayValue.splice(index, 1); handleChange(newArrayValue.length === 0 ? _useFieldProps.clearedArray : newArrayValue); delete modesRef.current?.[id]; delete isNewRef.current?.[id]; delete restoreValueCountRef.current?.[id]; const findIndex = idsRef.current.indexOf(id); idsRef.current.splice(findIndex, 1); forceUpdate(); }, restoreOriginalValue: (...args) => { if (args.length > 0) { const [value] = args; const newArrayValue = (0, _structuredClone.structuredClone)(arrayValueRef.current || []); newArrayValue[index] = value; arrayValueRef.current = newArrayValue; restoreValueCountRef.current[id] = (restoreValueCountRef.current[id] || 0) + 1; const restorePath = `${path && path !== '/' ? path : ''}/${index}`; dataContext?.handlePathChangeUnvalidated?.(restorePath, value, { preventUpdate: true }); handleChange(newArrayValue); forceUpdate(); } } }; 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?.[arrayItems.length - 1]; if (last?.isNew && !hadPushRef.current) { onChange?.(arrayValue); } else { hadPushRef.current = false; } }, [arrayValue, arrayItems, onChange]); const flexProps = { className: (0, _clsx.clsx)('dnb-forms-iterate', 'dnb-forms-section', props?.className), ...(0, _Container.pickFlexContainerProps)(props), ...(0, _utils.pickSpacingProps)(props), id: props?.id, ref: containerRef }; const arrayElements = total === 0 ? typeof placeholder === 'string' ? (0, _jsxRuntime.jsx)(_index4.Span, { size: "small", children: placeholder }) : placeholder : arrayItems.map(itemProps => { const { id } = itemProps; const elementRef = elementRefs.current[id] = elementRefs.current[id] || { current: null }; const element = (0, _jsxRuntime.jsx)(ArrayElement, { itemProps: itemProps, elementRef: elementRef, arrayItems: arrayItems, omitFlex: omitFlex, children: children }, omitFlex ? `element-${id}` : undefined); if (omitFlex) { return element; } return (0, _jsxRuntime.jsx)(_index3.Flex.Item, { className: "dnb-forms-iterate__element", tabIndex: -1, ref: elementRef, children: element }, `element-${id}`); }); const content = omitFlex ? arrayElements : (0, _jsxRuntime.jsx)(_index3.Flex.Stack, { ...flexProps, children: arrayElements }); return (0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, { children: [animate ? (0, _jsxRuntime.jsx)(_index3.HeightAnimation, { children: content }) : content, (0, _jsxRuntime.jsx)(_index3.FormStatus, { show: Boolean(error || limitWarning), state: !error && limitWarning ? 'warning' : undefined, shellSpace: { top: 0, bottom: 'medium' }, noAnimation: false, children: (0, _index6.getMessagesFromError)({ content: error || limitWarning })[0] })] }); } (0, _withComponentMarkers.default)(ArrayComponent, { _supportsSpacingProps: true }); var _default = exports.default = ArrayComponent; const ArrayElement = (0, _react.memo)(function ArrayElement({ itemProps, elementRef, arrayItems, children }) { const { value, index } = itemProps; 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); return (0, _jsxRuntime.jsx)(_IterateItemContext.default, { value: contextValue, children: (0, _jsxRuntime.jsx)(_FieldBoundaryProvider.default, { children: content }) }); }, shouldKeepArrayElement); function shouldKeepArrayElement(previous, next) { return previous.children === next.children && previous.elementRef === next.elementRef && previous.omitFlex === next.omitFlex && previous.itemProps.id === next.itemProps.id && previous.itemProps.index === next.itemProps.index && previous.itemProps.path === next.itemProps.path && previous.itemProps.itemPath === next.itemProps.itemPath && previous.itemProps.value === next.itemProps.value && previous.itemProps.arrayValue?.length === next.itemProps.arrayValue?.length && previous.itemProps.isNew === next.itemProps.isNew && previous.itemProps.containerMode === next.itemProps.containerMode && previous.itemProps.previousContainerMode === next.itemProps.previousContainerMode && previous.itemProps.initialContainerMode === next.itemProps.initialContainerMode && previous.itemProps.restoreValueCount === next.itemProps.restoreValueCount && previous.itemProps.modeOptions === next.itemProps.modeOptions; } function getArrayShapeSnapshot(value) { return Array.isArray(value) ? value.length : value; } //# sourceMappingURL=Array.js.map