修复聊天室在线名单初始化与 Reverb 来源校验

This commit is contained in:
pllx
2026-04-29 11:15:24 +08:00
parent 1192fe5bdb
commit 317dfd04d7
3 changed files with 86 additions and 5 deletions
+36 -4
View File
@@ -7,6 +7,7 @@ import { enqueueChatMessage } from "./message-renderer.js";
// ── 事件注册标记 ──
let chatEventsBound = false;
let chatWebSocketInitRetryTimer = null;
// ── 辅助函数 ──
function csrf() {
@@ -21,9 +22,40 @@ function getState() {
* 启动 WebSocket 初始化(DOMContentLoaded 之后调用)。
*/
function initChatWebSocket() {
if (chatWebSocketInitRetryTimer) {
window.clearTimeout(chatWebSocketInitRetryTimer);
chatWebSocketInitRetryTimer = null;
}
if (typeof window.initChat === "function" && window.chatContext?.roomId) {
window.initChat(window.chatContext.roomId);
return;
}
// chat.js 会在模块末尾才把 initChat 挂到 window;若这里抢先执行,稍后自动补一次初始化。
chatWebSocketInitRetryTimer = window.setTimeout(() => {
chatWebSocketInitRetryTimer = null;
initChatWebSocket();
}, 100);
}
/**
* 在 DOM 已就绪时立即执行回调,避免 Vite 模块晚于 DOMContentLoaded 执行时漏掉初始化。
*
* @param {() => void} callback 页面就绪后的回调
* @returns {void}
*/
function runWhenDomReady(callback) {
if (typeof callback !== "function") {
return;
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", callback, { once: true });
return;
}
callback();
}
// ── 禁言逻辑 ──
@@ -277,8 +309,8 @@ export function bindChatEvents() {
}
chatEventsBound = true;
// WebSocket 初始化
document.addEventListener("DOMContentLoaded", initChatWebSocket);
// 页面已完成解析时立刻补做初始化,确保 Presence 连接不会因为错过 DOMContentLoaded 而丢失。
runWhenDomReady(initChatWebSocket);
// chat:here — Presence 初始用户列表
window.addEventListener("chat:here", (e) => {
@@ -484,8 +516,8 @@ export function bindChatEvents() {
}
});
// Echo 级监听器(延迟绑定,等待 Echo 就绪)
document.addEventListener("DOMContentLoaded", () => {
// Echo 级监听器同样要兼容“脚本加载时页面已完成”的场景。
runWhenDomReady(() => {
setupScreenClearedListener();
setupRoomBrowserRefreshListener();
setupChangelogPublishedListener();
+11
View File
@@ -175,12 +175,19 @@ export function normalizeHolidayBroadcastEvent(payload = {}) {
window.normalizeHolidayBroadcastEvent = normalizeHolidayBroadcastEvent;
let chatConnectionInitialized = false;
export function initChat(roomId) {
if (chatConnectionInitialized) {
return;
}
if (!roomId) {
console.error("未提供 roomId,无法初始化 WebSocket 连接。");
return;
}
chatConnectionInitialized = true;
const userId = window.chatContext?.userId;
// 监听全局系统事件(如 AI 机器人开关)
@@ -420,3 +427,7 @@ export function initMarriagePrivateChannel(userId) {
// 供全局调用
window.initChat = initChat;
window.initMarriagePrivateChannel = initMarriagePrivateChannel;
if (window.chatContext?.roomId) {
window.initChat(window.chatContext.roomId);
}