tldraw implementation

This commit is contained in:
Kevin Carter 2026-03-01 22:42:10 +00:00
parent 9c9d1e8ae4
commit 2b7f446c03
13 changed files with 2775 additions and 1499 deletions

3520
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,13 +14,11 @@
"@clerk/elements": "^0.14.6",
"@clerk/nextjs": "^5.4.1",
"@hookform/resolvers": "^3.9.0",
"@prisma/client": "^5.19.1",
"@supabase/supabase-js": "^2.98.0",
"@types/react-big-calendar": "^1.8.9",
"moment": "^2.30.1",
"next": "14.2.5",
"next": "^14.2.35",
"next-cloudinary": "^6.13.0",
"prisma": "^5.19.1",
"react": "^18",
"react-big-calendar": "^1.13.2",
"react-calendar": "^5.0.0",
@ -37,11 +35,16 @@
"@types/react-dom": "^18",
"dotenv": "^17.3.1",
"eslint": "^8",
"eslint-config-next": "14.2.5",
"eslint-config-next": "^14.2.35",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
"tsx": "^4.21.0",
"typescript": "^5"
},
"overrides": {
"@clerk/types": "4.26.0",
"@clerk/shared": "2.9.2",
"@clerk/clerk-react": "5.12.0"
}
}

View File

