This commit is contained in:
Li1304553726 2025-02-25 22:46:19 +08:00
commit 6805aba768
16 changed files with 215 additions and 196 deletions

View File

@ -36,7 +36,7 @@ export class AppConfigRouter {
.mutation(async ({ input }) => {
return await this.appConfigService.deleteMany(input);
}),
findFirst: this.trpc.protectProcedure
findFirst: this.trpc.procedure
.input(AppConfigFindFirstArgsSchema)
.query(async ({ input }) => {
return await this.appConfigService.findFirst(input);

View File

@ -61,7 +61,7 @@ export class TermRouter {
.input(TermMethodSchema.getSimpleTree)
.query(async ({ input, ctx }) => {
const { staff } = ctx;
return await this.termService.getChildSimpleTree(staff, input);
return await this.termService.getChildSimpleTree(input, staff);
}),
getParentSimpleTree: this.trpc.procedure
.input(TermMethodSchema.getSimpleTree)

View File

@ -269,10 +269,10 @@ export class TermService extends BaseTreeService<Prisma.TermDelegate> {
}
async getChildSimpleTree(
staff: UserProfile,
data: z.infer<typeof TermMethodSchema.getSimpleTree>,
staff?: UserProfile,
) {
const { domainId = null, permissions } = staff;
const domainId = staff?.domainId || null;
const hasAnyPerms =
staff?.permissions?.includes(RolePerms.MANAGE_ANY_TERM) ||
staff?.permissions?.includes(RolePerms.READ_ANY_TERM);
@ -352,7 +352,9 @@ export class TermService extends BaseTreeService<Prisma.TermDelegate> {
staff: UserProfile,
data: z.infer<typeof TermMethodSchema.getSimpleTree>,
) {
const { domainId = null, permissions } = staff;
// const { domainId = null, permissions } = staff;
const permissions = staff?.permissions || [];
const domainId = staff?.domainId || null;
const hasAnyPerms =
permissions.includes(RolePerms.READ_ANY_TERM) ||
permissions.includes(RolePerms.MANAGE_ANY_TERM);

View File

@ -0,0 +1,52 @@
import CourseList from "@web/src/components/models/course/list/CourseList";
import { useMainContext } from "../../layout/MainProvider";
import { PostType, Prisma } from "@nice/common";
import { useMemo } from "react";
export function CoursesContainer() {
const { searchValue, selectedTerms } = useMainContext();
const termFilters = useMemo(() => {
return Object.entries(selectedTerms)
.filter(([, terms]) => terms.length > 0)
.map(([, terms]) => terms);
}, [selectedTerms]);
const searchCondition: Prisma.StringNullableFilter = {
contains: searchValue,
mode: "insensitive" as Prisma.QueryMode, // 使用类型断言
};
return (
<>
<CourseList
params={{
pageSize: 12,
where: {
type: PostType.COURSE,
AND: termFilters.map((termFilter) => ({
terms: {
some: {
id: {
in: termFilter, // 确保至少有一个 term.id 在当前 termFilter 中
},
},
},
})),
OR: [
{ title: searchCondition },
{ subTitle: searchCondition },
{ content: searchCondition },
{
terms: {
some: {
name: searchCondition,
},
},
},
],
},
}}
cols={4}></CourseList>
</>
);
}
export default CoursesContainer;

View File

@ -2,23 +2,48 @@ import { Checkbox, Divider, Radio, Space, Spin } from "antd";
import { TaxonomySlug, TermDto } from "@nice/common";
import { useEffect, useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import { api } from "@nice/client";
import { useSearchParams } from "react-router-dom";
import TermSelect from "@web/src/components/models/term/term-select";
import { useMainContext } from "../../layout/MainProvider";
export default function FilterSection() {
const { data: taxonomies } = api.taxonomy.getAll.useQuery({});
const { selectedTerms, setSelectedTerms } = useMainContext();
const handleTermChange = (slug: string, selected: string[]) => {
setSelectedTerms({
...selectedTerms,
[slug]: selected, // 更新对应 slug 的选择
});
};
return (
<div className="bg-white p-6 rounded-lg shadow-sm space-y-6 h-full">
{taxonomies?.map((tax, index) => {
const items = Object.entries(selectedTerms).find(
([key, items]) => key === tax.slug
)?.[1];
return (
<div key={index}>
<h3 className="text-lg font-medium mb-4">
{tax?.name}
</h3>
<TermSelect multiple taxonomyId={tax?.id}></TermSelect>
<TermSelect
// open
className="w-72"
value={items}
dropdownRender={(menu) => (
<div style={{ padding: "8px" }}>{menu}</div>
)}
dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
multiple
taxonomyId={tax?.id}
onChange={(selected) =>
handleTermChange(
tax?.slug,
selected as string[]
)
}></TermSelect>
{index < taxonomies.length - 1 && (
<Divider className="my-6" />
)}

View File

@ -1,9 +1,6 @@
import { useMainContext } from "../../layout/MainProvider";
import CourseList from "../components/CourseList";
import FilterSection from "../components/FilterSection";
import CoursesContainer from "../components/CoursesContainer";
export function AllCoursesLayout() {
const { searchValue, setSearchValue } = useMainContext();
return (
<>
<div className="min-h-screen bg-gray-50">
@ -12,12 +9,7 @@ export function AllCoursesLayout() {
<FilterSection></FilterSection>
</div>
<div className="w-5/6 p-4">
<CourseList
cols={4}
params={{
page: 1,
pageSize: 12,
}}></CourseList>
<CoursesContainer></CoursesContainer>
</div>
</div>
</div>

View File

@ -1,22 +1,4 @@
import { useState, useMemo, useEffect } from "react";
import FilterSection from "./components/FilterSection";
import CourseList from "./components/CourseList";
import { api } from "@nice/client";
import {
courseDetailSelect,
CourseDto,
LectureType,
PostType,
} from "@nice/common";
import { useSearchParams } from "react-router-dom";
import { set } from "idb-keyval";
import { useMainContext } from "../layout/MainProvider";
import AllCoursesLayout from "./layout/AllCoursesLayout";
interface paginationData {
items: CourseDto[];
totalPages: number;
}
export default function CoursesPage() {
return (
<>

View File

@ -1,15 +1,16 @@
import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Typography, Button, Spin, Skeleton } from "antd";
import { Typography, Skeleton } from "antd";
import { stringToColor, TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import LookForMore from "./LookForMore";
import CategorySectionCard from "./CategorySectionCard";
import { useNavigate } from "react-router-dom";
import { useMainContext } from "../../layout/MainProvider";
const { Title, Text } = Typography;
const CategorySection = () => {
const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
const [showAll, setShowAll] = useState(false);
//获得分类
const { selectedTerms, setSelectedTerms } = useMainContext();
const {
data: courseCategoriesData,
isLoading,
@ -18,28 +19,12 @@ const CategorySection = () => {
taxonomy: {
slug: TaxonomySlug.CATEGORY,
},
},
include: {
children: true,
},
orderBy: {
createdAt: "desc", // 按创建时间降序排列
parentId : null
},
take: 8,
});
// 分类展示
const [displayedCategories, setDisplayedCategories] = useState<TermDto[]>(
[]
);
useEffect(() => {
if (!isLoading) {
if (showAll) {
setDisplayedCategories(courseCategoriesData);
} else {
setDisplayedCategories(courseCategoriesData.slice(0, 8));
}
}
}, [courseCategoriesData, showAll]);
const navigate = useNavigate()
const handleMouseEnter = useCallback((index: number) => {
setHoveredIndex(index);
}, []);
@ -48,6 +33,13 @@ const CategorySection = () => {
setHoveredIndex(null);
}, []);
const handleMouseClick = useCallback((categoryId:string) => {
setSelectedTerms({
[TaxonomySlug.CATEGORY] : [categoryId]
})
navigate('/courses')
window.scrollTo({top: 0,behavior: "smooth",})
},[]);
return (
<section className="py-32 relative overflow-hidden">
<div className="max-w-screen-2xl mx-auto px-4 relative">
@ -63,9 +55,9 @@ const CategorySection = () => {
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{isLoading ? (
<Skeleton paragraph={{rows:4}}></Skeleton>
<Skeleton paragraph={{ rows: 4 }}></Skeleton>
) : (
displayedCategories.map((category, index) => {
courseCategoriesData.map((category, index) => {
const categoryColor = stringToColor(category.name);
const isHovered = hoveredIndex === index;
@ -78,6 +70,7 @@ const CategorySection = () => {
isHovered={isHovered}
handleMouseEnter={handleMouseEnter}
handleMouseLeave={handleMouseLeave}
handleMouseClick={handleMouseClick}
/>
);
})

View File

@ -1,6 +1,6 @@
import { useNavigate } from "react-router-dom";
import { Typography } from "antd";
export default function CategorySectionCard({index,handleMouseEnter,handleMouseLeave,category,categoryColor,isHovered,}) {
export default function CategorySectionCard({handleMouseClick, index,handleMouseEnter,handleMouseLeave,category,categoryColor,isHovered,}) {
const navigate = useNavigate()
const { Title, Text } = Typography;
return (
@ -12,16 +12,10 @@ export default function CategorySectionCard({index,handleMouseEnter,handleMouseL
role="button"
tabIndex={0}
aria-label={`查看${category.name}课程类别`}
onClick={() => {
console.log(category.name);
navigate(
`/courses?category=${category.name}`
);
window.scrollTo({
top: 0,
behavior: "smooth",
});
}}>
onClick={()=>{
handleMouseClick(category.id)
}}
>
<div className="absolute -inset-0.5 bg-gradient-to-r from-gray-200 to-gray-300 opacity-50 rounded-2xl transition-all duration-700 group-hover:opacity-75" />
<div
className={`absolute inset-0 rounded-2xl bg-gradient-to-br from-white to-gray-50 shadow-lg transition-all duration-700 ease-out ${isHovered

View File

@ -1,9 +1,9 @@
import React, { useState, useMemo } from "react";
import { Typography, Skeleton } from "antd";
import { Typography, Skeleton } from "antd";
import { TaxonomySlug, TermDto } from "@nice/common";
import { api } from "@nice/client";
import { CoursesSectionTag } from "./CoursesSectionTag";
import CourseList from "../../courses/components/CourseList";
import CourseList from "@web/src/components/models/course/list/CourseList";
import LookForMore from "./LookForMore";
interface GetTaxonomyProps {
categories: string[];

View File

@ -1,8 +1,13 @@
import React, { createContext, ReactNode, useContext, useState } from "react";
interface SelectedTerms {
[key: string]: string[]; // 每个 slug 对应一个 string 数组
}
interface MainContextType {
searchValue?: string;
selectedTerms?: SelectedTerms;
setSearchValue?: React.Dispatch<React.SetStateAction<string>>;
setSelectedTerms?: React.Dispatch<React.SetStateAction<SelectedTerms>>;
}
const MainContext = createContext<MainContextType | null>(null);
@ -12,11 +17,14 @@ interface MainProviderProps {
export function MainProvider({ children }: MainProviderProps) {
const [searchValue, setSearchValue] = useState("");
const [selectedTerms, setSelectedTerms] = useState<SelectedTerms>({}); // 初始化状态
return (
<MainContext.Provider
value={{
searchValue,
setSearchValue,
selectedTerms,
setSelectedTerms,
}}>
{children}
</MainContext.Provider>

View File

@ -1,31 +1,37 @@
import { Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
const menuItems = [
{ key: 'home', path: '/', label: '首页' },
{ key: 'courses', path: '/courses', label: '全部课程' },
{ key: 'paths', path: '/paths', label: '学习路径' }
{ key: "home", path: "/", label: "首页" },
{ key: "courses", path: "/courses", label: "全部课程" },
{ key: "paths", path: "/paths", label: "学习路径" },
];
export const NavigationMenu = () => {
const navigate = useNavigate();
const { pathname } = useLocation();
const selectedKey = menuItems.find(item => item.path === pathname)?.key || '';
return (
<Menu
mode="horizontal"
className="border-none font-medium"
selectedKeys={[selectedKey]}
onClick={({ key }) => {
const selectedItem = menuItems.find(item => item.key === key);
if (selectedItem) navigate(selectedItem.path);
}}
>
{menuItems.map(({ key, label }) => (
<Menu.Item key={key} className="text-gray-600 hover:text-blue-600">
{label}
</Menu.Item>
))}
</Menu>
);
const navigate = useNavigate();
const { pathname } = useLocation();
const selectedKey =
menuItems.find((item) => item.path === pathname)?.key || "";
return (
<Menu
mode="horizontal"
className="border-none font-medium"
selectedKeys={[selectedKey]}
onClick={({ key }) => {
const selectedItem = menuItems.find((item) => item.key === key);
if (selectedItem) navigate(selectedItem.path);
window.scrollTo({
top: 0,
behavior: "smooth",
});
}}>
{menuItems.map(({ key, label }) => (
<Menu.Item
key={key}
className="text-gray-600 hover:text-blue-600">
{label}
</Menu.Item>
))}
</Menu>
);
};

View File

@ -1,5 +1,5 @@
import { Pagination, Empty, Skeleton } from "antd";
import CourseCard from "./CourseCard";
import CourseCard from "../../../../app/main/courses/components/CourseCard";
import { courseDetailSelect, CourseDto, Prisma } from "@nice/common";
import { api } from "@nice/client";
import { DefaultArgs } from "@prisma/client/runtime/library";
@ -49,7 +49,7 @@ export default function CourseList({
useEffect(() => {
setCurrentPage(params?.page || 1);
}, [params?.page]);
}, [params?.page, params]);
function onPageChange(page: number, pageSize: number) {
setCurrentPage(page);
window.scrollTo({ top: 0, behavior: "smooth" });
@ -71,7 +71,7 @@ export default function CourseList({
<div className="flex justify-center mt-8">
<Pagination
current={currentPage}
total={totalPages}
total={totalPages * params.pageSize}
pageSize={params?.pageSize}
onChange={onPageChange}
showSizeChanger={false}

View File

@ -1,61 +0,0 @@
// CourseList.tsx
import { motion } from "framer-motion";
import { Course, CourseDto } from "@nice/common";
import { EmptyState } from "@web/src/components/common/space/Empty";
import { Pagination } from "@web/src/components/common/element/Pagination";
import React from "react";
interface CourseListProps {
courses?: CourseDto[];
renderItem: (course: CourseDto) => React.ReactNode;
emptyComponent?: React.ReactNode;
// 新增分页相关属性
currentPage: number;
totalPages: number;
onPageChange: (page: number) => void;
}
const container = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.05,
duration: 0.3,
},
},
};
export const CourseList = ({
courses,
renderItem,
emptyComponent: EmptyComponent,
currentPage,
totalPages,
onPageChange,
}: CourseListProps) => {
if (!courses || courses.length === 0) {
return EmptyComponent || <EmptyState />;
}
return (
<div>
<motion.div
variants={container}
initial="hidden"
animate="show"
className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{courses.map((course) => (
<motion.div key={course.id}>
{renderItem(course)}
</motion.div>
))}
</motion.div>
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={onPageChange}
/>
</div>
);
};

View File

@ -1,5 +1,12 @@
import { TreeSelect, TreeSelectProps } from "antd";
import React, { useEffect, useState, useCallback, useRef } from "react";
import React, {
useEffect,
useState,
useCallback,
useRef,
ReactElement,
JSXElementConstructor,
} from "react";
import { getUniqueItems } from "@nice/common";
import { api } from "@nice/client";
import { DefaultOptionType } from "antd/es/select";
@ -8,25 +15,35 @@ interface TermSelectProps {
defaultValue?: string | string[];
value?: string | string[];
onChange?: (value: string | string[]) => void;
placeholder?: string;
multiple?: boolean;
taxonomyId?: string;
disabled?: boolean;
className?: string;
domainId?: string;
dropdownStyle?: React.CSSProperties;
style?: React.CSSProperties;
open?: boolean;
showSearch?: boolean;
dropdownRender?: (
menu: ReactElement<any, string | JSXElementConstructor<any>>
) => ReactElement<any, string | JSXElementConstructor<any>>;
}
export default function TermSelect({
defaultValue,
value,
onChange,
className,
placeholder = "选择分类",
multiple = false,
taxonomyId,
open = undefined,
showSearch = true,
domainId,
dropdownStyle,
style,
disabled = false,
}: TermSelectProps) {
dropdownRender,
...treeSelectProps
}: TermSelectProps & TreeSelectProps) {
const utils = api.useUtils();
const [listTreeData, setListTreeData] = useState<
Omit<DefaultOptionType, "label">[]
@ -53,7 +70,7 @@ export default function TermSelect({
throw error;
}
},
[utils]
[utils, value]
);
const fetchTerms = useCallback(async () => {
@ -120,25 +137,35 @@ export default function TermSelect({
}
};
const handleExpand = async (keys: React.Key[]) => {
try {
const allKeyIds =
keys.map((key) => key.toString()).filter(Boolean) || [];
const expandedNodes = await utils.term.getChildSimpleTree.fetch({
termIds: allKeyIds,
taxonomyId,
domainId,
});
const flattenedNodes = expandedNodes.flat();
const newItems = getUniqueItems(
[...listTreeData, ...flattenedNodes],
"id"
);
setListTreeData(newItems);
} catch (error) {
console.error("Error expanding nodes with keys", keys, ":", error);
}
};
const handleExpand = useCallback(
async (keys: React.Key[]) => {
try {
const allKeyIds =
keys.map((key) => key.toString()).filter(Boolean) || [];
const expandedNodes = await utils.term.getChildSimpleTree.fetch(
{
termIds: allKeyIds,
taxonomyId,
domainId,
}
);
const flattenedNodes = expandedNodes.flat();
const newItems = getUniqueItems(
[...listTreeData, ...flattenedNodes],
"id"
);
setListTreeData(newItems);
} catch (error) {
console.error(
"Error expanding nodes with keys",
keys,
":",
error
);
}
},
[value]
);
const handleDropdownVisibleChange = async (open: boolean) => {
if (open) {
// This will attempt to expand all nodes and fetch their children when the dropdown opens
@ -150,17 +177,15 @@ export default function TermSelect({
<TreeSelect
treeDataSimpleMode
disabled={disabled}
showSearch
allowClear
// ref={selectRef}
dropdownStyle={{
width: "300px", // 固定宽度
minWidth: "200px", // 最小宽度
maxWidth: "600px", // 最大宽度
...dropdownStyle,
}}
defaultValue={defaultValue}
value={value}
className={className}
placeholder={placeholder}
onChange={handleChange}
loadData={onLoadData}
@ -171,6 +196,7 @@ export default function TermSelect({
onClear={() => handleChange(multiple ? [] : undefined)}
onTreeExpand={handleExpand}
onDropdownVisibleChange={handleDropdownVisibleChange}
{...treeSelectProps}
/>
);
}

View File

@ -69,10 +69,10 @@ export const InitTaxonomies: {
// name: "研判单元",
// slug: TaxonomySlug.UNIT,
// },
{
name: "标签",
slug: TaxonomySlug.TAG,
},
// {
// name: "标签",
// slug: TaxonomySlug.TAG,
// },
];
export const InitAppConfigs: Prisma.AppConfigCreateInput[] = [
{