2025-02-27 08:25:39 +08:00
|
|
|
import { Prisma } from "packages/common/dist";
|
|
|
|
import React, {
|
|
|
|
createContext,
|
|
|
|
ReactNode,
|
|
|
|
useContext,
|
|
|
|
useMemo,
|
|
|
|
useState,
|
|
|
|
} from "react";
|
2025-02-25 20:40:34 +08:00
|
|
|
interface SelectedTerms {
|
|
|
|
[key: string]: string[]; // 每个 slug 对应一个 string 数组
|
|
|
|
}
|
2025-02-25 21:48:41 +08:00
|
|
|
|
2025-02-25 16:04:55 +08:00
|
|
|
interface MainContextType {
|
|
|
|
searchValue?: string;
|
2025-02-25 20:40:34 +08:00
|
|
|
selectedTerms?: SelectedTerms;
|
2025-02-25 16:04:55 +08:00
|
|
|
setSearchValue?: React.Dispatch<React.SetStateAction<string>>;
|
2025-02-25 20:40:34 +08:00
|
|
|
setSelectedTerms?: React.Dispatch<React.SetStateAction<SelectedTerms>>;
|
2025-02-27 08:25:39 +08:00
|
|
|
searchCondition?: Prisma.PostWhereInput;
|
2025-02-25 16:04:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const MainContext = createContext<MainContextType | null>(null);
|
|
|
|
interface MainProviderProps {
|
|
|
|
children: ReactNode;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function MainProvider({ children }: MainProviderProps) {
|
|
|
|
const [searchValue, setSearchValue] = useState("");
|
2025-02-25 20:40:34 +08:00
|
|
|
const [selectedTerms, setSelectedTerms] = useState<SelectedTerms>({}); // 初始化状态
|
2025-02-27 08:25:39 +08:00
|
|
|
|
|
|
|
const searchCondition: Prisma.PostWhereInput = useMemo(() => {
|
|
|
|
const containTextCondition: Prisma.StringNullableFilter = {
|
|
|
|
contains: searchValue,
|
|
|
|
mode: "insensitive" as Prisma.QueryMode, // 使用类型断言
|
|
|
|
};
|
|
|
|
return searchValue
|
|
|
|
? {
|
|
|
|
OR: [
|
|
|
|
{ title: containTextCondition },
|
|
|
|
{ subTitle: containTextCondition },
|
|
|
|
{ content: containTextCondition },
|
|
|
|
{
|
|
|
|
terms: {
|
|
|
|
some: {
|
|
|
|
name: containTextCondition,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
],
|
|
|
|
}
|
|
|
|
: {};
|
|
|
|
}, [searchValue]);
|
2025-02-25 16:04:55 +08:00
|
|
|
return (
|
|
|
|
<MainContext.Provider
|
|
|
|
value={{
|
|
|
|
searchValue,
|
|
|
|
setSearchValue,
|
2025-02-25 20:40:34 +08:00
|
|
|
selectedTerms,
|
|
|
|
setSelectedTerms,
|
2025-02-27 08:25:39 +08:00
|
|
|
searchCondition,
|
2025-02-25 16:04:55 +08:00
|
|
|
}}>
|
|
|
|
{children}
|
|
|
|
</MainContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
export const useMainContext = () => {
|
|
|
|
const context = useContext(MainContext);
|
|
|
|
if (!context) {
|
|
|
|
throw new Error("useMainContext must be used within MainProvider");
|
|
|
|
}
|
|
|
|
return context;
|
|
|
|
};
|