UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

73 lines (72 loc) 2.68 kB
"use client"; import { useCallback, useRef } from 'react'; import { makeUniqueId } from '../../../shared/component-helper'; import pointer from '../utils/json-pointer'; import useDataContext from './useDataContext'; import useData from '../Form/data-context/useData'; export default function useSnapshot(id) { const internalSnapshotsRef = useRef(); if (!internalSnapshotsRef.current) { internalSnapshotsRef.current = new Map(); } const { getContext } = useDataContext(id); const { set: setData, update: updateData } = useData(id); const createSnapshot = useCallback((id = makeUniqueId(), name = null, content = null) => { const { internalDataRef, snapshotsRef } = getContext(); if (!content) { var _snapshotsRef$current, _snapshotsRef$current2; const snapshotWithPaths = snapshotsRef === null || snapshotsRef === void 0 ? void 0 : (_snapshotsRef$current = snapshotsRef.current) === null || _snapshotsRef$current === void 0 ? void 0 : (_snapshotsRef$current2 = _snapshotsRef$current.get) === null || _snapshotsRef$current2 === void 0 ? void 0 : _snapshotsRef$current2.call(_snapshotsRef$current, name); if (snapshotWithPaths) { const collectedData = new Map(); snapshotWithPaths.forEach((isMounted, path) => { if (isMounted && pointer.has(internalDataRef.current, path)) { collectedData.set(path, pointer.get(internalDataRef.current, path)); } }); content = collectedData; } else { content = internalDataRef.current; } } internalSnapshotsRef.current.set(combineIdWithName(id, name), content); return id; }, [getContext]); const getSnapshot = useCallback((id, name = null) => { return internalSnapshotsRef.current.get(combineIdWithName(id, name)); }, []); const deleteSnapshot = useCallback((id, name = null) => { internalSnapshotsRef.current.delete(combineIdWithName(id, name)); }, []); const applySnapshot = useCallback((id, name = null) => { const snapshot = getSnapshot(id, name); if (snapshot instanceof Map) { snapshot.forEach((value, path) => { updateData(path, value); }); } else if (snapshot) { setData(snapshot); } }, [getSnapshot, setData, updateData]); const revertSnapshot = useCallback((id, name = null) => { applySnapshot(id, name); deleteSnapshot(id, name); }, [applySnapshot, deleteSnapshot]); return { createSnapshot, revertSnapshot, applySnapshot, internalSnapshotsRef }; } function combineIdWithName(id, name = null) { return name ? `${id}-${name}` : id; } //# sourceMappingURL=useSnapshot.js.map