Stage 1: Course/Module/Lesson CRUD admin UI with TipTap editor
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const links = [
|
||||
{ href: "/admin/dashboard", label: "Обзор" },
|
||||
{ href: "/admin/courses", label: "Курсы" },
|
||||
{ href: "/admin/users", label: "Пользователи" },
|
||||
];
|
||||
|
||||
export function AdminNav() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<>
|
||||
{links.map(({ href, label }) => (
|
||||
<Link
|
||||
key={href}
|
||||
href={href}
|
||||
className={cn(
|
||||
"block px-3 py-2 rounded-lg text-sm transition-colors",
|
||||
pathname === href || (href !== "/admin/dashboard" && pathname.startsWith(href))
|
||||
? "bg-slate-700 text-white"
|
||||
: "text-slate-300 hover:bg-slate-800 hover:text-white"
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { updateCourse, deleteCourse } from "@/app/admin/courses/actions";
|
||||
|
||||
interface Course {
|
||||
id: string;
|
||||
title: string;
|
||||
slug: string;
|
||||
description: string | null;
|
||||
coverImage: string | null;
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
export function CourseEditForm({ course }: { course: Course }) {
|
||||
const [published, setPublished] = useState(course.published);
|
||||
const [coverImage, setCoverImage] = useState(course.coverImage ?? "");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
async function handleImageUpload(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/upload", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
if (data.url) setCoverImage(data.url);
|
||||
setUploading(false);
|
||||
}
|
||||
|
||||
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
fd.set("published", String(published));
|
||||
fd.set("coverImage", coverImage);
|
||||
startTransition(() => updateCourse(course.id, fd));
|
||||
}
|
||||
|
||||
function handleDelete() {
|
||||
if (!confirm("Удалить курс? Это действие нельзя отменить.")) return;
|
||||
startTransition(() => deleteCourse(course.id));
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title">Название</Label>
|
||||
<Input id="title" name="title" defaultValue={course.title} required />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="slug">Slug</Label>
|
||||
<Input id="slug" name="slug" defaultValue={course.slug} required />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="description">Описание</Label>
|
||||
<Textarea id="description" name="description" defaultValue={course.description ?? ""} rows={3} />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label>Обложка</Label>
|
||||
<div className="flex items-center gap-3">
|
||||
{coverImage && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={coverImage} alt="cover" className="w-16 h-10 object-cover rounded-md border" />
|
||||
)}
|
||||
<Input type="file" accept="image/*" onChange={handleImageUpload} disabled={uploading} className="max-w-xs" />
|
||||
{uploading && <span className="text-sm text-slate-400">Загрузка...</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={published}
|
||||
onClick={() => setPublished(!published)}
|
||||
className={`relative w-10 h-6 rounded-full transition-colors ${published ? "bg-green-500" : "bg-slate-300"}`}
|
||||
>
|
||||
<span className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full shadow transition-transform ${published ? "translate-x-4" : ""}`} />
|
||||
</button>
|
||||
<span className="text-sm text-slate-600">{published ? "Опубликован" : "Черновик"}</span>
|
||||
</div>
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button type="button" variant="destructive" onClick={handleDelete} disabled={pending}>
|
||||
Удалить курс
|
||||
</Button>
|
||||
<Button type="submit" disabled={pending || uploading}>
|
||||
{pending ? "Сохранение..." : "Сохранить"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { createCourse } from "@/app/admin/courses/actions";
|
||||
|
||||
export function CreateCourseDialog() {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button>+ Создать курс</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Новый курс</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form action={createCourse} className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="title">Название</Label>
|
||||
<Input id="title" name="title" placeholder="Obsidian PKM" required />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="slug">Slug (URL)</Label>
|
||||
<Input id="slug" name="slug" placeholder="obsidian-pkm (авто если пусто)" />
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="description">Описание</Label>
|
||||
<Textarea id="description" name="description" placeholder="Краткое описание курса" rows={3} />
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
|
||||
Отмена
|
||||
</Button>
|
||||
<Button type="submit">Создать</Button>
|
||||
</div>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { grantAccess, revokeAccess } from "@/app/admin/courses/[courseId]/actions";
|
||||
|
||||
interface Student {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
courseId: string;
|
||||
allStudents: Student[];
|
||||
enrolledIds: string[];
|
||||
}
|
||||
|
||||
export function EnrollmentManager({ courseId, allStudents, enrolledIds }: Props) {
|
||||
const [enrolled, setEnrolled] = useState(new Set(enrolledIds));
|
||||
const [search, setSearch] = useState("");
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const filtered = allStudents.filter(
|
||||
(s) =>
|
||||
s.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.email.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
function toggle(userId: string) {
|
||||
if (enrolled.has(userId)) {
|
||||
setEnrolled((prev) => { const s = new Set(prev); s.delete(userId); return s; });
|
||||
startTransition(() => revokeAccess(courseId, userId));
|
||||
} else {
|
||||
setEnrolled((prev) => new Set(prev).add(userId));
|
||||
startTransition(() => grantAccess(courseId, userId));
|
||||
}
|
||||
}
|
||||
|
||||
const enrolledStudents = allStudents.filter((s) => enrolled.has(s.id));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{enrolledStudents.length > 0 && (
|
||||
<div>
|
||||
<p className="text-sm text-slate-500 mb-2">Доступ открыт ({enrolledStudents.length}):</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{enrolledStudents.map((s) => (
|
||||
<Badge key={s.id} variant="secondary" className="gap-1.5 py-1 pr-1">
|
||||
{s.name}
|
||||
<button
|
||||
onClick={() => toggle(s.id)}
|
||||
disabled={pending}
|
||||
className="ml-1 text-slate-400 hover:text-red-500"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<p className="text-sm text-slate-500 mb-2">Добавить ученика:</p>
|
||||
<Input
|
||||
placeholder="Поиск по имени или email..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="max-w-sm mb-3"
|
||||
/>
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto">
|
||||
{filtered.map((student) => (
|
||||
<div key={student.id} className="flex items-center justify-between px-3 py-2 rounded-lg border border-slate-100 bg-slate-50">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-slate-700">{student.name}</p>
|
||||
<p className="text-xs text-slate-400">{student.email}</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={enrolled.has(student.id) ? "destructive" : "outline"}
|
||||
onClick={() => toggle(student.id)}
|
||||
disabled={pending}
|
||||
>
|
||||
{enrolled.has(student.id) ? "Убрать" : "Дать доступ"}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{filtered.length === 0 && (
|
||||
<p className="text-sm text-slate-400 py-2">Студентов не найдено</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback, useTransition } from "react";
|
||||
import { useEditor, EditorContent } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import Placeholder from "@tiptap/extension-placeholder";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { saveLesson } from "@/app/admin/courses/[courseId]/modules/[moduleId]/lessons/[lessonId]/actions";
|
||||
|
||||
interface LessonData {
|
||||
id: string;
|
||||
title: string;
|
||||
kinescopeId: string;
|
||||
content: object;
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
export function LessonEditor({
|
||||
lesson,
|
||||
courseId,
|
||||
moduleId,
|
||||
}: {
|
||||
lesson: LessonData;
|
||||
courseId: string;
|
||||
moduleId: string;
|
||||
}) {
|
||||
const [title, setTitle] = useState(lesson.title);
|
||||
const [kinescopeId, setKinescopeId] = useState(lesson.kinescopeId);
|
||||
const [published, setPublished] = useState(lesson.published);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Image.configure({ inline: false }),
|
||||
Link.configure({ openOnClick: false }),
|
||||
Placeholder.configure({ placeholder: "Начните писать текст урока..." }),
|
||||
],
|
||||
content: Object.keys(lesson.content).length ? lesson.content : undefined,
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: "prose prose-slate max-w-none min-h-[300px] focus:outline-none p-4",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const uploadImage = useCallback(async () => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "image/*";
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file || !editor) return;
|
||||
setUploading(true);
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/upload", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
if (data.url) editor.chain().focus().setImage({ src: data.url }).run();
|
||||
setUploading(false);
|
||||
};
|
||||
input.click();
|
||||
}, [editor]);
|
||||
|
||||
function handleSave() {
|
||||
if (!editor) return;
|
||||
startTransition(async () => {
|
||||
await saveLesson(lesson.id, courseId, moduleId, {
|
||||
title,
|
||||
kinescopeId,
|
||||
content: editor.getJSON(),
|
||||
published,
|
||||
});
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
{/* Header controls */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={published}
|
||||
onClick={() => setPublished(!published)}
|
||||
className={`relative w-10 h-6 rounded-full transition-colors ${published ? "bg-green-500" : "bg-slate-300"}`}
|
||||
>
|
||||
<span className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full shadow transition-transform ${published ? "translate-x-4" : ""}`} />
|
||||
</button>
|
||||
<span className="text-sm text-slate-600">{published ? "Опубликован" : "Черновик"}</span>
|
||||
</div>
|
||||
<Button onClick={handleSave} disabled={pending || uploading}>
|
||||
{pending ? "Сохранение..." : saved ? "✓ Сохранено" : "Сохранить урок"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Title */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="lesson-title">Заголовок урока</Label>
|
||||
<Input
|
||||
id="lesson-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
className="text-lg font-medium"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Kinescope ID */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="kinescope-id">Kinescope ID</Label>
|
||||
<Input
|
||||
id="kinescope-id"
|
||||
value={kinescopeId}
|
||||
onChange={(e) => setKinescopeId(e.target.value)}
|
||||
placeholder="Оставьте пустым если видео нет"
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* TipTap Editor */}
|
||||
<div className="space-y-1.5">
|
||||
<Label>Содержимое урока</Label>
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="flex flex-wrap gap-1 p-2 bg-slate-50 border border-slate-200 rounded-t-lg border-b-0">
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleBold().run()} active={editor?.isActive("bold")}>Ж</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleItalic().run()} active={editor?.isActive("italic")}><em>К</em></ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleHeading({ level: 2 }).run()} active={editor?.isActive("heading", { level: 2 })}>H2</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleHeading({ level: 3 }).run()} active={editor?.isActive("heading", { level: 3 })}>H3</ToolBtn>
|
||||
<div className="w-px bg-slate-200 mx-1" />
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleBulletList().run()} active={editor?.isActive("bulletList")}>• Список</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleOrderedList().run()} active={editor?.isActive("orderedList")}>1. Список</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleBlockquote().run()} active={editor?.isActive("blockquote")}>“”</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().toggleCodeBlock().run()} active={editor?.isActive("codeBlock")}>{'</>'}</ToolBtn>
|
||||
<div className="w-px bg-slate-200 mx-1" />
|
||||
<ToolBtn onClick={uploadImage} disabled={uploading}>{uploading ? "Загрузка..." : "🖼 Фото"}</ToolBtn>
|
||||
<div className="w-px bg-slate-200 mx-1" />
|
||||
<ToolBtn onClick={() => editor?.chain().focus().undo().run()}>↩</ToolBtn>
|
||||
<ToolBtn onClick={() => editor?.chain().focus().redo().run()}>↪</ToolBtn>
|
||||
</div>
|
||||
|
||||
{/* Editor content */}
|
||||
<div className="border border-slate-200 rounded-b-lg bg-white">
|
||||
<EditorContent editor={editor} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolBtn({
|
||||
onClick,
|
||||
active,
|
||||
disabled,
|
||||
children,
|
||||
}: {
|
||||
onClick: () => void;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className={`px-2 py-1 text-sm rounded transition-colors ${
|
||||
active ? "bg-slate-700 text-white" : "hover:bg-slate-200 text-slate-700"
|
||||
} disabled:opacity-50`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
useSortable,
|
||||
arrayMove,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import Link from "next/link";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { createLesson, deleteLesson, updateLesson, reorderLessons } from "@/app/admin/courses/[courseId]/modules/[moduleId]/actions";
|
||||
|
||||
interface Lesson {
|
||||
id: string;
|
||||
title: string;
|
||||
order: number;
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
function SortableLesson({
|
||||
lesson,
|
||||
courseId,
|
||||
moduleId,
|
||||
}: {
|
||||
lesson: Lesson;
|
||||
courseId: string;
|
||||
moduleId: string;
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [pending, startTransition] = useTransition();
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
|
||||
useSortable({ id: lesson.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
function handleUpdate(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
startTransition(() => updateLesson(lesson.id, courseId, moduleId, fd));
|
||||
setEditing(false);
|
||||
}
|
||||
|
||||
function handleDelete() {
|
||||
if (!confirm(`Удалить урок "${lesson.title}"?`)) return;
|
||||
startTransition(() => deleteLesson(lesson.id, courseId, moduleId));
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} className="flex items-center gap-3 bg-slate-50 border border-slate-200 rounded-xl px-4 py-3">
|
||||
<button type="button" {...attributes} {...listeners} className="text-slate-300 hover:text-slate-500 cursor-grab active:cursor-grabbing">
|
||||
⋮⋮
|
||||
</button>
|
||||
{editing ? (
|
||||
<form onSubmit={handleUpdate} className="flex items-center gap-2 flex-1">
|
||||
<Input name="title" defaultValue={lesson.title} autoFocus className="h-8 text-sm" />
|
||||
<Button type="submit" size="sm" disabled={pending}>Сохранить</Button>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>Отмена</Button>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<span className="flex-1 font-medium text-slate-700">{lesson.title}</span>
|
||||
<Badge variant={lesson.published ? "default" : "secondary"} className="text-xs">
|
||||
{lesson.published ? "Опубликован" : "Черновик"}
|
||||
</Badge>
|
||||
<Link
|
||||
href={`/admin/courses/${courseId}/modules/${moduleId}/lessons/${lesson.id}`}
|
||||
className="text-xs text-amber-600 hover:underline"
|
||||
>
|
||||
Редактировать
|
||||
</Link>
|
||||
<button type="button" onClick={() => setEditing(true)} className="text-xs text-slate-500 hover:text-slate-700">
|
||||
Переименовать
|
||||
</button>
|
||||
<button type="button" onClick={handleDelete} disabled={pending} className="text-xs text-red-400 hover:text-red-600">
|
||||
Удалить
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableLessons({
|
||||
courseId,
|
||||
moduleId,
|
||||
lessons,
|
||||
}: {
|
||||
courseId: string;
|
||||
moduleId: string;
|
||||
lessons: Lesson[];
|
||||
}) {
|
||||
const [items, setItems] = useState(lessons);
|
||||
const [, startTransition] = useTransition();
|
||||
|
||||
const sensors = useSensors(useSensor(PointerSensor));
|
||||
|
||||
function handleDragEnd(event: DragEndEvent) {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
const oldIndex = items.findIndex((l) => l.id === active.id);
|
||||
const newIndex = items.findIndex((l) => l.id === over.id);
|
||||
const newItems = arrayMove(items, oldIndex, newIndex);
|
||||
setItems(newItems);
|
||||
startTransition(() => reorderLessons(moduleId, courseId, newItems.map((l) => l.id)));
|
||||
}
|
||||
|
||||
function handleCreate(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
e.currentTarget.reset();
|
||||
startTransition(() => createLesson(moduleId, courseId, fd));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext items={items.map((l) => l.id)} strategy={verticalListSortingStrategy}>
|
||||
{items.map((lesson) => (
|
||||
<SortableLesson key={lesson.id} lesson={lesson} courseId={courseId} moduleId={moduleId} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
{items.length === 0 && (
|
||||
<p className="text-sm text-slate-400 py-2">Уроков пока нет. Добавьте первый.</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleCreate} className="flex gap-2 pt-2">
|
||||
<Input name="title" placeholder="Название нового урока" required className="max-w-xs" />
|
||||
<Button type="submit">+ Урок</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
DragEndEvent,
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
SortableContext,
|
||||
verticalListSortingStrategy,
|
||||
useSortable,
|
||||
arrayMove,
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import Link from "next/link";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { createModule, deleteModule, updateModule, reorderModules } from "@/app/admin/courses/[courseId]/actions";
|
||||
|
||||
interface Module {
|
||||
id: string;
|
||||
title: string;
|
||||
order: number;
|
||||
_count: { lessons: number };
|
||||
}
|
||||
|
||||
function SortableModule({
|
||||
mod,
|
||||
courseId,
|
||||
}: {
|
||||
mod: Module;
|
||||
courseId: string;
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [pending, startTransition] = useTransition();
|
||||
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
|
||||
useSortable({ id: mod.id });
|
||||
|
||||
const style = {
|
||||
transform: CSS.Transform.toString(transform),
|
||||
transition,
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
function handleUpdate(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
startTransition(() => updateModule(mod.id, courseId, fd));
|
||||
setEditing(false);
|
||||
}
|
||||
|
||||
function handleDelete() {
|
||||
if (!confirm(`Удалить модуль "${mod.title}"? Все уроки будут удалены.`)) return;
|
||||
startTransition(() => deleteModule(mod.id, courseId));
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={setNodeRef} style={style} className="flex items-center gap-3 bg-slate-50 border border-slate-200 rounded-xl px-4 py-3">
|
||||
<button type="button" {...attributes} {...listeners} className="text-slate-300 hover:text-slate-500 cursor-grab active:cursor-grabbing">
|
||||
⋮⋮
|
||||
</button>
|
||||
{editing ? (
|
||||
<form onSubmit={handleUpdate} className="flex items-center gap-2 flex-1">
|
||||
<Input name="title" defaultValue={mod.title} autoFocus className="h-8 text-sm" />
|
||||
<Button type="submit" size="sm" disabled={pending}>Сохранить</Button>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setEditing(false)}>Отмена</Button>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<span className="flex-1 font-medium text-slate-700">{mod.title}</span>
|
||||
<span className="text-sm text-slate-400">{mod._count.lessons} уроков</span>
|
||||
<Link
|
||||
href={`/admin/courses/${courseId}/modules/${mod.id}`}
|
||||
className="text-xs text-amber-600 hover:underline"
|
||||
>
|
||||
Уроки
|
||||
</Link>
|
||||
<button type="button" onClick={() => setEditing(true)} className="text-xs text-slate-500 hover:text-slate-700">
|
||||
Переименовать
|
||||
</button>
|
||||
<button type="button" onClick={handleDelete} disabled={pending} className="text-xs text-red-400 hover:text-red-600">
|
||||
Удалить
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SortableModules({ courseId, modules }: { courseId: string; modules: Module[] }) {
|
||||
const [items, setItems] = useState(modules);
|
||||
const [, startTransition] = useTransition();
|
||||
|
||||
const sensors = useSensors(useSensor(PointerSensor));
|
||||
|
||||
function handleDragEnd(event: DragEndEvent) {
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
const oldIndex = items.findIndex((m) => m.id === active.id);
|
||||
const newIndex = items.findIndex((m) => m.id === over.id);
|
||||
const newItems = arrayMove(items, oldIndex, newIndex);
|
||||
setItems(newItems);
|
||||
startTransition(() => reorderModules(courseId, newItems.map((m) => m.id)));
|
||||
}
|
||||
|
||||
function handleCreate(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
e.currentTarget.reset();
|
||||
startTransition(() => createModule(courseId, fd));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||
<SortableContext items={items.map((m) => m.id)} strategy={verticalListSortingStrategy}>
|
||||
{items.map((mod) => (
|
||||
<SortableModule key={mod.id} mod={mod} courseId={courseId} />
|
||||
))}
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
{items.length === 0 && (
|
||||
<p className="text-sm text-slate-400 py-2">Модулей пока нет. Добавьте первый.</p>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleCreate} className="flex gap-2 pt-2">
|
||||
<Input name="title" placeholder="Название нового модуля" required className="max-w-xs" />
|
||||
<Button type="submit">+ Модуль</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user