// PEP-228: new messages of a chat for the live channel — the same text a chat page renders on // the server (translation, cleaning, «Подробнее», links), built for one viewer. import { getUserLocale, isSuperadmin, splitForDisplay, type AttachmentView, type ChatMessageView } from "@peppa/core"; import { users, type Db } from "@peppa/db"; import { stripAsIs, translator } from "@peppa/shared/i18n"; import { eq } from "drizzle-orm"; import { cleanText, messageLink, STUCK_NOTICE } from "./chat-text"; import type { LiveChatMessage } from "./chat-live-types"; export async function liveChatView(db: Db, userId: number, messages: ChatMessageView[], files: Map): Promise { const user = (await db.select({ login: users.login }).from(users).where(eq(users.id, userId)))[0]; const superadmin = await isSuperadmin(db, user ?? null); const t = translator(await getUserLocale(db, userId)); const gitea = (process.env.GITEA_URL ?? "").replace(/\/+$/, ""); return messages.map((m) => { // Same as MessageItem / EventLines of the chat page. const shown = m.kind === "user" ? { main: m.authorKind === "agent" ? cleanText(t.role(m.text), superadmin, gitea) : m.text, more: null } : splitForDisplay(cleanText(t.text(m.text), superadmin, gitea), m.details ? t.text(m.details) : null); const label = m.threadTitle ? t.text(m.threadTitle) : null; return { id: m.id, threadKey: m.threadKey, kind: m.kind, authorKind: m.authorKind, authorUserId: m.authorUserId, login: m.authorLogin, agent: m.authorKind === "agent" && m.authorLogin ? t.role(m.authorLogin) : null, via: m.via, at: (m.updatedAt ?? m.createdAt).toISOString(), repeats: m.repeats, command: m.text.startsWith("/"), notice: m.authorKind !== "user" && STUCK_NOTICE.test(stripAsIs(m.text)), main: shown.main, more: shown.more, link: messageLink(m.url, superadmin, gitea), files: files.get(m.id) ?? [], render: !!m.question || !!m.offer, thread: label && m.projectKey && m.threadKey ? { label, href: `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` } : null, }; }); }