peppa/apps/web/components/ChatLiveFeed.tsx

177 lines
7.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
// PEP-228: new messages of the open conversation drawn in place. The page's chat scope
// (`chat:<id>`) brings them ready for this viewer (lib/chat-live.ts); what belongs to this
// conversation and needs no buttons is added to the end of the feed at once — no server
// re-render. Questions, offers, other threads go to LiveRefresh (the island leaves `m` to it).
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Bot, MessagesSquare, User as UserIcon } from "lucide-react";
import { PRODUCT_NAME } from "@peppa/shared/i18n";
import { AgentBadge } from "@/components/AgentBadge";
import { Attachments } from "@/components/Attachments";
import { ChatScroll } from "@/components/ChatScroll";
import { useT } from "@/components/I18n";
import { ago, linkify } from "@/lib/format";
import { useLiveIsland } from "@/lib/live";
import { cn } from "@/lib/utils";
import { chatParts, type ChatView, type LiveChatMessage } from "@/lib/chat-live-types";
import { markChatReadAction } from "@/app/(app)/chats/actions";
export function ChatLiveFeed({
chatId,
lastId,
view,
userId,
compact,
showThread,
agentName,
typing,
empty,
children,
}: {
chatId: number;
/** The last message the server drew: anything newer is ours to draw. */
lastId: number;
view: ChatView;
userId: number;
/** Events as compact lines (threads and «События агентов»). */
compact: boolean;
showThread: boolean;
agentName: string | null;
/** «Аналитик печатает…» while the analyst has not answered yet (PEP-110); hidden once an answer is drawn. */
typing: ReactNode;
/** The server drew no messages (its children are the empty state). */
empty: boolean;
children: ReactNode;
}) {
const t = useT();
const [added, setAdded] = useState<LiveChatMessage[]>([]);
const [answered, setAnswered] = useState(false);
const read = useRef<ReturnType<typeof setTimeout> | null>(null);
const scope = `chat:${chatId}`;
const thread = view.kind === "thread" ? view.key : view.kind === "discussion" ? null : undefined;
// A server re-render drew them itself.
const shown = added.filter((m) => m.id > lastId);
useEffect(() => setAnswered(false), [lastId]);
const markRead = () => {
if (thread === undefined || read.current) return;
read.current = setTimeout(() => {
read.current = null;
if (document.visibilityState === "visible") void markChatReadAction(chatId, thread).catch(() => {});
}, 1000);
};
useEffect(() => () => {
if (read.current) clearTimeout(read.current);
}, []);
useLiveIsland((e) => {
if (e.scope !== scope) return [];
const { applied, add } = chatParts(e, view);
const fresh = add.filter((m) => m.id > lastId);
if (fresh.length) {
setAdded((was) => {
const have = new Set(was.map((m) => m.id));
return [...was, ...fresh.filter((m) => !have.has(m.id))].sort((a, b) => a.id - b.id);
});
if (view.kind === "discussion" && fresh.some((m) => m.authorKind !== "user")) setAnswered(true);
markRead();
}
return applied;
});
const groups: Array<{ events: LiveChatMessage[] } | { m: LiveChatMessage }> = [];
for (const m of shown) {
const event = compact && (m.kind === "event" || m.kind === "system");
const last = groups.at(-1);
if (event && last && "events" in last) last.events.push(m);
else groups.push(event ? { events: [m] } : { m });
}
return (
<>
{!(empty && shown.length) && children}
{shown.length > 0 && (
<ol data-chat-live className="m-0 flex list-none flex-col gap-2 p-0 pr-12 md:pr-14">
{groups.map((g) =>
"events" in g ? (
<li key={`e${g.events[0]!.id}`} className="flex flex-col gap-1 border-y border-dashed py-1">
{g.events.map((m) => (
<div key={m.id} data-event-line className="flex items-baseline gap-2 px-1 text-xs text-muted-foreground">
<span className="min-w-0 flex-1 break-words">
{m.authorKind === "agent" && (m.agent ?? agentName) && <span className="mr-1.5 text-foreground/80">{m.agent ?? agentName}:</span>}
{m.main.split("\n")[0]}
{m.link && (
<a href={m.link} className="ml-1.5">
{t("открыть")}
</a>
)}
</span>
{m.repeats > 0 && <span className="shrink-0 font-mono">×{m.repeats + 1}</span>}
<span className="shrink-0 font-mono">{ago(new Date(m.at), t)}</span>
</div>
))}
</li>
) : (
<li key={g.m.id} className={cn("flex", view.kind === "discussion" && g.m.authorUserId === userId && g.m.kind === "user" ? "justify-end" : "justify-start")}>
<div className="min-w-0 max-w-[85%]">
<LiveMessage m={g.m} mine={view.kind === "discussion" && g.m.authorUserId === userId} showThread={showThread} agentName={agentName} />
</div>
</li>
),
)}
</ol>
)}
{!answered && typing}
<div data-chat-end />
<ChatScroll lastId={Math.max(lastId, shown.at(-1)?.id ?? 0)} />
</>
);
}
/** The client twin of the page's MessageItem for a message without buttons. */
function LiveMessage({ m, mine, showThread, agentName }: { m: LiveChatMessage; mine: boolean; showThread: boolean; agentName: string | null }) {
const t = useT();
const person = m.authorKind === "user" && m.kind === "user";
const agentLabel = m.authorKind === "agent" ? (m.agent ?? agentName) : null;
return (
<article data-live-message={m.id} className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", mine && "border-primary/30 bg-primary/10", m.kind === "system" && "border-dashed bg-transparent")}>
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
{person ? <UserIcon className="size-3.5" /> : agentLabel ? null : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
{agentLabel ? (
<AgentBadge name={agentLabel} className="text-foreground" />
) : (
<span className="font-medium text-foreground">{person ? (mine ? t("вы") : (m.login ?? "?")) : m.authorKind === "agent" ? t("агент") : PRODUCT_NAME}</span>
)}
{m.via === "telegram" && <span title={t("из Telegram")}>· Telegram</span>}
{showThread && m.thread && (
<a href={m.thread.href} className="max-w-full truncate">
🧵 {m.thread.label}
</a>
)}
{m.repeats > 0 && (
<span className="rounded-full border px-1.5 font-mono tabular-nums" title={t("Повторов: {n}", { n: m.repeats })}>
×{m.repeats + 1}
</span>
)}
<span className="ml-auto font-mono">{ago(new Date(m.at), t)}</span>
</div>
<p data-message-main className="m-0 text-sm break-words whitespace-pre-wrap">
{linkify(m.main)}
</p>
{m.more && (
<details data-message-details className="text-xs text-muted-foreground">
<summary className="cursor-pointer">{t("Подробнее")}</summary>
<p className="m-0 mt-1 max-h-72 overflow-auto break-words whitespace-pre-wrap">{linkify(m.more)}</p>
</details>
)}
<Attachments files={m.files} />
{m.link && (
<a href={m.link} target={m.link.startsWith("/") ? undefined : "_blank"} rel="noreferrer" className="truncate text-xs">
{m.link.startsWith("/") ? t("Открыть") : m.link}
</a>
)}
</article>
);
}