Signed-off-by: Kenneth Obsequio <k80308392@gmail.com>
This commit is contained in:
2026-07-11 12:12:40 +08:00
parent 01a2c63b06
commit 71f758fe0b
66 changed files with 3055 additions and 939 deletions
@@ -1,66 +1,451 @@
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useForm, useWatch } from "react-hook-form";
import { z } from "zod";
import { useForm, useFieldArray, useWatch } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { ArrowLeft } from "lucide-react";
import { z } from "zod";
import { nanoid } from "nanoid";
import {
ArrowLeft, ChevronLeft, ChevronRight, Check,
FileText, BookOpen, LayoutTemplate, ClipboardCheck,
Plus, Trash2,
} from "lucide-react";
import { useLibrary } from "@/contexts/AdminLibraryContext";
import { useAuth } from "@/contexts/AuthContext";
import { PageMeta } from "@/contexts/MetadataContext";
import api from "@/utils/api.util";
import { cn } from "@/lib/utils";
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 { Spinner } from "@/components/ui/spinner";
import { Badge } from "@/components/ui/badge";
import {
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerDescription,
DrawerFooter, DrawerClose,
} from "@/components/ui/drawer";
import { BlockList, DEFAULT_CONTENT } from "@/components/generic/BlockList";
import { AddBlockMenu } from "@/components/generic/AddBlockMenu";
import { PreviewContent, PreviewChrome } from "../../../components/courses/LessonsPreview";
import { useUnsavedChangesGuard } from "@/hooks/useUnsavedChangesGuard";
function makeBlock(type) {
return { id: nanoid(), type, content: { ...DEFAULT_CONTENT[type] } };
}
// ─── Schema ───────────────────────────────────────────────────────────────────
const lessonSchema = z.object({
title: z.string().min(1, "Title is required."),
description: z.string().optional(),
objectives: z.array(
z.object({ value: z.string().min(1, "Objective cannot be empty.") })
).optional(),
blocks: z.array(z.any()).optional(),
});
const schema = z.object({
title: z.string().min(1, "Title is required."),
description: z.string().optional(),
subscription: z.string().optional(),
lessons: z.array(lessonSchema).optional(),
});
const DEFAULT_VALUES = {
title: "",
description: "",
subscription: "",
lessons: [],
};
const STEPS = [
{ id: 0, label: "Create Unit", icon: FileText },
{ id: 1, label: "Lessons", icon: BookOpen },
{ id: 2, label: "Page Builder", icon: LayoutTemplate },
{ id: 3, label: "Review", icon: ClipboardCheck },
];
// Fields validated with trigger() before advancing past each step.
// Empty array means "validate the whole form" (nothing new to check that step).
const STEP_FIELDS = [["title", "description", "subscription"], ["lessons"], [], []];
function FieldError({ message }) {
if (!message) return null;
return <p className="text-xs text-destructive mt-1">{message}</p>;
}
// ─── Step 1 — Create Unit ─────────────────────────────────────────────────────
function StepUnit({ register, errors, control, setValue, tierCategories }) {
const watchedSubscr = useWatch({ control, name: "subscription" });
return (
<div className="space-y-5">
<div className="space-y-1.5">
<Label htmlFor="title">Title <span className="text-destructive">*</span></Label>
<Input id="title" placeholder="Unit title" {...register("title")} />
<FieldError message={errors.title?.message} />
</div>
<div className="space-y-1.5">
<Label htmlFor="description">Description</Label>
<Textarea id="description" placeholder="Optional description" rows={3} {...register("description")} />
</div>
<div className="space-y-1.5">
<Label>Subscription</Label>
<Select
value={watchedSubscr || "__open"}
onValueChange={(val) => setValue("subscription", val === "__open" ? "" : val, { shouldDirty: true })}
>
<SelectTrigger>
<SelectValue placeholder="No tier gate" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__open">No tier gate (open)</SelectItem>
{tierCategories.map((c) => (
<SelectItem key={c.slug} value={c.slug}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Optional. Gates this unit directly, independent of any course it may later be attached to.
</p>
</div>
</div>
);
}
// ─── Step 2 — Lessons ──────────────────────────────────────────────────────────
function LessonObjectives({ control, register, lessonIndex }) {
const { fields, append, remove } = useFieldArray({ control, name: `lessons.${lessonIndex}.objectives` });
return (
<div className="space-y-2">
<Label className="text-xs text-muted-foreground uppercase tracking-wide">Objectives</Label>
{fields.map((f, oi) => (
<div key={f.id} className="flex items-center gap-2">
<Input {...register(`lessons.${lessonIndex}.objectives.${oi}.value`)} placeholder="Learning objective" />
<Button
type="button"
variant="ghost"
size="icon"
className="text-destructive shrink-0"
onClick={() => remove(oi)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
<Button type="button" variant="outline" size="sm" onClick={() => append({ value: "" })}>
<Plus className="h-3.5 w-3.5 mr-1" /> Add Objective
</Button>
</div>
);
}
function StepLessons({ control, register, errors }) {
const { fields, append, remove } = useFieldArray({ control, name: "lessons" });
return (
<div className="space-y-4">
{fields.length === 0 && (
<p className="text-sm text-muted-foreground">
No lessons yet. A unit can be created without any, but add one now if you'd like to build its content in this wizard.
</p>
)}
{fields.map((f, i) => (
<div key={f.id} className="border border-border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-muted-foreground">Lesson {i + 1}</span>
<Button
type="button"
variant="ghost"
size="sm"
className="text-destructive h-7 px-2"
onClick={() => remove(i)}
>
Remove
</Button>
</div>
<div className="space-y-1.5">
<Label>Title <span className="text-destructive">*</span></Label>
<Input {...register(`lessons.${i}.title`)} placeholder="Lesson title" />
<FieldError message={errors.lessons?.[i]?.title?.message} />
</div>
<div className="space-y-1.5">
<Label>Description</Label>
<Textarea rows={2} {...register(`lessons.${i}.description`)} placeholder="Optional description" />
</div>
<LessonObjectives control={control} register={register} lessonIndex={i} />
</div>
))}
<Button
type="button"
variant="outline"
className="w-full"
onClick={() => append({ title: "", description: "", objectives: [], blocks: [] })}
>
<Plus className="h-4 w-4 mr-1" /> Add Lesson
</Button>
</div>
);
}
// ─── Step 3 — Page Builder ─────────────────────────────────────────────────────
function StepPageBuilder({ control, setValue }) {
const lessons = useWatch({ control, name: "lessons" }) ?? [];
const [rawIndex, setActiveIndex] = useState(0);
const [drawerOpen, setDrawerOpen] = useState(false);
if (lessons.length === 0) {
return (
<p className="text-sm text-muted-foreground">
Add at least one lesson in the previous step to build its page content here.
</p>
);
}
// Clamp instead of syncing via effect — a removed lesson (from the previous
// step) can leave rawIndex pointing past the end of the array.
const activeIndex = Math.min(rawIndex, lessons.length - 1);
const activeLesson = lessons[activeIndex];
const blocks = activeLesson?.blocks ?? [];
const setBlocks = (updater) => {
const next = typeof updater === "function" ? updater(blocks) : updater;
setValue(`lessons.${activeIndex}.blocks`, next, { shouldDirty: true });
};
const addBlock = (type) => setBlocks((prev) => [...prev, makeBlock(type)]);
const updateBlock = (id, content) => setBlocks((prev) => prev.map((b) => (b.id === id ? { ...b, content } : b)));
const deleteBlock = (id) => setBlocks((prev) => prev.filter((b) => b.id !== id));
const moveBlock = (id, direction) => setBlocks((prev) => {
const index = prev.findIndex((b) => b.id === id);
const swapIndex = direction === "up" ? index - 1 : index + 1;
if (swapIndex < 0 || swapIndex >= prev.length) return prev;
const next = [...prev];
[next[index], next[swapIndex]] = [next[swapIndex], next[index]];
return next;
});
return (
<div className="space-y-3">
{lessons.map((l, i) => (
<div key={i} className="flex items-center justify-between border border-border rounded-lg p-4">
<div>
<p className="text-sm font-medium">{l.title || `Lesson ${i + 1}`}</p>
<p className="text-xs text-muted-foreground">
{(l.blocks?.length ?? 0)} block{(l.blocks?.length ?? 0) !== 1 ? "s" : ""}
</p>
</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => { setActiveIndex(i); setDrawerOpen(true); }}
>
<LayoutTemplate className="h-4 w-4 mr-1.5" />
Open Page Builder
</Button>
</div>
))}
<Drawer open={drawerOpen} onOpenChange={setDrawerOpen} shouldScaleBackground>
<DrawerContent className="data-[vaul-drawer-direction=bottom]:max-h-[90vh]">
<DrawerHeader className="border-b text-left">
<DrawerTitle>Page Builder</DrawerTitle>
<DrawerDescription>{activeLesson?.title || `Lesson ${activeIndex + 1}`}</DrawerDescription>
</DrawerHeader>
<div className="px-4 pt-3">
<Tabs value={String(activeIndex)} onValueChange={(v) => setActiveIndex(Number(v))}>
<TabsList className="flex-wrap h-auto">
{lessons.map((l, i) => (
<TabsTrigger key={i} value={String(i)} className="gap-1.5">
{l.title || `Lesson ${i + 1}`}
{l.blocks?.length > 0 && (
<Badge variant="secondary" className="text-[10px] px-1.5">{l.blocks.length}</Badge>
)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
</div>
<div className="flex-1 overflow-y-auto p-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
Editor
{blocks.length > 0 && (
<span className="text-xs font-normal">· {blocks.length} block{blocks.length !== 1 ? "s" : ""}</span>
)}
</div>
<BlockList blocks={blocks} onUpdate={updateBlock} onMove={moveBlock} onDelete={deleteBlock} />
<AddBlockMenu onAdd={addBlock} />
</div>
<div className="space-y-3">
<div className="text-sm font-medium text-muted-foreground">Live Preview</div>
<PreviewChrome title={activeLesson.title}>
<div className="p-6 space-y-5 min-h-[300px]">
<PreviewContent
lesson={{
title: activeLesson.title,
description: activeLesson.description,
objectives: (activeLesson.objectives ?? []).map((o, oi) => ({ objective_id: oi, text: o.value })),
}}
blocks={blocks}
empty="Your content will appear here as you build."
/>
</div>
</PreviewChrome>
</div>
</div>
</div>
<DrawerFooter className="border-t flex-row justify-end">
<DrawerClose asChild>
<Button type="button">Done</Button>
</DrawerClose>
</DrawerFooter>
</DrawerContent>
</Drawer>
</div>
);
}
// ─── Step 4 — Review ───────────────────────────────────────────────────────────
function SummaryRow({ label, value }) {
if (!value) return null;
return (
<div className="flex justify-between py-1.5 text-sm">
<span className="text-muted-foreground min-w-[140px]">{label}</span>
<span className="text-foreground text-right">{value}</span>
</div>
);
}
function StepReview({ data, tierCategories }) {
const tierName = tierCategories.find((c) => c.slug === data.subscription)?.name;
return (
<div className="space-y-4">
<div className="border border-border rounded-lg p-4 space-y-1">
<div className="flex items-center gap-2 mb-3">
<FileText className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Unit</span>
</div>
<SummaryRow label="Title" value={data.title} />
<SummaryRow label="Description" value={data.description} />
<SummaryRow label="Subscription" value={tierName || "No tier gate (open)"} />
</div>
{(data.lessons ?? []).length === 0 ? (
<p className="text-sm text-muted-foreground">No lessons will be created with this unit.</p>
) : (
<div className="border border-border rounded-lg p-4 space-y-3">
<div className="flex items-center gap-2">
<BookOpen className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">Lessons ({data.lessons.length})</span>
</div>
{data.lessons.map((l, i) => (
<div key={i} className="flex items-center justify-between text-sm border-t border-border pt-2 first:border-t-0 first:pt-0">
<span>{i + 1}. {l.title}</span>
<span className="text-muted-foreground text-xs">
{(l.objectives ?? []).filter((o) => o.value).length} objective(s) · {(l.blocks ?? []).length} block(s)
</span>
</div>
))}
</div>
)}
</div>
);
}
// ─── Main Page ──────────────────────────────────────────────────────────────
export default function AddLibraryUnit() {
const navigate = useNavigate();
const { createUnit, loading } = useLibrary();
const { createUnitFull, loading } = useLibrary();
const { user } = useAuth();
const [step, setStep] = useState(0);
const [tierCategories, setTierCategories] = useState([]);
useEffect(() => {
api.get("/admin/tiers/categories")
.then(({ data }) => setTierCategories((data.data ?? []).filter((c) => c.is_active)))
.catch(() => {});
}, []);
const { register, handleSubmit, control, setValue, formState: { errors } } = useForm({
const {
register, control, trigger, getValues, setValue,
formState: { errors, isDirty },
} = useForm({
resolver: zodResolver(schema),
defaultValues: { title: "", description: "", subscription: "" },
defaultValues: DEFAULT_VALUES,
mode: "onTouched",
});
const watchedSubscr = useWatch({ control, name: "subscription" });
const { bypassOnce, dialog: unsavedChangesDialog } = useUnsavedChangesGuard(isDirty);
const onSubmit = async (data) => {
const result = await createUnit({ ...data, subscription: data.subscription || null, createdBy: user?.user_id });
const handleNext = async () => {
const fields = STEP_FIELDS[step];
const valid = await trigger(fields.length ? fields : undefined);
if (valid) setStep((s) => Math.min(s + 1, STEPS.length - 1));
};
const handleBack = () => {
if (step === 0) navigate(-1);
else setStep((s) => s - 1);
};
// Called manually on click — no <form> tag, so no accidental submit from
// Enter or another button while stepping through the wizard.
const handleCreate = async () => {
const valid = await trigger();
if (!valid) return;
const data = getValues();
const payload = {
title: data.title,
description: data.description || null,
subscription: data.subscription || null,
lessons: (data.lessons ?? []).map((l) => ({
title: l.title,
description: l.description || null,
objectives: (l.objectives ?? []).map((o) => o.value).filter(Boolean),
blocks: l.blocks ?? [],
})),
createdBy: user?.user_id,
};
// Single request creates the unit, its lessons, objectives, and page
// content in one transaction — no per-lesson/per-page follow-up calls.
const result = await createUnitFull(payload);
if (!result) return;
bypassOnce();
navigate("/admin/units");
};
return (
<section className="bg-muted h-full">
<section className="bg-muted min-h-full">
<PageMeta title="Add Unit - STARR" />
<div className="lg:container lg:mx-auto lg:px-0 flex flex-col items-center px-4 py-10">
<div className="w-full max-w-3xl mx-auto space-y-6">
<div className="w-full max-w-2xl mx-auto">
<div className="flex items-center gap-3 mb-6">
<div className="flex items-center gap-3">
<Button type="button" variant="ghost" size="icon" onClick={() => navigate(-1)}>
<ArrowLeft className="h-4 w-4" />
</Button>
@@ -72,57 +457,91 @@ export default function AddLibraryUnit() {
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<div className="rounded-lg border bg-card p-6 space-y-5">
{/* Stepper */}
<div className="flex items-center gap-0">
{STEPS.map((s, i) => {
const Icon = s.icon;
const isActive = step === i;
const isDone = step > i;
<div className="space-y-1.5">
<Label htmlFor="title">Title <span className="text-destructive">*</span></Label>
<Input id="title" placeholder="Unit title" {...register("title")} />
<FieldError message={errors.title?.message} />
</div>
return (
<div key={s.id} className="flex items-center flex-1 last:flex-none">
<div className="flex flex-col items-center gap-1">
<div className={cn(
"h-8 w-8 rounded-full flex items-center justify-center border transition-colors",
isDone && "bg-emerald-600 border-emerald-600 text-white",
isActive && "border-primary bg-primary text-primary-foreground",
!isActive && !isDone && "border-border bg-background text-muted-foreground"
)}>
{isDone ? <Check className="h-4 w-4" /> : <Icon className="h-4 w-4" />}
</div>
<span className={cn(
"text-[11px] font-medium whitespace-nowrap hidden sm:block",
isActive ? "text-foreground" : "text-muted-foreground",
isDone ? "text-emerald-600" : ""
)}>
{s.label}
</span>
</div>
{i < STEPS.length - 1 && (
<div className={cn(
"flex-1 h-px mx-2 mb-4 transition-colors",
step > i ? "bg-emerald-600" : "bg-border"
)} />
)}
</div>
);
})}
</div>
<div className="space-y-1.5">
<Label htmlFor="description">Description</Label>
<Textarea id="description" placeholder="Optional description" rows={3} {...register("description")} />
</div>
{/* Step content */}
<div className="rounded-lg border bg-card p-6 min-h-[320px]">
<h2 className="text-base font-medium mb-4">{STEPS[step].label}</h2>
<div className="space-y-1.5">
<Label>Subscription</Label>
<Select
value={watchedSubscr || "__open"}
onValueChange={(val) => setValue("subscription", val === "__open" ? "" : val, { shouldDirty: true })}
>
<SelectTrigger>
<SelectValue placeholder="No tier gate" />
</SelectTrigger>
<SelectContent>
<SelectItem value="__open">No tier gate (open)</SelectItem>
{tierCategories.map((c) => (
<SelectItem key={c.slug} value={c.slug}>
{c.name}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Optional. Gates this unit directly, independent of any course it may later be attached to.
</p>
</div>
{step === 0 && (
<StepUnit
register={register}
errors={errors}
control={control}
setValue={setValue}
tierCategories={tierCategories}
/>
)}
{step === 1 && (
<StepLessons control={control} register={register} errors={errors} />
)}
{step === 2 && (
<StepPageBuilder control={control} setValue={setValue} />
)}
{step === 3 && (
<StepReview data={getValues()} tierCategories={tierCategories} />
)}
</div>
</div>
{/* Navigation */}
<div className="flex items-center justify-between gap-3">
<Button type="button" variant="outline" onClick={handleBack} disabled={loading}>
<ChevronLeft className="h-4 w-4 mr-1" />
{step === 0 ? "Cancel" : "Back"}
</Button>
<div className="flex justify-end gap-3">
<Button type="button" variant="outline" onClick={() => navigate(-1)} disabled={loading}>
Cancel
{step < STEPS.length - 1 ? (
<Button type="button" onClick={handleNext}>
Next
<ChevronRight className="h-4 w-4 ml-1" />
</Button>
<Button type="submit" disabled={loading}>
) : (
<Button type="button" onClick={handleCreate} disabled={loading}>
{loading && <Spinner className="h-4 w-4 mr-2" />}
Create Unit
</Button>
</div>
</form>
)}
</div>
</div>
</div>
{unsavedChangesDialog}
</section>
);
}