whiteboards

This commit is contained in:
Kevin Carter 2026-03-02 07:08:55 +00:00
parent 2b7f446c03
commit ea95bf965f
12 changed files with 487 additions and 272 deletions

18
package-lock.json generated
View File

@ -13,6 +13,7 @@
"@hookform/resolvers": "^3.9.0",
"@supabase/supabase-js": "^2.98.0",
"@types/react-big-calendar": "^1.8.9",
"lucide-react": "^0.575.0",
"moment": "^2.30.1",
"next": "^14.2.35",
"next-cloudinary": "^6.13.0",
@ -33,6 +34,7 @@
"dotenv": "^17.3.1",
"eslint": "^8",
"eslint-config-next": "^14.2.35",
"phoenix": "^1.8.4",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
@ -7569,6 +7571,15 @@
"dev": true,
"license": "ISC"
},
"node_modules/lucide-react": {
"version": "0.575.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.575.0.tgz",
"integrity": "sha512-VuXgKZrk0uiDlWjGGXmKV6MSk9Yy4l10qgVvzGn2AWBx1Ylt0iBexKOAoA6I7JO3m+M9oeovJd3yYENfkUbOeg==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
@ -8254,6 +8265,13 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/phoenix": {
"version": "1.8.4",
"resolved": "https://registry.npmjs.org/phoenix/-/phoenix-1.8.4.tgz",
"integrity": "sha512-5wdO9mqU4l0AmcexN8mA0m1BsC4ROv2l55MN31gbxmJPzghc4SxVxnNTh9qaummYa2pbwkoBvG8FezO7cjdr8A==",
"dev": true,
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",

View File

@ -16,6 +16,7 @@
"@hookform/resolvers": "^3.9.0",
"@supabase/supabase-js": "^2.98.0",
"@types/react-big-calendar": "^1.8.9",
"lucide-react": "^0.575.0",
"moment": "^2.30.1",
"next": "^14.2.35",
"next-cloudinary": "^6.13.0",
@ -36,6 +37,7 @@
"dotenv": "^17.3.1",
"eslint": "^8",
"eslint-config-next": "^14.2.35",
"phoenix": "^1.8.4",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",

View File

@ -1,31 +1,28 @@
import Menu from "@/components/Menu";
import Navbar from "@/components/Navbar";
import Image from "next/image";
import Link from "next/link";
import DashboardShell from "@/components/DashboardShell";
import { currentUser } from "@clerk/nextjs/server";
import { redirect } from "next/navigation";
export default function DashboardLayout({
export default async function DashboardLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const user = await currentUser();
if (!user) {
redirect("/sign-in");
}
const role = user.publicMetadata.role as string;
const userMetadata = {
firstName: user.firstName,
lastName: user.lastName,
role: role
};
return (
<div className="h-screen flex">
{/* LEFT */}
<div className="w-[14%] md:w-[8%] lg:w-[16%] xl:w-[14%] p-4">
<Link
href="/"
className="flex items-center justify-center lg:justify-start gap-2"
>
<Image src="/logo.png" alt="logo" width={32} height={32} />
<span className="hidden lg:block font-bold">SchooLama</span>
</Link>
<Menu />
</div>
{/* RIGHT */}
<div className="w-[86%] md:w-[92%] lg:w-[84%] xl:w-[86%] bg-[#F7F8FA] overflow-scroll flex flex-col">
<Navbar />
<DashboardShell role={role} userMetadata={userMetadata}>
{children}
</div>
</div>
</DashboardShell>
);
}

View File

@ -0,0 +1,14 @@
"use client";
import { useSearchParams } from "next/navigation";
import WhiteboardCore from "@/components/Whiteboard/WhiteboardCore";
const DashboardWhiteboardPage = () => {
const searchParams = useSearchParams();
const lessonIdParam = searchParams.get("lessonId");
const lessonId = lessonIdParam ? parseInt(lessonIdParam) : null;
return <WhiteboardCore lessonId={lessonId} isFullscreen={false} />;
};
export default DashboardWhiteboardPage;

View File

@ -0,0 +1,14 @@
"use client";
import { useSearchParams } from "next/navigation";
import WhiteboardCore from "@/components/Whiteboard/WhiteboardCore";
const FullscreenWhiteboardPage = () => {
const searchParams = useSearchParams();
const lessonIdParam = searchParams.get("lessonId");
const lessonId = lessonIdParam ? parseInt(lessonIdParam) : null;
return <WhiteboardCore lessonId={lessonId} isFullscreen={true} />;
};
export default FullscreenWhiteboardPage;

View File

@ -0,0 +1,11 @@
export default function FullscreenLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<div className="w-screen h-screen overflow-hidden bg-white">
{children}
</div>
);
}

