feat(classes): optimize teacher dashboard ui and implement grade management

This commit is contained in:
SpecialX
2026-01-14 13:59:11 +08:00
parent ade8d4346c
commit 9bfc621d3f
104 changed files with 12793 additions and 2309 deletions

View File

@@ -9,10 +9,28 @@ import {
createKnowledgePoint,
deleteKnowledgePoint,
updateTextbook,
deleteTextbook
deleteTextbook,
reorderChapters
} from "./data-access";
import { CreateTextbookInput, UpdateTextbookInput } from "./types";
// ... existing code ...
export async function reorderChaptersAction(
chapterId: string,
newIndex: number,
parentId: string | null,
textbookId: string
): Promise<ActionState> {
try {
await reorderChapters(chapterId, newIndex, parentId);
revalidatePath(`/teacher/textbooks/${textbookId}`);
return { success: true, message: "Chapters reordered successfully" };
} catch {
return { success: false, message: "Failed to reorder chapters" };
}
}
export type ActionState = {
success: boolean;
message?: string;

View File

@@ -30,7 +30,7 @@ function ChapterItem({ chapter, level = 0, onView, showActions = true }: Chapter
const hasChildren = chapter.children && chapter.children.length > 0
return (
<div className={cn("w-full", level > 0 && "ml-4 border-l pl-2")}>
<div className={cn(level > 0 && "ml-2 border-l pl-2")}>
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<div className="flex items-center group py-1">
{hasChildren ? (

View File

@@ -1,8 +1,11 @@
"use client"
import { useState } from "react"
import { ChevronRight, FileText, Folder, MoreHorizontal, Plus, Trash2 } from "lucide-react"
import { ChevronRight, FileText, Folder, Plus, Trash2, GripVertical } from "lucide-react"
import { toast } from "sonner"
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from "@dnd-kit/core"
import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { Chapter } from "../types"
import {
Collapsible,
@@ -10,13 +13,6 @@ import {
CollapsibleTrigger,
} from "@/shared/components/ui/collapsible"
import { Button } from "@/shared/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
AlertDialog,
AlertDialogAction,
@@ -29,54 +25,62 @@ import {
} from "@/shared/components/ui/alert-dialog"
import { cn } from "@/shared/lib/utils"
import { CreateChapterDialog } from "./create-chapter-dialog"
import { deleteChapterAction } from "../actions"
import { deleteChapterAction, reorderChaptersAction } from "../actions"
interface ChapterItemProps {
interface SortableChapterItemProps {
chapter: Chapter
level?: number
level: number
selectedId?: string
onSelect: (chapter: Chapter) => void
textbookId: string
onDelete: (chapter: Chapter) => void
onCreateSub: (parentId: string) => void
}
function ChapterItem({ chapter, level = 0, selectedId, onSelect, textbookId }: ChapterItemProps) {
const [isOpen, setIsOpen] = useState(false)
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
function SortableChapterItem({ chapter, level, selectedId, onSelect, textbookId, onDelete, onCreateSub }: SortableChapterItemProps) {
const [isOpen, setIsOpen] = useState(level === 0)
const hasChildren = chapter.children && chapter.children.length > 0
const isSelected = chapter.id === selectedId
const handleDelete = async () => {
setIsDeleting(true)
const res = await deleteChapterAction(chapter.id, textbookId)
setIsDeleting(false)
if (res.success) {
toast.success(res.message)
setShowDeleteDialog(false)
} else {
toast.error(res.message)
}
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: chapter.id })
const style = {
transform: CSS.Transform.toString(transform),
transition,
zIndex: isDragging ? 10 : 1,
position: "relative" as const,
}
return (
<div className={cn("w-full", level > 0 && "ml-4 border-l pl-2")}>
<div ref={setNodeRef} style={style} className={cn(level > 0 && "ml-2 border-l border-muted/30 pl-2")}>
<Collapsible open={isOpen} onOpenChange={setIsOpen}>
<div className={cn(
"flex items-center group py-1 rounded-md transition-colors",
isSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted/50"
"flex items-center group py-1.5 px-2 rounded-md transition-colors cursor-pointer select-none",
isSelected ? "bg-accent text-accent-foreground font-medium" : "hover:bg-muted/50 text-muted-foreground hover:text-foreground",
isDragging && "opacity-50"
)}>
<div {...attributes} {...listeners} className="mr-1 cursor-grab opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-muted rounded">
<GripVertical className="h-3.5 w-3.5 text-muted-foreground/50" />
</div>
{hasChildren ? (
<CollapsibleTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 shrink-0 p-0 hover:bg-muted"
onClick={(e) => e.stopPropagation()} // Prevent selecting parent when toggling
className="h-5 w-5 shrink-0 p-0 mr-1 hover:bg-transparent text-muted-foreground/70"
onClick={(e) => e.stopPropagation()}
>
<ChevronRight
className={cn(
"h-4 w-4 transition-transform duration-200 text-muted-foreground",
"h-3.5 w-3.5 transition-transform duration-200",
isOpen && "rotate-90"
)}
/>
@@ -84,124 +88,257 @@ function ChapterItem({ chapter, level = 0, selectedId, onSelect, textbookId }: C
</Button>
</CollapsibleTrigger>
) : (
<div className="w-6 shrink-0" />
<div className="w-5 shrink-0 mr-1" />
)}
<div
className={cn(
"flex flex-1 min-w-0 items-center gap-2 px-2 py-1.5 text-sm cursor-pointer",
level === 0 ? "font-medium" : "text-muted-foreground",
isSelected && "text-accent-foreground font-medium"
)}
className="flex-1 min-w-0 flex items-center gap-2"
onClick={() => onSelect(chapter)}
>
{hasChildren ? (
<Folder className={cn("h-4 w-4", isOpen ? "text-primary" : "text-muted-foreground/70")} />
<Folder className={cn("h-4 w-4 shrink-0 transition-colors", isOpen || isSelected ? "text-blue-500/80" : "text-muted-foreground/50")} />
) : (
<FileText className="h-4 w-4 text-muted-foreground/50" />
<FileText className={cn("h-4 w-4 shrink-0 transition-colors", isSelected ? "text-blue-500/80" : "text-muted-foreground/50")} />
)}
<span className="truncate flex-1 min-w-0">{chapter.title}</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="ml-auto h-6 w-6 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity focus:opacity-100"
onClick={(e) => e.stopPropagation()}
>
<MoreHorizontal className="h-4 w-4 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onSelect={() => setShowCreateDialog(true)}
>
<Plus />
Add Subchapter
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onSelect={() => setShowDeleteDialog(true)}>
<Trash2 />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<span className="truncate text-sm">{chapter.title}</span>
</div>
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity ml-2">
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-foreground"
onClick={(e) => {
e.stopPropagation()
onCreateSub(chapter.id)
}}
title="Add Subchapter"
>
<Plus className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="icon"
className="h-6 w-6 text-muted-foreground hover:text-destructive"
onClick={(e) => {
e.stopPropagation()
onDelete(chapter)
}}
title="Delete Chapter"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</div>
{hasChildren && (
<CollapsibleContent className="overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
<div className="pt-1">
{chapter.children!.map((child) => (
<ChapterItem
key={child.id}
chapter={child}
level={level + 1}
<CollapsibleContent>
<div className="pt-1">
{hasChildren && (
<RecursiveSortableList
items={chapter.children!}
level={level + 1}
selectedId={selectedId}
onSelect={onSelect}
textbookId={textbookId}
onDelete={onDelete}
onCreateSub={onCreateSub}
/>
))}
</div>
</CollapsibleContent>
)}
)}
</div>
</CollapsibleContent>
</Collapsible>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete chapter?</AlertDialogTitle>
<AlertDialogDescription>
This will delete this chapter and all its subchapters and linked knowledge points.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={handleDelete}
disabled={isDeleting}
>
{isDeleting ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<CreateChapterDialog
textbookId={textbookId}
parentId={chapter.id}
trigger={null}
open={showCreateDialog}
onOpenChange={setShowCreateDialog}
/>
</div>
)
}
export function ChapterSidebarList({
chapters,
selectedChapterId,
onSelectChapter,
textbookId,
}: {
chapters: Chapter[],
selectedChapterId?: string,
onSelectChapter: (chapter: Chapter) => void
textbookId: string
function RecursiveSortableList({ items, level, selectedId, onSelect, textbookId, onDelete, onCreateSub }: {
items: Chapter[],
level: number,
selectedId?: string,
onSelect: (c: Chapter) => void,
textbookId: string,
onDelete: (c: Chapter) => void,
onCreateSub: (pid: string) => void
}) {
return (
<SortableContext items={items.map(i => i.id)} strategy={verticalListSortingStrategy}>
{items.map((chapter) => (
<SortableChapterItem
key={chapter.id}
chapter={chapter}
level={level}
selectedId={selectedId}
onSelect={onSelect}
textbookId={textbookId}
onDelete={onDelete}
onCreateSub={onCreateSub}
/>
))}
</SortableContext>
)
}
interface ChapterSidebarListProps {
chapters: Chapter[]
selectedChapterId?: string
onSelectChapter: (chapter: Chapter) => void
textbookId: string
}
export function ChapterSidebarList({ chapters, selectedChapterId, onSelectChapter, textbookId }: ChapterSidebarListProps) {
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [createParentId, setCreateParentId] = useState<string | undefined>(undefined)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [deleteTarget, setDeleteTarget] = useState<Chapter | null>(null)
const [isDeleting, setIsDeleting] = useState(false)
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
)
const handleDragEnd = async (event: DragEndEvent) => {
const { active, over } = event
if (!over || active.id === over.id) return
// Find which list the items belong to
// Since we only support sibling reordering for now, we assume active and over are in the same list
// We need a helper to find the parent of an item in the tree
const findParent = (items: Chapter[], id: string): Chapter | null => {
for (const item of items) {
if (item.children?.some(c => c.id === id)) return item
if (item.children) {
const found = findParent(item.children, id)
if (found) return found
}
}
return null
}
const activeParent = findParent(chapters, active.id as string)
const overParent = findParent(chapters, over.id as string)
// If parents don't match (and neither is root), we can't reorder easily in this simplified version
// But actually, we need to check if they are in the same list.
// If both are root items (activeParent is null), they are siblings.
const getSiblings = (parentId: string | null) => {
if (!parentId) return chapters
const parent = chapters.find(c => c.id === parentId) // This only finds root parents, we need recursive find
const findNode = (nodes: Chapter[], id: string): Chapter | null => {
for (const node of nodes) {
if (node.id === id) return node
if (node.children) {
const found = findNode(node.children, id)
if (found) return found
}
}
return null
}
return findNode(chapters, parentId)?.children || []
}
// Simplified logic: We trust dnd-kit's SortableContext to only allow valid drops if we restricted it?
// No, dnd-kit allows dropping anywhere by default unless restricted.
// We need to find the list that contains the 'active' item
// And the list that contains the 'over' item.
// If they are the same list, we reorder.
let activeList: Chapter[] = chapters
let activeParentId: string | null = null
if (activeParent) {
activeList = activeParent.children || []
activeParentId = activeParent.id
} else {
// Check if active is in root
if (!chapters.some(c => c.id === active.id)) {
// Should not happen if tree is consistent
return
}
}
// Check if over is in the same list
if (activeList.some(c => c.id === over.id)) {
const oldIndex = activeList.findIndex((item) => item.id === active.id)
const newIndex = activeList.findIndex((item) => item.id === over.id)
await reorderChaptersAction(active.id as string, newIndex, activeParentId, textbookId)
toast.success("Order updated")
}
}
const handleDelete = async () => {
if (!deleteTarget) return
setIsDeleting(true)
const res = await deleteChapterAction(deleteTarget.id, textbookId)
setIsDeleting(false)
if (res.success) {
toast.success(res.message)
setShowDeleteDialog(false)
setDeleteTarget(null)
} else {
toast.error(res.message)
}
}
const handleDeleteRequest = (chapter: Chapter) => {
if (chapter.children && chapter.children.length > 0) {
toast.error("Cannot delete chapter with subchapters")
return
}
setDeleteTarget(chapter)
setShowDeleteDialog(true)
}
const handleCreateSubRequest = (parentId: string) => {
setCreateParentId(parentId)
setShowCreateDialog(true)
}
return (
<div className="space-y-1">
{chapters.map((chapter) => (
<ChapterItem
key={chapter.id}
chapter={chapter}
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<RecursiveSortableList
items={chapters}
level={0}
selectedId={selectedChapterId}
onSelect={onSelectChapter}
textbookId={textbookId}
onDelete={handleDeleteRequest}
onCreateSub={handleCreateSubRequest}
/>
))}
</div>
<CreateChapterDialog
textbookId={textbookId}
parentId={createParentId}
open={showCreateDialog}
onOpenChange={(open) => {
setShowCreateDialog(open)
if (!open) setCreateParentId(undefined)
}}
/>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Chapter?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete <span className="font-medium text-foreground">{deleteTarget?.title}</span>.
This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={isDeleting}>
{isDeleting ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DndContext>
)
}

View File

@@ -54,8 +54,9 @@ export function CreateChapterDialog({ textbookId, parentId, trigger, open: contr
trigger === null
? null
: trigger || (
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<Button variant="ghost" size="icon" className="h-8 w-8 text-muted-foreground hover:text-foreground">
<Plus className="h-4 w-4" />
<span className="sr-only">Add Chapter</span>
</Button>
)

View File

@@ -68,9 +68,9 @@ export function KnowledgePointPanel({
: []
return (
<div className="h-full flex flex-col space-y-4">
<div className="flex items-center justify-between px-2">
<h3 className="font-semibold flex items-center gap-2">
<div className="h-full flex flex-col">
<div className="flex items-center justify-between p-4 border-b">
<h3 className="font-semibold text-sm uppercase tracking-wider text-muted-foreground flex items-center gap-2">
<Tag className="h-4 w-4" />
Knowledge Points
</h3>
@@ -82,16 +82,17 @@ export function KnowledgePointPanel({
)}
</div>
<ScrollArea className="flex-1 min-h-0 -mx-2 px-2">
<ScrollArea className="flex-1">
<div className="p-4 space-y-3">
{selectedChapterId ? (
chapterKPs.length > 0 ? (
<div className="space-y-3">
<>
{chapterKPs.map((kp) => (
<Card key={kp.id} className="relative group">
<Card key={kp.id} className="relative group hover:shadow-sm transition-shadow">
<CardContent className="p-3">
<div className="flex justify-between items-start gap-2">
<div className="space-y-1">
<div className="font-medium text-sm leading-tight">
<div className="font-medium text-sm leading-tight text-foreground">
{kp.name}
</div>
{kp.description && (
@@ -103,7 +104,7 @@ export function KnowledgePointPanel({
<Button
variant="ghost"
size="icon"
className="h-6 w-6 opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive hover:bg-destructive/10 -mt-1 -mr-1"
className="h-6 w-6 -mr-1 -mt-1 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
onClick={() => requestDelete(kp)}
>
<Trash2 className="h-3.5 w-3.5" />
@@ -112,47 +113,40 @@ export function KnowledgePointPanel({
</CardContent>
</Card>
))}
</div>
</>
) : (
<div className="text-sm text-muted-foreground text-center py-8 border rounded-md border-dashed bg-muted/30">
No knowledge points linked to this chapter yet.
<div className="flex flex-col items-center justify-center py-12 text-center space-y-3">
<div className="p-3 rounded-full bg-muted/50">
<Tag className="h-6 w-6 text-muted-foreground/40" />
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-muted-foreground">No points yet</p>
<p className="text-xs text-muted-foreground/60 max-w-[160px]">
Add knowledge points to tag content in this chapter.
</p>
</div>
</div>
)
) : (
<div className="text-sm text-muted-foreground text-center py-8">
Select a chapter to manage its knowledge points.
<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground space-y-2">
<p className="text-sm">Select a chapter to manage knowledge points</p>
</div>
)}
</div>
</ScrollArea>
<AlertDialog
open={showDeleteDialog}
onOpenChange={(open) => {
if (isDeleting) return
setShowDeleteDialog(open)
if (!open) setDeleteTarget(null)
}}
>
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete knowledge point?</AlertDialogTitle>
<AlertDialogTitle>Delete Knowledge Point?</AlertDialogTitle>
<AlertDialogDescription>
{deleteTarget ? (
<>
This will permanently delete <span className="font-medium text-foreground">{deleteTarget.name}</span>.
</>
) : (
"This will permanently delete the selected knowledge point."
)}
This action cannot be undone. This will permanently delete the knowledge point
<span className="font-medium text-foreground"> {deleteTarget?.name}</span>.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={handleDelete}
disabled={isDeleting}
>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={isDeleting}>
{isDeleting ? "Deleting..." : "Delete"}
</AlertDialogAction>
</AlertDialogFooter>

View File

@@ -1,77 +1,113 @@
import Link from "next/link";
import { GraduationCap, Building2, BookOpen } from "lucide-react";
import { Book, MoreVertical, Edit, Trash2, BookOpen, GraduationCap, Building2 } from "lucide-react";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle,
} from "@/shared/components/ui/card";
import { Badge } from "@/shared/components/ui/badge";
import { cn } from "@/shared/lib/utils";
import { Button } from "@/shared/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu";
import { cn, formatDate } from "@/shared/lib/utils";
import { Textbook } from "../types";
interface TextbookCardProps {
textbook: Textbook;
hrefBase?: string;
hideActions?: boolean;
}
export function TextbookCard({ textbook, hrefBase }: TextbookCardProps) {
const subjectColorMap: Record<string, string> = {
Mathematics: "from-blue-500/20 to-blue-600/20 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800",
Physics: "from-purple-500/20 to-purple-600/20 text-purple-700 dark:text-purple-300 border-purple-200 dark:border-purple-800",
Chemistry: "from-teal-500/20 to-teal-600/20 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800",
English: "from-orange-500/20 to-orange-600/20 text-orange-700 dark:text-orange-300 border-orange-200 dark:border-orange-800",
History: "from-amber-500/20 to-amber-600/20 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
Biology: "from-emerald-500/20 to-emerald-600/20 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",
Geography: "from-sky-500/20 to-sky-600/20 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800",
};
export function TextbookCard({ textbook, hrefBase, hideActions }: TextbookCardProps) {
const base = hrefBase || "/teacher/textbooks";
const colorClass = subjectColorMap[textbook.subject] || "from-zinc-500/20 to-zinc-600/20 text-zinc-700 dark:text-zinc-300 border-zinc-200 dark:border-zinc-800";
return (
<Link href={`${base}/${textbook.id}`} className="block h-full">
<Card
className={cn(
"group h-full overflow-hidden transition-all duration-300 ease-out",
"hover:-translate-y-1 hover:shadow-md hover:border-primary/50"
)}
>
<div className="relative aspect-[4/3] w-full overflow-hidden bg-muted/30 p-6 flex items-center justify-center">
{/* Fallback Cover Visualization */}
<div className="relative z-10 flex h-24 w-20 flex-col items-center justify-center rounded-sm bg-background shadow-sm border transition-transform duration-300 group-hover:scale-110">
<div className="h-full w-full bg-gradient-to-br from-primary/10 to-primary/5 p-2">
<div className="h-1 w-full rounded-full bg-primary/20 mb-1" />
<div className="h-1 w-2/3 rounded-full bg-primary/20" />
</div>
<Card className="group flex flex-col h-full overflow-hidden transition-all duration-300 hover:shadow-md hover:border-primary/50">
<Link href={`${base}/${textbook.id}`} className="flex-1">
<div className={cn("relative h-32 w-full overflow-hidden bg-gradient-to-br p-6 transition-all group-hover:scale-105", colorClass)}>
<div className="absolute inset-0 bg-grid-black/[0.05] dark:bg-grid-white/[0.05]" />
<div className="relative z-10 flex h-full flex-col justify-between">
<Badge variant="secondary" className="w-fit bg-background/50 backdrop-blur-sm border-transparent shadow-none">
{textbook.subject}
</Badge>
<Book className="h-8 w-8 opacity-50" />
</div>
{/* Decorative Background Pattern */}
<div className="absolute inset-0 bg-grid-black/[0.02] dark:bg-grid-white/[0.02]" />
</div>
<CardHeader className="p-4 pb-2">
<div className="flex items-start justify-between gap-2">
<div className="space-y-1">
<Badge variant="outline" className="w-fit text-[10px] h-5 px-1.5 font-normal border-primary/20 text-primary bg-primary/5">
{textbook.subject}
</Badge>
<CardTitle className="line-clamp-2 text-base leading-tight">
{textbook.title}
</CardTitle>
</div>
<h3 className="font-semibold text-lg leading-tight line-clamp-2 group-hover:text-primary transition-colors">
{textbook.title}
</h3>
</div>
</CardHeader>
<CardContent className="p-4 pt-0 text-sm text-muted-foreground">
<div className="flex flex-col gap-1.5">
<div className="flex items-center gap-2 text-xs">
<GraduationCap className="h-3.5 w-3.5 text-muted-foreground/70" />
<span>{textbook.grade}</span>
<CardContent className="p-4 pt-1 pb-2">
<div className="flex flex-wrap gap-y-1 gap-x-4 text-xs text-muted-foreground">
<div className="flex items-center gap-1.5">
<GraduationCap className="h-3.5 w-3.5" />
<span>{textbook.grade || "Grade N/A"}</span>
</div>
<div className="flex items-center gap-2 text-xs">
<Building2 className="h-3.5 w-3.5 text-muted-foreground/70" />
<span className="line-clamp-1">{textbook.publisher || "Unknown Publisher"}</span>
<div className="flex items-center gap-1.5">
<Building2 className="h-3.5 w-3.5" />
<span className="truncate max-w-[120px]" title={textbook.publisher || ""}>
{textbook.publisher || "Publisher N/A"}
</span>
</div>
</div>
</CardContent>
</Link>
<CardFooter className="p-4 pt-0 mt-auto">
<div className="flex items-center gap-2 text-xs text-muted-foreground/80 bg-muted/30 px-2 py-1 rounded-md w-full">
<BookOpen className="h-3.5 w-3.5" />
<span>{textbook._count?.chapters || 0} Chapters</span>
</div>
</CardFooter>
</Card>
</Link>
<CardFooter className="p-4 pt-2 mt-auto border-t bg-muted/20 flex items-center justify-between">
<div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
<BookOpen className="h-3.5 w-3.5" />
<span>{textbook._count?.chapters || 0} Chapters</span>
</div>
<div className="flex items-center gap-1">
<span className="text-[10px] text-muted-foreground/60 mr-2">
Updated {formatDate(textbook.updatedAt)}
</span>
{!hideActions && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-6 w-6 -mr-2">
<MoreVertical className="h-3.5 w-3.5" />
<span className="sr-only">More options</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link href={`${base}/${textbook.id}`}>
<Edit className="mr-2 h-4 w-4" />
Edit Content
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="text-destructive focus:text-destructive">
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</CardFooter>
</Card>
);
}

View File

@@ -9,11 +9,11 @@ import { ChapterSidebarList } from "./chapter-sidebar-list"
import { KnowledgePointPanel } from "./knowledge-point-panel"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { Button } from "@/shared/components/ui/button"
import { Edit2, Save } from "lucide-react"
import { Edit2, Save, Folder } from "lucide-react"
import { CreateChapterDialog } from "./create-chapter-dialog"
import { updateChapterContentAction } from "../actions"
import { toast } from "sonner"
import { Textarea } from "@/shared/components/ui/textarea"
import { RichTextEditor } from "@/shared/components/ui/rich-text-editor"
interface TextbookContentLayoutProps {
chapters: Chapter[]
@@ -50,29 +50,31 @@ export function TextbookContentLayout({ chapters, knowledgePoints, textbookId }:
}
return (
<div className="grid grid-cols-12 gap-6 h-[calc(100vh-140px)]">
<div className="grid grid-cols-12 h-[calc(100vh-8rem)]">
{/* Left Sidebar: TOC (3 cols) */}
<div className="col-span-3 border-r pr-6 flex flex-col h-full">
<div className="flex items-center justify-between mb-4 px-2">
<h3 className="font-semibold">Chapters</h3>
<div className="col-span-3 border-r flex flex-col h-full bg-muted/10">
<div className="flex items-center justify-between p-4 border-b">
<h3 className="font-semibold text-sm uppercase tracking-wider text-muted-foreground">Contents</h3>
<CreateChapterDialog textbookId={textbookId} />
</div>
<ScrollArea className="flex-1 px-2">
<ChapterSidebarList
chapters={chapters}
selectedChapterId={selectedChapter?.id}
onSelectChapter={handleSelectChapter}
textbookId={textbookId}
/>
<ScrollArea className="flex-1">
<div className="p-3">
<ChapterSidebarList
chapters={chapters}
selectedChapterId={selectedChapter?.id}
onSelectChapter={handleSelectChapter}
textbookId={textbookId}
/>
</div>
</ScrollArea>
</div>
{/* Middle: Content Viewer/Editor (6 cols) */}
<div className="col-span-6 flex flex-col h-full px-2 min-h-0">
<div className="col-span-6 flex flex-col h-full min-h-0 bg-background">
{selectedChapter ? (
<>
<div className="flex items-center justify-between mb-4 pb-2 border-b">
<h2 className="text-xl font-bold tracking-tight">{selectedChapter.title}</h2>
<div className="flex items-center justify-between px-8 py-4 border-b sticky top-0 bg-background/95 backdrop-blur z-10">
<h2 className="text-2xl font-bold tracking-tight">{selectedChapter.title}</h2>
<div className="flex gap-2">
{isEditing ? (
<>
@@ -93,24 +95,29 @@ export function TextbookContentLayout({ chapters, knowledgePoints, textbookId }:
</div>
</div>
<ScrollArea className="flex-1 min-h-0">
<div className="p-4 min-h-full">
<ScrollArea className="flex-1">
<div className="max-w-3xl mx-auto px-8 py-8 min-h-full">
{isEditing ? (
<Textarea
className="min-h-[500px] font-mono text-sm"
<RichTextEditor
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
placeholder="# Write markdown content here..."
onChange={setEditContent}
className="min-h-[500px] border-none shadow-none"
/>
) : (
<div className="prose prose-sm dark:prose-invert max-w-none">
<div className="prose prose-zinc dark:prose-invert max-w-none prose-headings:font-bold prose-h1:text-3xl prose-h2:text-2xl prose-h3:text-xl prose-p:leading-relaxed">
{selectedChapter.content ? (
<ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>
{selectedChapter.content}
</ReactMarkdown>
) : (
<div className="text-muted-foreground italic py-8 text-center">
No content available. Click edit to add content.
<div className="flex flex-col items-center justify-center py-20 text-muted-foreground space-y-4">
<div className="p-4 rounded-full bg-muted">
<Edit2 className="h-8 w-8 opacity-50" />
</div>
<p className="italic">No content available yet.</p>
<Button variant="outline" size="sm" onClick={() => setIsEditing(true)}>
Start Writing
</Button>
</div>
)}
</div>
@@ -119,14 +126,17 @@ export function TextbookContentLayout({ chapters, knowledgePoints, textbookId }:
</ScrollArea>
</>
) : (
<div className="h-full flex items-center justify-center text-muted-foreground">
Select a chapter from the left sidebar to view its content.
<div className="h-full flex flex-col items-center justify-center text-muted-foreground space-y-4">
<div className="p-6 rounded-full bg-muted/30">
<Folder className="h-12 w-12 opacity-20" />
</div>
<p>Select a chapter to view or edit content</p>
</div>
)}
</div>
{/* Right Sidebar: Knowledge Points (3 cols) */}
<div className="col-span-3 border-l pl-6 flex flex-col h-full">
<div className="col-span-3 border-l flex flex-col h-full bg-muted/10">
<KnowledgePointPanel
knowledgePoints={knowledgePoints}
selectedChapterId={selectedChapter?.id || null}

View File

@@ -21,21 +21,20 @@ export function TextbookFilters() {
const hasFilters = Boolean(search || subject !== "all" || grade !== "all")
return (
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between bg-card p-4 rounded-lg border shadow-sm">
<div className="relative w-full md:w-96">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="relative w-full md:w-80">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground/50" />
<Input
placeholder="Search textbooks..."
className="pl-9 bg-background"
placeholder="Search by title, publisher..."
className="pl-9 bg-background border-muted-foreground/20"
value={search}
onChange={(e) => setSearch(e.target.value || null)}
/>
</div>
<div className="flex gap-2 w-full md:w-auto">
<div className="flex flex-wrap gap-2 w-full md:w-auto">
<Select value={subject} onValueChange={(val) => setSubject(val === "all" ? null : val)}>
<SelectTrigger className="w-[160px] bg-background">
<Filter className="mr-2 h-4 w-4 text-muted-foreground" />
<SelectTrigger className="w-[140px] bg-background border-muted-foreground/20">
<SelectValue placeholder="Subject" />
</SelectTrigger>
<SelectContent>
@@ -43,17 +42,21 @@ export function TextbookFilters() {
<SelectItem value="Mathematics">Mathematics</SelectItem>
<SelectItem value="Physics">Physics</SelectItem>
<SelectItem value="Chemistry">Chemistry</SelectItem>
<SelectItem value="Biology">Biology</SelectItem>
<SelectItem value="English">English</SelectItem>
<SelectItem value="History">History</SelectItem>
<SelectItem value="Geography">Geography</SelectItem>
</SelectContent>
</Select>
<Select value={grade} onValueChange={(val) => setGrade(val === "all" ? null : val)}>
<SelectTrigger className="w-[160px] bg-background">
<SelectTrigger className="w-[130px] bg-background border-muted-foreground/20">
<SelectValue placeholder="Grade" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Grades</SelectItem>
<SelectItem value="Grade 7">Grade 7</SelectItem>
<SelectItem value="Grade 8">Grade 8</SelectItem>
<SelectItem value="Grade 9">Grade 9</SelectItem>
<SelectItem value="Grade 10">Grade 10</SelectItem>
<SelectItem value="Grade 11">Grade 11</SelectItem>
@@ -69,7 +72,7 @@ export function TextbookFilters() {
setSubject(null)
setGrade(null)
}}
className="h-10 px-3"
className="h-10 px-3 text-muted-foreground hover:text-foreground"
>
Reset
<X className="ml-2 h-4 w-4" />

View File

@@ -89,9 +89,11 @@ export function TextbookFormDialog() {
<SelectContent>
<SelectItem value="Mathematics">Mathematics</SelectItem>
<SelectItem value="Physics">Physics</SelectItem>
<SelectItem value="History">History</SelectItem>
<SelectItem value="English">English</SelectItem>
<SelectItem value="Chemistry">Chemistry</SelectItem>
<SelectItem value="Biology">Biology</SelectItem>
<SelectItem value="English">English</SelectItem>
<SelectItem value="History">History</SelectItem>
<SelectItem value="Geography">Geography</SelectItem>
</SelectContent>
</Select>
</div>

View File

@@ -42,7 +42,7 @@ function ReaderChapterItem({
const isSelected = selectedId === chapter.id
return (
<div className={cn("w-full", level > 0 && "ml-4 border-l pl-2")}>
<div className={cn(level > 0 && "ml-2 border-l pl-2")}>
<div
className={cn(
"flex items-center group py-1 rounded-md transition-colors",

View File

@@ -1,7 +1,7 @@
import "server-only"
import { cache } from "react"
import { and, asc, eq, inArray, like, or, sql, type SQL } from "drizzle-orm"
import { and, asc, eq, inArray, like, or, sql, isNull, type SQL } from "drizzle-orm"
import { createId } from "@paralleldrive/cuid2"
import { db } from "@/shared/db"
@@ -394,3 +394,37 @@ export async function createKnowledgePoint(data: CreateKnowledgePointInput): Pro
export async function deleteKnowledgePoint(id: string): Promise<void> {
await db.delete(knowledgePoints).where(eq(knowledgePoints.id, id))
}
export async function reorderChapters(chapterId: string, newIndex: number, parentId: string | null): Promise<void> {
const [target] = await db.select().from(chapters).where(eq(chapters.id, chapterId)).limit(1)
if (!target) throw new Error("Chapter not found")
const siblings = await db
.select()
.from(chapters)
.where(
and(
eq(chapters.textbookId, target.textbookId),
parentId ? eq(chapters.parentId, parentId) : isNull(chapters.parentId)
)
)
.orderBy(asc(chapters.order))
const currentSiblings = siblings.filter((c) => c.id !== chapterId)
currentSiblings.splice(newIndex, 0, target)
await db.transaction(async (tx) => {
for (let i = 0; i < currentSiblings.length; i++) {
const ch = currentSiblings[i]
if (ch.order !== i || (ch.id === chapterId && ch.parentId !== parentId)) {
await tx
.update(chapters)
.set({
order: i,
parentId: ch.id === chapterId ? parentId : ch.parentId
})
.where(eq(chapters.id, ch.id))
}
}
})
}