Files
jiang13-bbs/frontend/components/CommentsPolicyProvider.tsx
freefire d93635c961 feat: 全站评论开关,并统一后台表单控件
关闭评论后前台隐藏评论能力;外观/设置/公告改用 AdminField 与 Stepper。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 01:22:00 +08:00

53 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"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>
);
}