@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
75 lines (74 loc) • 2.48 kB
JavaScript
"use client";
import { useCallback, useMemo, useRef } from 'react';
import { makeUniqueId } from "../../../shared/component-helper.js";
import pointer from "../utils/json-pointer/index.js";
import useDataContext from "./useDataContext.js";
import useData from "../Form/data-context/useData.js";
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 {
internalDataRef,
snapshotsRef
} = getContext() || {};
const internalData = internalDataRef?.current;
const createSnapshot = useCallback((id = makeUniqueId(), name = null, content = null) => {
if (!content) {
const snapshotWithPaths = snapshotsRef?.current?.get?.(name);
if (snapshotWithPaths) {
const collectedData = new Map();
snapshotWithPaths.forEach((isMounted, path) => {
if (isMounted && pointer.has(internalData, path)) {
collectedData.set(path, pointer.get(internalData, path));
}
});
content = collectedData;
} else {
content = internalData;
}
}
internalSnapshotsRef.current.set(combineIdWithName(id, name), content);
return id;
}, [internalData, snapshotsRef]);
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 useMemo(() => {
return {
createSnapshot,
revertSnapshot,
applySnapshot,
internalSnapshotsRef
};
}, [applySnapshot, createSnapshot, revertSnapshot]);
}
function combineIdWithName(id, name = null) {
return name ? `${id}-${name}` : id;
}
//# sourceMappingURL=useSnapshot.js.map