Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/screens/chat/ChatInterimScreens.test.tsx
T

895 lines
32 KiB
TypeScript

// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildChatChannelDetailVM, buildChatChannelListVM, type ChatMessageCandidate } from "@hivegrid/view-models";
import { ChatChannelDetailPage, type ChatChannelDetailActions } from "./ChatChannelDetailPage";
import { ChatChannelListPage, type ChatChannelListActions } from "./ChatChannelListPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join("/")}` : key),
i18n: { language: "de" },
}),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
number: (value: number) => String(value),
date: (value: string) => `date:${value}`,
relativeDate: (value: string) => `relative:${value}`,
}),
}));
function listActions(overrides: Partial<ChatChannelListActions> = {}): ChatChannelListActions {
return {
onOpenChannel: vi.fn(),
onQueryChange: vi.fn(),
onViewChange: vi.fn(),
onShowArchivedChange: vi.fn(),
onRetry: vi.fn(),
...overrides,
};
}
function detailActions(overrides: Partial<ChatChannelDetailActions> = {}): ChatChannelDetailActions {
return {
onBack: vi.fn(),
onDraftChange: vi.fn(),
onSend: vi.fn(),
onRetryMessage: vi.fn(),
onDiscardMessage: vi.fn(),
onMessageVisibilityChange: vi.fn(),
onRetryConnection: vi.fn(),
onLoadOlder: vi.fn(),
onOpenSettings: vi.fn(),
...overrides,
};
}
function messageCandidate(id: string, overrides: Partial<ChatMessageCandidate> = {}): ChatMessageCandidate {
return {
id,
clientMessageId: `client_${id}`,
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
author: {
userId: "user_current",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "RS" },
isCurrentUser: true,
},
bodyMarkdown: `Body ${id}`,
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-15T10:00:00.000Z",
updatedAtIso: "2026-07-15T10:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: {
readCount: 1,
recipientCount: 2,
readerUserIds: ["user-mara"],
readerLabels: ["Mara"],
labelKey: "chat.message.read.aggregate",
},
pin: null,
actions: {
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
},
...overrides,
};
}
function detailVm(messages: readonly ChatMessageCandidate[] = [messageCandidate("message_sent")]) {
return buildChatChannelDetailVM({
header: {
id: "chat_group",
kind: "group",
title: "Montage-Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "MT" },
project: null,
memberCount: 4,
isPrivate: true,
isArchived: false,
isAuditMode: false,
canManage: false,
settingsHref: null,
pinnedHref: "/demo/chat/chat_group/pinned",
searchHref: "/demo/chat/search?channel=chat_group",
},
messages,
pinnedMessages: [],
typingLabels: ["Mara"],
history: { hasOlder: false, olderCursor: null },
composer: {
disabledReasonKey: null,
canSend: true,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
draftStorageKey: "chat:draft:chat_group",
maxBodyLength: 4_000,
},
connection: {
state: "reconnecting",
reconnectAttempt: 2,
retryAtIso: "2026-07-15T10:03:00.000Z",
},
});
}
describe("AK-P15b chat interim screens", () => {
beforeEach(() => vi.clearAllMocks());
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("renders a server-projected channel row and delegates filtering and navigation", () => {
const onOpenChannel = vi.fn();
const onQueryChange = vi.fn();
const onLoadMore = vi.fn();
const onSetPinned = vi.fn();
const onSetNotificationPreference = vi.fn();
const actions = listActions({ onOpenChannel, onQueryChange, onLoadMore, onSetPinned, onSetNotificationPreference });
const vm = buildChatChannelListVM({
rows: [
{
id: "chat_project",
kind: "project",
title: "Heizungstausch Müller",
subtitle: null,
detailHref: "/demo/chat/chat_project",
avatar: { imageUrl: null, fallbackLabel: "HM" },
project: {
id: "project_1",
number: "P-1042",
label: "Heizungstausch Müller",
stageLabel: "Montage",
href: "/demo/projects/project_1",
},
lastMessage: {
authorLabel: "Mara",
snippet: "Material ist bestellt.",
systemEvent: null,
createdAtIso: "2026-07-15T09:30:00.000Z",
},
typingLabels: [],
unreadCount: 3,
hasMention: true,
isPinned: true,
isPrivate: true,
notificationPreference: "all_messages",
archivedAtIso: null,
memberCount: 4,
canManage: false,
},
],
discoverRows: [],
filter: { query: "", view: "all", showArchived: false },
permissions: {
canWrite: true,
canCreateGroup: false,
canCreateDm: false,
canDiscover: false,
canViewMentions: true,
canSearch: true,
canViewArchived: true,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new",
newDm: "/demo/chat/new?kind=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat?archived=true",
},
totals: { unread: 3, mentions: 1 },
nextCursor: "cursor_2",
});
render(
<MemoryRouter>
<ChatChannelListPage vm={vm} actions={actions} />
</MemoryRouter>
);
expect(screen.getByText("Heizungstausch Müller")).toBeInTheDocument();
expect(screen.getByText("Mara: Material ist bestellt.")).toBeInTheDocument();
fireEvent.change(screen.getByRole("searchbox"), { target: { value: "Müller" } });
expect(onQueryChange).toHaveBeenCalledWith("Müller");
expect(screen.getByRole("combobox", { name: "shared.viewMode" })).toBeInTheDocument();
const channelLink = document.querySelector('[data-ui-id="ui.chat.channelList.open"]');
expect(channelLink).toBeInstanceOf(HTMLButtonElement);
expect(channelLink).toHaveAttribute("aria-label", expect.stringContaining("chat.channelList.a11y.unread:3"));
expect(channelLink).toHaveAttribute("aria-label", expect.stringContaining("chat.channelList.a11y.mention"));
expect(channelLink).toHaveAttribute("aria-label", expect.stringContaining("chat.channelList.private"));
expect(channelLink).toHaveAttribute("aria-label", expect.stringContaining("chat.channelList.pinned"));
fireEvent.click(channelLink!);
expect(onOpenChannel).toHaveBeenCalledWith("chat_project", "/demo/chat/chat_project");
onOpenChannel.mockClear();
fireEvent.click(screen.getByRole("button", { name: "chat.channelList.actions.unpin:Heizungstausch Müller" }));
expect(onSetPinned).toHaveBeenCalledWith("chat_project", false);
fireEvent.click(screen.getByRole("button", { name: "chat.channelList.actions.mute:Heizungstausch Müller" }));
expect(onSetNotificationPreference).toHaveBeenCalledWith("chat_project", "muted");
expect(onOpenChannel).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "shared.loadMore" }));
expect(onLoadMore).toHaveBeenCalledWith("cursor_2");
});
it("renders a translated system-event preview in the channel list without an author prefix", () => {
const vm = buildChatChannelListVM({
rows: [
{
id: "chat_project",
kind: "project",
title: "Heizungstausch Müller",
subtitle: null,
detailHref: "/demo/chat/chat_project",
avatar: { imageUrl: null, fallbackLabel: "HM" },
project: null,
lastMessage: {
authorLabel: null,
snippet: "",
systemEvent: {
kind: "member_added",
labelKey: "chat.systemEvent.memberAdded",
values: { member: "Mara" },
},
createdAtIso: "2026-07-15T09:30:00.000Z",
},
typingLabels: [],
unreadCount: 1,
hasMention: false,
isPinned: false,
isPrivate: false,
notificationPreference: "all_messages",
archivedAtIso: null,
memberCount: 4,
canManage: false,
},
],
discoverRows: [],
filter: { query: "", view: "all", showArchived: false },
permissions: {
canWrite: true,
canCreateGroup: false,
canCreateDm: false,
canDiscover: false,
canViewMentions: false,
canSearch: true,
canViewArchived: false,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new",
newDm: "/demo/chat/new?kind=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat?archived=true",
},
totals: { unread: 1, mentions: 0 },
});
render(
<MemoryRouter>
<ChatChannelListPage vm={vm} actions={listActions()} />
</MemoryRouter>
);
expect(screen.getByText("chat.systemEvent.memberAdded:Mara")).toBeInTheDocument();
expect(screen.queryByText(/null:|Unbekannt:/)).not.toBeInTheDocument();
});
it("renders loading and error states with a real retry callback", () => {
const onRetry = vi.fn();
const actions = listActions({ onRetry });
const { rerender } = render(
<MemoryRouter>
<ChatChannelListPage vm={{ status: "loading" }} actions={actions} />
</MemoryRouter>
);
expect(screen.getByRole("status", { name: "shared.loading" })).toBeInTheDocument();
rerender(
<MemoryRouter>
<ChatChannelListPage vm={{ status: "error", error: { messageKey: "chat.errors.realtimeUnavailable" } }} actions={actions} />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
expect(onRetry).toHaveBeenCalledOnce();
});
it("exposes the permitted group and DM create actions without a discover entry", () => {
const onCreateGroup = vi.fn();
const onCreateDm = vi.fn();
const vm = buildChatChannelListVM({
rows: [],
discoverRows: [],
filter: { query: "", view: "all", showArchived: false },
permissions: {
canWrite: true,
canCreateGroup: true,
canCreateDm: true,
canDiscover: false,
canViewMentions: true,
canSearch: true,
canViewArchived: false,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new?kind=group",
newDm: "/demo/chat/new?kind=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat?archived=true",
},
totals: { unread: 0, mentions: 0 },
});
render(
<MemoryRouter>
<ChatChannelListPage vm={vm} actions={listActions({ onCreateGroup, onCreateDm })} />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "chat.channelList.actions.newGroup" }));
fireEvent.click(screen.getByRole("button", { name: "chat.channelList.actions.newDm" }));
expect(onCreateGroup).toHaveBeenCalledWith("/demo/chat/new?kind=group");
expect(onCreateDm).toHaveBeenCalledWith("/demo/chat/new?kind=dm");
expect(screen.queryByText("chat.channelList.discover.headline")).not.toBeInTheDocument();
});
it("shows reconnect, optimistic delivery, failed retry, read state, typing, and delegates sending", async () => {
const onDraftChange = vi.fn();
const onSend = vi.fn();
const onRetryMessage = vi.fn();
const onDiscardMessage = vi.fn();
const onRetryConnection = vi.fn();
const actions = detailActions({
onDraftChange,
onSend,
onRetryMessage,
onDiscardMessage,
onRetryConnection,
});
const baseVm = detailVm([
messageCandidate("message_sent"),
messageCandidate("message_sending", {
source: "local_echo",
deliveryState: "sending",
createdAtIso: "2026-07-15T10:01:00.000Z",
updatedAtIso: "2026-07-15T10:01:00.000Z",
}),
messageCandidate("message_failed", {
source: "local_echo",
deliveryState: "failed",
failureReasonKey: "chat.message.sendFailed",
retryable: true,
createdAtIso: "2026-07-15T10:02:00.000Z",
updatedAtIso: "2026-07-15T10:02:00.000Z",
}),
]);
if (baseVm.status !== "ready") throw new Error("fixture must be ready");
const vm = {
...baseVm,
data: {
...baseVm.data,
presence: [
{ userId: "user_online", status: "online" as const },
{ userId: "user_away", status: "away" as const },
],
},
};
const view = render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={actions} draft="" />
</MemoryRouter>
);
expect(screen.getAllByText("chat.connection.reconnecting")).toHaveLength(2);
expect(document.querySelector('[data-ui-id="ui.chat.channelDetail.connectionStatus"]')).toHaveAttribute("role", "status");
expect(document.querySelector('[data-ui-id="ui.chat.channelDetail.connectionStatus"]')).toHaveAttribute("aria-live", "polite");
expect(screen.getByText("chat.message.delivery.sending")).toBeInTheDocument();
expect(screen.getByText("chat.message.read.aggregate:1/2")).toBeInTheDocument();
expect(screen.getByText("chat.channel.presenceOnline:1")).toBeInTheDocument();
expect(screen.getByText("chat.channel.presenceAway:1")).toBeInTheDocument();
expect(screen.getByRole("group", { name: "chat.channel.presenceAria" })).toBeInTheDocument();
expect(screen.getByText("chat.channel.typing:1/Mara")).toBeInTheDocument();
const composerDock = document.querySelector('[data-ui-id="ui.chat.channelDetail.composerDock"]');
expect(composerDock).toBeInTheDocument();
expect(composerDock?.querySelector('[data-ui-id="ui.chat.channelDetail.composer"]')).toBeInTheDocument();
const failedMessage = document.querySelector('[data-message-id="message_failed"]');
expect(failedMessage).not.toBeNull();
fireEvent.click(within(failedMessage as HTMLElement).getByRole("button", { name: "shared.retry" }));
fireEvent.click(within(failedMessage as HTMLElement).getByRole("button", { name: "shared.remove" }));
expect(onRetryMessage).toHaveBeenCalledWith("client_message_failed");
expect(onDiscardMessage).toHaveBeenCalledWith("client_message_failed");
fireEvent.click(screen.getAllByRole("button", { name: "shared.retry" })[0]);
expect(onRetryConnection).toHaveBeenCalledOnce();
fireEvent.change(screen.getByRole("combobox", { name: "chat.composer.placeholder" }), {
target: { value: "Bin unterwegs" },
});
expect(onDraftChange).toHaveBeenCalledWith("Bin unterwegs", "chat:draft:chat_group", 13);
view.rerender(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={actions} draft="Bin unterwegs" />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "shared.send" }));
expect(onSend).toHaveBeenCalledWith("Bin unterwegs");
expect(screen.getByRole("combobox", { name: "chat.composer.placeholder" })).toHaveValue("Bin unterwegs");
await waitFor(() => expect(screen.getByRole("combobox", { name: "chat.composer.placeholder" })).toHaveFocus());
});
it("opens channel settings through the injected route callback", () => {
const baseVm = detailVm();
if (baseVm.status !== "ready") throw new Error("fixture must be ready");
const vm = {
...baseVm,
data: {
...baseVm.data,
header: { ...baseVm.data.header, settingsHref: "/demo/chat/chat_group/settings" },
},
};
const onOpenSettings = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={detailActions({ onOpenSettings })} draft="" />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.title" }));
expect(onOpenSettings).toHaveBeenCalledOnce();
});
it("supports mobile photo upload, voice recording and attachment-only sends", () => {
const baseVm = detailVm();
if (baseVm.status !== "ready") throw new Error("fixture must be ready");
const vm = {
...baseVm,
data: {
...baseVm.data,
composer: {
...baseVm.data.composer,
canAttachFiles: true,
canRecordVoice: true,
},
},
};
const onAddPhotos = vi.fn();
const onStartRecording = vi.fn();
const onSend = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage
vm={vm}
actions={detailActions({ onAddPhotos, onStartRecording, onSend })}
draft=""
pendingAttachments={[
{
clientId: "upload_1",
fileId: "file_1",
fileName: "camera.jpg",
mimeType: "image/jpeg",
sizeBytes: 1024,
kind: "image",
status: "ready",
progress: 100,
errorKey: null,
durationSeconds: null,
},
]}
/>
</MemoryRouter>
);
const photoInput = document.querySelector('[data-ui-id="ui.chat.channelDetail.photoInput"]') as HTMLInputElement;
const photo = new File(["image"], "camera.jpg", { type: "image/jpeg" });
fireEvent.change(photoInput, { target: { files: [photo] } });
expect(onAddPhotos).toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "chat.attachments.startRecording" }));
expect(onStartRecording).toHaveBeenCalledOnce();
fireEvent.click(screen.getByRole("button", { name: "shared.send" }));
expect(onSend).toHaveBeenCalledWith("");
expect(screen.getByText("chat.attachments.ready")).toBeInTheDocument();
});
it("does not offer a no-op retry for a non-retryable failed message", () => {
const onRetryMessage = vi.fn();
const onDiscardMessage = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage
vm={detailVm([
messageCandidate("message_rejected", {
source: "local_echo",
deliveryState: "failed",
failureReasonKey: "chat.errors.invalidInput",
retryable: false,
}),
])}
actions={detailActions({ onRetryMessage, onDiscardMessage })}
draft=""
/>
</MemoryRouter>
);
const failedMessage = document.querySelector('[data-message-id="message_rejected"]');
expect(failedMessage).not.toBeNull();
expect(within(failedMessage as HTMLElement).queryByRole("button", { name: "shared.retry" })).not.toBeInTheDocument();
fireEvent.click(within(failedMessage as HTMLElement).getByRole("button", { name: "shared.remove" }));
expect(onRetryMessage).not.toHaveBeenCalled();
expect(onDiscardMessage).toHaveBeenCalledWith("client_message_rejected");
});
it("renders an actorless system event centered without avatar, receipt, body, or message actions", () => {
render(
<MemoryRouter>
<ChatChannelDetailPage
vm={detailVm([
messageCandidate("system_project_created", {
clientMessageId: "system:project-created:project_1",
author: null,
bodyMarkdown: null,
bodyFormat: "system",
systemEvent: {
kind: "project_created",
labelKey: "chat.systemEvent.projectCreated",
values: { project: "Wärmepumpe Müller" },
},
readAggregate: null,
}),
])}
actions={detailActions()}
draft=""
/>
</MemoryRouter>
);
const systemMessage = screen.getByRole("note");
expect(systemMessage).toHaveAttribute("data-system-event-kind", "project_created");
expect(within(systemMessage).getByText("chat.systemEvent.projectCreated:Wärmepumpe Müller")).toBeInTheDocument();
expect(within(systemMessage).queryByText("Raffael")).not.toBeInTheDocument();
expect(systemMessage.querySelector('[data-ui-id="ui.chat.channelDetail.messageBody"]')).toBeNull();
expect(systemMessage.querySelector('[data-ui-id="ui.chat.channelDetail.readReceipt"]')).toBeNull();
expect(within(systemMessage).queryByRole("button")).not.toBeInTheDocument();
expect(within(systemMessage).queryByRole("img")).not.toBeInTheDocument();
});
it("limits a busy typing announcement to two names plus the remaining count", () => {
const baseVm = detailVm();
if (baseVm.status !== "ready") throw new Error("fixture must be ready");
const vm = { ...baseVm, data: { ...baseVm.data, typingLabels: ["Mara", "Ada", "Linus", "Grace"] } };
render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={detailActions()} draft="" />
</MemoryRouter>
);
expect(screen.getByText("chat.channel.typingOverflow:Mara, Ada/2")).toBeInTheDocument();
expect(screen.queryByText(/Linus|Grace/)).not.toBeInTheDocument();
});
it("keeps the polite connection live region mounted after recovery", () => {
const baseVm = detailVm();
if (baseVm.status !== "ready") throw new Error("fixture must be ready");
const vm = {
...baseVm,
data: {
...baseVm.data,
connection: {
state: "online" as const,
stateLabelKey: "chat.connection.online" as const,
reconnectAttempt: 0,
retryAtIso: null,
canRetry: false,
},
},
};
render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={detailActions()} draft="" />
</MemoryRouter>
);
expect(document.querySelector('[data-connection-state="online"]')).not.toBeInTheDocument();
const status = document.querySelector('[data-ui-id="ui.chat.channelDetail.connectionStatus"]');
expect(status).toHaveAttribute("role", "status");
expect(status).toHaveTextContent("chat.connection.online");
});
it("announces consecutive remote messages from the same author with distinct previews", async () => {
const remoteAuthor = {
userId: "user_mara",
displayName: "Mara",
avatar: { imageUrl: null, fallbackLabel: "MK" },
isCurrentUser: false,
} as const;
const first = messageCandidate("message_remote_1", { author: remoteAuthor, bodyMarkdown: "Erste Nachricht" });
const second = messageCandidate("message_remote_2", { author: remoteAuthor, bodyMarkdown: "**Gleiche** Nachricht" });
const third = messageCandidate("message_remote_3", { author: remoteAuthor, bodyMarkdown: "**Gleiche** Nachricht" });
const actions = detailActions();
const view = render(
<MemoryRouter>
<main>
<ChatChannelDetailPage vm={detailVm([first])} actions={actions} draft="" />
</main>
</MemoryRouter>
);
view.rerender(
<MemoryRouter>
<main>
<ChatChannelDetailPage vm={detailVm([first, second])} actions={actions} draft="" />
</main>
</MemoryRouter>
);
const firstAnnouncement = await screen.findByText("chat.channel.newMessageAnnouncement:Mara/Gleiche Nachricht");
view.rerender(
<MemoryRouter>
<main>
<ChatChannelDetailPage vm={detailVm([first, second, third])} actions={actions} draft="" />
</main>
</MemoryRouter>
);
await waitFor(() => expect(screen.getByText("chat.channel.newMessageAnnouncement:Mara/Gleiche Nachricht")).not.toBe(firstAnnouncement));
});
it.each(["rejected", "false"] as const)("keeps and refocuses the controlled draft when sending is %s", async (outcome) => {
const onSend = outcome === "false" ? vi.fn().mockResolvedValue(false) : vi.fn().mockRejectedValue(new Error("offline"));
const onDraftChange = vi.fn();
const actions = detailActions({ onSend, onDraftChange });
render(
<MemoryRouter>
<ChatChannelDetailPage vm={detailVm()} actions={actions} draft="Bleibt erhalten" />
</MemoryRouter>
);
const input = screen.getByRole("combobox", { name: "chat.composer.placeholder" });
fireEvent.click(screen.getByRole("button", { name: "shared.send" }));
await waitFor(() => expect(onSend).toHaveBeenCalledWith("Bleibt erhalten"));
expect(input).toHaveValue("Bleibt erhalten");
expect(onDraftChange).not.toHaveBeenCalled();
await waitFor(() => expect(input).toHaveFocus());
});
it("does not submit Enter while an IME composition is active", () => {
const onSend = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage vm={detailVm()} actions={detailActions({ onSend })} draft="Montage bestätigt" />
</MemoryRouter>
);
fireEvent.keyDown(screen.getByRole("combobox", { name: "chat.composer.placeholder" }), {
key: "Enter",
keyCode: 229,
isComposing: true,
});
expect(onSend).not.toHaveBeenCalled();
});
it("renders the allowed markdown subset and neutralizes raw HTML", () => {
const vm = detailVm([
messageCandidate("message_markdown", {
bodyMarkdown: "**Wichtig** <img src=x onerror=alert(1)> [unsicher](javascript:alert(1))",
}),
]);
const view = render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={detailActions()} draft="" />
</MemoryRouter>
);
const body = view.container.querySelector('[data-ui-id="ui.chat.channelDetail.messageBody"]');
expect(body).not.toBeNull();
expect(within(body as HTMLElement).getByText("Wichtig").tagName).toBe("STRONG");
expect(body?.querySelector("img")).toBeNull();
expect(body?.innerHTML).toContain("&lt;img");
expect(body?.innerHTML).not.toContain("javascript:");
});
it("always exposes the canonical link host next to remote preview metadata", () => {
const vm = detailVm([
messageCandidate("message_link_preview", {
linkPreviews: [
{
url: "https://secure.example/account/verify",
title: "Trusted banking login",
description: "Remote metadata may describe another brand.",
imageUrl: null,
siteName: "unrelated-bank.example",
},
],
}),
]);
render(
<MemoryRouter>
<ChatChannelDetailPage vm={vm} actions={detailActions()} draft="" />
</MemoryRouter>
);
expect(screen.getByText("secure.example")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /secure\.example/u })).toHaveAttribute("href", "https://secure.example/account/verify");
});
function stubMessageIntersectionObserver(): Array<{
emit: (visible: boolean) => void;
emitRatio: (ratio: number, elementHeight: number) => void;
disconnected: () => boolean;
threshold: () => number | readonly number[] | undefined;
}> {
const observers: Array<{
emit: (visible: boolean) => void;
emitRatio: (ratio: number, elementHeight: number) => void;
disconnected: () => boolean;
threshold: () => number | readonly number[] | undefined;
}> = [];
class MockIntersectionObserver implements IntersectionObserver {
readonly root = null;
readonly rootMargin = "0px";
readonly thresholds: readonly number[];
private target: Element | null = null;
private isDisconnected = false;
constructor(
private readonly callback: IntersectionObserverCallback,
options?: IntersectionObserverInit
) {
this.thresholds = Array.isArray(options?.threshold) ? options.threshold : [options?.threshold ?? 0];
const emitRatio = (ratio: number, elementHeight: number) => {
if (!this.target) throw new Error("IntersectionObserver target was not registered");
this.callback(
[
{
isIntersecting: ratio > 0,
intersectionRatio: ratio,
boundingClientRect: { height: elementHeight },
target: this.target,
} as IntersectionObserverEntry,
],
this
);
};
observers.push({
emit: (visible) => emitRatio(visible ? 1 : 0, 100),
emitRatio,
disconnected: () => this.isDisconnected,
threshold: () => options?.threshold,
});
}
disconnect(): void {
this.isDisconnected = true;
}
unobserve(): void {}
takeRecords(): IntersectionObserverEntry[] {
return [];
}
observe(target: Element): void {
this.target = target;
}
}
vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);
return observers;
}
it("reports persisted message visibility enter and exit without disconnecting after enter", async () => {
const observers = stubMessageIntersectionObserver();
const onMessageVisibilityChange = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage vm={detailVm()} actions={detailActions({ onMessageVisibilityChange })} draft="" />
</MemoryRouter>
);
expect(observers).toHaveLength(1);
observers[0].emit(true);
await waitFor(() => expect(onMessageVisibilityChange).toHaveBeenLastCalledWith("message_sent", "2026-07-15T10:00:00.000Z", true));
expect(observers[0].disconnected()).toBe(false);
observers[0].emit(false);
await waitFor(() => expect(onMessageVisibilityChange).toHaveBeenLastCalledWith("message_sent", "2026-07-15T10:00:00.000Z", false));
});
it("ends active persisted message visibility during cleanup", async () => {
const observers = stubMessageIntersectionObserver();
const onMessageVisibilityChange = vi.fn();
const view = render(
<MemoryRouter>
<ChatChannelDetailPage vm={detailVm()} actions={detailActions({ onMessageVisibilityChange })} draft="" />
</MemoryRouter>
);
observers[0].emit(true);
await waitFor(() => expect(onMessageVisibilityChange).toHaveBeenCalledTimes(1));
view.unmount();
expect(observers[0].disconnected()).toBe(true);
expect(onMessageVisibilityChange).toHaveBeenLastCalledWith("message_sent", "2026-07-15T10:00:00.000Z", false);
});
it("never observes a deleted message for a read receipt", () => {
const observers = stubMessageIntersectionObserver();
const onMessageVisibilityChange = vi.fn();
const deletedAtIso = "2026-07-15T10:05:00.000Z";
render(
<MemoryRouter>
<ChatChannelDetailPage
vm={detailVm([
messageCandidate("message_deleted", {
bodyMarkdown: null,
deletedAtIso,
updatedAtIso: deletedAtIso,
}),
])}
actions={detailActions({ onMessageVisibilityChange })}
draft=""
/>
</MemoryRouter>
);
expect(observers).toHaveLength(0);
expect(onMessageVisibilityChange).not.toHaveBeenCalled();
});
it("wraps an unbroken maximum-size body and marks a tall message after a meaningful visible slice", async () => {
const geometry = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue({ height: 2_000 } as DOMRect);
const observers = stubMessageIntersectionObserver();
const onMessageVisibilityChange = vi.fn();
const bodyMarkdown = "x".repeat(8_000);
const view = render(
<MemoryRouter>
<ChatChannelDetailPage
vm={detailVm([messageCandidate("message_tall", { bodyMarkdown })])}
actions={detailActions({ onMessageVisibilityChange })}
draft=""
/>
</MemoryRouter>
);
const body = view.container.querySelector('[data-ui-id="ui.chat.channelDetail.messageBody"]');
expect(body?.parentElement).toHaveClass("min-w-0", "[overflow-wrap:anywhere]");
expect(observers[0]?.threshold()).toBeCloseTo(0.12);
observers[0]?.emitRatio(0.12, 2_000);
await waitFor(() => expect(onMessageVisibilityChange).toHaveBeenCalledWith("message_tall", "2026-07-15T10:00:00.000Z", true));
geometry.mockRestore();
});
});