feat(workspace): integrate persisted canvas, element editing and session renewal
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { api } from "@/lib/api";
|
||||
import { canvasFingerprint, canvasPath, CanvasSync, type CanvasSnapshot, type SyncState } from "@/lib/canvas-sync";
|
||||
import { decodeCanvas, type CanvasDocument } from "@/lib/canvas";
|
||||
|
||||
export function useCanvasPersistence(document: CanvasDocument, workspace: string, board: string, key: string, snapshot: CanvasSnapshot | undefined, paused: boolean) {
|
||||
const [sync, setSync] = useState<SyncState>({ status: "saved", version: snapshot?.version || 1 });
|
||||
const alive = useRef(false);
|
||||
const latest = useRef(document); latest.current = document;
|
||||
const pausedRef = useRef(paused); pausedRef.current = paused;
|
||||
const [writer] = useState(() => snapshot ? new CanvasSync(api, canvasPath(workspace, board), snapshot, (next) => {
|
||||
if (alive.current) { setSync(next); backup(); }
|
||||
}) : null);
|
||||
function backup() {
|
||||
if (pausedRef.current) return;
|
||||
try {
|
||||
const current = latest.current;
|
||||
localStorage.setItem(key + ":recovery", JSON.stringify({ document: decodeCanvas(JSON.stringify(current)), baseVersion: writer?.version || 1, dirty: writer ? canvasFingerprint(current) !== writer.saved : false }));
|
||||
} catch { /* Storage failure is surfaced by the effect below. */ }
|
||||
}
|
||||
useEffect(() => {
|
||||
if (paused) return;
|
||||
const local = setTimeout(() => {
|
||||
try { localStorage.setItem(key + ":recovery", JSON.stringify({ document: decodeCanvas(JSON.stringify(latest.current)), baseVersion: writer?.version || 1, dirty: writer ? canvasFingerprint(latest.current) !== writer.saved : false })); }
|
||||
catch { setSync({ status: "error", version: writer?.version || 1, error: "local_backup_failed" }); }
|
||||
}, 250);
|
||||
const remote = writer ? setTimeout(() => void writer.enqueue(latest.current), 800) : null;
|
||||
return () => { clearTimeout(local); if (remote) clearTimeout(remote); };
|
||||
}, [document, writer, key, paused]);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
const flush = () => backup();
|
||||
window.addEventListener("pagehide", flush);
|
||||
return () => { window.removeEventListener("pagehide", flush); backup(); alive.current = false; };
|
||||
// Writer and key are stable for this board's mounted editor.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [writer, key]);
|
||||
return { ...sync, retry: () => { backup(); return writer?.retry(); } };
|
||||
}
|
||||
Reference in New Issue
Block a user