UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

390 lines (389 loc) 14.2 kB
"use client"; import _pushInstanceProperty from "core-js-pure/stable/instance/push.js"; import { memo, useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react'; import * as z from 'zod'; import { clsx } from 'clsx'; import pointer from "../../utils/json-pointer/index.js"; import { useFieldProps } from "../../hooks/index.js"; import { makeUniqueId } from "../../../../shared/component-helper.js"; import { Flex, FormStatus, HeightAnimation } from "../../../../components/index.js"; import { Span } from "../../../../elements/index.js"; import { pickSpacingProps } from "../../../../components/flex/utils.js"; import useMountEffect from "../../../../shared/helpers/useMountEffect.js"; import useUpdateEffect from "../../../../shared/helpers/useUpdateEffect.js"; import { pickFlexContainerProps } from "../../../../components/flex/Container.js"; import IterateItemContext from "../IterateItemContext.js"; import SummaryListContext from "../../Value/SummaryList/SummaryListContext.js"; import ValueBlockContext from "../../ValueBlock/ValueBlockContext.js"; import FieldBoundaryProvider from "../../DataContext/FieldBoundary/FieldBoundaryProvider.js"; import DataContext from "../../DataContext/Context.js"; import useDataValue from "../../hooks/useDataValue.js"; import { useArrayLimit, useItemPath, useSwitchContainerMode } from "../hooks/index.js"; import { getMessagesFromError } from "../../FieldBlock/index.js"; import { clearedArray } from "../../hooks/useFieldProps.js"; import { structuredClone } from "../../../../shared/helpers/structuredClone.js"; import withComponentMarkers from "../../../../shared/helpers/withComponentMarkers.js"; import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime"; function ArrayComponent(props) { const [salt, forceUpdate] = useReducer(() => ({}), {}); const { path: pathProp, itemPath: itemPathProp, reverse, countPath, countPathTransform, countPathLimit = Infinity, omitSectionPath } = 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 { value: countPathValue, getValueByPath } = useDataValue(countPath); const { value: contextArrayValue } = useDataValue(countPath ? pathProp : undefined); const countValue = 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 = useCallback((value, { emptyValue, required, error }) => { if (required && (!value || value?.length === 0 || value === emptyValue)) { return error; } }, []); const preparedProps = 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]; _pushInstanceProperty(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 } = useFieldProps(preparedProps, { updateContextDataInSync: true, omitMultiplePathWarning: true, forceUpdateWhenContextDataIsSet: Boolean(countPath), omitSectionPath, getExternalValueSnapshot: getArrayShapeSnapshot }); useMountEffect(() => { if (path && dataContext?.internalDataRef?.current && props.defaultValue !== undefined) { const currentValue = pointer.has(dataContext.internalDataRef.current, path) ? pointer.get(dataContext.internalDataRef.current, path) : undefined; if (!Array.isArray(currentValue)) { dataContext.updateDataValue?.(path, arrayValue); } } }); const countValueRef = useRef(undefined); useUpdateEffect(() => { if (countPath) { if (typeof countValueRef.current === 'number' && countValue !== countValueRef.current) { window.requestAnimationFrame(() => { dataContext.handlePathChange(path, getValueByPath(path)); }); } countValueRef.current = countValue; } }, [countValue]); const idsRef = useRef([]); const isNewRef = useRef({}); const modesRef = useRef({}); const restoreValueCountRef = useRef({}); const valueCountRef = useRef(arrayValue); const arrayValueRef = useRef(arrayValue); const containerRef = useRef(undefined); const hadPushRef = useRef(undefined); const elementRefs = useRef({}); const omitFlex = withoutFlex !== null && withoutFlex !== void 0 ? withoutFlex : Boolean(summaryListContext || valueBlockContext); const { getNextContainerMode } = useSwitchContainerMode(); useEffect(() => { valueCountRef.current = arrayValue || []; arrayValueRef.current = arrayValue || []; }, [arrayValue]); const arrayItems = 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] || makeUniqueId(); const hasNewItems = arrayValue?.length > valueCountRef.current?.length; if (!idsRef.current[index]) { var _context; isNewRef.current[id] = hasNewItems; _pushInstanceProperty(_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' ? structuredClone(currentItemValue) : {}; pointer.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 = structuredClone(arrayValueRef.current || []); newArrayValue.splice(index, 1); handleChange(newArrayValue.length === 0 ? 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 = 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; useEffect(() => { if (limit) { setLimitProps({ limit, total }); } }, [total, limit, setLimitProps]); useUpdateEffect(() => { validateValue(); }, [total, validateValue]); useMountEffect(() => { setChanged(true); }); useMemo(() => { const last = arrayItems?.[arrayItems.length - 1]; if (last?.isNew && !hadPushRef.current) { onChange?.(arrayValue); } else { hadPushRef.current = false; } }, [arrayValue, arrayItems, onChange]); const flexProps = { className: clsx('dnb-forms-iterate', 'dnb-forms-section', props?.className), ...pickFlexContainerProps(props), ...pickSpacingProps(props), id: props?.id, ref: containerRef }; const arrayElements = total === 0 ? typeof placeholder === 'string' ? _jsx(Span, { size: "small", children: placeholder }) : placeholder : arrayItems.map(itemProps => { const { id } = itemProps; const elementRef = elementRefs.current[id] = elementRefs.current[id] || { current: null }; const element = _jsx(ArrayElement, { itemProps: itemProps, elementRef: elementRef, arrayItems: arrayItems, omitFlex: omitFlex, children: children }, omitFlex ? `element-${id}` : undefined); if (omitFlex) { return element; } return _jsx(Flex.Item, { className: "dnb-forms-iterate__element", tabIndex: -1, ref: elementRef, children: element }, `element-${id}`); }); const content = omitFlex ? arrayElements : _jsx(Flex.Stack, { ...flexProps, children: arrayElements }); return _jsxs(_Fragment, { children: [animate ? _jsx(HeightAnimation, { children: content }) : content, _jsx(FormStatus, { show: Boolean(error || limitWarning), state: !error && limitWarning ? 'warning' : undefined, shellSpace: { top: 0, bottom: 'medium' }, noAnimation: false, children: getMessagesFromError({ content: error || limitWarning })[0] })] }); } withComponentMarkers(ArrayComponent, { _supportsSpacingProps: true }); export default ArrayComponent; const ArrayElement = 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 _jsx(IterateItemContext, { value: contextValue, children: _jsx(FieldBoundaryProvider, { 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