1"use client";
2
3
13import { useCallback, useEffect, useRef } from "react";
14import { useQueryClient } from "@tanstack/react-query";
15import { blockApi, isApiError } from "@/lib/api";
16import { getBlockBatchQueue } from "@/lib/batch-queue";
17
18export function useBlockSaveQueue(pageId: string) {
19 const qc = useQueryClient();
20 const pageIdRef = useRef(pageId);
21 pageIdRef.current = pageId;
22
23 const invalidate = useCallback(
24 (pid: string) => qc.invalidateQueries({ queryKey: ["pages", pid, "blocks"] }),
25 [qc]
26 );
27
28 const queueChange = useCallback(
29 (blockId: string, content: unknown) => {
30 const id = pageIdRef.current;
31 if (!id) return;
32 getBlockBatchQueue(id).queue({ op: "update", blockId, patch: { content } });
33 },
34 []
35 );
36
37 const saveNow = useCallback(
38 async (blockId: string, content: unknown) => {
39 const id = pageIdRef.current;
40 if (!id) return;
41 try {
42 await blockApi.update(blockId, { content });
43 invalidate(id);
44 } catch (err) {
45
46
47
48
49
50 if (isApiError(err) && err.status === 404) return;
51
52 getBlockBatchQueue(id).queue({ op: "update", blockId, patch: { content } });
53 }
54 },
55 [invalidate]
56 );
57
58
59 useEffect(() => {
60 const id = pageIdRef.current;
61 return () => {
62 if (!id) return;
63 void getBlockBatchQueue(id).flush().then(() => invalidate(id));
64 };
65
66 }, [pageId]);
67
68
69
70
71 return { queueChange, saveNow, invalidate };
72}
73