This commit is contained in:
rgrgogu
2026-05-20 13:25:03 +08:00
parent 2b1955608d
commit 95242709b0
71 changed files with 5535 additions and 1035 deletions
@@ -0,0 +1,132 @@
import { useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useCourses } from "@/contexts/AdminCoursesContext";
import { useAuth } from "@/contexts/AuthContext";
import DataTable from "@/components/generic/Table/DataTable";
import { FilterSheet } from "@/components/generic/Sheet/FilterSheet";
import { RestoreDialog } from "@/components/generic/Dialogs/RestoreDialog";
import { buildDataColumns, columnPinning } from "../../config/courses/archive/columns.config";
import { buildToolbarActions } from "../../config/courses/archive/toolbar.config";
import { buildSelectionActions } from "../../config/courses/archive/selection.config";
import { buildRowActions } from "../../config/courses/archive/rowActions.config";
import { getTimestamp } from "@/utils/timestamp.util";
export default function ArchivedCoursesTable() {
const [restoreTarget, setRestoreTarget] = useState(null);
const [restoreIds, setRestoreIds] = useState(null);
const tableRefsRef = useRef({
getFilters: () => [],
getSort: () => [],
resetSelection: () => { },
setFilters: () => { },
});
const navigate = useNavigate();
const { courses, attributes, pagination, setPagination, loading, fetchArchivedCourses, restoreCourse, restoreCourses } = useCourses();
const handleRefsReady = (refs) => {
tableRefsRef.current = refs;
};
const exportConfig = {
allData: courses,
attributes,
filename: `${getTimestamp()}_ArchivedCourses`,
sheetName: "Archived Courses",
};
const rowActions = useMemo(() => buildRowActions({
navigate,
onRestore: (row) => setRestoreTarget(row),
}), []);
const toolbarActions = buildToolbarActions({
fetchArchivedCourses,
pagination,
exportConfig,
navigate,
getFilters: () => tableRefsRef.current.getFilters(),
getSort: () => tableRefsRef.current.getSort(),
getTableInstance: () => tableRefsRef.current.tableInstance,
});
const selectionActions = buildSelectionActions({
exportConfig,
restoreCourse: (row) => setRestoreTarget(row), // single
restoreCourses: (ids) => setRestoreIds(ids), // bulk
getTableInstance: () => tableRefsRef.current.tableInstance,
});
const columns = useMemo(
() => buildDataColumns(attributes, rowActions),
[attributes]
);
const handleRestoreSuccess = () => {
setRestoreTarget(null);
setRestoreIds(null);
tableRefsRef.current.resetSelection?.();
fetchArchivedCourses({ page: 1, limit: pagination?.limit ?? 10 });
};
return (
<>
<DataTable
title="Archived Courses"
data={courses}
columns={columns}
attributes={attributes}
pagination={pagination}
setPagination={setPagination}
loading={loading}
onFetch={fetchArchivedCourses}
onFetchFilterData={() => []}
onRefsReady={handleRefsReady}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
open={open}
onOpenChange={onOpenChange}
column={column}
attr={attr}
data={data}
loading={loading}
/>
)}
columnPinning={columnPinning}
toolbarActions={toolbarActions}
selectionActions={selectionActions}
recordLabel="course"
emptyMessage="No courses found."
/>
{/* Single restore */}
<RestoreDialog
open={!!restoreTarget}
onOpenChange={(v) => !v && setRestoreTarget(null)}
entity={restoreTarget}
entityLabel="Course"
getName={(c) => c?.title}
onRestore={(c) => restoreCourse(c?.course_id)}
loading={loading}
onSuccess={handleRestoreSuccess}
/>
{/* Bulk restore */}
<RestoreDialog
open={!!restoreIds}
onOpenChange={(v) => !v && setRestoreIds(null)}
ids={restoreIds ?? []}
entityLabel="Course"
onRestore={restoreCourses}
loading={loading}
onSuccess={handleRestoreSuccess}
/>
</>
);
}
@@ -17,6 +17,7 @@ import { getTimestamp } from "@/utils/timestamp.util";
export default function CoursesTable() {
const [archiveTarget, setArchiveTarget] = useState(null);
const [archiveIds, setArchiveIds] = useState(null);
const tableRefsRef = useRef({
getFilters: () => [],
@@ -26,9 +27,8 @@ export default function CoursesTable() {
});
const navigate = useNavigate();
const { user } = useAuth();
const { courses, attributes, pagination, setPagination, loading, fetchCourses, deleteCourse, } = useCourses();
const { courses, attributes, pagination, setPagination, loading, fetchCourses, archiveCourse, archiveCourses, fetchCourseFieldValues } = useCourses();
const handleRefsReady = (refs) => {
tableRefsRef.current = refs;
@@ -42,7 +42,9 @@ export default function CoursesTable() {
};
const rowActions = useMemo(() => buildRowActions({
onView: (row) => navigate(`/admin/courses/${row.course_id}`),
onAssessment: (row) => navigate(`/admin/courses/${row.course_id}/assessment`),
onViewUnits: (row) => navigate(`/admin/courses/${row.course_id}/units`),
onView: (row) => navigate(`/admin/courses/${row.course_id}/view`),
onEdit: (row) => navigate(`/admin/courses/${row.course_id}/edit`),
onArchive: (row) => setArchiveTarget(row),
}), []);
@@ -60,16 +62,18 @@ export default function CoursesTable() {
const selectionActions = buildSelectionActions({
exportConfig,
onArchive: (row) => setArchiveTarget(row),
onArchiveMany: (ids) => setArchiveIds(ids),
getTableInstance: () => tableRefsRef.current.tableInstance,
});
const columns = useMemo(
() => buildDataColumns(attributes, rowActions),
[attributes, rowActions]
[attributes]
);
const handleArchiveSuccess = () => {
setArchiveTarget(null);
setArchiveIds(null);
tableRefsRef.current.resetSelection?.();
fetchCourses({ page: 1, limit: pagination?.limit ?? 10 });
};
@@ -85,7 +89,7 @@ export default function CoursesTable() {
setPagination={setPagination}
loading={loading}
onFetch={fetchCourses}
onFetchFilterData={() => []}
onFetchFilterData={fetchCourseFieldValues}
onRefsReady={handleRefsReady}
renderFilterSheet={({ open, onOpenChange, column, attr, data, loading }) => (
<FilterSheet
@@ -104,13 +108,25 @@ export default function CoursesTable() {
emptyMessage="No courses found."
/>
{/* ── Single archive ── */}
<ArchiveDialog
open={!!archiveTarget}
onOpenChange={(v) => !v && setArchiveTarget(null)}
entity={archiveTarget}
entityLabel="Course"
getName={(c) => c?.title}
onArchive={(c) => deleteCourse(c?.course_id)}
onArchive={(c) => archiveCourse(c?.course_id)}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
{/* ── Bulk archive ── */}
<ArchiveDialog
open={!!archiveIds}
onOpenChange={(v) => !v && setArchiveIds(null)}
ids={archiveIds ?? []}
entityLabel="Course"
onArchive={(ids) => archiveCourses(ids)}
loading={loading}
onSuccess={handleArchiveSuccess}
/>
@@ -0,0 +1,208 @@
import { Eye, ImageIcon, VideoIcon } from "lucide-react";
import { WYSIWYG_STYLES } from "@/components/generic/Blocks/TextBlock";
export function LessonHeader({ lesson }) {
if (!lesson) return null;
return (
<div className="space-y-4 pb-2">
<div>
<h1 style={{ fontSize: "1.875rem", fontWeight: 700, lineHeight: 1.2, margin: "0 0 0.4rem 0" }}>
{lesson.title}
</h1>
{lesson.description && (
<p style={{ margin: "0.2rem 0", lineHeight: 1.75, textAlign: "justify" }}
className="text-muted-foreground">
{lesson.description}
</p>
)}
</div>
{lesson.objectives?.length > 0 && (
<div className="rounded-lg border p-4 space-y-3">
<div className="flex items-center gap-2">
<div className="h-8 w-8 rounded-md bg-green-100 flex items-center justify-center shrink-0">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-4 w-4 text-green-600"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
<circle cx="12" cy="12" r="6" />
<circle cx="12" cy="12" r="2" />
</svg>
</div>
<p className="text-sm font-semibold">Objective</p>
</div>
<ul className="space-y-1.5 list-disc list-inside">
{lesson.objectives.map((o) => (
<li key={o.objective_id} className="text-sm text-muted-foreground">
{o.text}
</li>
))}
</ul>
</div>
)}
</div>
);
}
export function PreviewImage({ url, alt }) {
if (!url) {
return (
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<ImageIcon className="h-4 w-4" />
No image
</div>
);
}
return (
<img src={url} alt={alt ?? ""} className="w-full rounded-md object-cover aspect-video" />
);
}
export function PreviewVideo({ url, thumb }) {
if (!url) {
return (
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<VideoIcon className="h-4 w-4" />
No video
</div>
);
}
return (
<div className="relative rounded-md overflow-hidden aspect-video bg-muted">
{thumb ? (
<img src={thumb} alt="Video thumbnail" className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex items-center justify-center">
<VideoIcon className="h-10 w-10 text-muted-foreground/40" />
</div>
)}
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="h-10 w-10 rounded-full bg-black/50 flex items-center justify-center">
<VideoIcon className="h-5 w-5 text-white" />
</div>
</div>
<div className="absolute bottom-0 inset-x-0 bg-black/60 px-2 py-1">
<p className="text-white text-[10px] truncate">{url}</p>
</div>
</div>
);
}
export function PreviewBlock({ block }) {
const { type, content } = block;
if (type === "text") {
if (!content.body) {
return <div className="text-xs text-muted-foreground italic py-2">Empty text block</div>;
}
return (
<div
className="wysiwyg-preview text-sm"
dangerouslySetInnerHTML={{ __html: content.body }}
/>
);
}
if (type === "image") {
if (!content.url) {
return (
<div className="flex items-center justify-center h-24 rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<ImageIcon className="h-4 w-4" />
No image selected
</div>
);
}
return (
<figure>
<img src={content.url} alt={content.alt ?? ""} className="w-full rounded-md object-cover" />
</figure>
);
}
if (type === "text-image") {
const imgLeft = content.image_position === "left";
return (
<div className="grid grid-cols-2 gap-4 items-start">
{imgLeft && <PreviewImage url={content.url} alt={content.alt} />}
<div
className="wysiwyg-preview text-sm"
dangerouslySetInnerHTML={{ __html: content.body || "<p class='text-muted-foreground italic'>Empty text</p>" }}
/>
{!imgLeft && <PreviewImage url={content.url} alt={content.alt} />}
</div>
);
}
if (type === "video") {
if (!content.url) {
return (
<div className="flex items-center justify-center h-24 rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<VideoIcon className="h-4 w-4" />
No video selected
</div>
);
}
return <PreviewVideo url={content.url} thumb={content.thumbnail_url} />;
}
if (type === "text-video") {
const vidLeft = content.video_position === "left";
return (
<div className="grid grid-cols-2 gap-4 items-start">
{vidLeft && <PreviewVideo url={content.url} thumb={content.thumbnail_url} />}
<div
className="wysiwyg-preview text-sm"
dangerouslySetInnerHTML={{ __html: content.body || "<p class='text-muted-foreground italic'>Empty text</p>" }}
/>
{!vidLeft && <PreviewVideo url={content.url} thumb={content.thumbnail_url} />}
</div>
);
}
return null;
}
export function PreviewContent({ lesson, blocks, empty = "No content yet." }) {
return (
<>
<LessonHeader lesson={lesson} />
{blocks.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-2 py-16 text-sm text-muted-foreground">
<Eye className="h-8 w-8 opacity-20" />
<p>{empty}</p>
</div>
) : (
blocks.map((block) => (
<div key={block.id}>
<PreviewBlock block={block} />
</div>
))
)}
</>
);
}
export function PreviewChrome({ title, children }) {
return (
<div className="rounded-xl border bg-card shadow-sm overflow-hidden">
<style>{WYSIWYG_STYLES}</style>
<div className="flex items-center gap-1.5 px-3 py-2 bg-muted/60 border-b">
<span className="h-2.5 w-2.5 rounded-full bg-red-400" />
<span className="h-2.5 w-2.5 rounded-full bg-yellow-400" />
<span className="h-2.5 w-2.5 rounded-full bg-green-400" />
<div className="flex-1 mx-3 h-5 rounded bg-background/60 border text-[10px] flex items-center px-2 text-muted-foreground/60 truncate">
{title ?? "Lesson Preview"}
</div>
<Eye className="h-3.5 w-3.5 text-muted-foreground/60" />
</div>
{children}
</div>
);
}
@@ -47,7 +47,9 @@ export default function LessonsTable({ courseId, unitId }) {
);
const rowActions = useMemo(() => buildRowActions({
onView: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}`),
onViewPage: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}/page/view`),
onCreatePage: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}/page`),
onView: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}/view`),
onEdit: (row) => navigate(`/admin/courses/${courseId}/units/${unitId}/lessons/${row.lesson_id}/edit`),
onArchive: (row) => setArchiveTarget(row),
}), [courseId, unitId]);
@@ -0,0 +1,274 @@
import { useState } from "react";
import { Plus, Trash2, GripVertical, CheckCircle2, Circle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
const QUESTION_TYPES = [
{ value: "true_false", label: "True / False" },
{ value: "multiple_choice", label: "Multiple Choice (1 correct)" },
{ value: "multi_select", label: "Multi Select (multiple correct)" },
];
function FieldError({ message }) {
if (!message) return null;
return <p className="text-xs text-destructive mt-1">{message}</p>;
}
// ── Single Option Row ─────────────────────────────────────────────────────────
function OptionRow({ option, index, questionType, onUpdate, onRemove, onToggleCorrect }) {
const isCorrect = option.is_correct;
return (
<div className={cn(
"flex items-center gap-2 rounded-lg border px-3 py-2 transition-colors",
isCorrect ? "border-green-300 bg-green-50/60" : "border-border bg-background"
)}>
<GripVertical className="h-4 w-4 text-muted-foreground/40 shrink-0" />
{/* Correct toggle */}
<button
type="button"
onClick={() => onToggleCorrect(index)}
className="shrink-0"
title={isCorrect ? "Mark as incorrect" : "Mark as correct"}
>
{isCorrect
? <CheckCircle2 className="h-4 w-4 text-green-600" />
: <Circle className="h-4 w-4 text-muted-foreground" />
}
</button>
<Input
value={option.text}
onChange={(e) => onUpdate(index, { ...option, text: e.target.value })}
placeholder={`Option ${index + 1}`}
className="flex-1 border-0 shadow-none focus-visible:ring-0 p-0 h-auto text-sm"
/>
<button
type="button"
onClick={() => onRemove(index)}
className="shrink-0 text-muted-foreground hover:text-destructive transition-colors"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
);
}
// ── Question Card ─────────────────────────────────────────────────────────────
export function QuestionCard({ question, index, onChange, onRemove, error }) {
const updateField = (field, value) => onChange({ ...question, [field]: value });
const updateOption = (i, updated) => {
const options = [...question.options];
options[i] = updated;
onChange({ ...question, options });
};
const toggleCorrect = (i) => {
const options = question.options.map((o, idx) => {
if (question.type === "multiple_choice" || question.type === "true_false") {
// single correct — deselect all others
return { ...o, is_correct: idx === i };
}
// multi_select — toggle individual
return idx === i ? { ...o, is_correct: !o.is_correct } : o;
});
onChange({ ...question, options });
};
const addOption = () => {
onChange({
...question,
options: [
...question.options,
{ text: "", is_correct: false, order_index: question.options.length },
],
});
};
const removeOption = (i) => {
onChange({
...question,
options: question.options.filter((_, idx) => idx !== i),
});
};
const handleTypeChange = (type) => {
// Reset options based on type
const defaultOptions =
type === "true_false"
? [
{ text: "True", is_correct: true, order_index: 0 },
{ text: "False", is_correct: false, order_index: 1 },
]
: question.options.map((o) => ({ ...o, is_correct: false }));
onChange({ ...question, type, options: defaultOptions });
};
const correctCount = question.options.filter((o) => o.is_correct).length;
return (
<div className="rounded-xl border bg-card shadow-sm overflow-hidden">
{/* Card header */}
<div className="flex items-center justify-between px-4 py-3 bg-muted/40 border-b">
<div className="flex items-center gap-2">
<span className="flex h-6 w-6 items-center justify-center rounded-full bg-primary/10 text-primary text-xs font-semibold">
{index + 1}
</span>
<Select value={question.type} onValueChange={handleTypeChange}>
<SelectTrigger className="h-7 text-xs border-0 bg-transparent shadow-none w-auto gap-1 px-1">
<SelectValue />
</SelectTrigger>
<SelectContent>
{QUESTION_TYPES.map((t) => (
<SelectItem key={t.value} value={t.value} className="text-xs">
{t.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Badge variant="secondary" className="text-xs">
{question.points ?? 1} pt{(question.points ?? 1) !== 1 ? "s" : ""}
</Badge>
{correctCount > 0 && (
<Badge variant="outline" className="text-xs text-green-600 border-green-300">
{correctCount} correct
</Badge>
)}
</div>
<Button
type="button"
variant="ghost"
size="icon"
onClick={onRemove}
className="h-7 w-7 text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
<div className="p-4 space-y-4">
{/* Question text */}
<div className="space-y-1.5">
<Label className="text-xs text-muted-foreground uppercase tracking-wide">Question</Label>
<Textarea
value={question.question}
onChange={(e) => updateField("question", e.target.value)}
placeholder="Enter your question here…"
rows={2}
className="resize-none"
/>
<FieldError message={error?.question} />
</div>
{/* Options */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
Options
<span className="ml-1 normal-case text-muted-foreground/60">
— click circle to mark correct
</span>
</Label>
{question.type !== "true_false" && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={addOption}
className="h-6 text-xs gap-1"
>
<Plus className="h-3 w-3" />
Add option
</Button>
)}
</div>
<div className="space-y-2">
{question.options.map((option, i) => (
<OptionRow
key={i}
option={option}
index={i}
questionType={question.type}
onUpdate={updateOption}
onRemove={removeOption}
onToggleCorrect={toggleCorrect}
/>
))}
</div>
<FieldError message={error?.options} />
</div>
{/* Points + Explanation row */}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label className="text-xs text-muted-foreground uppercase tracking-wide">Points</Label>
<Input
type="number"
min={1}
value={question.points ?? 1}
onChange={(e) => updateField("points", parseInt(e.target.value) || 1)}
className="h-8 text-sm"
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs text-muted-foreground uppercase tracking-wide">
Explanation <span className="normal-case text-muted-foreground/60">(optional)</span>
</Label>
<Input
value={question.explanation ?? ""}
onChange={(e) => updateField("explanation", e.target.value)}
placeholder="Shown after answer"
className="h-8 text-sm"
/>
</div>
</div>
</div>
</div>
);
}
// ── Make a blank question ─────────────────────────────────────────────────────
export function makeQuestion(type = "multiple_choice") {
const defaultOptions = {
true_false: [
{ text: "True", is_correct: true, order_index: 0 },
{ text: "False", is_correct: false, order_index: 1 },
],
multiple_choice: [
{ text: "", is_correct: true, order_index: 0 },
{ text: "", is_correct: false, order_index: 1 },
{ text: "", is_correct: false, order_index: 2 },
],
multi_select: [
{ text: "", is_correct: true, order_index: 0 },
{ text: "", is_correct: true, order_index: 1 },
{ text: "", is_correct: false, order_index: 2 },
],
};
return {
_tempId: crypto.randomUUID(),
type,
question: "",
explanation: "",
points: 1,
order_index: 0,
options: defaultOptions[type] ?? [],
};
}
@@ -48,7 +48,9 @@ export default function UnitsTable({ courseId }) {
);
const rowActions = useMemo(() => buildRowActions({
onView: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}`),
onQuiz: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}/quiz`),
onViewLessons: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}/lessons`),
onView: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}/view`),
onEdit: (row) => navigate(`/admin/courses/${courseId}/units/${row.unit_id}/edit`),
onArchive: (row) => setArchiveTarget(row),
}), [courseId]);