nomadro/src/modules/social/lib/messageTranslate.ts
Eric abdcafb1eb Ship Work access gate, pads/boards upgrades, and locale hydration fix on .com.
Gate /social/work behind join/login/profile; harden Work UX and LanguageSwitcher SSR; deploy portal, admin, and work API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 00:14:39 +08:00

186 lines
5.0 KiB
TypeScript

"use client";
/**
* Chat bubble bilingual: original + translate into the viewer's UI locale.
* Separate from UI chrome phrases (socialTx / translateBus zh→*).
*/
import type { Locale } from "~/lib/i18n";
import {
getTranslateVersion,
subscribeTranslate,
} from "./translateBus";
const STORAGE_KEY = "nomadro-social-msg-tx-v1";
type CacheMap = Record<string, string>;
let memory: CacheMap = {};
let hydrated = false;
const pending = new Set<string>();
const queue: { text: string; source: Locale; target: Locale }[] = [];
let flushTimer: ReturnType<typeof setTimeout> | null = null;
const bumpListeners = new Set<() => void>();
let localVersion = 0;
function msgKey(source: string, target: string, text: string) {
return `${source}->${target}::${text}`;
}
function hydrate() {
if (hydrated || typeof window === "undefined") return;
hydrated = true;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return;
const parsed = JSON.parse(raw) as CacheMap;
if (parsed && typeof parsed === "object") memory = { ...parsed, ...memory };
} catch {
/* ignore */
}
}
function persist() {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(memory));
} catch {
/* ignore */
}
}
function bumpLocal() {
localVersion += 1;
bumpListeners.forEach((fn) => {
try {
fn();
} catch {
/* ignore */
}
});
}
export function subscribeMessageTranslate(listener: () => void) {
bumpListeners.add(listener);
const unsubBus = subscribeTranslate(listener);
return () => {
bumpListeners.delete(listener);
unsubBus();
};
}
export function getMessageTranslateVersion() {
return localVersion + getTranslateVersion();
}
/** Rough source lang for chat text (enough for Argos pairs). */
export function detectMessageLang(text: string): Locale {
const t = (text || "").trim();
if (!t) return "en";
if (/[\u4e00-\u9fff]/.test(t)) return "zh";
if (/[\u3040-\u30ff]/.test(t)) return "ja";
if (/[\uac00-\ud7af]/.test(t)) return "ko";
if (/[\u0e00-\u0e7f]/.test(t)) return "th";
return "en";
}
/** Skip emoji / numbers / urls-only noise. */
export function shouldTranslateMessage(text: string): boolean {
const t = (text || "").trim();
if (t.length < 2) return false;
if (/^https?:\/\/\S+$/i.test(t)) return false;
// has letters (latin / CJK / hangul / thai)
return /[A-Za-z\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af\u0e00-\u0e7f]/.test(t);
}
export function lookupMessageTranslation(
text: string,
source: Locale,
target: Locale,
): string | null {
hydrate();
if (!text || source === target) return null;
return memory[msgKey(source, target, text)] || memory[msgKey(source, target, text.trim())] || null;
}
function putMessageTranslation(
text: string,
translated: string,
source: Locale,
target: Locale,
) {
if (!text || !translated || text === translated || source === target) return;
hydrate();
const key = msgKey(source, target, text);
if (memory[key] === translated) return;
memory[key] = translated;
persist();
bumpLocal();
}
export function enqueueMessageTranslation(
text: string,
source: Locale,
target: Locale,
) {
const body = (text || "").trim();
if (!body || source === target) return;
if (!shouldTranslateMessage(body)) return;
hydrate();
const key = msgKey(source, target, body);
if (memory[key] || pending.has(key)) return;
pending.add(key);
queue.push({ text: body, source, target });
if (flushTimer) return;
flushTimer = setTimeout(() => {
flushTimer = null;
void flushMessageQueue();
}, 100);
}
async function flushMessageQueue() {
if (!queue.length) return;
const batch = queue.splice(0, 40);
const groups = new Map<string, { source: Locale; target: Locale; texts: string[] }>();
for (const item of batch) {
const gkey = `${item.source}->${item.target}`;
const g = groups.get(gkey) || {
source: item.source,
target: item.target,
texts: [],
};
g.texts.push(item.text);
groups.set(gkey, g);
}
await Promise.all(
[...groups.values()].map(async ({ source, target, texts }) => {
const unique = [...new Set(texts)];
try {
const res = await fetch("/api/social/translate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ q: unique, source, target }),
});
if (!res.ok) throw new Error(`msg-tx ${res.status}`);
const data = (await res.json()) as { translations?: string[] };
const list = Array.isArray(data.translations) ? data.translations : [];
unique.forEach((text, i) => {
pending.delete(msgKey(source, target, text));
const out = (list[i] || "").trim();
if (out && out !== text) putMessageTranslation(text, out, source, target);
});
} catch {
unique.forEach((text) => pending.delete(msgKey(source, target, text)));
}
}),
);
if (queue.length) {
flushTimer = setTimeout(() => {
flushTimer = null;
void flushMessageQueue();
}, 140);
}
}