This commit is contained in:
ditiqi 2025-02-06 19:23:21 +08:00
parent eb9eec00d9
commit 548187169f
1 changed files with 504 additions and 251 deletions

View File

@ -5,8 +5,17 @@ import {
CaretRightOutlined, CaretRightOutlined,
SaveOutlined, SaveOutlined,
} from "@ant-design/icons"; } from "@ant-design/icons";
import { Form, Alert, Button, Input, Select, Space, Collapse, message } from "antd"; import {
import React, { useState } from "react"; Form,
Alert,
Button,
Input,
Select,
Space,
Collapse,
message,
} from "antd";
import React, { useCallback, useEffect, useState } from "react";
import { import {
DndContext, DndContext,
closestCenter, closestCenter,
@ -14,8 +23,9 @@ import {
PointerSensor, PointerSensor,
useSensor, useSensor,
useSensors, useSensors,
DragEndEvent,
} from "@dnd-kit/core"; } from "@dnd-kit/core";
import { usePost } from "@nice/client"; import { api, emitDataChange } from "@nice/client";
import { import {
arrayMove, arrayMove,
SortableContext, SortableContext,
@ -26,9 +36,27 @@ import {
import { CSS } from "@dnd-kit/utilities"; import { CSS } from "@dnd-kit/utilities";
import QuillEditor from "../../../../common/editor/quill/QuillEditor"; import QuillEditor from "../../../../common/editor/quill/QuillEditor";
import { TusUploader } from "../../../../common/uploader/TusUploader"; import { TusUploader } from "../../../../common/uploader/TusUploader";
import { LectureType } from "@nice/common"; import { Lecture, LectureType, PostType } from "@nice/common";
import { useCourseEditor } from "../context/CourseEditorContext"; import { useCourseEditor } from "../context/CourseEditorContext";
import { usePost } from "@nice/client";
import toast from "react-hot-toast";
interface SectionData {
id: string;
title: string;
content?: string;
courseId?: string;
}
interface LectureData {
id: string;
title: string;
meta?: {
type?: LectureType;
fieldIds?: [];
};
content?: string;
sectionId?: string;
}
const CourseContentFormHeader = () => ( const CourseContentFormHeader = () => (
<Alert <Alert
type="info" type="info"
@ -57,236 +85,356 @@ const CourseSectionEmpty = () => (
</div> </div>
); );
const SortableSection = ({ id, field, remove, children }: any) => { interface SortableSectionProps {
const { attributes, listeners, setNodeRef, transform, transition } = courseId?: string;
useSortable({ id }); field: SectionData;
const [form] = Form.useForm(); remove: () => void;
const { update, create } = usePost(); children: React.ReactNode;
const [loading, setLoading] = useState(false); }
const style = { const SortableSection: React.FC<SortableSectionProps> = ({
transform: CSS.Transform.toString(transform), field,
remove,
courseId,
children,
}) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition, transition,
}; isDragging,
} = useSortable({ id: field?.id });
const [form] = Form.useForm();
const [editing, setEditing] = useState(field.id ? false : true);
const [loading, setLoading] = useState(false);
const { create, update } = usePost();
const handleSave = async () => { const handleSave = async () => {
if (!courseId) {
toast.error("课程未创建,请先填写课程基本信息完成创建");
return;
}
try { try {
const values = await form.validateFields();
setLoading(true); setLoading(true);
const values = await form.validateFields();
if (values.id) { let result;
// await update({ ...values, type: 'section' }); try {
message.success('章节更新成功'); if (!field?.id) {
} else { result = await create.mutateAsync({
// await create({ ...values, type: 'section' }); data: {
message.success('章节创建成功'); title: values?.title,
type: PostType.SECTION,
parentId: courseId,
},
});
} else {
result = await update.mutateAsync({
data: {
title: values?.title,
},
});
}
} catch (err) {
console.log(err);
} }
} catch (error: any) {
message.error(error.message || '保存失败'); field.id = result.id;
setEditing(false);
message.success("保存成功");
} catch (error) {
console.log(error);
message.error("保存失败");
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const items = [
{
key: field.name,
label: (
<Form
form={form}
initialValues={field.value}>
<div className="flex items-center justify-between flex-1">
<Form.Item
name="title"
rules={[{ required: true, message: "请输入章节标题" }]}
className="mb-0 flex-1 mr-4">
<Input placeholder="输入章节标题" />
</Form.Item>
<div className="flex items-center gap-2">
<Button
type="primary"
icon={<SaveOutlined />}
loading={loading}
onClick={handleSave}>
</Button>
<span
{...listeners}
{...attributes}
className="cursor-move">
<DragOutlined className="text-gray-400 hover:text-gray-600" />
</span>
<DeleteOutlined
onClick={() => remove(field.name)}
className="text-red-500 cursor-pointer"
/>
</div>
</div>
</Form>
),
children: <div className="mt-4">{children}</div>,
},
];
return (
<div ref={setNodeRef} style={style} className="mb-4">
<Collapse
items={items}
defaultActiveKey={[field.name]}
expandIcon={({ isActive }) => (
<CaretRightOutlined rotate={isActive ? 90 : 0} />
)}
className="bg-gray-50"
/>
</div>
);
};
const SortableLecture = ({ id, field, remove, sectionId }: any) => {
const { attributes, listeners, setNodeRef, transform, transition } =
useSortable({ id });
const style = { const style = {
transform: CSS.Transform.toString(transform), transform: CSS.Transform.toString(transform),
transition, transition,
backgroundColor: isDragging ? "#f5f5f5" : undefined,
}; };
const { form, taxonomies } = useCourseEditor();
const lectureType =
Form.useWatch(
["sections", sectionId, "lectures", field.name, "type"],
form
) || LectureType.VIDEO;
const renderLabel = () => (
<div className="flex items-center justify-between w-full">
<Form.Item
{...field}
name={[field.name, "title"]}
rules={[{ required: true, message: "请输入课时标题" }]}
className="mb-0 flex-1 mr-4">
<Input placeholder="输入课时标题" />
</Form.Item>
<Form.Item
{...field}
name={[field.name, "type"]}
rules={[{ required: true }]}
initialValue={LectureType.VIDEO}
className="mb-0 w-32">
<Select
options={[
{ label: "视频", value: LectureType.VIDEO },
{ label: "文章", value: LectureType.ARTICLE },
]}
/>
</Form.Item>
<div className="flex items-center">
<DeleteOutlined
onClick={() => remove(field.name)}
className="text-red-500 cursor-pointer mx-2"
/>
<span {...listeners} {...attributes} className="cursor-move">
<DragOutlined className="text-gray-400 hover:text-gray-600" />
</span>
</div>
</div>
);
const renderContent = () => (
<div className="mt-4">
{lectureType === LectureType.ARTICLE && (
<Form.Item
{...field}
name={[field.name, "content"]}
rules={[{ required: true, message: "请输入文章内容" }]}>
<QuillEditor />
</Form.Item>
)}
{lectureType === LectureType.VIDEO && (
<Form.Item
{...field}
name={[field.name, "resourceIds"]}
rules={[{ required: true, message: "请上传视频" }]}>
<TusUploader />
</Form.Item>
)}
</div>
);
return ( return (
<div ref={setNodeRef} style={style} className="mb-4"> <div ref={setNodeRef} style={style} className="mb-4">
<Collapse <Collapse>
defaultActiveKey={[field.key]} <Collapse.Panel
expandIcon={({ isActive }) => ( header={
<CaretRightOutlined rotate={isActive ? 90 : 0} /> editing ? (
)} <Form
className="bg-white shadow-sm border"> form={form}
<Collapse.Panel key={field.key} header={renderLabel()}> className="flex items-center gap-4">
{renderContent()} <Form.Item
name="title"
className="mb-0 flex-1"
initialValue={field?.title}>
<Input placeholder="章节标题" />
</Form.Item>
<Space>
<Button
onClick={handleSave}
loading={loading}
icon={<SaveOutlined />}
type="primary">
</Button>
<Button
onClick={() => {
setEditing(false);
if (!field?.id) {
remove();
}
}}>
</Button>
</Space>
</Form>
) : (
<div className="flex items-center justify-between">
<Space>
<DragOutlined
{...attributes}
{...listeners}
className="cursor-move"
/>
<span>{field.title || "未命名章节"}</span>
</Space>
<Space>
<Button
type="link"
onClick={() => setEditing(true)}>
</Button>
<Button type="link" danger onClick={remove}>
</Button>
</Space>
</div>
)
}
key={field.id || "new"}>
{children}
</Collapse.Panel> </Collapse.Panel>
</Collapse> </Collapse>
</div> </div>
); );
}; };
const LectureList = ({ field }: any) => { interface SortableLectureProps {
const sensors = useSensors( field: LectureData;
useSensor(PointerSensor), remove: () => void;
useSensor(KeyboardSensor, { sectionFieldKey: string;
coordinateGetter: sortableKeyboardCoordinates, }
})
); const SortableLecture: React.FC<SortableLectureProps> = ({
field,
remove,
sectionFieldKey,
}) => {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: field?.id });
const { create, update } = usePost();
const [form] = Form.useForm();
const [editing, setEditing] = useState(field?.id ? false : true);
const [loading, setLoading] = useState(false);
const lectureType =
Form.useWatch(["meta", "type"], form) || LectureType.ARTICLE;
const handleSave = async () => {
try {
setLoading(true);
const values = await form.validateFields();
let result;
try {
if (!field.id) {
result = await create.mutateAsync({
data: {
parentId: sectionFieldKey,
type: PostType.LECTURE,
title: values?.title,
meta: {
type: values?.meta?.type,
fileIds: values?.meta?.fileIds,
},
resources: {
connect: (values?.meta?.fileIds || []).map(
(fileId) => ({
fileId,
})
),
},
content: values?.content,
},
});
} else {
result = await update.mutateAsync({
where: {
id: field?.id,
},
data: {
title: values?.title,
meta: {
type: values?.meta?.type,
fieldIds: values?.meta?.fileIds,
},
resources: {
connect: (values?.meta?.fileIds || []).map(
(fileId) => ({
fileId,
})
),
},
content: values?.content,
},
});
}
} catch (err) {
console.log(err);
}
field.id = result.id;
setEditing(false);
message.success("保存成功");
} catch (error) {
message.error("保存失败");
} finally {
setLoading(false);
}
};
const style = {
transform: CSS.Transform.toString(transform),
transition,
borderBottom: "1px solid #f0f0f0",
backgroundColor: isDragging ? "#f5f5f5" : undefined,
};
return ( return (
<Form.List name={[field.name, "lectures"]}> <div ref={setNodeRef} style={style} className="p-4">
{(fields, { add, remove, move }) => ( {editing ? (
<> <Form form={form} initialValues={field}>
<DndContext <div className="flex gap-4">
sensors={sensors} <Form.Item
collisionDetection={closestCenter} name="title"
onDragEnd={({ active, over }) => { initialValue={field?.title}
if (over && active.id !== over.id) { className="mb-0 flex-1"
const oldIndex = fields.findIndex( rules={[{ required: true }]}>
(field) => field.key === active.id <Input placeholder="课时标题" />
); </Form.Item>
const newIndex = fields.findIndex( <Form.Item
(field) => field.key === over.id name={["meta", "type"]}
); className="mb-0 w-32"
if (oldIndex !== -1 && newIndex !== -1) { rules={[{ required: true }]}>
move(oldIndex, newIndex); <Select
placeholder="选择类型"
options={[
{ label: "视频", value: LectureType.VIDEO },
{
label: "文章",
value: LectureType.ARTICLE,
},
]}
/>
</Form.Item>
</div>
<div className="mt-4 flex flex-1 ">
{lectureType === LectureType.VIDEO ? (
<Form.Item
name={["meta", "fileIds"]}
className="mb-0 flex-1"
rules={[{ required: true }]}>
<TusUploader multiple={false} />
</Form.Item>
) : (
<Form.Item
name="content"
className="mb-0 flex-1"
rules={[{ required: true }]}>
<QuillEditor />
</Form.Item>
)}
</div>
<div className="mt-4 flex justify-end gap-2">
<Button
onClick={handleSave}
loading={loading}
type="primary"
icon={<SaveOutlined />}>
</Button>
<Button
onClick={() => {
setEditing(false);
if (!field?.id) {
remove();
} }
} }}>
}}>
<SortableContext </Button>
items={fields.map((f) => f.key)} </div>
strategy={verticalListSortingStrategy}> </Form>
{fields.map((lectureField) => ( ) : (
<SortableLecture <div className="flex items-center justify-between">
key={lectureField.key} <Space>
id={lectureField.key} <DragOutlined
field={lectureField} {...attributes}
sectionId={field.name} {...listeners}
remove={remove} className="cursor-move"
/> />
))} <CaretRightOutlined />
</SortableContext> <span>{field?.title || "未命名课时"}</span>
</DndContext> </Space>
<Button <Space>
type="dashed" <Button type="link" onClick={() => setEditing(true)}>
onClick={() => add({ type: LectureType.VIDEO })}
block </Button>
icon={<PlusOutlined />}> <Button type="link" danger onClick={remove}>
</Button> </Button>
</> </Space>
</div>
)} )}
</Form.List> </div>
); );
}; };
export default function CourseContentForm() { interface LectureListProps {
const { form, taxonomies } = useCourseEditor(); field: SectionData;
sectionId: string;
}
const LectureList: React.FC<LectureListProps> = ({ field, sectionId }) => {
const { softDeleteByIds } = usePost();
const { data: lectures = [], isLoading } = (
api.post.findMany as any
).useQuery(
{
where: {
parentId: sectionId,
type: PostType.LECTURE,
deletedAt: null,
},
},
{
enabled: !!sectionId,
}
);
useEffect(() => {
if (lectures && !isLoading) {
setItems(lectures);
}
}, [lectures, isLoading]);
const [items, setItems] = useState<LectureData[]>(lectures);
const sensors = useSensors( const sensors = useSensors(
useSensor(PointerSensor), useSensor(PointerSensor),
useSensor(KeyboardSensor, { useSensor(KeyboardSensor, {
@ -294,58 +442,163 @@ export default function CourseContentForm() {
}) })
); );
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="pl-8">
<div
onClick={() => {
console.log(lectures);
}}>
123
</div>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}>
<SortableContext
items={items}
strategy={verticalListSortingStrategy}>
{items.map((lecture) => (
<SortableLecture
key={lecture.id}
field={lecture}
remove={async () => {
if (lecture?.id) {
await softDeleteByIds.mutateAsync({
ids: [lecture.id],
});
}
setItems(lectures);
}}
sectionFieldKey={sectionId}
/>
))}
</SortableContext>
</DndContext>
<Button
type="dashed"
block
icon={<PlusOutlined />}
className="mt-4"
onClick={() => {
setItems([
...items.filter((item) => !!item.id),
{
id: null,
title: "",
meta: {
type: LectureType.ARTICLE,
},
},
]);
}}>
</Button>
</div>
);
};
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 ( return (
<div className="max-w-4xl mx-auto p-6"> <div className="max-w-4xl mx-auto p-6">
<CourseContentFormHeader /> <CourseContentFormHeader />
<Form.List name="sections"> {items.length === 0 ? (
{(fields, { add, remove, move }) => ( <CourseSectionEmpty />
<DndContext ) : (
sensors={sensors} <DndContext
collisionDetection={closestCenter} sensors={sensors}
onDragEnd={({ active, over }) => { collisionDetection={closestCenter}
if (over && active.id !== over.id) { onDragEnd={handleDragEnd}>
const oldIndex = fields.findIndex( <SortableContext
(field) => field.key === active.id items={items}
); strategy={verticalListSortingStrategy}>
const newIndex = fields.findIndex( {items?.map((section, index) => (
(field) => field.key === over.id <SortableSection
); courseId={editId}
if (oldIndex !== -1 && newIndex !== -1) { key={section.id}
move(oldIndex, newIndex); field={section}
} remove={async () => {
} if (section?.id) {
}}> await softDeleteByIds.mutateAsync({
<SortableContext ids: [section.id],
items={fields.map((f) => f.key)} });
strategy={verticalListSortingStrategy}> }
{fields.length === 0 && <CourseSectionEmpty />} setItems(sections);
{fields.map((field) => ( }}>
<SortableSection <LectureList
key={field.key} field={section}
id={field.key} sectionId={section.id}
field={field} />
remove={remove}> </SortableSection>
<LectureList field={field} /> ))}
</SortableSection> </SortableContext>
))} </DndContext>
</SortableContext> )}
<Form.Item>
<Button <Button
block type="dashed"
size="large" block
onClick={() => icon={<PlusOutlined />}
add({ title: "新章节", lectures: [] }) className="mt-4"
} onClick={() => {
icon={<PlusOutlined />} setItems([
type="primary" ...items.filter((item) => !!item.id),
className="mt-4"> { id: null, title: "" },
]);
</Button> }}>
</Form.Item>
</DndContext> </Button>
)}
</Form.List>
</div> </div>
); );
} };
export default CourseContentForm;