This commit is contained in:
ditiqi 2025-02-06 19:23:28 +08:00
parent ad38c5ca39
commit c995df08d8
1 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,121 @@
import { PlusOutlined } from "@ant-design/icons";
import { Button } from "antd";
import React, { useEffect, useState } from "react";
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from "@dnd-kit/core";
import { api } from "@nice/client";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { PostType } from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import { CourseContentFormHeader } from "./CourseContentFormHeader";
import { CourseSectionEmpty } from "./CourseSectionEmpty";
import { SortableSection } from "./SortableSection";
import { LectureList } from "./LectureList";
const CourseContentForm: React.FC = () => {
const { editId } = useCourseEditor();
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const { softDeleteByIds } = usePost();
const { data: sections = [], isLoading } = api.post.findMany.useQuery(
{
where: {
parentId: editId,
type: PostType.SECTION,
deletedAt: null,
},
},
{
enabled: !!editId,
}
);
const [items, setItems] = useState<any[]>(sections);
useEffect(() => {
if (sections && !isLoading) {
setItems(sections);
}
}, [sections]);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
setItems((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id);
const newIndex = items.findIndex((item) => item.id === over.id);
return arrayMove(items, oldIndex, newIndex);
});
};
return (
<div className="max-w-4xl mx-auto p-6">
<CourseContentFormHeader />
{items.length === 0 ? (
<CourseSectionEmpty />
) : (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}>
<SortableContext
items={items}
strategy={verticalListSortingStrategy}>
{items?.map((section, index) => (
<SortableSection
courseId={editId}
key={section.id}
field={section}
remove={async () => {
if (section?.id) {
await softDeleteByIds.mutateAsync({
ids: [section.id],
});
}
setItems(sections);
}}>
<LectureList
field={section}
sectionId={section.id}
/>
</SortableSection>
))}
</SortableContext>
</DndContext>
)}
<Button
type="dashed"
block
icon={<PlusOutlined />}
className="mt-4"
onClick={() => {
setItems([
...items.filter((item) => !!item.id),
{ id: null, title: "" },
]);
}}>
</Button>
</div>
);
};
export default CourseContentForm;