perf(renderer): cache stable team message keys

This commit is contained in:
777genius 2026-05-31 06:54:46 +03:00
parent b9b337ea15
commit d5db717b54

View file

@ -2,13 +2,45 @@ import type { InboxMessage } from '@shared/types';
const FALLBACK_SLICE = 80;
interface CachedMessageKey {
readonly messageId: InboxMessage['messageId'];
readonly timestamp: InboxMessage['timestamp'];
readonly from: InboxMessage['from'];
readonly text: InboxMessage['text'];
readonly key: string;
}
const messageKeyCache = new WeakMap<InboxMessage, CachedMessageKey>();
/**
* Stable key for a team message. Prefer messageId; otherwise build from timestamp, from, and text.
*/
export function toMessageKey(message: InboxMessage): string {
if (typeof message.messageId === 'string' && message.messageId.trim().length > 0) {
return message.messageId;
const cached = messageKeyCache.get(message);
if (
cached &&
cached.messageId === message.messageId &&
cached.timestamp === message.timestamp &&
cached.from === message.from &&
cached.text === message.text
) {
return cached.key;
}
const text = (message.text ?? '').slice(0, FALLBACK_SLICE);
return `${message.timestamp}-${message.from}-${text}`;
const rawMessageId = typeof message.messageId === 'string' ? message.messageId : '';
const trimmedMessageId = rawMessageId.trim();
const key =
trimmedMessageId.length > 0
? rawMessageId
: `${message.timestamp}-${message.from}-${(message.text ?? '').slice(0, FALLBACK_SLICE)}`;
messageKeyCache.set(message, {
messageId: message.messageId,
timestamp: message.timestamp,
from: message.from,
text: message.text,
key,
});
return key;
}