UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

302 lines (301 loc) 12.5 kB
"use client"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; 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; } import React, { useMemo, useRef, useEffect, useReducer, createRef, useContext, useCallback } from 'react'; import classnames from 'classnames'; import pointer from '../../utils/json-pointer'; import { useFieldProps } from '../../hooks'; import { makeUniqueId } from '../../../../shared/component-helper'; import { Flex, FormStatus, HeightAnimation } from '../../../../components'; import { Span } from '../../../../elements'; import { pickSpacingProps } from '../../../../components/flex/utils'; import useMountEffect from '../../../../shared/helpers/useMountEffect'; import useUpdateEffect from '../../../../shared/helpers/useUpdateEffect'; import { pickFlexContainerProps } from '../../../../components/flex/Container'; import IterateItemContext from '../IterateItemContext'; import SummaryListContext from '../../Value/SummaryList/SummaryListContext'; import ValueBlockContext from '../../ValueBlock/ValueBlockContext'; import FieldBoundaryProvider from '../../DataContext/FieldBoundary/FieldBoundaryProvider'; import DataContext from '../../DataContext/Context'; import useDataValue from '../../hooks/useDataValue'; import { useArrayLimit, useItemPath, useSwitchContainerMode } from '../hooks'; import { getMessagesFromError } from '../../FieldBlock'; import structuredClone from '@ungap/structured-clone'; function ArrayComponent(props) { var _props$value; const [salt, forceUpdate] = useReducer(() => ({}), {}); const { path: pathProp, itemPath: itemPathProp, reverse, countPath, countPathTransform, countPathLimit = Infinity } = props || {}; const dataContext = useContext(DataContext); const summaryListContext = useContext(SummaryListContext); const valueBlockContext = useContext(ValueBlockContext); const { absolutePath } = useItemPath(itemPathProp); const { setLimitProps, error: limitWarning } = useArrayLimit(pathProp || absolutePath); const { getValueByPath } = useDataValue(); const getCountValue = 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 = useCallback((value, { emptyValue, required, error }) => { if (required && (!value || (value === null || value === void 0 ? void 0 : value.length) === 0 || value === emptyValue)) { return error; } }, []); const preparedProps = 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 } = useFieldProps(preparedProps, { updateContextDataInSync: true, omitMultiplePathWarning: true, forceUpdateWhenContextDataIsSet: Boolean(countPath) }); const countValueRef = useRef(); useUpdateEffect(() => { if (countPath) { if (typeof countValueRef.current === 'number' && countValue !== countValueRef.current) { window.requestAnimationFrame(() => { dataContext.handlePathChange(path, getValueByPath(path)); }); } countValueRef.current = countValue; } }, [countValue]); useEffect(() => { valueCountRef.current = arrayValue || []; }, [arrayValue]); const idsRef = useRef([]); const isNewRef = useRef({}); const modesRef = useRef({}); const valueWhileClosingRef = useRef(); const valueCountRef = useRef(arrayValue); const containerRef = useRef(); const hadPushRef = useRef(); const innerRefs = useRef({}); const omitFlex = withoutFlex !== null && withoutFlex !== void 0 ? withoutFlex : summaryListContext || valueBlockContext; const { getNextContainerMode } = useSwitchContainerMode(); const arrayItems = useMemo(() => { var _ref; const list = (_ref = valueWhileClosingRef.current || arrayValue) !== null && _ref !== void 0 ? _ref : []; 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] || 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: (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 ? true : delete _isNewRef$current[id]; if ((options === null || options === void 0 ? void 0 : options.preventUpdate) !== true) { forceUpdate(); } }, handleChange: (path, value) => { const newArrayValue = structuredClone(arrayValue); newArrayValue[index] = _objectSpread({}, newArrayValue[index]); pointer.set(newArrayValue, path, value); handleChange(newArrayValue); }, handlePush: element => { hadPushRef.current = true; handleChange([...(arrayValue || []), element]); }, handleRemove: ({ keepItems = false } = {}) => { if (keepItems) { valueWhileClosingRef.current = arrayValue; } const newArrayValue = structuredClone(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 = structuredClone(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; useEffect(() => { if (limit) { setLimitProps({ limit, total }); } }, [total, limit, setLimitProps]); useUpdateEffect(() => { validateValue(); }, [total, validateValue]); useMountEffect(() => { setChanged(true); }); 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: classnames("dnb-forms-iterate dnb-forms-section", props === null || props === void 0 ? void 0 : props.className) }, pickFlexContainerProps(props)), 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.createElement(Span, { size: "small" }, placeholder) : placeholder : arrayItems.map(itemProps => { const { id, value, index } = itemProps; const elementRef = innerRefs.current[id] = innerRefs.current[id] || 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.createElement(IterateItemContext.Provider, { key: `element-${id}`, value: contextValue }, React.createElement(FieldBoundaryProvider, null, content)); } return React.createElement(Flex.Item, { className: "dnb-forms-iterate__element", tabIndex: -1, innerRef: elementRef, key: `element-${id}` }, React.createElement(IterateItemContext.Provider, { value: contextValue }, React.createElement(FieldBoundaryProvider, null, content))); }); const content = omitFlex ? arrayElements : React.createElement(Flex.Stack, flexProps, arrayElements); return React.createElement(React.Fragment, null, animate ? React.createElement(HeightAnimation, null, content) : content, React.createElement(FormStatus, { show: Boolean(error || limitWarning), state: !error && limitWarning ? 'warning' : undefined, shellSpace: { top: 0, bottom: 'medium' }, no_animation: false }, getMessagesFromError({ content: error || limitWarning })[0])); } ArrayComponent._supportsSpacingProps = true; export default ArrayComponent; //# sourceMappingURL=Array.js.map