@ -1,99 +1,99 @@
{
"teacherMap": {
"1": "user_3AJAkSqshofbdPsW7lZh6q2eCe5",
"2": "user_3AJAkVye7wKBBK8seog6gljyc7L",
"3": "user_3AJAkXA9lrOHxsGcJNoJGOXKNOr",
"4": "user_3AJAkc3f42kZzVPLvaRBFHor14J",
"5": "user_3AJAkbsXvHmZcGu3wFpRZm732LX",
"6": "user_3AJAke4rOtbf26yRM9JoHhtEjyD",
"7": "user_3AJAklVf8Pnm2pH6Ql1PnfQBIID",
"8": "user_3AJAki8tuWw9rWvZZD9xIP6CxVp",
"9": "user_3AJAkn3ET3kFyUrx636ayvHrLds",
"10": "user_3AJAkuiTMWimGNBtw7ymHVUqwVW",
"11": "user_3AJAkvjGTDDsscx7g9dD998d6Gq",
"12": "user_3AJAkr08HMjIKMG1Guzw3HJqB9L",
"13": "user_3AJAl1xiX1ZtMg0ohV7QB2TpHm5",
"14": "user_3AJAl1tyuI5t3DfmleToHAw6HgJ",
"15": "user_3AJAl3Rr5gq7K1W0fhl6AVNFXrY"
"1": "user_3AMTkSb5aZsaWlYnCd2x5iImprs",
"2": "user_3AMTkUkKWrV9QWt9dvD2qOjoxiE",
"3": "user_3AMTkRjafcujtrgbyS4SNoWFgjh",
"4": "user_3AMTkfb5Y9O7a55cye9iQAHxLAB",
"5": "user_3AMTkaTAmH3VOUCcxgeCfSTaaIX",
"6": "user_3AMTkZQ1Jea1Mdc4gT9qqwhX9zb",
"7": "user_3AMTkio1bTs7CEgKbXJQuJkcDYu",
"8": "user_3AMTkkYnJUOui3Z73yZlx7KNg21",
"9": "user_3AMTkmAn0DTuaxFdyR4ii1oPQr7",
"10": "user_3AMTkvIYftbqLCpyuhSnCp0Xdcv",
"11": "user_3AMTksKS8GKlkstBeBndBvDSMi8",
"12": "user_3AMTkqRKtBPzjilxeONx344GQJS",
"13": "user_3AMTkx8ZtB15yOcnEDgoAic3Z60",
"14": "user_3AMTkz65CADkvCgyC5fh2qRxRQV",
"15": "user_3AMTkzAvbz587Hc36Kvk4MXIBsL"
},
"parentMap": {
"1": "user_3AJAl6KD5fVP5MbjDZLpyoZ7sDG",
"2": "user_3AJAl9gkapHVzn5Tik7RteIEJVZ",
"3": "user_3AJAl5BLWwfpho7phY16SrCleE8",
"4": "user_3AJAl7BN77L27mpmHzjCp96OlFx",
"5": "user_3AJAlFko0fvXyleuRuyqmGkpgTV",
"6": "user_3AJAlEyIdgY7vVA7yZQUbTwimOC",
"7": "user_3AJAlIlHOwSpcR92ENGiHrz0nCg",
"8": "user_3AJAlKekpw2nrtGnnMBvN0xdh3c",
"9": "user_3AJAlLmCzuvKoqh9yh2ulnmz26h",
"10": "user_3AJAlPbUuestp7PvH2BuX2GQK6R",
"11": "user_3AJAlWR17pNYP0S24hiNnUKI2R1",
"12": "user_3AJAlWTNINh2uIOEueR8dPKXjlc",
"13": "user_3AJAlUx3a2u65hTIoxWLjmDnDuj",
"14": "user_3AJAlac7l5vhi9lbnvuOIEZ2zoz",
"15": "user_3AJAldy0F23q4Jm8kz8olXdoao0",
"16": "user_3AJAlekANUdcMJeZ34EFcCjluAq",
"17": "user_3AJAllI3cBBjs5JbcUimhrLEYvf",
"18": "user_3AJAlp8YJPzQwvcutFoCsHAz3Sn",
"19": "user_3AJAllVI1vR6vwSPlLPCyIb9oZB",
"20": "user_3AJAlwjmMMnvV9la8fFlH7TYuOS",
"21": "user_3AJAlxGYIRJnKZmvkt2HB9ukrlC",
"22": "user_3AJAltSwlQoPrRGcsAZcJpH2sH9",
"23": "user_3AJAlvcnUE4GGbYKK0odLUjwxqu",
"24": "user_3AJAm16YficrMn5CeAOCAxV8iu1",
"25": "user_3AJAlxj9Z9gE4EIwQ5pljEywIV0"
"1": "user_3AMTl8n08l1L5ierzRsTYWMdFZP",
"2": "user_3AMTl8u9bFoUz7mFK14Zhh85K6X",
"3": "user_3AMTlCd06BO0Y9WoBWXy2ictYYz",
"4": "user_3AMTlCMBaMKRQv5BCQPX46Iv5xK",
"5": "user_3AMTlGoIV7fNrrYhuOjoyTs1h1a",
"6": "user_3AMTlGZpGBcdicxrK5pjYa901Hv",
"7": "user_3AMTlQ4wTNdagORX0RmbdfDPdFT",
"8": "user_3AMTlLQtI62V185SDKt3mge25gk",
"9": "user_3AMTlMjordV5M4W13cg8XiQGMaP",
"10": "user_3AMTlZKLWrUlRjeCFCiGBOmqI5l",
"11": "user_3AMTlWlRgP2UBskbHenAXzqzNjn",
"12": "user_3AMTlbgjdcsv8HKKnlpWoA42jiW",
"13": "user_3AMTlauWbEOSp4xb9NzBTu7uNeI",
"14": "user_3AMTlfzhy2jrbLrhCBaUSB6LwfW",
"15": "user_3AMTll6wXmJI0KjTUvbXZZvSlGq",
"16": "user_3AMTlosVB9G5Nr8ZSY4JkVtqGqT",
"17": "user_3AMTlkMhTzRgPBEHDfu47qtwJ6i",
"18": "user_3AMTlrbxKFS3HnwNQVKJaLNF3X7",
"19": "user_3AMTlqQnvCBDhiH4qrUChkNxbE5",
"20": "user_3AMTm3oZYPIAnNdzN63xfpV4QPI",
"21": "user_3AMTm5OrIhMbQ325RYoCa0HAZlh",
"22": "user_3AMTmB28qoyEFvcUlhXzaHVDJL9",
"23": "user_3AMTmAPi7FmXoUirnikOnGfKIlO",
"24": "user_3AMTmCaqV2OPnTRJk3Z902P9nos",
"25": "user_3AMTmCnG8IyhdHGTskXDIWfVgKK"
},
"studentMap": {
"1": "user_3AJAm7o0RjL16Gt1jE9YLG0tib7",
"2": "user_3AJAm9SoYdWl5sQfbf8slNI2Qn4",
"3": "user_3AJAm8NIt39YG9DPjnAwq2G2V3G",
"4": "user_3AJAm5KPpNLvz8DjwNU6MRCBO5e",
"5": "user_3AJAmGDojjfnVtn7LrmLVemoCiM",
"6": "user_3AJAmDK9jVHWfe3FjdR7emQ329K",
"7": "user_3AJAmMNLtdeplBIS9kwXYW0FC9Z",
"8": "user_3AJAmNXiIZz0FYILKDOZxq1ET56",
"9": "user_3AJAmMeKtN7oMMrLgcxIEWsm0EV",
"10": "user_3AJAmQsp9Xg8LDpxCkkmccjDCuU",
"11": "user_3AJAmZtzvmAwwu7QJRvIpxZCNYF",
"12": "user_3AJAmXM1fL4b0fONRdM5uIRIxBS",
"13": "user_3AJAmi4pxmDtV24YaIaNmmack33",
"14": "user_3AJAmf864NjSUdQ6ExiMR3zaDCn",
"15": "user_3AJAmbZArRtgzFrBdW77qbd7P1z",
"16": "user_3AJAmpWu9wzc4ve2kwTKPLveFST",
"17": "user_3AJAmoVVKEmMeE8GMd7A2fgn5nY",
"18": "user_3AJAmlYITikQW1km45TqvQ2biBm",
"19": "user_3AJAmuEU2s2CLT9391jnj6Uxb3e",
"20": "user_3AJAmwfQjhHcnd6Y2HGvXWTxTj8",
"21": "user_3AJAmxavPXIvafOo84MWRqKPyRN",
"22": "user_3AJAmxtksJ1U2UjHoP1wzXgk3JB",
"23": "user_3AJAn3gfMCCyfaFrX0yY69XfQfQ",
"24": "user_3AJAn1UL8HJe9pfcZboyDCqg4Zd",
"25": "user_3AJAn4fAYAtcYCLKv1fBkBJSyxw",
"26": "user_3AJAnBlPYjZBRY7HrMaY95WRQ59",
"27": "user_3AJAnD31sahtYeq9Zfzu867VgB8",
"28": "user_3AJAnK8qcNr259cZnIKpH4ZuoRH",
"29": "user_3AJAnECM3SCOTVaHQvwaIkV1YnJ",
"30": "user_3AJAnH4sNG5lbNwuvYHmmbU9J3U",
"31": "user_3AJAnRjFXzyoALI4egtIvZEUFuA",
"32": "user_3AJAnYhwtMvevCuQScoLSJePp79",
"33": "user_3AJAnXQkG2mOAFxFm1lHaOV2aJQ",
"34": "user_3AJAnYU4Frx0bX863nwBE9EJaGH",
"35": "user_3AJAncF3uP2xfkU6WixizrfSSrl",
"36": "user_3AJAngPagGao0QCe5AcGeeGGpDS",
"37": "user_3AJAnazAi3ERTCfqVQr7jDtTOK4",
"38": "user_3AJAnoJnVGxwohyI3ot6cwnZ6iO",
"39": "user_3AJAnoCbmMiBBlXE3PvUN1vg3CT",
"40": "user_3AJAniemPzyyEwPSZZ2h7iXK9lV",
"41": "user_3AJAnvqsElaS1dwqPtmhw4N7dCS",
"42": "user_3AJAnqp0r30RwkxKEJK3nrPJcwR",
"43": "user_3AJAnsBcWHQQGYCpKxLbfWpSWdE",
"44": "user_3AJAnrDUy5R1iFD1Vsb8FNlDO1I",
"45": "user_3AJAo1kdbtoIYYx3gvEcr3D9WT8",
"46": "user_3AJAo0CALCnqJle4D4JGt5VNqHJ",
"47": "user_3AJAo1fZPiFTp8U0NYaprnET0Ls",
"48": "user_3AJAoB35YG2oZHKLvT4UFBQVBqj",
"49": "user_3AJAoDZ1nOyp3f3KO2Lefzgi6Ah",
"50": "user_3AJAo6si4CGdeQ3teM04nPmrJe2"
"1": "user_3AMTmFbsTvd1bTYxbuaiJEWEib6",
"2": "user_3AMTmLp1BkbpUdSDn9ynA4Y6JF2",
"3": "user_3AMTmNTKwZ70qJn1VqqOgsMsn6B",
"4": "user_3AMTmOWj8vhMDBh9wsO2rWFEfO3",
"5": "user_3AMTmVJMwFUQ5xphwLHFFoCJ5hl",
"6": "user_3AMTmVAfVEpQldG5aEZYNoObmqE",
"7": "user_3AMTmXvXbUJ0hbMSGy2GxR4XBq3",
"8": "user_3AMTmTZJJUaHpC6vPrRnlNQjzV1",
"9": "user_3AMTmenWIejkaHVpU9ECpu2ym0b",
"10": "user_3AMTmb2na93TGqMYW6dAO7bRhzZ",
"11": "user_3AMTmmAhGdPyG73SqbZy65xo4zR",
"12": "user_3AMTmiNz7s34137Vm7R40tldWFj",
"13": "user_3AMTmhhd6xR4jQhqlytwF4JVc0N",
"14": "user_3AMTmud3UuGWrvcCstxciqaRhJP",
"15": "user_3AMTmwPzZcSKvVE1vCYagb4IrQO",
"16": "user_3AMTmvzkaBKZs4f0qwc4Q2L0GNe",
"17": "user_3AMTn3lCnHDzMShKlenMMPkDtoA",
"18": "user_3AMTn3bE5un9OCnYr0iwftXrPPy",
"19": "user_3AMTn4QZQqYQIps95xfehqdp4dt",
"20": "user_3AMTn7sakhjRDyoKY7LmjcudCMn",
"21": "user_3AMTnIgyMm8qJDxqYczGISUl4SU",
"22": "user_3AMTnJj4Nd0oVkAZRssvRMAVbk7",
"23": "user_3AMTnN15QzCO98nkpYo5eD34R5S",
"24": "user_3AMTnM51Kdx7VxvbO7pIxIKCHcs",
"25": "user_3AMTnPCxefgX1zECfff75vIMQEG",
"26": "user_3AMTnXwI5GcroWoCvDREunhXuLA",
"27": "user_3AMTnVoqmZanh2rqRKylP2KFPU2",
"28": "user_3AMTnUCYRW9lfzGCj2X1agCKBR3",
"29": "user_3AMTnV2uWRevLmHMpAgcLXpiM3k",
"30": "user_3AMTnaDOgQgbZmJAcIJTX3exNeq",
"31": "user_3AMTnaVlrBUic7iwIUBXZlrBNYp",
"32": "user_3AMTng8nP5U5uzriwfkvmX1LbVo",
"33": "user_3AMTnje4x1ektrJKGRUulxI2kJz",
"34": "user_3AMTnnDJTdBhWYZZXl2mrlGHpgc",
"35": "user_3AMTnoayLsbHr2ZmuUcuP40RImH",
"36": "user_3AMTnupHywRyiHEgfOYls192hUs",
"37": "user_3AMTnvI2VJoPiARcUuO7hP00C0m",
"38": "user_3AMTnwh5t3ngn4U98Il3Ba9zn3b",
"39": "user_3AMTnyC41WG5cG9ryBTXXazSXp2",
"40": "user_3AMTo4h5975zlCH2h1GsSj4lmab",
"41": "user_3AMTo3S5SZW96jfUZhZ1qr80BSe",
"42": "user_3AMTo7ubYy6cgkvVbIClDnxR9UW",
"43": "user_3AMToANk7wfWM411FkpwodGtz6J",
"44": "user_3AMTo7Jb4xAnwiaUWdUqVPns950",
"45": "user_3AMToDel0WihAMkoD28W7pgSoFf",
"46": "user_3AMToGI2FXT9ZRi8WRoADjvu03i",
"47": "user_3AMToDID2tATAjoVnaaxToKon3R",
"48": "user_3AMToLwHwVZYvznCjPa58b29eQE",
"49": "user_3AMToRmg19Bu1CwZ8rGz4ODkxjS",
"50": "user_3AMToPjQulU7sRNtDe83TAnxnY1"
},
"classes": [
{
@ -101,42 +101,42 @@
"name": "1A",
"gradeId": 1,
"capacity": 20,
"supervisorId": "user_3AJAkSqshofbdPsW7lZh6q2eCe5"
"supervisorId": "user_3AMTkSb5aZsaWlYnCd2x5iImprs"
},
{
"id": 2,
"name": "2A",
"gradeId": 2,
"capacity": 20,
"supervisorId": "user_3AJAkVye7wKBBK8seog6gljyc7L"
"supervisorId": "user_3AMTkUkKWrV9QWt9dvD2qOjoxiE"
},
{
"id": 3,
"name": "3A",
"gradeId": 3,
"capacity": 20,
"supervisorId": "user_3AJAkXA9lrOHxsGcJNoJGOXKNOr"
"supervisorId": "user_3AMTkRjafcujtrgbyS4SNoWFgjh"
},
{
"id": 4,
"name": "4A",
"gradeId": 4,
"capacity": 20,
"supervisorId": "user_3AJAkc3f42kZzVPLvaRBFHor14J"
"supervisorId": "user_3AMTkfb5Y9O7a55cye9iQAHxLAB"
},
{
"id": 5,
"name": "5A",
"gradeId": 5,
"capacity": 20,
"supervisorId": "user_3AJAkbsXvHmZcGu3wFpRZm732LX"
"supervisorId": "user_3AMTkaTAmH3VOUCcxgeCfSTaaIX"
},
{
"id": 6,
"name": "6A",
"gradeId": 6,
"capacity": 20,
"supervisorId": "user_3AJAkSqshofbdPsW7lZh6q2eCe5"
"supervisorId": "user_3AMTkSb5aZsaWlYnCd2x5iImprs"
}
]
}

