30 lines
893 B
TypeScript
30 lines
893 B
TypeScript
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import type { FeatureCollection } from "@/types/geo";
|
|
import { deepClone } from "@/lib/editor/draft/draftDiff";
|
|
|
|
export function useDraftState(initialData: FeatureCollection) {
|
|
const [draft, setDraft] = useState<FeatureCollection>(() => deepClone(initialData));
|
|
const draftRef = useRef<FeatureCollection>(deepClone(initialData));
|
|
|
|
const commitDraft = useCallback((nextDraft: FeatureCollection) => {
|
|
const cloned = deepClone(nextDraft);
|
|
draftRef.current = cloned;
|
|
setDraft(cloned);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
draftRef.current = draft;
|
|
}, [draft]);
|
|
|
|
const resetDraft = useCallback((nextDraft: FeatureCollection) => {
|
|
commitDraft(nextDraft);
|
|
}, [commitDraft]);
|
|
|
|
return {
|
|
draft,
|
|
draftRef,
|
|
commitDraft,
|
|
resetDraft,
|
|
};
|
|
}
|