Skip to content

Implement whiteboard management #3137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions apps/db/supabase/migrations/20250620034755_create_whiteboards.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
create table "public"."workspace_whiteboards" (
"id" uuid not null default gen_random_uuid(),
"title" text not null,
"description" text,
"snapshot" jsonb,
"ws_id" uuid not null,
"created_at" timestamp with time zone not null default now(),
"thumbnail_url" text,
"updated_at" timestamp with time zone not null default now(),
"creator_id" uuid not null
);

alter table "public"."workspace_whiteboards" enable row level security;

CREATE UNIQUE INDEX workspace_whiteboards_pkey ON public.workspace_whiteboards USING btree (id);

alter table "public"."workspace_whiteboards" add constraint "workspace_whiteboards_pkey" PRIMARY KEY using index "workspace_whiteboards_pkey";

alter table "public"."workspace_whiteboards" add constraint "workspace_whiteboards_creator_id_fkey" FOREIGN KEY (creator_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE not valid;

alter table "public"."workspace_whiteboards" validate constraint "workspace_whiteboards_creator_id_fkey";

alter table "public"."workspace_whiteboards" add constraint "workspace_whiteboards_ws_id_fkey" FOREIGN KEY (ws_id) REFERENCES workspaces(id) ON UPDATE CASCADE ON DELETE CASCADE not valid;

alter table "public"."workspace_whiteboards" validate constraint "workspace_whiteboards_ws_id_fkey";

grant delete on table "public"."workspace_whiteboards" to "anon";

grant insert on table "public"."workspace_whiteboards" to "anon";

grant references on table "public"."workspace_whiteboards" to "anon";

grant select on table "public"."workspace_whiteboards" to "anon";

grant trigger on table "public"."workspace_whiteboards" to "anon";

grant truncate on table "public"."workspace_whiteboards" to "anon";

grant update on table "public"."workspace_whiteboards" to "anon";

grant delete on table "public"."workspace_whiteboards" to "authenticated";

grant insert on table "public"."workspace_whiteboards" to "authenticated";

grant references on table "public"."workspace_whiteboards" to "authenticated";

grant select on table "public"."workspace_whiteboards" to "authenticated";

grant trigger on table "public"."workspace_whiteboards" to "authenticated";

grant truncate on table "public"."workspace_whiteboards" to "authenticated";

grant update on table "public"."workspace_whiteboards" to "authenticated";

grant delete on table "public"."workspace_whiteboards" to "service_role";

grant insert on table "public"."workspace_whiteboards" to "service_role";

grant references on table "public"."workspace_whiteboards" to "service_role";

grant select on table "public"."workspace_whiteboards" to "service_role";

grant trigger on table "public"."workspace_whiteboards" to "service_role";

grant truncate on table "public"."workspace_whiteboards" to "service_role";

grant update on table "public"."workspace_whiteboards" to "service_role";

-- Add an index to improve join performance
CREATE INDEX IF NOT EXISTS idx_whiteboards_ws_id ON workspace_whiteboards(ws_id);
CREATE INDEX IF NOT EXISTS idx_whiteboards_creator_id ON workspace_whiteboards(creator_id);

CREATE INDEX idx_whiteboards_snapshot_gin ON public.workspace_whiteboards USING GIN (snapshot);

CREATE POLICY "Workspace members can read and write whiteboards" ON public.workspace_whiteboards
FOR ALL TO authenticated
USING (
ws_id IN (
SELECT ws_id FROM public.workspace_members
WHERE user_id = auth.uid()
)
)
WITH CHECK (
ws_id IN (
SELECT ws_id FROM public.workspace_members
WHERE user_id = auth.uid()
)
);
5 changes: 4 additions & 1 deletion apps/web/messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,10 @@
"whats_the_title": "What's the title?",
"write_something": "Write something",
"error_saving_content": "There was an error saving your content",
"not_completed": "Not completed"
"not_completed": "Not completed",
"whiteboards": "Whiteboards",
"whiteboards_description": "Collaborate and visualize ideas with your team",
"new_whiteboard": "New whiteboard"
},
"date_helper": {
"time-unit": "Time unit",
Expand Down
5 changes: 4 additions & 1 deletion apps/web/messages/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,10 @@
"whats_the_title": "Tiêu đề là gì?",
"write_something": "Hãy viết gì đó...",
"error_saving_content": "Lỗi khi lưu nội dung của bạn",
"not_completed": "Chưa hoàn thành"
"not_completed": "Chưa hoàn thành",
"whiteboards": "Bảng trắng",
"whiteboards_description": "Hợp tác và minh họa ý tưởng với đội của bạn",
"new_whiteboard": "Bảng trắng mới"
},
"date_helper": {
"time-unit": "Đơn vị thời gian",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
'use client';

import Toolbar from './toolbar';

Check warning on line 3 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx#L3

Added line #L3 was not covered by tests
import { LoadingIndicator } from '@tuturuuu/ui/custom/loading-indicator';
import { useTheme } from 'next-themes';
import { useEffect, useState } from 'react';
import { type Editor, Tldraw } from 'tldraw';
import { type Editor, type TLStoreSnapshot, Tldraw } from 'tldraw';

Check warning on line 7 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx#L7

Added line #L7 was not covered by tests
import 'tldraw/tldraw.css';

type Theme = 'system' | 'dark' | 'light';

export function CustomTldraw({ persistenceKey }: { persistenceKey: string }) {
interface CustomTldrawProps {
wsId: string;
boardId: string;
initialData?: TLStoreSnapshot;
}

export function CustomTldraw({
wsId,
boardId,
initialData,
}: CustomTldrawProps) {

Check warning on line 22 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx#L12-L22

Added lines #L12 - L22 were not covered by tests
const { resolvedTheme } = useTheme();
const [editor, setEditor] = useState<Editor | null>(null);

Expand All @@ -28,7 +39,10 @@
)}

<Tldraw
persistenceKey={`ws-${persistenceKey}-tldraw`}
snapshot={initialData}
components={{
SharePanel: () => <Toolbar wsId={wsId} boardId={boardId} />,
}}

Check warning on line 45 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/custom-tldraw.tsx#L42-L45

Added lines #L42 - L45 were not covered by tests
onMount={setEditor}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default function Loading() {
return (
<div className="flex h-full w-full flex-col gap-4 p-4">
<div className="h-10 w-48 animate-pulse rounded-lg bg-foreground/5" />
<div className="h-full w-full animate-pulse rounded-lg bg-foreground/5" />
</div>
);
}

Check warning on line 8 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/loading.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/loading.tsx#L2-L8

Added lines #L2 - L8 were not covered by tests
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { CustomTldraw } from './custom-tldraw';
import { createClient } from '@tuturuuu/supabase/next/server';
import { notFound } from 'next/navigation';
import { TLStoreSnapshot } from 'tldraw';

interface TLDrawPageProps {
params: Promise<{ wsId: string; boardId: string }>;
}

export default async function TLDrawPage({ params }: TLDrawPageProps) {
const { wsId, boardId } = await params;

const supabase = await createClient();

const { data: whiteboard } = await supabase
.from('workspace_whiteboards')
.select('*')
.eq('id', boardId)
.eq('ws_id', wsId)
.single();

if (!whiteboard) return notFound();

return (
<div className="absolute inset-0">
<CustomTldraw
wsId={wsId}
boardId={boardId}
initialData={
whiteboard.snapshot
? (JSON.parse(whiteboard.snapshot as string) as TLStoreSnapshot)
: undefined
}
/>
</div>
);
}

Check warning on line 37 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/page.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/page.tsx#L2-L37

Added lines #L2 - L37 were not covered by tests
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { createClient } from '@tuturuuu/supabase/next/client';
import { Button } from '@tuturuuu/ui/button';
import { useToast } from '@tuturuuu/ui/hooks/use-toast';
import { ArrowLeftIcon } from '@tuturuuu/ui/icons';
import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useEditor } from 'tldraw';

