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 8 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
69 changes: 69 additions & 0 deletions apps/db/supabase/migrations/20250620034755_create_whiteboards.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
create table "public"."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"."whiteboards" enable row level security;

CREATE UNIQUE INDEX whiteboards_pkey ON public.whiteboards USING btree (id);

alter table "public"."whiteboards" add constraint "whiteboards_pkey" PRIMARY KEY using index "whiteboards_pkey";

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

alter table "public"."whiteboards" validate constraint "whiteboards_creator_id_fkey";

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

alter table "public"."whiteboards" validate constraint "whiteboards_ws_id_fkey";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


20 changes: 20 additions & 0 deletions apps/db/supabase/migrations/20250620034855_add_whiteboards_rls.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
-- Add an index to improve join performance
CREATE INDEX IF NOT EXISTS idx_whiteboards_ws_id ON whiteboards(ws_id);
CREATE INDEX IF NOT EXISTS idx_whiteboards_creator_id ON whiteboards(creator_id);

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

CREATE POLICY "Workspace members can read and write whiteboards" ON public.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,21 @@
'use client';

import Toolbar from './toolbar';
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';
import 'tldraw/tldraw.css';

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

export function CustomTldraw({ persistenceKey }: { persistenceKey: string }) {
export function CustomTldraw({
initialData,
boardId,
}: {
initialData?: TLStoreSnapshot;
boardId: string;
}) {
const { resolvedTheme } = useTheme();
const [editor, setEditor] = useState<Editor | null>(null);

Expand All @@ -28,7 +35,10 @@ export function CustomTldraw({ persistenceKey }: { persistenceKey: string }) {
)}

<Tldraw
persistenceKey={`ws-${persistenceKey}-tldraw`}
snapshot={initialData}
components={{
SharePanel: () => <Toolbar boardId={boardId} />,
}}
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>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { CustomTldraw } from './custom-tldraw';
import { createClient } from '@tuturuuu/supabase/next/server';
import { notFound } from 'next/navigation';
import { TLStoreSnapshot } from 'tldraw';

export default async function TLDrawPage({
params,
}: {
params: Promise<{ boardId: string }>;
}) {
const { boardId } = await params;

const supabase = await createClient();

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

if (!whiteboard) return notFound();

return (
<div className="absolute inset-0">
<CustomTldraw
boardId={boardId}
initialData={
whiteboard.snapshot
? (JSON.parse(whiteboard.snapshot as string) as TLStoreSnapshot)
: undefined
}
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
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 } from 'react';
import { useEditor } from 'tldraw';

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

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

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();
const thumbnailFileName = generateFileName(`${boardId}.png`);
const thumbnailFile = new File([thumbnailBlob], thumbnailFileName, {
type: 'image/png',
});

const { error: thumbnailError } = await supabase.storage
.from('whiteboards-thumbnails')
.upload(thumbnailFileName, thumbnailFile);

if (thumbnailError) throw thumbnailError;

const { data: thumbnailUrl } = supabase.storage
.from('whiteboards-thumbnails')
.getPublicUrl(thumbnailFileName);

const snapshot = editor.getSnapshot();

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

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]);

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