View File

@ -1,218 +0,0 @@
"use client";
import { useEffect, useState, useRef } from "react";
import { useSearchParams } from "next/navigation";
import { Tldraw, createTLStore, TLStore, Editor, getSnapshot, loadSnapshot } from "tldraw";
import "tldraw/tldraw.css";
import { getLessonWhiteboard, saveLessonSnapshot, SnapshotType } from "@/lib/whiteboardActions";
import { toast } from "react-toastify";
import { useUser } from "@clerk/nextjs";
const WhiteboardPage = () => {
const searchParams = useSearchParams();
const lessonIdParam = searchParams.get("lessonId");
const lessonId = lessonIdParam ? parseInt(lessonIdParam) : null;
const { user } = useUser();
const role = user?.publicMetadata?.role as string | undefined;
const isTeacherOrAdmin = role === "teacher" || role === "admin";
const [store, setStore] = useState<TLStore | null>(null);
const [loading, setLoading] = useState(true);
const [activeState, setActiveState] = useState<SnapshotType>("planned");
const [whiteboardRecord, setWhiteboardRecord] = useState<any>(null);
const editorRef = useRef<Editor | null>(null);
useEffect(() => {
const fetchWhiteboard = async () => {
if (!lessonId) {
setLoading(false);
return;
}
const { success, data } = await getLessonWhiteboard(lessonId);
if (success && data) {
setWhiteboardRecord(data);
// Initialize store based on role
const newStore = createTLStore();
let defaultSnapshot = data.plannedSnapshotData;
let defaultState: SnapshotType = "planned";
// For students, default to live, or final if live doesn't exist. If neither, show empty.
if (!isTeacherOrAdmin) {
if (data.liveSnapshotData) {
defaultSnapshot = data.liveSnapshotData;
defaultState = "live";
} else if (data.finalSnapshotData) {
defaultSnapshot = data.finalSnapshotData;
defaultState = "final";
} else {
defaultSnapshot = null;
defaultState = "live"; // Wait for live
}
}
if (defaultSnapshot) {
try {
loadSnapshot(newStore, defaultSnapshot as any);
} catch (e) {
console.error("Failed to load snapshot", e);
}
}
setStore(newStore);
setActiveState(defaultState);
}
setLoading(false);
};
if (role !== undefined) {
fetchWhiteboard();
}
}, [lessonId, role]);
const handleSave = async (type: SnapshotType) => {
if (!lessonId || !editorRef.current || !isTeacherOrAdmin) return;
const snapshot = getSnapshot(editorRef.current.store);
const { success } = await saveLessonSnapshot(lessonId, type, snapshot);
if (success) {
toast.success(`Successfully saved ${type} snapshot!`);
setActiveState(type);
} else {
toast.error("Failed to save snapshot.");
}
};
const handleLoadData = (type: SnapshotType) => {
if (!whiteboardRecord || !editorRef.current) return;
let snapshotData = null;
if (type === "planned") snapshotData = whiteboardRecord.plannedSnapshotData;
if (type === "live") snapshotData = whiteboardRecord.liveSnapshotData;
if (type === "final") snapshotData = whiteboardRecord.finalSnapshotData;
if (snapshotData) {
try {
loadSnapshot(editorRef.current.store, snapshotData as any);
toast.success(`Loaded ${type} snapshot.`);
setActiveState(type);
} catch (e) {
console.error("Failed to load snapshot", e);
toast.error("Snapshot data is invalid or corrupted.");
}
} else {
toast.info(`No data found for ${type} snapshot.`);
}
};
return (
<div className="flex-1 p-4 flex gap-4 flex-col xl:flex-row h-full">
<div className="w-full xl:w-3/4 flex flex-col h-full">
{/* Header Banner */}
<div className="bg-white p-4 rounded-md shadow-sm border mb-4 flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-gray-800">
Lesson Whiteboard {lessonId ? `#${lessonId}` : "(No Lesson Selected)"}
</h1>
<p className="text-sm text-gray-500">
Current mode: <span className="font-medium text-lamaPurple">{activeState.toUpperCase()}</span>
</p>
</div>
{!isTeacherOrAdmin && (
<div className="bg-blue-50 text-blue-600 px-3 py-1 rounded-full text-sm font-medium">
View Only
</div>
)}
</div>
<div className="flex-1 border rounded-md relative bg-white overflow-hidden min-h-[600px] shadow-sm">
{loading || role === undefined ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Loading whiteboard...
</div>
) : !lessonId ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Please provide a ?lessonId URL parameter.
</div>
) : store ? (
<div className="absolute inset-0 pointer-events-auto" style={!isTeacherOrAdmin ? { pointerEvents: 'none' } : {}}>
<Tldraw
store={store}
hideUi={!isTeacherOrAdmin}
onMount={(editor) => {
editorRef.current = editor;
if (!isTeacherOrAdmin) {
editor.updateInstanceState({ isReadonly: true });
}
}}
/>
</div>
) : (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Failed to initialize whiteboard.
</div>
)}
</div>
</div>
<div className="w-full xl:w-1/4 flex flex-col gap-4">
{isTeacherOrAdmin && (
<div className="bg-white p-4 rounded-md shadow-sm border flex flex-col gap-4">
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">Save Actions</h2>
<p className="text-xs text-gray-500 mb-2">Save your current canvas state to the database.</p>
<button
onClick={() => handleSave("planned")}
className="bg-lamaSky text-white px-4 py-2 rounded-md hover:opacity-90 transition-opacity"
>
Save as Planned
</button>
<button
onClick={() => handleSave("live")}
className="bg-lamaYellow text-gray-800 px-4 py-2 rounded-md hover:opacity-90 transition-opacity"
>
Save as Live
</button>
<button
onClick={() => handleSave("final")}
className="bg-lamaPurple text-white px-4 py-2 rounded-md hover:opacity-90 transition-opacity"
>
Save as Final
</button>
</div>
)}
<div className="bg-white p-4 rounded-md shadow-sm border flex flex-col gap-4">
<h2 className="text-lg font-semibold text-gray-800 border-b pb-2">Load Actions</h2>
<p className="text-xs text-gray-500 mb-2">Switch between different saved states for this lesson.</p>
{isTeacherOrAdmin && (
<button
onClick={() => handleLoadData("planned")}
className="border border-lamaSky text-lamaSky px-4 py-2 rounded-md hover:bg-lamaSkyLight transition-colors"
>
Load Planned
</button>
)}
<button
onClick={() => handleLoadData("live")}
className="border border-lamaYellow text-yellow-600 px-4 py-2 rounded-md hover:bg-lamaYellowLight transition-colors"
>
Load Live
</button>
<button
onClick={() => handleLoadData("final")}
className="border border-lamaPurple text-lamaPurple px-4 py-2 rounded-md hover:bg-lamaPurpleLight transition-colors"
>
Load Final
</button>
</div>
</div>
</div>
);
};
export default WhiteboardPage;

