This commit is contained in:
ditiqi 2025-02-26 16:11:08 +08:00
parent 10248c0e73
commit 37da7cbbf8
21 changed files with 367 additions and 181 deletions

View File

@ -1,6 +1,7 @@
import {
db,
EnrollmentStatus,
Lecture,
Post,
PostType,
SectionDto,
@ -144,14 +145,14 @@ export async function setCourseInfo({ data }: { data: Post }) {
},
});
const descendants = ancestries.map((ancestry) => ancestry.descendant);
const sections: SectionDto[] = descendants
.filter((descendant) => {
const sections: SectionDto[] = (
descendants.filter((descendant) => {
return (
descendant.type === PostType.SECTION &&
descendant.parentId === data.id
);
})
.map((section) => ({
}) as any
).map((section) => ({
...section,
lectures: [],
}));
@ -161,11 +162,12 @@ export async function setCourseInfo({ data }: { data: Post }) {
sections.map((section) => section.id).includes(descendant.parentId)
);
});
const lectureCount = lectures?.length || 0;
sections.forEach((section) => {
section.lectures = lectures.filter(
(lecture) => lecture.parentId === section.id,
);
) as any as Lecture[];
});
Object.assign(data, { sections, lectureCount });
}

View File

@ -6,39 +6,13 @@ interface CollapsibleContentProps {
maxHeight?: number;
}
const CollapsibleContent: React.FC<CollapsibleContentProps> = ({
content,
maxHeight = 150,
}) => {
const CollapsibleContent: React.FC<CollapsibleContentProps> = ({ content }) => {
const contentWrapperRef = useRef(null);
const [isExpanded, setIsExpanded] = useState(false);
const [shouldCollapse, setShouldCollapse] = useState(false);
useEffect(() => {
if (contentWrapperRef.current) {
const shouldCollapse =
contentWrapperRef.current.scrollHeight > maxHeight;
setShouldCollapse(shouldCollapse);
}
}, [content]);
return (
<div className=" text-base ">
<div className=" flex flex-col gap-4 border border-white hover:ring-1 ring-white transition-all duration-300 ease-in-out rounded-xl p-6 ">
{/* 包装整个内容区域的容器 */}
<div
ref={contentWrapperRef}
style={{
maxHeight:
shouldCollapse && !isExpanded
? maxHeight
: undefined,
}}
className={`duration-300 ${
shouldCollapse && !isExpanded
? ` overflow-hidden relative`
: ""
}`}>
<div ref={contentWrapperRef}>
{/* 内容区域 */}
<div
className="ql-editor p-0 space-y-1 leading-relaxed"
@ -46,23 +20,7 @@ const CollapsibleContent: React.FC<CollapsibleContentProps> = ({
__html: content || "",
}}
/>
{/* 渐变遮罩 */}
{shouldCollapse && !isExpanded && (
<div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-white to-transparent" />
)}
</div>
{/* 展开/收起按钮 */}
{shouldCollapse && (
<button
onClick={() => setIsExpanded(!isExpanded)}
className="mt-2 text-blue-500 hover:text-blue-700">
{isExpanded ? "收起" : "展开"}
</button>
)}
{/* PostResources 组件 */}
{/* <PostResources post={post} /> */}
</div>
</div>
);

View File

@ -1,11 +1,11 @@
export const defaultModules = {
toolbar: [
[{ 'header': [1, 2, 3, 4, 5, 6, false] }],
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered' }, { 'list': 'bullet' }],
[{ 'color': [] }, { 'background': [] }],
[{ 'align': [] }],
['link', 'image'],
['clean']
]
[{ header: [1, 2, 3, 4, 5, 6, false] }],
["bold", "italic", "underline", "strike"],
[{ list: "ordered" }, { list: "bullet" }],
[{ color: [] }, { background: [] }],
[{ align: [] }],
["link"],
["clean"],
],
};

View File

@ -1,5 +1,4 @@
import { useEffect, useState } from "react";
// import UncoverAvatarUploader from "../uploader/UncoverAvatarUploader ";
import React, { useEffect, useState } from "react";
import { Upload, Progress, Button, Image, Form } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import AvatarUploader from "./AvatarUploader";
@ -8,11 +7,17 @@ import { isEqual } from "lodash";
interface MultiAvatarUploaderProps {
value?: string[];
onChange?: (value: string[]) => void;
className?: string;
placeholder?: string;
style?: React.CSSProperties;
}
export function MultiAvatarUploader({
value,
onChange,
className,
style,
placeholder = "点击上传",
}: MultiAvatarUploaderProps) {
const [imageList, setImageList] = useState<string[]>(value || []);
const [previewImage, setPreviewImage] = useState<string>("");
@ -30,12 +35,21 @@ export function MultiAvatarUploader({
{(imageList || [])?.map((image, index) => {
return (
<div
className="mr-2px relative"
className={`mr-2px relative ${className}`}
key={index}
style={{ width: "200px", height: "100px" }}>
style={{
width: "100px",
height: "100px",
...style,
}}>
<Image
alt=""
style={{ width: "200px", height: "100px" }}
className={className}
style={{
width: "100px",
height: "100px",
...style,
}}
src={image}
preview={{
visible: previewImage === image,
@ -70,7 +84,10 @@ export function MultiAvatarUploader({
</div>
<div className="flex">
<AvatarUploader
style={style}
className={className}
showCover={false}
placeholder={placeholder}
successText={"轮播图上传成功"}
onChange={(value) => {
console.log(value);

View File

@ -0,0 +1,135 @@
import React, { useMemo } from "react";
import { Image, Button, Row, Col, Tooltip } from "antd";
import { ResourceDto } from "@nice/common";
import { env } from "@web/src/env";
import { getFileIcon } from "./utils";
import { formatFileSize, getCompressedImageUrl } from "@nice/utils";
export default function ResourcesShower({
resources = [],
}: {
resources: ResourceDto[];
}) {
const { resources: dealedResources } = useMemo(() => {
if (!resources) return { resources: [] };
const isImage = (url: string) =>
/\.(png|jpg|jpeg|gif|webp)$/i.test(url);
const sortedResources = resources
.map((resource) => {
const original = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${resource.url}`;
const isImg = isImage(resource.url);
return {
...resource,
url: isImg ? getCompressedImageUrl(original) : original,
originalUrl: original,
isImage: isImg,
};
})
.sort((a, b) => (a.isImage === b.isImage ? 0 : a.isImage ? -1 : 1));
return { resources: sortedResources };
}, [resources]);
const imageResources = dealedResources.filter((res) => res.isImage);
const fileResources = dealedResources.filter((res) => !res.isImage);
return (
<div className="space-y-6">
{imageResources.length > 0 && (
<Row gutter={[16, 16]} className="mb-6">
<Image.PreviewGroup>
{imageResources.map((resource) => (
<Col
key={resource.url}
xs={12}
sm={8}
md={6}
lg={6}
xl={4}
className="relative">
<div className="relative aspect-square rounded-lg overflow-hidden bg-gray-100">
<div className="w-full h-full">
<Image
src={resource.url}
alt={resource.title}
preview={{
src: resource.originalUrl,
mask: (
<div className="flex items-center justify-center text-white">
</div>
),
}}
style={{
position: "absolute",
inset: 0,
width: "100%",
height: "100%",
objectFit: "cover",
}}
rootClassName="w-full h-full"
/>
</div>
{resource.title && (
<div className="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/60 to-transparent text-white text-sm truncate">
{resource.title}
</div>
)}
</div>
</Col>
))}
</Image.PreviewGroup>
</Row>
)}
{fileResources.length > 0 && (
<div className="rounded-xl p-1 border border-gray-100 bg-white">
<div className="flex flex-nowrap overflow-x-auto scrollbar-hide gap-1.5">
{fileResources.map((resource) => {
return (
<a
key={resource.url}
className="flex-shrink-0 relative active:scale-95 transition-transform select-none "
href={resource.originalUrl}
target="_blank"
download={true}
title="点击下载文件">
{/* 超紧凑卡片容器 */}
<div className="w-[120px] h-[80px] p-2 flex flex-col items-center justify-between rounded-xl hover:bg-primary-50/40 cursor-pointer">
{/* 微型文件图标 */}
<div className="text-primary-600 text-base">
{getFileIcon(resource.url)}
</div>
{/* 压缩信息展示 */}
<div className="w-full text-center space-y-0.5">
<p className="text-xs font-medium text-gray-800 truncate">
{resource.title?.slice(0, 12) ||
"未命名"}
</p>
<div className="flex items-center justify-between text-xs text-gray-500">
<span className="bg-gray-100 px-0.5 rounded-sm">
{resource.url
.split(".")
.pop()
?.slice(0, 4)
.toUpperCase()}
</span>
<span>
{resource.meta.size &&
formatFileSize(
resource.meta.size
)}
</span>
</div>
</div>
</div>
</a>
);
})}
</div>
</div>
)}
</div>
);
}

View File

@ -0,0 +1,48 @@
import {
FilePdfOutlined,
FileWordOutlined,
FileExcelOutlined,
FilePptOutlined,
FileTextOutlined,
FileZipOutlined,
FileImageOutlined,
FileUnknownOutlined,
} from "@ant-design/icons";
export const isContentEmpty = (html: string) => {
// 创建一个临时 div 来解析 HTML 内容
const temp = document.createElement("div");
temp.innerHTML = html;
// 获取纯文本内容并检查是否为空
return !temp.textContent?.trim();
};
export const getFileIcon = (filename: string) => {
const extension = filename.split(".").pop()?.toLowerCase();
switch (extension) {
case "pdf":
return <FilePdfOutlined className="text-red-500" />;
case "doc":
case "docx":
return <FileWordOutlined className="text-blue-500" />;
case "xls":
case "xlsx":
return <FileExcelOutlined className="text-green-600" />;
case "ppt":
case "pptx":
return <FilePptOutlined className="text-orange-500" />;
case "txt":
return <FileTextOutlined className="text-gray-600" />;
case "zip":
case "rar":
case "7z":
return <FileZipOutlined className="text-purple-500" />;
case "png":
case "jpg":
case "jpeg":
case "gif":
case "webp":
return <FileImageOutlined className="text-pink-400" />;
default:
return <FileUnknownOutlined className="text-gray-500" />;
}
};

View File

@ -3,6 +3,7 @@ import {
courseDetailSelect,
CourseDto,
Lecture,
lectureDetailSelect,
RolePerms,
VisitType,
} from "@nice/common";
@ -72,16 +73,17 @@ export function CourseDetailProvider({
).findFirst.useQuery(
{
where: { id: selectedLectureId },
select: lectureDetailSelect,
},
{ enabled: Boolean(editId) }
);
useEffect(() => {
if (course) {
if (lecture?.id) {
read.mutateAsync({
data: {
visitorId: user?.id || null,
postId: course.id,
postId: lecture?.id,
type: VisitType.READED,
},
});

View File

@ -1,67 +0,0 @@
// import { useContext } from "react";
// import { CourseDetailContext } from "../../CourseDetailContext";
// import { CheckCircleIcon } from "@heroicons/react/24/solid";
// export function Overview() {
// const { course } = useContext(CourseDetailContext);
// return (
// <>
// <div className="space-y-8">
// {/* 课程描述 */}
// <div className="prose max-w-none">
// <p>{course?.description}</p>
// </div>
// {/* 学习目标 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">学习目标</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.objectives.map((objective, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-green-500 flex-shrink-0 mt-1" />
// <span>{objective}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 适合人群 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">适合人群</h2>
// <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
// {course?.audiences.map((audience, index) => (
// <div key={index} className="flex items-start gap-2">
// <CheckCircleIcon className="w-5 h-5 text-blue-500 flex-shrink-0 mt-1" />
// <span>{audience}</span>
// </div>
// ))}
// </div>
// </div>
// {/* 课程要求 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">课程要求</h2>
// <ul className="list-disc list-inside space-y-2 text-gray-700">
// {course?.requirements.map((requirement, index) => (
// <li key={index}>{requirement}</li>
// ))}
// </ul>
// </div>
// {/* 可获得技能 */}
// <div>
// <h2 className="text-xl font-semibold mb-4">可获得技能</h2>
// <div className="flex flex-wrap gap-2">
// {course?.skills.map((skill, index) => (
// <span
// key={index}
// className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
// {skill}
// </span>
// ))}
// </div>
// </div>
// </div>
// </>
// );
// }

View File

@ -8,6 +8,7 @@ import { CourseDetailContext } from "./CourseDetailContext";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { Skeleton } from "antd";
import { CoursePreview } from "./CoursePreview/CoursePreview";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
// interface CourseDetailDisplayAreaProps {
// // course: Course;
@ -53,6 +54,12 @@ export const CourseDetailDisplayArea: React.FC = () => {
content={lecture?.content || ""}
maxHeight={500} // Optional, defaults to 150
/>
<div className="px-6">
<ResourcesShower
resources={
lecture?.resources
}></ResourcesShower>
</div>
</div>
</div>
)}

View File

@ -33,7 +33,12 @@ import {
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { Lecture, LectureType, PostType } from "@nice/common";
import {
Lecture,
lectureDetailSelect,
LectureType,
PostType,
} from "@nice/common";
import { useCourseEditor } from "../../context/CourseEditorContext";
import { usePost } from "@nice/client";
import { LectureData, SectionData } from "./interface";
@ -62,6 +67,7 @@ export const LectureList: React.FC<LectureListProps> = ({
orderBy: {
order: "asc",
},
select: lectureDetailSelect,
},
{
enabled: !!sectionId,

View File

@ -15,6 +15,7 @@ import {
LectureType,
LessonTypeLabel,
PostType,
ResourceStatus,
videoMimeTypes,
} from "@nice/common";
import { usePost } from "@nice/client";
@ -23,6 +24,8 @@ import toast from "react-hot-toast";
import { env } from "@web/src/env";
import CollapsibleContent from "@web/src/components/common/container/CollapsibleContent";
import { VideoPlayer } from "@web/src/components/presentation/video-player/VideoPlayer";
import MultiAvatarUploader from "@web/src/components/common/uploader/MultiAvatarUploader";
import ResourcesShower from "@web/src/components/common/uploader/ResourceShower";
interface SortableLectureProps {
field: Lecture;
@ -58,6 +61,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
setLoading(true);
const values = await form.validateFields();
let result;
const fileIds = values?.meta?.fileIds || [];
const videoUrlId = Array.isArray(values?.meta?.videoIds)
? values?.meta?.videoIds[0]
: typeof values?.meta?.videoIds === "string"
@ -72,13 +76,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title,
meta: {
type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined,
},
resources: {
connect: [videoUrlId]
connect: [videoUrlId, ...fileIds]
.filter(Boolean)
.map((fileId) => ({
fileId,
@ -97,13 +102,14 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
title: values?.title,
meta: {
type: values?.meta?.type,
fileIds: fileIds,
videoIds: videoUrlId ? [videoUrlId] : [],
videoUrl: videoUrlId
? `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${videoUrlId}/stream/index.m3u8`
: undefined,
},
resources: {
connect: [videoUrlId]
connect: [videoUrlId, ...fileIds]
.filter(Boolean)
.map((fileId) => ({
fileId,
@ -113,6 +119,7 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
},
});
}
setIsContentVisible(false);
toast.success("课时已更新");
field.id = result.id;
setEditing(false);
@ -178,14 +185,30 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
/>
</Form.Item>
) : (
<div>
<Form.Item
name="content"
className="mb-0 flex-1"
rules={[
{ required: true, message: "请输入内容" },
{
required: true,
message: "请输入内容",
},
]}>
<QuillEditor />
</Form.Item>
<Form.Item
name={["meta", "fileIds"]}
className="mb-0 flex-1"
rules={[
{
required: true,
message: "请传入文件",
},
]}>
<TusUploader multiple={true} />
</Form.Item>
</div>
)}
</div>
@ -237,10 +260,16 @@ export const SortableLecture: React.FC<SortableLectureProps> = ({
{isContentVisible &&
!editing && // Conditionally render content based on type
(field?.meta?.type === LectureType.ARTICLE ? (
<div>
<CollapsibleContent
maxHeight={200}
content={field?.content}
/>
<div className="px-6 ">
<ResourcesShower
resources={field?.resources}></ResourcesShower>
</div>
</div>
) : (
<VideoPlayer src={field?.meta?.videoUrl} />
))}

View File

@ -96,7 +96,6 @@ export const Controls = () => {
<div className="flex items-center space-x-4">
{/* 播放/暂停按钮 */}
<Play></Play>
{/* 时间显示 */}
{duration && (
<span className="text-white text-xl">
@ -114,7 +113,7 @@ export const Controls = () => {
{/* 倍速控制 */}
<Speed></Speed>
{/* 设置按钮 */}
<Setting></Setting>
{/* <Setting></Setting> */}
{/* 全屏按钮 */}
<FullScreen></FullScreen>

View File

@ -14,7 +14,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
onError,
videoRef,
setIsReady,
isPlaying,
setIsPlaying,
setError,
setBufferingState,
@ -26,8 +25,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
isDragging,
setIsDragging,
progressRef,
resolution,
setResolutions,
} = useContext(VideoPlayerContext);
// 处理进度条拖拽
@ -40,7 +37,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
);
videoRef.current.currentTime = percent * videoRef.current.duration;
};
// 添加拖拽事件监听
useEffect(() => {
const handleMouseUp = () => setIsDragging(false);
@ -66,15 +62,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
setError(null);
setLoadingProgress(0);
setBufferingState(false);
// Check for native HLS support (Safari)
if (videoRef.current.canPlayType("application/vnd.apple.mpegurl")) {
videoRef.current.src = src;
setIsReady(true);
// 设置视频时长
setDuration(videoRef.current.duration);
if (autoPlay) {
try {
await videoRef.current.play();
@ -85,14 +78,12 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
}
return;
}
if (!Hls.isSupported()) {
const errorMessage = "您的浏览器不支持 HLS 视频播放";
setError(errorMessage);
onError?.(errorMessage);
return;
}
hls = new Hls({
maxBufferLength: 30,
maxMaxBufferLength: 600,
@ -102,13 +93,10 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
hls.loadSource(src);
hls.attachMedia(videoRef.current);
hls.on(Hls.Events.MANIFEST_PARSED, async () => {
setIsReady(true);
// 设置视频时长
setDuration(videoRef.current?.duration || 0);
if (autoPlay && videoRef.current) {
try {
await videoRef.current.play();
@ -118,7 +106,6 @@ export const VideoDisplay: React.FC<VideoDisplayProps> = ({
}
}
});
hls.on(Hls.Events.BUFFER_APPENDING, () => {
setBufferingState(true);
});

View File

@ -71,7 +71,7 @@ export const routes: CustomRouteObject[] = [
{
path: ":id?/editor",
element: (
<WithAuth>
<WithAuth >
<CourseEditorLayout></CourseEditorLayout>
</WithAuth>
),

View File

@ -1,7 +1,8 @@
export * from "./department"
export * from "./message"
export * from "./staff"
export * from "./term"
export * from "./post"
export * from "./rbac"
export * from "./select"
export * from "./department";
export * from "./message";
export * from "./staff";
export * from "./term";
export * from "./post";
export * from "./rbac";
export * from "./select";
export * from "./resource";

View File

@ -8,6 +8,7 @@ import {
} from "@prisma/client";
import { StaffDto } from "./staff";
import { TermDto } from "./term";
import { ResourceDto } from "./resource";
export type PostComment = {
id: string;
@ -51,6 +52,7 @@ export type LectureMeta = {
};
export type Lecture = Post & {
resources?: ResourceDto[];
meta?: LectureMeta;
};
@ -79,5 +81,5 @@ export type CourseDto = Course & {
sections?: SectionDto[];
terms: TermDto[];
lectureCount?: number;
depts:Department[]
depts: Department[];
};

View File

@ -0,0 +1,52 @@
import { Resource } from "@prisma/client";
export interface BaseMetadata {
size: number;
filetype: string;
filename: string;
extension: string;
modifiedAt: Date;
}
/**
*
*/
export interface ImageMetadata {
width: number; // 图片宽度(px)
height: number; // 图片高度(px)
compressedUrl?: string;
orientation?: number; // EXIF方向信息
space?: string; // 色彩空间 (如: RGB, CMYK)
hasAlpha?: boolean; // 是否包含透明通道
}
/**
*
*/
export interface VideoMetadata {
width?: number;
height?: number;
duration?: number;
videoCodec?: string;
audioCodec?: string;
coverUrl?: string;
}
/**
*
*/
export interface AudioMetadata {
duration: number; // 音频时长(秒)
bitrate?: number; // 比特率(bps)
sampleRate?: number; // 采样率(Hz)
channels?: number; // 声道数
codec?: string; // 音频编码格式
}
export type FileMetadata = ImageMetadata &
VideoMetadata &
AudioMetadata &
BaseMetadata;
export type ResourceDto = Resource & {
meta: FileMetadata;
};

View File

@ -1,5 +0,0 @@
import { Lecture, Section } from "@prisma/client";
export type SectionDto = Section & {
lectures: Lecture[];
};

View File

@ -79,6 +79,7 @@ export const courseDetailSelect: Prisma.PostSelect = {
select: {
id: true,
name: true,
taxonomyId: true,
taxonomy: {
select: {
id: true,
@ -95,3 +96,15 @@ export const courseDetailSelect: Prisma.PostSelect = {
meta: true,
rating: true,
};
export const lectureDetailSelect: Prisma.PostSelect = {
id: true,
title: true,
subTitle: true,
content: true,
resources: true,
createdAt: true,
updatedAt: true,
// 关联表选择
meta: true,
};