View File

@ -67,7 +67,7 @@ async function main() {
const { teacherMap, studentMap, classes } = data;
console.log("Cleaning old Schedule & Attendance data...");
const tablesToClean = ["Attendance", "Result", "Assignment", "Exam", "Lesson"];
const tablesToClean = ["LessonWhiteboard", "Attendance", "Result", "Assignment", "Exam", "Lesson"];
for (const table of tablesToClean) {
await supabase.from(table).delete().neq("id", "0" as any);
}
@ -86,6 +86,7 @@ async function main() {
let attendanceIdCounter = 1;
const lessonsData = [];
const whiteboardsData = [];
const examsData = [];
const assignmentsData = [];
const resultsData = [];
@ -149,6 +150,10 @@ async function main() {
teacherId: teacherId
});
whiteboardsData.push({
lessonId: lessonIdCounter
});
// 2. Insert Exam / Results (Random Probability)
if (Math.random() < CONFIG.examProbability) {
examsData.push({
@ -206,6 +211,7 @@ async function main() {
// Send payload in bulk batches to Supabase to prevent network/memory bottlenecks
await insertInChunks("Lesson", lessonsData);
await insertInChunks("LessonWhiteboard", whiteboardsData);
await insertInChunks("Exam", examsData);
await insertInChunks("Assignment", assignmentsData);
await insertInChunks("Result", resultsData);
@ -213,6 +219,7 @@ async function main() {
console.log(`\n✅ Timeline successfully generated!`);
console.log(`- Lessons: ${lessonsData.length}`);
console.log(`- Whiteboards: ${whiteboardsData.length}`);
console.log(`- Exams: ${examsData.length}`);
console.log(`- Assignments: ${assignmentsData.length}`);
console.log(`- Results: ${resultsData.length}`);

View File

@ -1,3 +1,4 @@
import Link from "next/link";
import FormContainer from "@/components/FormContainer";
import Pagination from "@/components/Pagination";
import Table from "@/components/Table";
@ -39,7 +40,7 @@ const LessonListPage = async ({
accessor: "teacher",
className: "hidden md:table-cell",
},
...(role === "admin"
...(role === "admin" || role === "teacher" || role === "student"
? [
{
header: "Actions",
@ -61,6 +62,16 @@ const LessonListPage = async ({
</td>
<td>
<div className="flex items-center gap-2">
{(role === "admin" || role === "teacher" || role === "student") && (
<Link href={`/lesson?lessonId=${item.id}`}>
<button
className="w-7 h-7 flex items-center justify-center rounded-full bg-lamaSky"
title="View Whiteboard"
>
<Image src="/student.png" alt="Board" width={14} height={14} />
</button>
</Link>
)}
{role === "admin" && (
<>
<FormContainer table="lesson" type="update" data={item} />

View File

@ -0,0 +1,218 @@
"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

@ -25,6 +25,7 @@ const BigCalendarContainer = async ({
const dataRes = rawData || [];
const data = dataRes.map((lesson) => ({
id: lesson.id,
title: lesson.name,
start: new Date(lesson.startTime),
end: new Date(lesson.endTime),

View File

@ -4,13 +4,15 @@ import { Calendar, momentLocalizer, View, Views } from "react-big-calendar";
import moment from "moment";
import "react-big-calendar/lib/css/react-big-calendar.css";
import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
const localizer = momentLocalizer(moment);
const BigCalendar = ({
data,
}: {
data: { title: string; start: Date; end: Date }[];
data: { id?: number; title: string; start: Date; end: Date }[];
}) => {
const [view, setView] = useState<View>(Views.WORK_WEEK);
const [date, setDate] = useState<Date>(new Date());
@ -23,7 +25,23 @@ const BigCalendar = ({
<Calendar
localizer={localizer}
events={data}
components={{}}
components={{
event: (props) => (
<div className="flex flex-col h-full justify-between p-1">
<span className="text-xs font-semibold truncate leading-tight" title={props.title}>{props.title}</span>
{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} />
<span>Board</span>
</Link>
)}
</div>
)
}}
startAccessor="start"
endAccessor="end"
views={["month", "work_week", "day"]}

View File

@ -465,7 +465,7 @@ export const createLesson = async (
) => {
try {
const supabase = await getSupabaseClient();
const { error: lessonError } = await supabase
const { data: newLesson, error: lessonError } = await supabase
.from("Lesson")
.insert([
{
@ -477,10 +477,23 @@ export const createLesson = async (
classId: data.classId,
teacherId: data.teacherId,
},
]);
])
.select()
.single();
if (lessonError) throw lessonError;
// Create an associated LessonWhiteboard entry
const { error: whiteboardError } = await supabase
.from("LessonWhiteboard")
.insert([
{
lessonId: newLesson.id,
},
]);
if (whiteboardError) throw whiteboardError;
return { success: true, error: false };
} catch (err) {
console.log(err);

View File

@ -0,0 +1,80 @@
"use server";
import { getSupabaseClient } from "./supabase";
export type SnapshotType = "planned" | "live" | "final";
// Get the whiteboard record for a lesson
export const getLessonWhiteboard = async (lessonId: number) => {
try {
const supabase = await getSupabaseClient();
const { data, error } = await supabase
.from("LessonWhiteboard")
.select("*")
.eq("lessonId", lessonId)
.single();
if (error) {
if (error.code === 'PGRST116') return { success: true, data: null }; // not found
throw error;
}
return { success: true, data };
} catch (err) {
console.error("Failed to fetch whiteboard:", err);
return { success: false, data: null };
}
};
// Save a specific snapshot state (planned, live, or final)
export const saveLessonSnapshot = async (
lessonId: number,
snapshotType: SnapshotType,
snapshotData: any
) => {
try {
const supabase = await getSupabaseClient();
const updatePayload: Record<string, any> = {};
if (snapshotType === "planned") updatePayload.plannedSnapshotData = snapshotData;
if (snapshotType === "live") updatePayload.liveSnapshotData = snapshotData;
if (snapshotType === "final") updatePayload.finalSnapshotData = snapshotData;
const { error } = await supabase
.from("LessonWhiteboard")
.update(updatePayload)
.eq("lessonId", lessonId);
if (error) throw error;
return { success: true };
} catch (err) {
console.error("Failed to save snapshot:", err);
return { success: false };
}
};
// Duplicate a planned snapshot to a new lesson
export const duplicateLessonPlan = async (sourceLessonId: number, targetLessonId: number) => {
try {
const supabase = await getSupabaseClient();
const { data: sourceBoard, error: fetchError } = await supabase
.from("LessonWhiteboard")
.select("plannedSnapshotData")
.eq("lessonId", sourceLessonId)
.single();
if (fetchError) throw fetchError;
if (!sourceBoard?.plannedSnapshotData) throw new Error("No planned snapshot found to copy.");
const { error: updateError } = await supabase
.from("LessonWhiteboard")
.update({ plannedSnapshotData: sourceBoard.plannedSnapshotData })
.eq("lessonId", targetLessonId);
if (updateError) throw updateError;
return { success: true };
} catch (err) {
console.error("Failed to duplicate lesson plan:", err);
return { success: false };
}
};

View File

@ -328,6 +328,47 @@ export type Database = {
},
]
}
LessonWhiteboard: {
Row: {
createdAt: string
finalSnapshotData: Json | null
id: number
lessonId: number
liveSnapshotData: Json | null
plannedSnapshotData: Json | null
title: string | null
updatedAt: string
}
Insert: {
createdAt?: string
finalSnapshotData?: Json | null
id?: number
lessonId: number
liveSnapshotData?: Json | null
plannedSnapshotData?: Json | null
title?: string | null
updatedAt?: string
}
Update: {
createdAt?: string
finalSnapshotData?: Json | null
id?: number
lessonId?: number
liveSnapshotData?: Json | null
plannedSnapshotData?: Json | null
title?: string | null
updatedAt?: string
}
Relationships: [
{
foreignKeyName: "LessonWhiteboard_lessonId_fkey"
columns: ["lessonId"]
isOneToOne: true
referencedRelation: "Lesson"
referencedColumns: ["id"]
},
]
}
Parent: {
Row: {
address: string

View File

@ -0,0 +1,19 @@
-- CreateTable LessonWhiteboard
CREATE TABLE "LessonWhiteboard" (
"id" SERIAL NOT NULL,
"lessonId" INTEGER NOT NULL,
"title" TEXT,
"plannedSnapshotData" JSONB,
"liveSnapshotData" JSONB,
"finalSnapshotData" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "LessonWhiteboard_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "LessonWhiteboard" ADD CONSTRAINT "LessonWhiteboard_lessonId_fkey" FOREIGN KEY ("lessonId") REFERENCES "Lesson"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- CreateIndex
CREATE UNIQUE INDEX "LessonWhiteboard_lessonId_key" ON "LessonWhiteboard"("lessonId");

View File

@ -0,0 +1,15 @@
ALTER TABLE "LessonWhiteboard" ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Admins have full access" ON "LessonWhiteboard" FOR ALL USING (is_admin());
CREATE POLICY "Users can view permitted lesson whiteboards" ON "LessonWhiteboard" FOR SELECT USING (
is_admin() OR "lessonId" IN (SELECT auth_user_lessons())
);
CREATE POLICY "Teachers can update lesson whiteboards" ON "LessonWhiteboard" FOR UPDATE USING (
is_admin() OR ("lessonId" IN (SELECT auth_user_lessons()) AND requesting_user_role() = 'teacher')
);
CREATE POLICY "Teachers can insert lesson whiteboards" ON "LessonWhiteboard" FOR INSERT WITH CHECK (
is_admin() OR ("lessonId" IN (SELECT auth_user_lessons()) AND requesting_user_role() = 'teacher')
);