View File

@ -32,7 +32,6 @@ const BigCalendar = ({
{props.event.id && (
<Link
href={`/lesson?lessonId=${props.event.id}`}
target="_blank"
className="mt-1 flex items-center gap-1 w-max rounded text-xs bg-white bg-opacity-30 hover:bg-opacity-50 transition-all px-1 py-0.5"
>
<Image src="/student.png" alt="Board" width={10} height={10} />

View File

@ -0,0 +1,70 @@
"use client";
import { useState } from "react";
import Menu from "@/components/Menu";
import Navbar from "@/components/Navbar";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
export default function DashboardShell({
children,
role,
userMetadata
}: {
children: React.ReactNode;
role: string;
userMetadata: any;
}) {
const [isCollapsed, setIsCollapsed] = useState(false);
const toggleSidebar = () => {
setIsCollapsed((prev) => !prev);
};
return (
<div className="h-screen flex overflow-hidden">
{/* LEFT SIDEBAR */}
<div
className={`${isCollapsed ? "w-[80px]" : "w-[14%] md:w-[8%] lg:w-[16%] xl:w-[14%]"
} p-4 transition-all duration-300 ease-in-out border-r bg-white z-20 overflow-y-auto no-scrollbar`}
>
{/* Logo Area (Hidden when collapsed, moves to Navbar) */}
<div
className={`flex items-center justify-center lg:justify-start gap-2 mb-4 transition-all duration-300 ${isCollapsed ? "opacity-0 h-0 hidden" : "opacity-100 h-8"
}`}
>
<Link href="/" className="flex items-center gap-2">
<Image src="/logo.png" alt="logo" width={32} height={32} />
<span className="hidden lg:block font-bold">SchooLama</span>
</Link>
</div>
{/* Collapsed Logo (Shows only when collapsed) */}
<div
className={`flex items-center justify-center gap-2 mb-4 transition-all duration-300 ${!isCollapsed ? "opacity-0 h-0 hidden" : "opacity-100 h-8"
}`}
>
<Link href="/" className="flex items-center justify-center w-full">
<Image src="/logo.png" alt="logo" width={32} height={32} />
</Link>
</div>
<Menu role={role} isCollapsed={isCollapsed} />
</div>
{/* RIGHT MAIN CONTENT */}
<div className="flex-1 bg-[#F7F8FA] overflow-y-auto flex flex-col relative w-full">
<Navbar
role={role}
userMetadata={userMetadata}
toggleSidebar={toggleSidebar}
isCollapsed={isCollapsed}
/>
<main className="flex-1 relative">
{children}
</main>
</div>
</div>
);
}

View File

@ -1,4 +1,3 @@
import { currentUser } from "@clerk/nextjs/server";
import Image from "next/image";
import Link from "next/link";
@ -117,26 +116,43 @@ const menuItems = [
},
];
const Menu = async () => {
const user = await currentUser();
const role = user?.publicMetadata.role as string;
const Menu = ({ role, isCollapsed }: { role: string; isCollapsed: boolean }) => {
return (
<div className="mt-4 text-sm">
<div className="mt-4 text-sm w-full">
{menuItems.map((i) => (
<div className="flex flex-col gap-2" key={i.title}>
<span className="hidden lg:block text-gray-400 font-light my-4">
<div className="flex flex-col gap-2 relative w-full" key={i.title}>
<span
className={`hidden lg:block text-gray-400 font-light my-4 transition-all duration-300 ease-in-out whitespace-nowrap overflow-hidden ${isCollapsed ? "opacity-0 h-0 my-0 mt-4 text-[0px]" : "opacity-100 h-4 my-4 text-xs"
}`}
>
{i.title}
</span>
<div className={`block lg:hidden w-full h-4 ${isCollapsed ? '' : 'my-4'}`} />
{i.items.map((item) => {
if (item.visible.includes(role)) {
return (
<Link
href={item.href}
key={item.label}
className="flex items-center justify-center lg:justify-start gap-4 text-gray-500 py-2 md:px-2 rounded-md hover:bg-lamaSkyLight"
className={`flex items-center text-gray-500 py-2 rounded-md hover:bg-lamaSkyLight transition-all relative group
${isCollapsed ? "justify-center px-0 w-10 h-10 mx-auto" : "justify-center lg:justify-start md:px-2"}
`}
>
<Image src={item.icon} alt="" width={20} height={20} />
<span className="hidden lg:block">{item.label}</span>
<Image src={item.icon} alt="" width={20} height={20} className="min-w-[20px]" />
<span
className={`hidden lg:block whitespace-nowrap overflow-hidden transition-all duration-300 ease-in-out origin-left
${isCollapsed ? "opacity-0 w-0 max-w-0" : "opacity-100 w-auto ml-4 max-w-[200px]"}
`}
>
{item.label}
</span>
{/* Tooltip on hover when collapsed */}
{isCollapsed && (
<div className="absolute left-14 bg-gray-800 text-white text-xs py-1 px-2 rounded opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all whitespace-nowrap z-50 pointer-events-none">
{item.label}
</div>
)}
</Link>
);
}

View File

@ -1,11 +1,46 @@
import { UserButton } from "@clerk/nextjs";
import { currentUser } from "@clerk/nextjs/server";
import Image from "next/image";
import Link from "next/link";
import { Menu as MenuIcon } from "lucide-react";
const Navbar = async () => {
const user = await currentUser();
const Navbar = ({
role,
userMetadata,
toggleSidebar,
isCollapsed
}: {
role: string;
userMetadata: any;
toggleSidebar: () => void;
isCollapsed: boolean;
}) => {
return (
<div className="flex items-center justify-between p-4">
<div className="flex items-center justify-between p-4 bg-white shadow-sm z-10 sticky top-0">
{/* LEFT AREA: Toggle and Animated Logo */}
<div className="flex items-center gap-4">
{/* Hamburger Toggle */}
<button
onClick={toggleSidebar}
className="p-2 rounded-md hover:bg-gray-100 transition-colors text-gray-600 focus:outline-none focus:ring-2 focus:ring-lamaSky"
aria-label="Toggle Sidebar"
>
<MenuIcon size={20} />
</button>
{/* Logo (Appears here when sidebar is collapsed) */}
<div
className={`flex items-center gap-2 overflow-hidden transition-all duration-300 ease-in-out origin-left
${isCollapsed ? "opacity-100 max-w-[200px]" : "opacity-0 max-w-0"}`}
>
<Link href="/" className="flex items-center gap-2">
<Image src="/logo.png" alt="logo" width={24} height={24} />
<span className="font-bold text-lg hidden sm:block">SchooLama</span>
</Link>
</div>
</div>
{/* RIGHT: ICONS AND USER */}
<div className="flex items-center gap-6 justify-end">
{/* SEARCH BAR */}
<div className="hidden md:flex items-center gap-2 text-xs rounded-full ring-[1.5px] ring-gray-300 px-2">
<Image src="/search.png" alt="" width={14} height={14} />
@ -15,24 +50,24 @@ const Navbar = async () => {
className="w-[200px] p-2 bg-transparent outline-none"
/>
</div>
{/* ICONS AND USER */}
<div className="flex items-center gap-6 justify-end w-full">
<div className="bg-white rounded-full w-7 h-7 flex items-center justify-center cursor-pointer">
<div className="bg-lamaSkyLight rounded-full w-7 h-7 flex items-center justify-center cursor-pointer">
<Image src="/message.png" alt="" width={20} height={20} />
</div>
<div className="bg-white rounded-full w-7 h-7 flex items-center justify-center cursor-pointer relative">
<div className="bg-lamaSkyLight rounded-full w-7 h-7 flex items-center justify-center cursor-pointer relative">
<Image src="/announcement.png" alt="" width={20} height={20} />
<div className="absolute -top-3 -right-3 w-5 h-5 flex items-center justify-center bg-purple-500 text-white rounded-full text-xs">
1
</div>
</div>
<div className="flex flex-col">
<span className="text-xs leading-3 font-medium">John Doe</span>
<span className="text-xs leading-3 font-medium">
{userMetadata?.firstName} {userMetadata?.lastName}
</span>
<span className="text-[10px] text-gray-500 text-right">
{user?.publicMetadata?.role as string}
{role}
</span>
</div>
{/* <Image src="/avatar.png" alt="" width={36} height={36} className="rounded-full"/> */}
<UserButton />
</div>
</div>

View File

@ -0,0 +1,257 @@
"use client";
import { useEffect, useState, useRef, createContext, useContext } from "react";
import {
Tldraw,
createTLStore,
TLStore,
Editor,
getSnapshot,
loadSnapshot,
useDialogs,
TldrawUiButton,
TldrawUiButtonLabel,
TldrawUiButtonIcon,
TldrawUiDialogHeader,
TldrawUiDialogTitle,
TldrawUiDialogCloseButton,
TldrawUiDialogBody,
TldrawUiIcon
} from "tldraw";
import "tldraw/tldraw.css";
import { getLessonWhiteboard, saveLessonSnapshot, SnapshotType } from "@/lib/whiteboardActions";
import { toast } from "react-toastify";
import { useUser } from "@clerk/nextjs";
type WhiteboardContextType = {
activeState: SnapshotType;
isTeacherOrAdmin: boolean;
handleSave: (type: SnapshotType) => void;
handleLoadData: (type: SnapshotType) => void;
lessonId: number | null;
whiteboardRecord: any;
isFullscreen: boolean;
};
const WhiteboardContext = createContext<WhiteboardContextType | null>(null);
const useWhiteboardContext = () => {
const ctx = useContext(WhiteboardContext);
if (!ctx) throw new Error("Missing WhiteboardContext.Provider");
return ctx;
};
function NativeFileManagerDialog({ onClose }: { onClose: () => void }) {
const { activeState, isTeacherOrAdmin, handleSave, handleLoadData, whiteboardRecord } = useWhiteboardContext();
const renderFileRow = (type: SnapshotType, title: string) => {
const hasData = whiteboardRecord && whiteboardRecord[`${type}SnapshotData`];
const isActive = activeState === type;
return (
<div className="flex items-center justify-between p-3 border rounded-md mb-2 bg-gray-50" key={type}>
<div className="flex flex-col">
<span className="font-semibold text-gray-800 flex items-center gap-2">
{title}
{isActive && <span className="text-[10px] bg-lamaPurple text-white px-2 py-0.5 rounded-full mt-0.5">ACTIVE</span>}
</span>
<span className="text-xs text-gray-500">
{hasData ? "Snapshot available" : "No snapshot saved"}
</span>
</div>
<div className="flex gap-2">
{isTeacherOrAdmin && (
<TldrawUiButton type="normal" onClick={() => { handleSave(type); }}>
<TldrawUiButtonLabel>Save Here</TldrawUiButtonLabel>
</TldrawUiButton>
)}
<TldrawUiButton type="primary" disabled={!hasData} onClick={() => { handleLoadData(type); onClose(); }}>
<TldrawUiButtonLabel>Load</TldrawUiButtonLabel>
</TldrawUiButton>
</div>
</div>
);
};
return (
<>
<TldrawUiDialogHeader>
<TldrawUiDialogTitle>File Manager</TldrawUiDialogTitle>
<TldrawUiDialogCloseButton />
</TldrawUiDialogHeader>
<TldrawUiDialogBody style={{ maxWidth: 450 }}>
<div className="mb-4 text-sm text-gray-600">
Manage your lesson whiteboard snapshots below.
{!isTeacherOrAdmin && " As a student, you can only load available snapshots."}
</div>
{renderFileRow("planned", "Planned")}
{renderFileRow("live", "Live")}
{renderFileRow("final", "Final")}
</TldrawUiDialogBody>
</>
)
}
const CustomSharePanel = () => {
const { addDialog } = useDialogs();
const { isFullscreen, lessonId } = useWhiteboardContext();
return (
<div style={{ pointerEvents: 'all', display: 'flex', gap: '8px' }}>
{!isFullscreen && lessonId && (
<TldrawUiButton
type="icon"
title="Open Fullscreen in New Window"
onClick={() => {
window.open(`/board?lessonId=${lessonId}`, '_blank');
}}
>
<TldrawUiButtonIcon icon="external-link" />
</TldrawUiButton>
)}
<TldrawUiButton
type="icon"
title="File Manager"
onClick={() => addDialog({ component: NativeFileManagerDialog })}
>
<TldrawUiButtonIcon icon="menu" />
</TldrawUiButton>
</div>
);
};
const WhiteboardCore = ({ lessonId, isFullscreen = false }: { lessonId: number | null, isFullscreen?: boolean }) => {
const { user } = useUser();
const role = user?.publicMetadata?.role as string | undefined;
const isTeacherOrAdmin = role === "teacher" || role === "admin";
const [store, setStore] = useState<TLStore | null>(null);
const [loading, setLoading] = useState(true);
const [activeState, setActiveState] = useState<SnapshotType>("planned");
const [whiteboardRecord, setWhiteboardRecord] = useState<any>(null);
const editorRef = useRef<Editor | null>(null);
useEffect(() => {
const fetchWhiteboard = async () => {
if (!lessonId) {
setLoading(false);
return;
}
const { success, data } = await getLessonWhiteboard(lessonId);
if (success && data) {
setWhiteboardRecord(data);
// Initialize store based on role
const newStore = createTLStore();
let defaultSnapshot = data.plannedSnapshotData;
let defaultState: SnapshotType = "planned";
// For students, default to live, or final if live doesn't exist. If neither, show empty.
if (!isTeacherOrAdmin) {
if (data.liveSnapshotData) {
defaultSnapshot = data.liveSnapshotData;
defaultState = "live";
} else if (data.finalSnapshotData) {
defaultSnapshot = data.finalSnapshotData;
defaultState = "final";
} else {
defaultSnapshot = null;
defaultState = "live"; // Wait for live
}
}
if (defaultSnapshot) {
try {
loadSnapshot(newStore, defaultSnapshot as any);
} catch (e) {
console.error("Failed to load snapshot", e);
}
}
setStore(newStore);
setActiveState(defaultState);
}
setLoading(false);
};
if (role !== undefined) {
fetchWhiteboard();
}
}, [lessonId, role]);
const handleSave = async (type: SnapshotType) => {
if (!lessonId || !editorRef.current || !isTeacherOrAdmin) return;
const snapshot = getSnapshot(editorRef.current.store);
const { success } = await saveLessonSnapshot(lessonId, type, snapshot);
if (success) {
toast.success(`Successfully saved ${type} snapshot!`);
setActiveState(type);
setWhiteboardRecord((prev: any) => ({
...prev,
[`${type}SnapshotData`]: snapshot
}));
} else {
toast.error("Failed to save snapshot.");
}
};
const handleLoadData = (type: SnapshotType) => {
if (!whiteboardRecord || !editorRef.current) return;
let snapshotData = null;
if (type === "planned") snapshotData = whiteboardRecord.plannedSnapshotData;
if (type === "live") snapshotData = whiteboardRecord.liveSnapshotData;
if (type === "final") snapshotData = whiteboardRecord.finalSnapshotData;
if (snapshotData) {
try {
loadSnapshot(editorRef.current.store, snapshotData as any);
toast.success(`Loaded ${type} snapshot.`);
setActiveState(type);
} catch (e) {
console.error("Failed to load snapshot", e);
toast.error("Snapshot data is invalid or corrupted.");
}
} else {
toast.info(`No data found for ${type} snapshot.`);
}
};
return (
<div className={`flex-1 w-full relative bg-white overflow-hidden ${isFullscreen ? 'h-screen' : 'h-[calc(100vh-80px)]'}`}>
{loading || role === undefined ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Loading whiteboard...
</div>
) : !lessonId ? (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Please provide a ?lessonId URL parameter.
</div>
) : store ? (
<WhiteboardContext.Provider value={{ activeState, isTeacherOrAdmin, handleSave, handleLoadData, lessonId, whiteboardRecord, isFullscreen }}>
<div className="absolute inset-0">
<Tldraw
store={store}
components={{ SharePanel: CustomSharePanel }}
onMount={(editor) => {
editorRef.current = editor;
if (!isTeacherOrAdmin) {
editor.updateInstanceState({ isReadonly: true });
}
}}
/>
</div>
</WhiteboardContext.Provider>
) : (
<div className="absolute inset-0 flex items-center justify-center text-gray-400">
Failed to initialize whiteboard.
</div>
)}
</div>
);
};
export default WhiteboardCore;