1"use client";
2
3
13import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
14import { whiteboardApi, type WhiteboardCanvasResponse } from "@/lib/api";
15import type { Canvas } from "@factory/whiteboard";
16
17export const whiteboardKey = (pageId: string) => ["pages", pageId, "whiteboard"] as const;
18
19
20export function useWhiteboardCanvas(pageId: string) {
21 return useQuery({
22 queryKey: whiteboardKey(pageId),
23 queryFn: () => whiteboardApi.get(pageId),
24 enabled: pageId.length > 0
25 });
26}
27
28
29export function useWhiteboardSave(pageId: string) {
30 const qc = useQueryClient();
31 return useMutation({
32 mutationFn: (canvas: Canvas) => whiteboardApi.save(pageId, canvas),
33 onMutate: async (canvas) => {
34
35
36 await qc.cancelQueries({ queryKey: whiteboardKey(pageId) });
37 const prev = qc.getQueryData<WhiteboardCanvasResponse>(whiteboardKey(pageId));
38 if (prev) qc.setQueryData(whiteboardKey(pageId), { ...prev, canvas, updatedAt: prev.updatedAt });
39 return { prev };
40 },
41 onError: (_err, _canvas, ctx) => {
42
43 if (ctx?.prev) qc.setQueryData(whiteboardKey(pageId), ctx.prev);
44 else qc.invalidateQueries({ queryKey: whiteboardKey(pageId) });
45 },
46 onSuccess: (res) => {
47
48
49
50 qc.setQueryData<WhiteboardCanvasResponse>(whiteboardKey(pageId), (prev) =>
51 prev ? { ...prev, updatedAt: res.updatedAt } : prev
52 );
53 }
54 });
55}
56