@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
83 lines (82 loc) • 2.31 kB
JavaScript
"use client";
import { useCallback, useContext, useEffect, useRef } from 'react';
import FieldBoundaryContext from "../../DataContext/FieldBoundary/FieldBoundaryContext.js";
import IterateItemContext from "../IterateItemContext.js";
const globalContainerModeRef = {
current: undefined
};
const globalCache = {};
export default function useSwitchContainerMode(path) {
const nextContainerModeRef = useRef();
const {
hasError
} = useContext(FieldBoundaryContext) || {};
const iterateItemContext = useContext(IterateItemContext);
const id = iterateItemContext?.id;
const hash = (path || '') + 'useSwitchContainerMode';
useEffect(() => {
nextContainerModeRef.current = globalContainerModeRef.current;
requestAnimationFrame(() => {
if (nextContainerModeRef.current) {
globalContainerModeRef.current = undefined;
}
});
});
useEffect(() => {
if (hash && iterateItemContext) {
globalCache[hash] = globalCache[hash] || {};
const {
index,
arrayValue,
switchContainerMode
} = iterateItemContext;
globalCache[hash][id] = {
index,
hasError,
count: arrayValue?.length,
switchContainerMode
};
}
return () => {
if (id) {
globalCache[hash][id] = undefined;
}
};
}, [hasError, hash, id, iterateItemContext]);
const setNextContainerMode = useCallback(mode => {
globalContainerModeRef.current = mode;
}, []);
const setContainerMode = useCallback(fn => {
const data = globalCache[hash];
for (const id in data) {
const item = data[id];
const mode = item && fn?.(item);
if (mode) {
item.switchContainerMode(mode, {
omitFocusManagement: true
});
}
}
}, [hash]);
const setLastItemContainerMode = useCallback(mode => {
setContainerMode(({
hasError,
index,
count
}) => {
if (!hasError && index === count - 2) {
return mode;
}
});
}, [setContainerMode]);
const getNextContainerMode = useCallback(() => {
return nextContainerModeRef.current;
}, []);
return {
getNextContainerMode,
nextContainerModeRef,
setNextContainerMode,
setLastItemContainerMode
};
}
//# sourceMappingURL=useSwitchContainerMode.js.map