34 lines
1.3 KiB
TypeScript
34 lines
1.3 KiB
TypeScript
/**
|
|
* Hook for canvas graph state and persistence. Wraps useGraphStateWithHistory
|
|
* with initial graph from project storage (or example) and debounced save.
|
|
* Keeps CanvasPage focused on composition and layout.
|
|
*/
|
|
|
|
import { useEffect, useMemo, useRef } from 'react'
|
|
import { useGraphStateWithHistory } from '@/hooks/useGraphStateWithHistory'
|
|
import { getInitialGraph } from '@/app/canvas/canvasGraphUtils'
|
|
import { saveGraphToStorage, PROJECT_VERSION } from '@/app/pleroma/projectGraphStorage'
|
|
import type { AppNode, AppEdge } from '@/lib/graph/nodeTypes'
|
|
|
|
export type UseCanvasGraphResult = ReturnType<typeof useGraphStateWithHistory>
|
|
|
|
export function useCanvasGraph(projectId: string | undefined): UseCanvasGraphResult {
|
|
const initialGraph = useMemo(() => getInitialGraph(projectId), [projectId])
|
|
const result = useGraphStateWithHistory(initialGraph.nodes, initialGraph.edges)
|
|
const { nodes, edges } = result
|
|
|
|
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
|
useEffect(() => {
|
|
if (!projectId) return
|
|
const save = () => {
|
|
saveGraphToStorage(projectId, { version: PROJECT_VERSION, nodes, edges })
|
|
}
|
|
saveTimeoutRef.current = setTimeout(save, 500)
|
|
return () => {
|
|
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current)
|
|
}
|
|
}, [projectId, nodes, edges])
|
|
|
|
return result
|
|
}
|