Merge branch 'main' of http://113.45.157.195:3003/insiinc/re-mooc
This commit is contained in:
commit
3a21c5bab0
|
@ -1,10 +1,12 @@
|
||||||
import { Checkbox, Divider, Radio, Space , Spin} from 'antd';
|
import { Checkbox, Divider, Radio, Space, Spin } from "antd";
|
||||||
import { categories, levels } from '../mockData';
|
import { categories, levels } from "../mockData";
|
||||||
import { TaxonomySlug, TermDto } from '@nice/common';
|
import { TaxonomySlug, TermDto } from "@nice/common";
|
||||||
|
|
||||||
import { useEffect, useMemo } from 'react';
|
import { useEffect, useMemo } from "react";
|
||||||
import { api } from '@nice/client';
|
import { api } from "@nice/client";
|
||||||
import { useSearchParams } from 'react-router-dom';
|
import { useSearchParams } from "react-router-dom";
|
||||||
|
import TermTree from "@web/src/components/models/term/term-tree";
|
||||||
|
import TermSelect from "@web/src/components/models/term/term-select";
|
||||||
|
|
||||||
interface FilterSectionProps {
|
interface FilterSectionProps {
|
||||||
selectedCategory: string;
|
selectedCategory: string;
|
||||||
|
@ -19,29 +21,31 @@ interface GetTaxonomyProps {
|
||||||
}
|
}
|
||||||
|
|
||||||
function useGetTaxonomy({ type }): GetTaxonomyProps {
|
function useGetTaxonomy({ type }): GetTaxonomyProps {
|
||||||
const {data,isLoading} :{data:TermDto[],isLoading:boolean}= api.term.findMany.useQuery({
|
const { data, isLoading }: { data: TermDto[]; isLoading: boolean } =
|
||||||
|
api.term.findMany.useQuery({
|
||||||
where: {
|
where: {
|
||||||
taxonomy: {
|
taxonomy: {
|
||||||
//TaxonomySlug.CATEGORY
|
//TaxonomySlug.CATEGORY
|
||||||
slug:type
|
slug: type,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
children :true
|
children: true,
|
||||||
},
|
},
|
||||||
take:20, // 只取前10个
|
take: 10, // 只取前10个
|
||||||
orderBy: {
|
orderBy: {
|
||||||
createdAt: 'desc', // 按创建时间降序排列
|
createdAt: "desc", // 按创建时间降序排列
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
const categories = useMemo(() => {
|
const categories = useMemo(() => {
|
||||||
const allCategories = isLoading ? [] : data?.map((course) => course.name);
|
const allCategories = isLoading
|
||||||
|
? []
|
||||||
|
: data?.map((course) => course.name);
|
||||||
return [...Array.from(new Set(allCategories))];
|
return [...Array.from(new Set(allCategories))];
|
||||||
}, [data]);
|
}, [data]);
|
||||||
return {categories,isLoading}
|
return { categories, isLoading };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export default function FilterSection({
|
export default function FilterSection({
|
||||||
selectedCategory,
|
selectedCategory,
|
||||||
selectedLevel,
|
selectedLevel,
|
||||||
|
@ -50,42 +54,38 @@ export default function FilterSection({
|
||||||
}: FilterSectionProps) {
|
}: FilterSectionProps) {
|
||||||
const gateGory: GetTaxonomyProps = useGetTaxonomy({
|
const gateGory: GetTaxonomyProps = useGetTaxonomy({
|
||||||
type: TaxonomySlug.CATEGORY,
|
type: TaxonomySlug.CATEGORY,
|
||||||
})
|
});
|
||||||
const levels: GetTaxonomyProps = useGetTaxonomy({
|
const levels: GetTaxonomyProps = useGetTaxonomy({
|
||||||
type: TaxonomySlug.LEVEL,
|
type: TaxonomySlug.LEVEL,
|
||||||
})
|
});
|
||||||
|
|
||||||
const [searchParams,setSearchParams] = useSearchParams()
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if(searchParams.get('category')) onCategoryChange(searchParams.get('category'))
|
if (searchParams.get("category"))
|
||||||
},[searchParams.get('category')])
|
onCategoryChange(searchParams.get("category"));
|
||||||
|
}, [searchParams.get("category")]);
|
||||||
|
|
||||||
|
const { data: taxonomies } = api.taxonomy.getAll.useQuery({});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="bg-white p-6 rounded-lg shadow-sm space-y-6">
|
<div className="bg-white p-6 rounded-lg shadow-sm space-y-6">
|
||||||
<div>
|
<Form>
|
||||||
<h3 className="text-lg font-medium mb-4">课程分类</h3>
|
|
||||||
<Radio.Group
|
|
||||||
value={selectedCategory}
|
|
||||||
onChange={(e) => onCategoryChange(e.target.value)}
|
|
||||||
className="flex flex-col space-y-3"
|
|
||||||
>
|
|
||||||
{
|
|
||||||
gateGory.isLoading?
|
|
||||||
(<Spin/>)
|
|
||||||
:
|
|
||||||
(
|
|
||||||
<>
|
|
||||||
<Radio value="" >全部课程</Radio>
|
|
||||||
{gateGory.categories.map(category => (
|
|
||||||
<Radio key={category} value={category}>
|
|
||||||
{category}
|
|
||||||
</Radio>
|
|
||||||
))}
|
|
||||||
</>)
|
|
||||||
}
|
|
||||||
|
|
||||||
</Radio.Group>
|
</Form>
|
||||||
|
{taxonomies.map((tax) => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-lg font-medium mb-4">
|
||||||
|
{tax?.name}
|
||||||
|
</h3>
|
||||||
|
<TermSelect
|
||||||
|
multiple
|
||||||
|
taxonomyId={tax?.id}></TermSelect>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
<Divider className="my-6" />
|
<Divider className="my-6" />
|
||||||
|
|
||||||
|
@ -94,23 +94,19 @@ export default function FilterSection({
|
||||||
<Radio.Group
|
<Radio.Group
|
||||||
value={selectedLevel}
|
value={selectedLevel}
|
||||||
onChange={(e) => onLevelChange(e.target.value)}
|
onChange={(e) => onLevelChange(e.target.value)}
|
||||||
className="flex flex-col space-y-3"
|
className="flex flex-col space-y-3">
|
||||||
>
|
{levels.isLoading ? (
|
||||||
{
|
<Spin />
|
||||||
levels.isLoading ?
|
) : (
|
||||||
(<Spin/>)
|
|
||||||
:
|
|
||||||
(
|
|
||||||
<>
|
<>
|
||||||
<Radio value="">全部难度</Radio>
|
<Radio value="">全部难度</Radio>
|
||||||
{levels.categories.map(level => (
|
{levels.categories.map((level) => (
|
||||||
<Radio key={level} value={level}>
|
<Radio key={level} value={level}>
|
||||||
{level}
|
{level}
|
||||||
</Radio>
|
</Radio>
|
||||||
))}
|
))}
|
||||||
</>)
|
</>
|
||||||
}
|
)}
|
||||||
|
|
||||||
</Radio.Group>
|
</Radio.Group>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -3,7 +3,12 @@ import { mockCourses } from "./mockData";
|
||||||
import FilterSection from "./components/FilterSection";
|
import FilterSection from "./components/FilterSection";
|
||||||
import CourseList from "./components/CourseList";
|
import CourseList from "./components/CourseList";
|
||||||
import { api } from "@nice/client";
|
import { api } from "@nice/client";
|
||||||
import { courseDetailSelect, CourseDto, LectureType, PostType } from "@nice/common";
|
import {
|
||||||
|
courseDetailSelect,
|
||||||
|
CourseDto,
|
||||||
|
LectureType,
|
||||||
|
PostType,
|
||||||
|
} from "@nice/common";
|
||||||
import { useSearchParams } from "react-router-dom";
|
import { useSearchParams } from "react-router-dom";
|
||||||
import { set } from "idb-keyval";
|
import { set } from "idb-keyval";
|
||||||
|
|
||||||
|
@ -27,15 +32,20 @@ export default function CoursesPage() {
|
||||||
const {data,isLoading} :{ data:paginationData,isLoading:boolean} = api.post.findManyWithPagination.useQuery({
|
const {data,isLoading} :{ data:paginationData,isLoading:boolean} = api.post.findManyWithPagination.useQuery({
|
||||||
where: {
|
where: {
|
||||||
type: PostType.COURSE,
|
type: PostType.COURSE,
|
||||||
terms:isAll?{}:{
|
terms: isAll
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
some: {
|
some: {
|
||||||
OR: [
|
OR: [
|
||||||
selectedCategory?{name:selectedCategory}:{},
|
selectedCategory
|
||||||
selectedLevel?{name:selectedLevel}:{}
|
? { name: selectedCategory }
|
||||||
|
: {},
|
||||||
|
selectedLevel
|
||||||
|
? { name: selectedLevel }
|
||||||
|
: {},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
},
|
},
|
||||||
pageSize,
|
pageSize,
|
||||||
page:currentPage,
|
page:currentPage,
|
||||||
|
@ -55,11 +65,25 @@ export default function CoursesPage() {
|
||||||
where: {
|
where: {
|
||||||
type: PostType.COURSE,
|
type: PostType.COURSE,
|
||||||
OR: [
|
OR: [
|
||||||
{ title: { contains: searchValue, mode: 'insensitive' } },
|
{ title: { contains: searchValue, mode: "insensitive" } },
|
||||||
{ subTitle: { contains: searchValue, mode: 'insensitive' } },
|
{
|
||||||
{ content: { contains: searchValue, mode: 'insensitive' } },
|
subTitle: {
|
||||||
{ terms: { some: { name: { contains: searchValue, mode: 'insensitive' } } } }
|
contains: searchValue,
|
||||||
]
|
mode: "insensitive",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ content: { contains: searchValue, mode: "insensitive" } },
|
||||||
|
{
|
||||||
|
terms: {
|
||||||
|
some: {
|
||||||
|
name: {
|
||||||
|
contains: searchValue,
|
||||||
|
mode: "insensitive",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
select:courseDetailSelect,
|
select:courseDetailSelect,
|
||||||
pageSize,
|
pageSize,
|
||||||
|
@ -72,18 +96,23 @@ export default function CoursesPage() {
|
||||||
},[currentPage])
|
},[currentPage])
|
||||||
}
|
}
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if(searchParams.get('searchValue')==''){
|
if (searchParams.get("searchValue") == "") {
|
||||||
setSelectedCategory('');
|
setSelectedCategory("");
|
||||||
setSelectedLevel('')
|
setSelectedLevel("");
|
||||||
}
|
}
|
||||||
}, [searchParams.get('searchValue')]);
|
}, [searchParams.get("searchValue")]);
|
||||||
const filteredCourses = useMemo(() => {
|
const filteredCourses = useMemo(() => {
|
||||||
return isCourseLoading ? [] : coursesData;
|
return isCourseLoading ? [] : coursesData;
|
||||||
}, [isCourseLoading, coursesData, selectedCategory, selectedLevel]);
|
}, [isCourseLoading, coursesData, selectedCategory, selectedLevel]);
|
||||||
|
|
||||||
const paginatedCourses: CourseDto[] = useMemo(() => {
|
const paginatedCourses: CourseDto[] = useMemo(() => {
|
||||||
const startIndex = (currentPage - 1) * pageSize;
|
const startIndex = (currentPage - 1) * pageSize;
|
||||||
return isCourseLoading ? [] : (filteredCourses.slice(startIndex, startIndex + pageSize) as any as CourseDto[]);
|
return isCourseLoading
|
||||||
|
? []
|
||||||
|
: (filteredCourses.slice(
|
||||||
|
startIndex,
|
||||||
|
startIndex + pageSize
|
||||||
|
) as any as CourseDto[]);
|
||||||
}, [filteredCourses, currentPage]);
|
}, [filteredCourses, currentPage]);
|
||||||
|
|
||||||
const handlePageChange = (page: number) => {
|
const handlePageChange = (page: number) => {
|
||||||
|
@ -91,9 +120,8 @@ export default function CoursesPage() {
|
||||||
window.scrollTo({ top: 0, behavior: "smooth" });
|
window.scrollTo({ top: 0, behavior: "smooth" });
|
||||||
};
|
};
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setCurrentPage(1)
|
setCurrentPage(1);
|
||||||
},[])
|
}, []);
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
|
|
|
@ -39,8 +39,7 @@ function useGetTaxonomy({ type }): GetTaxonomyProps {
|
||||||
}, [data]);
|
}, [data]);
|
||||||
return { categories, isLoading }
|
return { categories, isLoading }
|
||||||
}
|
}
|
||||||
// 修改useGetName中的查询条件
|
// 不同分类跳转
|
||||||
|
|
||||||
function useFetchCoursesByCategory(category: string) {
|
function useFetchCoursesByCategory(category: string) {
|
||||||
const isAll = category === '全部';
|
const isAll = category === '全部';
|
||||||
const { data, isLoading }: { data: CourseDto[], isLoading: boolean } = api.post.findMany.useQuery({
|
const { data, isLoading }: { data: CourseDto[], isLoading: boolean } = api.post.findMany.useQuery({
|
||||||
|
@ -56,11 +55,11 @@ function useFetchCoursesByCategory(category: string) {
|
||||||
terms: true
|
terms: true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
console.log("ss",data)
|
|
||||||
return { data, isLoading };
|
return { data, isLoading };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 不同分类跳转
|
|
||||||
|
|
||||||
const { Title, Text } = Typography;
|
const { Title, Text } = Typography;
|
||||||
|
|
||||||
|
@ -102,31 +101,8 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
console.log('data:', data)
|
console.log('data:', data)
|
||||||
})
|
})
|
||||||
// const { data } = api.post.findMany.useQuery({
|
|
||||||
// where: {}, // 必选参数
|
|
||||||
// include: { // 关联查询
|
|
||||||
// instructors: true
|
|
||||||
// },
|
|
||||||
// orderBy: { // 排序规则
|
|
||||||
// createdAt: 'desc'
|
|
||||||
// },
|
|
||||||
// take: 8
|
|
||||||
// })
|
|
||||||
// useEffect(() => {
|
|
||||||
// // 添加空值保护
|
|
||||||
// if (data && data.length > 0) {
|
|
||||||
// console.log('有效数据:', data)
|
|
||||||
// // 执行后续操作
|
|
||||||
// } else {
|
|
||||||
// console.log('无数据或加载中')
|
|
||||||
// }
|
|
||||||
// }, [data])
|
|
||||||
// const formatted = data?.map(course => ({
|
|
||||||
// id: course.id,
|
|
||||||
// title: course.title
|
|
||||||
// }));
|
|
||||||
const handleClick = (course: CourseDto) => {
|
const handleClick = (course: CourseDto) => {
|
||||||
navigate(`/course?courseId=${course.id}/detail`);
|
navigate(`/course/${course.id}/detail`);
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
@ -168,13 +144,7 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
|
||||||
: 'bg-white text-gray-600 hover:bg-gray-100'
|
: 'bg-white text-gray-600 hover:bg-gray-100'
|
||||||
}`}
|
}`}
|
||||||
>全部</Tag>
|
>全部</Tag>
|
||||||
{gateGory.categories.length === 0 && (
|
{gateGory.categories.map((category) => (
|
||||||
<Empty
|
|
||||||
description="暂无课程分类"
|
|
||||||
image={Empty.PRESENTED_IMAGE_DEFAULT}
|
|
||||||
/>
|
|
||||||
)}:{
|
|
||||||
gateGory.categories.map((category) => (
|
|
||||||
<Tag
|
<Tag
|
||||||
key={category}
|
key={category}
|
||||||
color={selectedCategory === category ? 'blue' : 'default'}
|
color={selectedCategory === category ? 'blue' : 'default'}
|
||||||
|
@ -190,6 +160,7 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
|
||||||
>
|
>
|
||||||
{category}
|
{category}
|
||||||
</Tag>
|
</Tag>
|
||||||
|
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -199,7 +170,11 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
|
||||||
{displayedCourses?.map((course) => (
|
{displayedCourses.length=== 0 ? (
|
||||||
|
<div className="col-span-full">
|
||||||
|
<Empty description="暂无课程" image={Empty.PRESENTED_IMAGE_DEFAULT} />
|
||||||
|
</div>
|
||||||
|
) : displayedCourses?.map((course) => (
|
||||||
<Card
|
<Card
|
||||||
onClick={() => handleClick(course)}
|
onClick={() => handleClick(course)}
|
||||||
key={course.id}
|
key={course.id}
|
||||||
|
@ -249,7 +224,6 @@ const CoursesSection: React.FC<CoursesSectionProps> = ({
|
||||||
<TeamOutlined className="text-blue-500 text-lg transform group-hover:scale-110 transition-transform duration-300" />
|
<TeamOutlined className="text-blue-500 text-lg transform group-hover:scale-110 transition-transform duration-300" />
|
||||||
<div className="ml-2 flex items-center flex-grow">
|
<div className="ml-2 flex items-center flex-grow">
|
||||||
<Text className="font-medium text-blue-500 hover:text-blue-600 transition-colors duration-300">
|
<Text className="font-medium text-blue-500 hover:text-blue-600 transition-colors duration-300">
|
||||||
{/* {course.} */}
|
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
<span className="flex items-center bg-blue-100 px-2 py-1 rounded-full text-blue-600 hover:bg-blue-200 transition-colors duration-300">
|
<span className="flex items-center bg-blue-100 px-2 py-1 rounded-full text-blue-600 hover:bg-blue-200 transition-colors duration-300">
|
||||||
|
|
|
@ -1,9 +1,10 @@
|
||||||
import HeroSection from './components/HeroSection';
|
import HeroSection from "./components/HeroSection";
|
||||||
import CategorySection from './components/CategorySection';
|
import CategorySection from "./components/CategorySection";
|
||||||
import CoursesSection from './components/CoursesSection';
|
import CoursesSection from "./components/CoursesSection";
|
||||||
import FeaturedTeachersSection from './components/FeaturedTeachersSection';
|
import FeaturedTeachersSection from "./components/FeaturedTeachersSection";
|
||||||
import { api } from '@nice/client';
|
import { api } from "@nice/client";
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from "react";
|
||||||
|
import TermTree from "@web/src/components/models/term/term-tree";
|
||||||
interface Courses {
|
interface Courses {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
|
@ -17,7 +18,6 @@ interface Courses{
|
||||||
thumbnail: string;
|
thumbnail: string;
|
||||||
}
|
}
|
||||||
const HomePage = () => {
|
const HomePage = () => {
|
||||||
// const mockCourses = [
|
|
||||||
// {
|
// {
|
||||||
// id: 1,
|
// id: 1,
|
||||||
// title: 'Python 零基础入门',
|
// title: 'Python 零基础入门',
|
||||||
|
@ -115,25 +115,29 @@ const HomePage = () => {
|
||||||
// thumbnail: '/images/course8.jpg',
|
// thumbnail: '/images/course8.jpg',
|
||||||
// },
|
// },
|
||||||
// ];
|
// ];
|
||||||
const { data ,isLoading}: { data: Courses[] , isLoading:boolean} = api.post.findMany.useQuery({
|
const { data, isLoading }: { data: Courses[]; isLoading: boolean } =
|
||||||
|
api.post.findMany.useQuery({
|
||||||
where: {},
|
where: {},
|
||||||
include: {
|
include: {
|
||||||
instructors: true,
|
instructors: true,
|
||||||
},
|
},
|
||||||
orderBy: {
|
orderBy: {
|
||||||
createdAt: 'desc' // 按创建时间降序排列
|
createdAt: "desc", // 按创建时间降序排列
|
||||||
},
|
},
|
||||||
take: 8 // 只获取前8个课程
|
take: 8, // 只获取前8个课程
|
||||||
});
|
});
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (data) {
|
if (data) {
|
||||||
console.log('Courses data:', data);
|
console.log("mockCourses data:", data);
|
||||||
}
|
}
|
||||||
}, [data]);
|
}, [data]);
|
||||||
|
|
||||||
|
// 数据处理逻辑
|
||||||
|
// 修正依赖数组
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen">
|
<div className="min-h-screen">
|
||||||
<HeroSection />
|
<HeroSection />
|
||||||
|
|
||||||
<CoursesSection
|
<CoursesSection
|
||||||
title="推荐课程"
|
title="推荐课程"
|
||||||
description="最受欢迎的精品课程,助你快速成长"
|
description="最受欢迎的精品课程,助你快速成长"
|
||||||
|
|
|
@ -23,7 +23,7 @@ export default function TermSelect({
|
||||||
value,
|
value,
|
||||||
onChange,
|
onChange,
|
||||||
className,
|
className,
|
||||||
placeholder = "选择单位",
|
placeholder = "选择分类",
|
||||||
multiple = false,
|
multiple = false,
|
||||||
taxonomyId,
|
taxonomyId,
|
||||||
domainId,
|
domainId,
|
||||||
|
|
|
@ -0,0 +1,199 @@
|
||||||
|
import React, { useEffect, useState, useCallback } from "react";
|
||||||
|
import { Tree } from "antd";
|
||||||
|
import type { DataNode, TreeProps } from "antd/es/tree";
|
||||||
|
import { getUniqueItems } from "@nice/common";
|
||||||
|
import { api } from "@nice/client";
|
||||||
|
|
||||||
|
interface TermData {
|
||||||
|
value?: string;
|
||||||
|
children?: TermData[];
|
||||||
|
key?: string;
|
||||||
|
hasChildren?: boolean;
|
||||||
|
isLeaf?: boolean;
|
||||||
|
pId?: string;
|
||||||
|
title?: React.ReactNode;
|
||||||
|
data?: any;
|
||||||
|
order?: string;
|
||||||
|
id?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TermTreeProps {
|
||||||
|
defaultValue?: string | string[];
|
||||||
|
value?: string | string[];
|
||||||
|
onChange?: (value: string | string[]) => void;
|
||||||
|
multiple?: boolean;
|
||||||
|
taxonomyId?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
className?: string;
|
||||||
|
domainId?: string;
|
||||||
|
style?: React.CSSProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TermTree: React.FC<TermTreeProps> = ({
|
||||||
|
defaultValue,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
className,
|
||||||
|
multiple = false,
|
||||||
|
taxonomyId,
|
||||||
|
domainId,
|
||||||
|
disabled = false,
|
||||||
|
style,
|
||||||
|
}) => {
|
||||||
|
const utils = api.useUtils();
|
||||||
|
const [treeData, setTreeData] = useState<TermData[]>([]);
|
||||||
|
|
||||||
|
const processTermData = (terms: TermData[]): TermData[] => {
|
||||||
|
return terms.map((term) => ({
|
||||||
|
...term,
|
||||||
|
key: term.key || term.id || "",
|
||||||
|
title: term.title || term.value,
|
||||||
|
children: term.children
|
||||||
|
? processTermData(term.children)
|
||||||
|
: undefined,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchParentTerms = useCallback(
|
||||||
|
async (termIds: string | string[], taxonomyId?: string) => {
|
||||||
|
const idsArray = Array.isArray(termIds)
|
||||||
|
? termIds
|
||||||
|
: [termIds].filter(Boolean);
|
||||||
|
try {
|
||||||
|
const result = await utils.term.getParentSimpleTree.fetch({
|
||||||
|
termIds: idsArray,
|
||||||
|
taxonomyId,
|
||||||
|
domainId,
|
||||||
|
});
|
||||||
|
return processTermData(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"Error fetching parent terms for termIds",
|
||||||
|
idsArray,
|
||||||
|
":",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[utils, domainId]
|
||||||
|
);
|
||||||
|
|
||||||
|
const fetchTerms = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const rootTerms = await utils.term.getChildSimpleTree.fetch({
|
||||||
|
taxonomyId,
|
||||||
|
domainId,
|
||||||
|
});
|
||||||
|
let combinedTerms = processTermData(rootTerms);
|
||||||
|
if (defaultValue) {
|
||||||
|
const defaultTerms = await fetchParentTerms(
|
||||||
|
defaultValue,
|
||||||
|
taxonomyId
|
||||||
|
);
|
||||||
|
combinedTerms = getUniqueItems(
|
||||||
|
[...treeData, ...combinedTerms, ...defaultTerms],
|
||||||
|
"key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (value) {
|
||||||
|
const valueTerms = await fetchParentTerms(value, taxonomyId);
|
||||||
|
combinedTerms = getUniqueItems(
|
||||||
|
[...treeData, ...combinedTerms, ...valueTerms],
|
||||||
|
"key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTreeData(combinedTerms);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching terms:", error);
|
||||||
|
}
|
||||||
|
}, [
|
||||||
|
defaultValue,
|
||||||
|
value,
|
||||||
|
taxonomyId,
|
||||||
|
utils,
|
||||||
|
fetchParentTerms,
|
||||||
|
domainId,
|
||||||
|
treeData,
|
||||||
|
]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchTerms();
|
||||||
|
}, [fetchTerms]);
|
||||||
|
|
||||||
|
const onLoadData = async ({ key }: any) => {
|
||||||
|
try {
|
||||||
|
const result = await utils.term.getChildSimpleTree.fetch({
|
||||||
|
termIds: [key],
|
||||||
|
taxonomyId,
|
||||||
|
domainId,
|
||||||
|
});
|
||||||
|
const processedResult = processTermData(result);
|
||||||
|
const newItems = getUniqueItems(
|
||||||
|
[...treeData, ...processedResult],
|
||||||
|
"key"
|
||||||
|
);
|
||||||
|
setTreeData(newItems);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"Error loading data for node with key",
|
||||||
|
key,
|
||||||
|
":",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCheck: TreeProps["onCheck"] = (checkedKeys, info) => {
|
||||||
|
if (onChange) {
|
||||||
|
if (multiple) {
|
||||||
|
onChange(checkedKeys as string[]);
|
||||||
|
} else {
|
||||||
|
onChange((checkedKeys as string[])[0] || "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExpand = async (expandedKeys: React.Key[]) => {
|
||||||
|
try {
|
||||||
|
const allKeyIds = expandedKeys
|
||||||
|
.map((key) => key.toString())
|
||||||
|
.filter(Boolean);
|
||||||
|
const expandedNodes = await utils.term.getChildSimpleTree.fetch({
|
||||||
|
termIds: allKeyIds,
|
||||||
|
taxonomyId,
|
||||||
|
domainId,
|
||||||
|
});
|
||||||
|
const processedNodes = processTermData(expandedNodes);
|
||||||
|
const newItems = getUniqueItems(
|
||||||
|
[...treeData, ...processedNodes],
|
||||||
|
"key"
|
||||||
|
);
|
||||||
|
setTreeData(newItems);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
"Error expanding nodes with keys",
|
||||||
|
expandedKeys,
|
||||||
|
":",
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Tree
|
||||||
|
checkable={multiple}
|
||||||
|
disabled={disabled}
|
||||||
|
className={className}
|
||||||
|
style={style}
|
||||||
|
treeData={treeData as DataNode[]}
|
||||||
|
checkedKeys={Array.isArray(value) ? value : value ? [value] : []}
|
||||||
|
onCheck={handleCheck}
|
||||||
|
loadData={onLoadData}
|
||||||
|
onExpand={handleExpand}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default TermTree;
|
|
@ -1,4 +1,5 @@
|
||||||
import { TreeDataNode } from "@nice/common"
|
import { TreeDataNode } from "@nice/common";
|
||||||
|
import React from "react";
|
||||||
export const treeVisitor = (
|
export const treeVisitor = (
|
||||||
data: TreeDataNode[],
|
data: TreeDataNode[],
|
||||||
key: React.Key,
|
key: React.Key,
|
||||||
|
|
Loading…
Reference in New Issue