UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

291 lines (290 loc) 9.95 kB
"use client"; import _extends from "@babel/runtime/helpers/esm/extends"; import React, { useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react'; import classnames from 'classnames'; import Isolation from "../../Form/Isolation/index.js"; import { extractZodSubSchema } from "../../Form/Isolation/extractZodSubSchema.js"; import * as z from 'zod'; import { isZodSchema } from "../../utils/zod.js"; import pointer from "../../utils/json-pointer/index.js"; import useHandleStatus from "../../Form/Isolation/useHandleStatus.js"; import PushContainerContext from "./PushContainerContext.js"; import IterateItemContext from "../IterateItemContext.js"; import DataContext from "../../DataContext/Context.js"; import VisibilityContext from "../../Form/Visibility/VisibilityContext.js"; import useDataValue from "../../hooks/useDataValue.js"; import EditContainer, { DoneButton, CancelButton, ResetButton } from "../EditContainer/index.js"; import IterateArray from "../Array/index.js"; import OpenButton from "./OpenButton.js"; import { Flex, FormStatus, HeightAnimation } from "../../../../components/index.js"; import { useArrayLimit, useItemPath, useSwitchContainerMode } from "../hooks/index.js"; import Toolbar from "../Toolbar/index.js"; import { usePath, useTranslation } from "../../hooks/index.js"; import { clearedData } from "../../DataContext/Provider/index.js"; import { structuredClone } from "../../../../shared/helpers/structuredClone.js"; function PushContainer(props) { const [, forceUpdate] = useReducer(() => ({}), {}); const outerContext = useContext(DataContext); const { data: outerData, required: requiredInherited } = outerContext; const { data: dataProp, defaultData: defaultDataProp, isolatedData, bubbleValidation, preventUncommittedChanges = props?.requireCommit, requireCommit, dataReference, showResetButton, path, itemPath, insertAt, title, required = requiredInherited, children, openButton, showOpenButtonWhen, onCommit, ...rest } = props; const { absolutePath } = useItemPath(itemPath); const { path: relativePath } = usePath({ path, itemPath }); const commitHandleRef = useRef(); const switchContainerModeRef = useRef(); const containerModeRef = useRef(); const { value: entries = [], moveValueToPath, getValueByPath } = useDataValue(path || itemPath); const { setNextContainerMode } = useSwitchContainerMode(path || absolutePath); const { hasReachedLimit, setShowStatus } = useArrayLimit(path || absolutePath); const cancelHandler = useCallback(() => { if (hasReachedLimit) { setShowStatus(false); } }, [hasReachedLimit, setShowStatus]); const showOpenButton = showOpenButtonWhen?.(entries); const newItemContextProps = { path, itemPath, entries, commitHandleRef, switchContainerMode: switchContainerModeRef.current }; const data = useMemo(() => { var _Object$freeze; if (defaultDataProp) { return; } return { ...isolatedData, pushContainerItems: [(_Object$freeze = Object.freeze(dataProp)) !== null && _Object$freeze !== void 0 ? _Object$freeze : clearedData] }; }, [dataProp, defaultDataProp, isolatedData]); if (outerData) { if (!Object.isFrozen(data)) { Object.assign(data || {}, outerData); } } const defaultData = useMemo(() => { return { ...(!dataProp ? isolatedData : null), pushContainerItems: [Object.freeze(defaultDataProp !== null && defaultDataProp !== void 0 ? defaultDataProp : clearedData)] }; }, [dataProp, defaultDataProp, isolatedData]); const emptyData = useCallback(data => { var _ref; const firstItem = data.pushContainerItems?.[0]; if (firstItem === null || typeof firstItem !== 'object') { return { ...isolatedData, pushContainerItems: [null] }; } return { ...isolatedData, pushContainerItems: [(_ref = dataProp !== null && dataProp !== void 0 ? dataProp : defaultDataProp) !== null && _ref !== void 0 ? _ref : clearedData] }; }, [dataProp, defaultDataProp, isolatedData]); const isolationSchema = useMemo(() => { const parentSchema = outerContext?.props?.schema; const targetPath = absolutePath || relativePath; if (!parentSchema || !targetPath) { return; } if (isZodSchema(parentSchema)) { const element = extractZodSubSchema(parentSchema, `${targetPath}/0`); return z.object({ pushContainerItems: z.array(element) }); } else { const segments = String(targetPath).split('/').filter(Boolean); const schemaPointer = `/properties/${segments.join('/properties/')}/items`; const itemsSchema = pointer.has(parentSchema, schemaPointer) ? pointer.get(parentSchema, schemaPointer) : undefined; if (!itemsSchema) { return; } return { type: 'object', properties: { pushContainerItems: { type: 'array', items: itemsSchema } } }; } }, [outerContext?.props?.schema, absolutePath, relativePath]); return React.createElement(Isolation, { data: data, defaultData: defaultData, required: required, dataReference: dataReference, emptyData: emptyData, bubbleValidation: containerModeRef.current === 'view' ? false : bubbleValidation, commitHandleRef: commitHandleRef, schema: isolationSchema, transformOnCommit: ({ pushContainerItems }) => { return moveValueToPath(absolutePath || relativePath, typeof insertAt === 'number' ? [...entries.slice(0, insertAt), ...pushContainerItems, ...entries.slice(insertAt)] : [...entries, ...pushContainerItems], absolutePath ? structuredClone(getValueByPath('/')) : {}); }, onCommit: (data, options) => { const { clearData, preventCommit } = options; if (hasReachedLimit) { preventCommit(); setShowStatus(true); } else { setNextContainerMode('view'); switchContainerModeRef.current?.('view'); clearData(); } onCommit?.(data, options); } }, React.createElement(PushContainerContext.Provider, { value: newItemContextProps }, React.createElement(IterateArray, { path: "/pushContainerItems", containerMode: showOpenButton ? 'view' : 'edit', withoutFlex: true, omitSectionPath: true }, React.createElement(NewContainer, _extends({ title: title, openButton: openButton, switchContainerModeRef: switchContainerModeRef, showOpenButton: showOpenButton, cancelHandler: cancelHandler, containerModeRef: containerModeRef, rerenderPushContainer: forceUpdate, preventUncommittedChanges: preventUncommittedChanges, showResetButton: showResetButton, outerContext: outerContext, required: required }, rest), children)))); } function NewContainer({ title, openButton, showOpenButton, showResetButton, switchContainerModeRef, cancelHandler, containerModeRef, rerenderPushContainer, preventUncommittedChanges, outerContext, required, children, ...rest }) { var _DoneButton, _CancelButton, _FormStatus; const { containerMode, switchContainerMode } = useContext(IterateItemContext) || {}; containerModeRef.current = containerMode; const { hasContentChanged, showStatus } = useHandleStatus({ outerContext, preventUncommittedChanges, error: pushContainerError, name: 'push-container' }); useEffect(() => { rerenderPushContainer(); }, [containerMode, rerenderPushContainer]); const visibilityContext = useContext(VisibilityContext); switchContainerModeRef.current = switchContainerMode; const isVisible = visibilityContext?.isVisible === false ? false : Boolean(!showOpenButton || containerMode === 'edit' || (required || hasContentChanged) && showStatus); const { preventUncommittedChangesText } = useTranslation().Isolation; const { createButton } = useTranslation().IteratePushContainer; const { clearData } = useContext(DataContext) || {}; const restoreOriginalValue = useCallback(() => { clearData?.(); }, [clearData]); const toolbar = React.createElement(Toolbar, null, React.createElement(IterateItemContext.Consumer, null, context => { const newItemContextProps = { ...context, restoreOriginalValue }; return React.createElement(IterateItemContext.Provider, { value: newItemContextProps }, React.createElement(Flex.Horizontal, { gap: "large" }, _DoneButton || (_DoneButton = React.createElement(DoneButton, { text: createButton })), showOpenButton && (_CancelButton || (_CancelButton = React.createElement(CancelButton, { onClick: cancelHandler }))), (preventUncommittedChanges || showResetButton) && React.createElement(ResetButton, { hidden: !(showResetButton || showStatus) })), preventUncommittedChanges && showStatus && (_FormStatus || (_FormStatus = React.createElement(FormStatus, { no_animation: false, show: hasContentChanged }, preventUncommittedChangesText)))); })); return React.createElement(VisibilityContext.Provider, { value: { isVisible, keepInDOM: false } }, React.createElement(EditContainer, _extends({ open: isVisible, title: title, toolbar: toolbar }, rest, { className: classnames('dnb-forms-section-block--error', rest.className) }), children), openButton && typeof showOpenButton === 'boolean' && React.createElement(HeightAnimation, { open: showOpenButton && containerMode === 'view' }, openButton)); } const pushContainerError = new Error('Iterate.PushContainer'); PushContainer.OpenButton = OpenButton; PushContainer._supportsSpacingProps = true; export default PushContainer; //# sourceMappingURL=PushContainer.js.map