关闭评论后前台隐藏评论能力;外观/设置/公告改用 AdminField 与 Stepper。 Co-authored-by: Cursor <cursoragent@cursor.com>
53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
"use client";
|
||
|
||
import {
|
||
createContext,
|
||
useContext,
|
||
useEffect,
|
||
useRef,
|
||
useState,
|
||
type ReactNode,
|
||
} from "react";
|
||
import { useRouter } from "next/navigation";
|
||
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
|
||
|
||
const AllowCommentsContext = createContext(true);
|
||
|
||
/** 前台是否开放评论(SSR 初值 + 后台开关热更新) */
|
||
export function useAllowComments(): boolean {
|
||
return useContext(AllowCommentsContext);
|
||
}
|
||
|
||
/**
|
||
* 根布局注入:关闭评论后前台立即隐藏评论区/数量;开启则刷新以拉回评论。
|
||
*/
|
||
export default function CommentsPolicyProvider({
|
||
allowComments,
|
||
children,
|
||
}: {
|
||
allowComments: boolean;
|
||
children: ReactNode;
|
||
}) {
|
||
const router = useRouter();
|
||
const [open, setOpen] = useState(allowComments);
|
||
const openRef = useRef(open);
|
||
openRef.current = open;
|
||
|
||
useEffect(() => {
|
||
setOpen(allowComments);
|
||
}, [allowComments]);
|
||
|
||
useEffect(() => {
|
||
return realtime.on<RtSettingsData>(RT_SETTINGS_CHANGED, (data) => {
|
||
if (typeof data?.allow_comments !== "boolean") return;
|
||
if (openRef.current === data.allow_comments) return;
|
||
setOpen(data.allow_comments);
|
||
router.refresh();
|
||
});
|
||
}, [router]);
|
||
|
||
return (
|
||
<AllowCommentsContext.Provider value={open}>{children}</AllowCommentsContext.Provider>
|
||
);
|
||
}
|