export default function Toolbar({
wsId,
boardId,
}: {
wsId: string;
boardId: string;
}) {
const supabase = createClient();

const editor = useEditor();
const { toast } = useToast();

const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const lastSavedSnapshotRef = useRef<string | null>(null);

// Initialize the last saved snapshot on mount
useEffect(() => {
if (editor && lastSavedSnapshotRef.current === null) {
const currentSnapshot = JSON.stringify(editor.getSnapshot());
lastSavedSnapshotRef.current = currentSnapshot;
}
}, [editor]);

// Listen for changes in the editor
useEffect(() => {
if (!editor) return;

const checkForChanges = () => {
const currentSnapshot = JSON.stringify(editor.getSnapshot());
const hasChanges = currentSnapshot !== lastSavedSnapshotRef.current;
setHasUnsavedChanges(hasChanges);
};

// Check for changes on various editor events
const unsubscribeHistory = editor.store.listen(() => {
checkForChanges();
});

return () => {
unsubscribeHistory();
};
}, [editor]);

const generateThumbnail = async () => {
const shapeIds = editor.getCurrentPageShapeIds();
if (shapeIds.size === 0) {
throw new Error('No shapes on canvas');
}

const { blob } = await editor.toImage([...shapeIds], {
format: 'png',
background: true,
scale: 0.3,
padding: 16,
});

return blob;
};

const generateFileName = (name: string) => {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

return `${year}${month}${day}-${hours}-${minutes}-${seconds}-${name}`;
};

const save = useCallback(async () => {
try {
const thumbnailBlob = await generateThumbnail();
if (!thumbnailBlob) {
throw new Error('Failed to generate thumbnail');
}

const thumbnailFileName = generateFileName(`${boardId}.png`);
const thumbnailFile = new File([thumbnailBlob], thumbnailFileName, {
type: 'image/png',
});

const { error: thumbnailError } = await supabase.storage
.from('workspaces')
.upload(
`${wsId}/whiteboards/${boardId}/${thumbnailFileName}`,
thumbnailFile
);

if (thumbnailError) throw thumbnailError;

const { data: thumbnailUrl } = supabase.storage
.from('workspaces')
.getPublicUrl(`${wsId}/whiteboards/${boardId}/${thumbnailFileName}`);

const snapshot = editor.getSnapshot();

const { error: updateError } = await supabase
.from('workspace_whiteboards')
.update({
snapshot: JSON.stringify(snapshot),
thumbnail_url: thumbnailUrl.publicUrl,
updated_at: new Date().toISOString(),
})
.eq('id', boardId);

if (updateError) throw updateError;

// Update the last saved snapshot reference
lastSavedSnapshotRef.current = JSON.stringify(snapshot);
setHasUnsavedChanges(false);

toast({
title: 'Saved successfully!',
description: 'Your whiteboard has been saved.',
variant: 'default',
});
} catch (error: any) {
console.error(error);
toast({
title: 'Error saving',
description: 'Failed to save whiteboard',
variant: 'destructive',
});
}
}, [editor, boardId, supabase, toast, wsId]);

return (
<div className="pointer-events-auto flex gap-4 p-4">
<Link href={`/${wsId}/whiteboards`}>
<Button variant="ghost">
<ArrowLeftIcon className="h-4 w-4" />
Back
</Button>
</Link>
<Button variant="default" onClick={save} disabled={!hasUnsavedChanges}>
Save Snapshot
</Button>
</div>
);
}

Check warning on line 150 in apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/toolbar.tsx

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/[locale]/(dashboard)/[wsId]/whiteboards/[boardId]/toolbar.tsx#L2-L150

Added lines #L2 - L150 were not covered by tests
Loading