"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(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 ( {children} ); }