Files
chatroom/resources/js/chat-room/message-utils.js
T

81 lines
2.5 KiB
JavaScript

// 聊天消息工具函数,承接主消息渲染脚本里可独立复用的判断逻辑。
/**
* 判断图片消息是否已经超过前端允许展示的保留期。
*
* @param {Record<string, any>|null|undefined} message 聊天消息
* @param {number} retentionDays 图片保留天数
* @param {number} nowTimestamp 当前时间戳
* @returns {boolean}
*/
export function isExpiredChatImageMessage(
message,
retentionDays = Number.parseInt(window.chatContext?.chatImageRetentionDays || 3, 10),
nowTimestamp = Date.now(),
) {
if (!message) {
return false;
}
if (message.message_type === "expired_image") {
return true;
}
if (message.message_type !== "image") {
return false;
}
if (!message.image_url || !message.image_thumb_url) {
return true;
}
const sentAtText = String(message.sent_at || "").replace(" ", "T");
const sentAt = sentAtText ? new Date(sentAtText) : null;
if (!sentAt || Number.isNaN(sentAt.getTime())) {
return false;
}
return nowTimestamp >= sentAt.getTime() + retentionDays * 24 * 60 * 60 * 1000;
}
/**
* 只清理当前浏览器的聊天窗口,并记录本地清屏的最大消息 ID。
*
* @param {number|string} roomId 房间 ID
* @param {number|string} maxMessageId 当前已接收最大消息 ID
* @returns {void}
*/
export function localClearScreen(roomId = window.chatContext?.roomId, maxMessageId = 0) {
const publicPane = document.getElementById("chat-messages-container");
const privatePane = document.getElementById("chat-messages-container2");
if (publicPane) {
publicPane.innerHTML = "";
}
if (privatePane) {
privatePane.innerHTML = "";
}
// 刷新页面时只恢复本地清屏点之后的新消息,避免旧消息重新回流。
localStorage.setItem(`local_clear_msg_id_${roomId}`, maxMessageId);
const notice = document.createElement("div");
notice.className = "msg-line";
const now = new Date();
const timeText = [
now.getHours().toString().padStart(2, "0"),
now.getMinutes().toString().padStart(2, "0"),
now.getSeconds().toString().padStart(2, "0"),
].join(":");
notice.innerHTML = `<span style="color: #64748b; font-weight: bold;">🧹 您已执行本地清屏</span><span class="msg-time">(${timeText})</span>`;
if (publicPane) {
publicPane.appendChild(notice);
publicPane.scrollTop = publicPane.scrollHeight;
}
}