aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/canvas/savesnap.tsx
blob: a8cacd3ed598d74f8bb5b42bad3bc1f8e3dfb86d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useCallback, useEffect, useState } from "react";
import { debounce, getSnapshot, useEditor } from "tldraw";
import { SaveCanvas } from "@/app/actions/doers";

export function SaveStatus({ id }: { id: string }) {
  const [save, setSave] = useState("saved!");
  const editor = useEditor();

  const debouncedSave = useCallback(
    debounce(async () => {
      const snapshot = getSnapshot(editor.store);
      const bounds = editor.getViewportPageBounds();
      console.log(bounds);

      SaveCanvas({ id, data: JSON.stringify({ snapshot, bounds }) });

      setSave("saved!");
    }, 3000),
    [editor], // Dependency array ensures the function is not recreated on every render
  );

  useEffect(() => {
    const unsubscribe = editor.store.listen(
      () => {
        setSave("saving...");
        debouncedSave();
      },
      { scope: "document", source: "user" },
    );

    return () => unsubscribe(); // Cleanup on unmount
  }, [editor, debouncedSave]);

  return <button>{save}</button>;
}