完善站点运营设置:分路由管理、登录可见评论、邮件模板内联与关闭注册 SSR。
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -11,42 +11,68 @@ import {
|
||||
import { useRouter } from "next/navigation";
|
||||
import { realtime, RT_SETTINGS_CHANGED, type RtSettingsData } from "@/lib/realtime";
|
||||
|
||||
const AllowCommentsContext = createContext(true);
|
||||
type CommentsPolicy = {
|
||||
open: boolean;
|
||||
requireLogin: boolean;
|
||||
};
|
||||
|
||||
const CommentsPolicyContext = createContext<CommentsPolicy>({
|
||||
open: true,
|
||||
requireLogin: false,
|
||||
});
|
||||
|
||||
/** 前台是否开放评论(SSR 初值 + 后台开关热更新) */
|
||||
export function useAllowComments(): boolean {
|
||||
return useContext(AllowCommentsContext);
|
||||
return useContext(CommentsPolicyContext).open;
|
||||
}
|
||||
|
||||
/** 评论是否仅登录可见 */
|
||||
export function useCommentsRequireLogin(): boolean {
|
||||
return useContext(CommentsPolicyContext).requireLogin;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根布局注入:关闭评论后前台立即隐藏评论区/数量;开启则刷新以拉回评论。
|
||||
* 根布局注入:关闭评论后前台立即隐藏评论区/数量;
|
||||
* 「登录可见」切换时刷新以重拉/清空评论树。
|
||||
*/
|
||||
export default function CommentsPolicyProvider({
|
||||
allowComments,
|
||||
requireLogin = false,
|
||||
children,
|
||||
}: {
|
||||
allowComments: boolean;
|
||||
requireLogin?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(allowComments);
|
||||
const openRef = useRef(open);
|
||||
openRef.current = open;
|
||||
const [policy, setPolicy] = useState<CommentsPolicy>({
|
||||
open: allowComments,
|
||||
requireLogin,
|
||||
});
|
||||
const policyRef = useRef(policy);
|
||||
policyRef.current = policy;
|
||||
|
||||
useEffect(() => {
|
||||
setOpen(allowComments);
|
||||
}, [allowComments]);
|
||||
setPolicy({ open: allowComments, requireLogin });
|
||||
}, [allowComments, requireLogin]);
|
||||
|
||||
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);
|
||||
if (!data) return;
|
||||
const prev = policyRef.current;
|
||||
const nextOpen =
|
||||
typeof data.allow_comments === "boolean" ? data.allow_comments : prev.open;
|
||||
const nextRequire =
|
||||
typeof data.comments_require_login === "boolean"
|
||||
? data.comments_require_login
|
||||
: prev.requireLogin;
|
||||
if (nextOpen === prev.open && nextRequire === prev.requireLogin) return;
|
||||
setPolicy({ open: nextOpen, requireLogin: nextRequire });
|
||||
router.refresh();
|
||||
});
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<AllowCommentsContext.Provider value={open}>{children}</AllowCommentsContext.Provider>
|
||||
<CommentsPolicyContext.Provider value={policy}>{children}</CommentsPolicyContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user