Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,57 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${JSON.stringify(values)}` : key),
}),
}));
import { buildChatAuditAdministrationVM } from "@hivegrid/view-models";
import { ChatAuditAdministrationPanel } from "./ChatAuditAdministrationPanel";
describe("AK-P15b chat audit administration panel", () => {
it("shows no mutation controls to a read-all auditor without chat admin", () => {
render(
<ChatAuditAdministrationPanel
vm={vm(false)}
actions={{ onArchive: vi.fn(), onChangeMemberRole: vi.fn(), onRemoveMember: vi.fn() }}
/>
);
expect(screen.getByText("chat.audit.administration.readOnlyTitle")).toBeTruthy();
expect(screen.queryByRole("button", { name: "chat.audit.actions.promote" })).toBeNull();
});
it("supports force-role, force-remove, and archive actions with confirmation", () => {
const onArchive = vi.fn();
const onChangeMemberRole = vi.fn();
const onRemoveMember = vi.fn();
render(
<ChatAuditAdministrationPanel
vm={vm(true)}
actions={{ onArchive, onChangeMemberRole, onRemoveMember }}
/>
);
fireEvent.click(screen.getByRole("button", { name: "chat.audit.actions.promote" }));
expect(onChangeMemberRole).toHaveBeenCalledWith("member-a", "admin");
fireEvent.click(screen.getByRole("button", { name: /chat.audit.actions.removeMemberLabel/u }));
fireEvent.click(screen.getByRole("button", { name: "shared.confirm" }));
expect(onRemoveMember).toHaveBeenCalledWith("member-a");
fireEvent.click(screen.getByRole("button", { name: "chat.audit.actions.archive" }));
fireEvent.click(screen.getByRole("button", { name: "shared.confirm" }));
expect(onArchive).toHaveBeenCalledOnce();
});
});
function vm(canAdminister: boolean) {
return buildChatAuditAdministrationVM({
channel: { id: "chat-a", kind: "group", title: "Bauleitung", archivedAtIso: null },
canAdminister,
members: [{ userId: "member-a", displayName: "Anna Adler", avatarUrl: null, roleInChat: "member" }],
});
}
@@ -0,0 +1,176 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Description as DialogDescription, Title as DialogTitle } from "@radix-ui/react-dialog";
import { FeatherArchive, FeatherShield, FeatherTrash2 } from "@subframe/core";
import type { ChatAuditAdministrationVM } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
export type ChatAuditAdministrationActions = Readonly<{
onArchive: () => void | Promise<void>;
onChangeMemberRole: (userId: string, role: "admin" | "member") => void | Promise<void>;
onRemoveMember: (userId: string) => void | Promise<void>;
}>;
type Confirmation = Readonly<{ type: "archive" }> | Readonly<{ type: "remove"; userId: string; memberName: string }>;
export function ChatAuditAdministrationPanel({
vm,
actions,
busy = false,
actionErrorKey = null,
}: {
readonly vm: ChatAuditAdministrationVM;
readonly actions: ChatAuditAdministrationActions;
readonly busy?: boolean;
readonly actionErrorKey?: string | null;
}): React.JSX.Element | null {
const { t } = useTranslation();
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
if (vm.status !== "ready") return null;
const data = vm.data;
return (
<div className="flex w-full flex-col gap-4 px-6 pt-6" data-ui-id="ui.chat.audit.administration">
{actionErrorKey ? (
<Alert variant="error" notDismissible title={t("chat.audit.errors.title")} description={t(actionErrorKey)} />
) : null}
{!data.canAdminister ? (
<Alert
variant="information"
notDismissible
title={t("chat.audit.administration.readOnlyTitle")}
description={t("chat.audit.administration.readOnlyDescription")}
/>
) : (
<Card size="large">
<ButtonGroup align="space-between">
<ButtonGroup>
<FeatherShield aria-hidden="true" />
<ButtonGroup align="stack">
<strong>{t("chat.audit.administration.title")}</strong>
<span>{t("chat.audit.administration.description")}</span>
</ButtonGroup>
</ButtonGroup>
{data.canArchive ? (
<Button
variant="destructive"
icon={<FeatherArchive />}
disabled={busy}
onClick={() => setConfirmation({ type: "archive" })}
data-ui-id="ui.chat.audit.archiveChannel"
>
{t("chat.audit.actions.archive")}
</Button>
) : (
<BadgeFeedback farbe="subtle-neutral">{t("chat.audit.archived")}</BadgeFeedback>
)}
</ButtonGroup>
<div className="flex w-full flex-col gap-2">
<strong>{t("chat.audit.members.title")}</strong>
{data.members.map((member) => (
<Card key={member.userId} size="small">
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar image={member.avatarUrl ?? undefined} size="small">
{initials(member.displayName)}
</Avatar>
<strong>{member.displayName}</strong>
<BadgeFeedback farbe={member.roleInChat === "admin" ? "subtle-brand-primary" : "subtle-neutral"} size="small">
{t(member.roleLabelKey)}
</BadgeFeedback>
</ButtonGroup>
<ButtonGroup>
{member.canPromote ? (
<Button
size="small"
variant="tertiary"
disabled={busy}
onClick={() => void actions.onChangeMemberRole(member.userId, "admin")}
>
{t("chat.audit.actions.promote")}
</Button>
) : null}
{member.canDemote ? (
<Button
size="small"
variant="tertiary"
disabled={busy}
onClick={() => void actions.onChangeMemberRole(member.userId, "member")}
>
{t("chat.audit.actions.demote")}
</Button>
) : null}
{member.canRemove ? (
<Button
size="small"
variant="destructive"
icon={<FeatherTrash2 />}
disabled={busy}
onClick={() => setConfirmation({ type: "remove", userId: member.userId, memberName: member.displayName })}
aria-label={t("chat.audit.actions.removeMemberLabel", { member: member.displayName })}
/>
) : null}
</ButtonGroup>
</ButtonGroup>
</Card>
))}
</div>
</Card>
)}
<Dialog open={confirmation !== null} onOpenChange={(open: boolean) => (open ? undefined : setConfirmation(null))}>
<Dialog.Content
className="w-[420px] max-w-[90vw] p-4"
aria-label={t(confirmation?.type === "remove" ? "chat.audit.confirm.remove.title" : "chat.audit.confirm.archive.title")}
>
<ButtonGroup align="stack">
<DialogTitle>
{t(confirmation?.type === "remove" ? "chat.audit.confirm.remove.title" : "chat.audit.confirm.archive.title")}
</DialogTitle>
<DialogDescription>
{confirmation?.type === "remove"
? t("chat.audit.confirm.remove.body", { member: confirmation.memberName })
: t("chat.audit.confirm.archive.body")}
</DialogDescription>
</ButtonGroup>
<ButtonGroup align="end">
<Button variant="tertiary" disabled={busy} onClick={() => setConfirmation(null)}>
{t("shared.cancel")}
</Button>
<Button
variant="destructive"
loading={busy}
onClick={() => {
if (confirmation?.type === "archive") void actions.onArchive();
if (confirmation?.type === "remove") void actions.onRemoveMember(confirmation.userId);
setConfirmation(null);
}}
>
{t("shared.confirm")}
</Button>
</ButtonGroup>
</Dialog.Content>
</Dialog>
</div>
);
}
function initials(label: string): string {
return (
label
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("") || "?"
);
}
@@ -0,0 +1,95 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${JSON.stringify(values)}` : key),
}),
}));
vi.mock("~/locale/format", () => ({ useLocaleFormatters: () => ({ date: (value: string) => value }) }));
import { buildChatAuditOverviewVM } from "@hivegrid/view-models";
import { ChatAuditOverviewPage } from "./ChatAuditOverviewPage";
describe("AK-P15b chat audit interim UI", () => {
it("keeps the audit list locked until a non-empty justification is submitted", () => {
const onStartSession = vi.fn();
render(
<ChatAuditOverviewPage
vm={buildChatAuditOverviewVM({ session: null, channels: [] })}
actions={{ onStartSession, onEndSession: vi.fn(), onOpenChannel: vi.fn(), onArchiveChannel: vi.fn() }}
/>
);
const button = screen.getByRole("button", { name: "chat.audit.session.start" });
expect((button as HTMLButtonElement).disabled).toBe(true);
fireEvent.change(screen.getByRole("textbox", { name: "chat.audit.reason.label" }), { target: { value: "Kundenreklamation prüfen" } });
expect((button as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(button);
expect(onStartSession).toHaveBeenCalledWith("Kundenreklamation prüfen");
});
it("only exposes read-only open actions during an active session", () => {
const onOpenChannel = vi.fn();
render(
<ChatAuditOverviewPage
vm={buildChatAuditOverviewVM({
session: { id: "session-1", reason: "Supportfall", expiresAtIso: "2026-07-16T10:15:00.000Z" },
channels: [
{
id: "dm-1",
kind: "dm",
title: "Anna · Ben",
description: null,
participantLabels: ["Anna", "Ben"],
memberCount: 2,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: null,
detailHref: "/demo/settings/chat/audit/dm-1",
},
],
canAdminister: false,
})}
actions={{ onStartSession: vi.fn(), onEndSession: vi.fn(), onOpenChannel, onArchiveChannel: vi.fn() }}
/>
);
expect(screen.getByText("chat.audit.readOnly.title")).toBeTruthy();
expect(screen.queryByText(/send|delete|edit/iu)).toBeNull();
fireEvent.click(screen.getByRole("button", { name: /chat.audit.openChannelLabel/u }));
expect(onOpenChannel).toHaveBeenCalledWith("/demo/settings/chat/audit/dm-1");
});
it("confirms an audited cleanup archive only for chat administrators", () => {
const onArchiveChannel = vi.fn();
render(
<ChatAuditOverviewPage
vm={buildChatAuditOverviewVM({
session: { id: "session-1", reason: "Supportfall", expiresAtIso: "2026-07-16T10:15:00.000Z" },
canAdminister: true,
channels: [
{
id: "group-1",
kind: "group",
title: "Bauleitung",
description: null,
participantLabels: [],
memberCount: 2,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: null,
detailHref: "/demo/settings/chat/audit/group-1",
},
],
})}
actions={{ onStartSession: vi.fn(), onEndSession: vi.fn(), onOpenChannel: vi.fn(), onArchiveChannel }}
/>
);
fireEvent.click(screen.getByRole("button", { name: /chat.audit.actions.archiveLabel/u }));
fireEvent.click(screen.getByRole("button", { name: "shared.confirm" }));
expect(onArchiveChannel).toHaveBeenCalledWith("group-1");
});
});
@@ -0,0 +1,226 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Description as DialogDescription, Title as DialogTitle } from "@radix-ui/react-dialog";
import { FeatherArchive, FeatherEye, FeatherLock, FeatherShield } from "@subframe/core";
import type { ChatAuditOverviewVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { TextArea } from "~/ui/components/TextArea";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageIntro, PageShell } from "../shared/PageShell";
export type ChatAuditOverviewActions = Readonly<{
onStartSession: (reason: string) => void | Promise<void>;
onEndSession: () => void | Promise<void>;
onOpenChannel: (href: string) => void | Promise<void>;
onArchiveChannel: (chatId: string) => void | Promise<void>;
}>;
export function ChatAuditOverviewPage({
vm,
actions,
busy = false,
actionErrorKey = null,
embedded = false,
}: {
readonly vm: ChatAuditOverviewVM;
readonly actions: ChatAuditOverviewActions;
readonly busy?: boolean;
readonly actionErrorKey?: string | null;
/** Inside the Compliance hub (AK-SET-01) the hub owns the header. */
readonly embedded?: boolean;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [reason, setReason] = useState("");
const [archiveCandidate, setArchiveCandidate] = useState<{ id: string; title: string } | null>(null);
const data = vm.status === "ready" ? vm.data : null;
return (
<PageShell uiId="ui.chat.audit.page" className="bg-surface-neutral-primary mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
{embedded ? null : (
<PageHeader
icon={<FeatherShield className={PAGE_HEADER_ICON_CLASS} />}
title={t("chat.audit.title")}
subtitle={t("chat.audit.description")}
actions={
data?.session ? (
<Button variant="tertiary" onClick={() => void actions.onEndSession()} disabled={busy}>
{t("chat.audit.session.end")}
</Button>
) : null
}
/>
)}
<PageBody>
{embedded ? (
<div className="mobile:flex-col mobile:items-start flex w-full items-start justify-between gap-4">
<PageIntro uiId="ui.chat.audit.intro">{t("chat.audit.description")}</PageIntro>
{data?.session ? (
<Button variant="tertiary" onClick={() => void actions.onEndSession()} disabled={busy}>
{t("chat.audit.session.end")}
</Button>
) : null}
</div>
) : null}
<Alert
variant="warning"
notDismissible
title={t("chat.audit.readOnly.title")}
description={t("chat.audit.readOnly.description")}
data-ui-id="ui.chat.audit.readOnlyNotice"
/>
{actionErrorKey ? <Alert variant="error" notDismissible title={t("chat.audit.errors.title")} description={t(actionErrorKey)} /> : null}
{!data?.session ? (
<Card size="large" data-ui-id="ui.chat.audit.reasonGate">
<div className="flex w-full flex-col items-start gap-4">
<div className="flex items-start gap-3">
<FeatherLock aria-hidden="true" />
<div className="flex flex-col items-start gap-1">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("chat.audit.reason.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("chat.audit.reason.help")}</span>
</div>
</div>
<TextArea showLabel label={t("chat.audit.reason.label")} helpText={t("chat.audit.reason.maxLength")}>
<TextArea.Input
value={reason}
maxLength={500}
required
onChange={(event) => setReason(event.currentTarget.value)}
placeholder={t("chat.audit.reason.placeholder")}
aria-label={t("chat.audit.reason.label")}
data-ui-id="ui.chat.audit.reasonInput"
/>
</TextArea>
<Button
variant="warning"
icon={<FeatherEye />}
disabled={busy || reason.trim().length === 0}
loading={busy}
onClick={() => void actions.onStartSession(reason)}
data-ui-id="ui.chat.audit.startSession"
>
{t("chat.audit.session.start")}
</Button>
</div>
</Card>
) : (
<>
<Alert
variant="information"
notDismissible
title={t("chat.audit.session.active")}
description={t("chat.audit.session.activeDescription", {
reason: data.session.reason,
expiresAt: formatters.date(data.session.expiresAtIso, { dateStyle: "medium", timeStyle: "short" }),
})}
data-ui-id="ui.chat.audit.sessionActive"
/>
{data.channels.length === 0 ? (
<EmptyState outlined title={t(data.keys.emptyTitle)} body={t(data.keys.emptyBody)} data-ui-id="ui.chat.audit.empty" />
) : (
<div className="w-full overflow-x-auto" data-ui-id="ui.chat.audit.channelList">
<Table
header={
<Table.HeaderRow>
<Table.HeaderCell>{t("chat.audit.columns.channel")}</Table.HeaderCell>
<Table.HeaderCell>{t("chat.audit.columns.kind")}</Table.HeaderCell>
<Table.HeaderCell>{t("chat.audit.columns.members")}</Table.HeaderCell>
<Table.HeaderCell>{t("chat.audit.columns.visibility")}</Table.HeaderCell>
<Table.HeaderCell>{t("chat.audit.columns.lastActivity")}</Table.HeaderCell>
<Table.HeaderCell>{t("chat.audit.columns.action")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{data.channels.map((channel) => (
<Table.Row key={channel.id}>
<Table.Cell>
<div className="flex flex-col items-start gap-1">
<span className="text-body-default-medium-0 font-body-default-medium-0 text-text-neutral-primary">{channel.title}</span>
{channel.participantLabels.length > 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{channel.participantLabels.join(", ")}
</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<BadgeFeedback farbe="subtle-neutral">{t(channel.kindLabelKey)}</BadgeFeedback>
</Table.Cell>
<Table.Cell>{t("chat.audit.memberCount", { count: channel.memberCount })}</Table.Cell>
<Table.Cell>{t(channel.isPrivate ? "chat.audit.visibility.private" : "chat.audit.visibility.public")}</Table.Cell>
<Table.Cell>
{channel.lastMessageAtIso
? formatters.date(channel.lastMessageAtIso, { dateStyle: "medium", timeStyle: "short" })
: t("chat.audit.noActivity")}
</Table.Cell>
<Table.Cell>
<div className="flex items-center gap-2">
<Button
variant="tertiary"
size="small"
icon={<FeatherEye />}
onClick={() => void actions.onOpenChannel(channel.detailHref)}
aria-label={t("chat.audit.openChannelLabel", { channel: channel.title })}
>
{t("chat.audit.openChannel")}
</Button>
{channel.canArchive ? (
<Button
variant="destructive"
size="small"
icon={<FeatherArchive />}
disabled={busy}
onClick={() => setArchiveCandidate({ id: channel.id, title: channel.title })}
aria-label={t("chat.audit.actions.archiveLabel", { channel: channel.title })}
/>
) : null}
</div>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
</>
)}
<Dialog open={archiveCandidate !== null} onOpenChange={(open: boolean) => (open ? undefined : setArchiveCandidate(null))}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-4" aria-label={t("chat.audit.confirm.archive.title")} data-ui-id="ui.chat.audit.archiveConfirm">
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<DialogTitle>{t("chat.audit.confirm.archive.title")}</DialogTitle>
<DialogDescription>{t("chat.audit.confirm.archive.bodyNamed", { channel: archiveCandidate?.title ?? "" })}</DialogDescription>
</div>
<div className="flex justify-end gap-2">
<Button variant="tertiary" disabled={busy} onClick={() => setArchiveCandidate(null)}>
{t("shared.cancel")}
</Button>
<Button
variant="destructive"
loading={busy}
onClick={() => {
if (archiveCandidate) void actions.onArchiveChannel(archiveCandidate.id);
setArchiveCandidate(null);
}}
>
{t("shared.confirm")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
</PageBody>
</PageShell>
);
}
@@ -0,0 +1,163 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildChatChannelCreateVM } from "@hivegrid/view-models";
import { ChatChannelCreatePage, type ChatChannelCreateActions } from "./ChatChannelCreatePage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
function actions(overrides: Partial<ChatChannelCreateActions> = {}): ChatChannelCreateActions {
return {
onCancel: vi.fn(),
onCreate: vi.fn(),
onRetry: vi.fn(),
...overrides,
};
}
function createVm(requestedMode: "group" | "dm" = "group") {
return buildChatChannelCreateVM({
currentUserId: "user_current",
requestedMode,
permissions: { canCreateGroup: true, canCreateDm: true },
tenantGroups: [{ groupId: "group_south", name: "Team Süd", description: "Montage", memberCount: 3 }],
tenantUsers: [
{
userId: "user_current",
displayName: "Raffael Sheikh",
email: "raffael@example.test",
avatar: { imageUrl: null, fallbackLabel: "RS" },
},
{
userId: "user_mara",
displayName: "Mara Klein",
email: "mara@example.test",
avatar: { imageUrl: null, fallbackLabel: "MK" },
},
],
});
}
describe("AK-P15b chat channel create interim UI", () => {
beforeEach(() => vi.clearAllMocks());
it("submits a private group with selected initial members", () => {
const onCreate = vi.fn();
render(
<MemoryRouter>
<ChatChannelCreatePage vm={createVm()} actions={actions({ onCreate })} />
</MemoryRouter>
);
fireEvent.change(screen.getByRole("textbox", { name: /chat\.channelCreate\.fields\.name/ }), {
target: { value: "Montage Nord" },
});
fireEvent.change(screen.getByRole("textbox", { name: /chat\.channelCreate\.fields\.description/ }), {
target: { value: "Abstimmung für das Montageteam" },
});
fireEvent.click(screen.getByRole("switch", { name: "chat.channelCreate.fields.private" }));
fireEvent.click(screen.getByRole("checkbox", { name: "mara@example.test" }));
fireEvent.click(screen.getByRole("checkbox", { name: "Team Süd" }));
fireEvent.click(screen.getByRole("switch", { name: "chat.channelCreate.fields.groupSync" }));
fireEvent.click(screen.getByRole("button", { name: "chat.channelCreate.actions.createGroup" }));
expect(onCreate).toHaveBeenCalledWith({
mode: "group",
name: "Montage Nord",
description: "Abstimmung für das Montageteam",
privacy: "private",
initialUserIds: ["user_mara"],
initialGroupIds: ["group_south"],
syncGroupMembership: true,
});
});
it("renders loading, error, and permission states with working recovery actions", () => {
const onRetry = vi.fn();
const onCancel = vi.fn();
const view = render(
<MemoryRouter>
<ChatChannelCreatePage vm={{ status: "loading" }} actions={actions({ onRetry, onCancel })} />
</MemoryRouter>
);
expect(screen.getByRole("status", { name: "chat.channelCreate.users.loading" })).toBeInTheDocument();
view.rerender(
<MemoryRouter>
<ChatChannelCreatePage vm={{ status: "error", error: { messageKey: "chat.errors.realtimeUnavailable" } }} actions={actions({ onRetry, onCancel })} />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
expect(onRetry).toHaveBeenCalledOnce();
const permissionVm = buildChatChannelCreateVM({
currentUserId: "user_current",
tenantUsers: [],
permissions: { canCreateGroup: false, canCreateDm: false },
});
view.rerender(
<MemoryRouter>
<ChatChannelCreatePage vm={permissionVm} actions={actions({ onRetry, onCancel })} />
</MemoryRouter>
);
expect(screen.getByText("chat.channelCreate.permissions.none")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "chat.channelCreate.actions.backToChat" }));
expect(onCancel).toHaveBeenCalledOnce();
});
it("shows an explicit empty state when a DM has no available peer", () => {
const vm = buildChatChannelCreateVM({
currentUserId: "user_current",
requestedMode: "dm",
tenantUsers: [
{
userId: "user_current",
displayName: "Raffael Sheikh",
email: "raffael@example.test",
avatar: { imageUrl: null, fallbackLabel: "RS" },
},
],
permissions: { canCreateGroup: false, canCreateDm: true },
});
render(
<MemoryRouter>
<ChatChannelCreatePage vm={vm} actions={actions()} />
</MemoryRouter>
);
expect(screen.getByText("chat.channelCreate.users.empty")).toBeInTheDocument();
expect(screen.getByText("chat.channelCreate.users.dmEmptyBody")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "chat.channelCreate.actions.startDm" })).toBeDisabled();
});
it("starts a DM with exactly the selected tenant user", () => {
const onCreate = vi.fn();
render(
<MemoryRouter>
<ChatChannelCreatePage vm={createVm("dm")} actions={actions({ onCreate })} />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("combobox", { name: "chat.channelCreate.fields.peer" }));
fireEvent.click(screen.getByRole("option", { name: "Mara Klein · mara@example.test" }));
fireEvent.click(screen.getByRole("button", { name: "chat.channelCreate.actions.startDm" }));
expect(onCreate).toHaveBeenCalledWith({ mode: "dm", peerUserId: "user_mara" });
});
it("renders an action error key from the server", () => {
render(
<MemoryRouter>
<ChatChannelCreatePage vm={createVm()} actionErrorKey="chat.errors.invalidInput" actions={actions()} />
</MemoryRouter>
);
expect(screen.getByText("chat.errors.invalidInput")).toBeInTheDocument();
});
});
@@ -0,0 +1,417 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherHash, FeatherMessageCircle, FeatherPlus, FeatherUsers } from "@subframe/core";
import type { ChatChannelCreateMode, ChatChannelCreateSubmission, ChatChannelCreateVM, ChatGroupPrivacy } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { Checkbox } from "~/ui/components/Checkbox";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatSwitch } from "./ChatSwitch";
export type ChatChannelCreateActions = {
readonly onCancel: () => void;
readonly onCreate: (submission: ChatChannelCreateSubmission) => void | Promise<void>;
readonly onRetry: () => void | Promise<void>;
};
export type ChatChannelCreatePageProps = {
readonly vm: ChatChannelCreateVM;
readonly actions: ChatChannelCreateActions;
readonly busy?: boolean;
readonly actionErrorKey?: string | null;
};
function CreateShell({ children, actions }: { readonly children: React.ReactNode; readonly actions?: React.ReactNode }): React.JSX.Element {
const { t } = useTranslation();
return (
<PageShell uiId="ui.chat.channelCreate" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherMessageCircle className={PAGE_HEADER_ICON_CLASS} />}
title={t("chat.channelCreate.title")}
subtitle={t("chat.channelCreate.subtitle")}
actions={actions}
uiId="ui.chat.channelCreate.header"
/>
<PageBody>{children}</PageBody>
</PageShell>
);
}
export function ChatChannelCreatePage({ vm, actions, busy = false, actionErrorKey = null }: ChatChannelCreatePageProps): React.JSX.Element {
const { t } = useTranslation();
const readyData = vm.status === "ready" ? vm.data : null;
const initialMode = readyData?.selectedMode ?? null;
const initialGroupForm = readyData?.form?.mode === "group" ? readyData.form : null;
const initialDmForm = readyData?.form?.mode === "dm" ? readyData.form : null;
const [mode, setMode] = useState<ChatChannelCreateMode | null>(initialMode);
const [name, setName] = useState(initialGroupForm?.name ?? "");
const [description, setDescription] = useState(initialGroupForm?.description ?? "");
const [privacy, setPrivacy] = useState<ChatGroupPrivacy>(initialGroupForm?.privacy ?? "public");
const [initialUserIds, setInitialUserIds] = useState<readonly string[]>(initialGroupForm?.initialUserIds ?? []);
const [initialGroupIds, setInitialGroupIds] = useState<readonly string[]>(initialGroupForm?.initialGroupIds ?? []);
const [syncGroupMembership, setSyncGroupMembership] = useState(initialGroupForm?.syncGroupMembership ?? false);
const [peerUserId, setPeerUserId] = useState(initialDmForm?.peerUserId ?? "");
const [localErrorKey, setLocalErrorKey] = useState<string | null>(null);
const groupTabRef = useRef<HTMLButtonElement | null>(null);
const dmTabRef = useRef<HTMLButtonElement | null>(null);
useEffect(() => {
if (!readyData) return;
setMode(readyData.selectedMode);
if (readyData.form?.mode === "group") {
setName(readyData.form.name);
setDescription(readyData.form.description);
setPrivacy(readyData.form.privacy);
setInitialUserIds(readyData.form.initialUserIds);
setInitialGroupIds(readyData.form.initialGroupIds);
setSyncGroupMembership(readyData.form.syncGroupMembership);
} else if (readyData.form?.mode === "dm") {
setPeerUserId(readyData.form.peerUserId ?? "");
}
setLocalErrorKey(null);
}, [readyData]);
const selectedUserIds = useMemo(() => new Set(initialUserIds), [initialUserIds]);
const selectedGroupIds = useMemo(() => new Set(initialGroupIds), [initialGroupIds]);
const canSubmit = mode === "group" ? name.trim().length > 0 : mode === "dm" ? peerUserId.length > 0 : false;
function selectMode(nextMode: ChatChannelCreateMode, focus = false): void {
setMode(nextMode);
setLocalErrorKey(null);
if (focus) requestAnimationFrame(() => (nextMode === "group" ? groupTabRef.current : dmTabRef.current)?.focus());
}
function handleModeKeyDown(event: React.KeyboardEvent<HTMLButtonElement>, currentMode: ChatChannelCreateMode): void {
if (!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const allowed = readyData?.allowedModes ?? [];
if (allowed.length < 2) return;
const currentIndex = allowed.indexOf(currentMode);
const nextIndex =
event.key === "Home"
? 0
: event.key === "End"
? allowed.length - 1
: event.key === "ArrowRight"
? (currentIndex + 1) % allowed.length
: (currentIndex - 1 + allowed.length) % allowed.length;
const nextMode = allowed[nextIndex];
if (nextMode) selectMode(nextMode, true);
}
const submit = () => {
if (mode === "group") {
if (!name.trim()) {
setLocalErrorKey("chat.channelCreate.validation.groupNameRequired");
return;
}
setLocalErrorKey(null);
void actions.onCreate({
mode: "group",
name: name.trim(),
description: description.trim() || null,
privacy,
initialUserIds: [...new Set(initialUserIds)],
initialGroupIds: [...new Set(initialGroupIds)],
syncGroupMembership: syncGroupMembership && initialGroupIds.length > 0,
});
return;
}
if (mode === "dm") {
if (!peerUserId) {
setLocalErrorKey("chat.channelCreate.validation.dmPeerRequired");
return;
}
setLocalErrorKey(null);
void actions.onCreate({ mode: "dm", peerUserId });
}
};
const headerActions = (
<ButtonGroup align="end">
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={actions.onCancel} disabled={busy}>
{t("chat.channelCreate.actions.cancel")}
</Button>
{readyData?.allowedModes.length ? (
<Button icon={<FeatherPlus />} onClick={submit} disabled={!canSubmit || busy} loading={busy} data-ui-id="ui.chat.channelCreate.submit">
{t(mode === "dm" ? "chat.channelCreate.actions.startDm" : "chat.channelCreate.actions.createGroup")}
</Button>
) : null}
</ButtonGroup>
);
if (vm.status === "idle" || vm.status === "loading") {
return (
<CreateShell actions={headerActions}>
<LoadingIndicatorSkeleton variant="card" role="status" aria-label={t("chat.channelCreate.users.loading")} data-ui-id="ui.chat.channelCreate.loading" />
</CreateShell>
);
}
if (vm.status === "error") {
return (
<CreateShell actions={headerActions}>
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
data-ui-id="ui.chat.channelCreate.error"
/>
</CreateShell>
);
}
if (vm.status === "empty" || !readyData || readyData.allowedModes.length === 0 || !mode) {
return (
<CreateShell actions={headerActions}>
<EmptyState
outlined
title={t(readyData?.keys.noAllowedModesKey ?? "chat.channelCreate.permissions.none")}
body={t("chat.channelCreate.permissions.noneBody")}
action={
<Button variant="tertiary" onClick={actions.onCancel}>
{t("chat.channelCreate.actions.backToChat")}
</Button>
}
data-ui-id="ui.chat.channelCreate.permissionDenied"
/>
</CreateShell>
);
}
return (
<CreateShell actions={headerActions}>
{actionErrorKey || localErrorKey ? (
<Alert
variant="error"
notDismissible
title={t("chat.channelCreate.errors.title")}
description={t(actionErrorKey ?? localErrorKey ?? "chat.errors.invalidInput")}
data-ui-id="ui.chat.channelCreate.actionError"
/>
) : null}
{readyData.allowedModes.length > 1 ? (
<ButtonGroup role="tablist" aria-label={t("chat.channelCreate.mode.label")} data-ui-id="ui.chat.channelCreate.modeTabs">
{readyData.allowedModes.includes("group") ? (
<Button
ref={groupTabRef}
role="tab"
id="chat-channel-create-tab-group"
aria-controls="chat-channel-create-panel-group"
aria-selected={mode === "group"}
tabIndex={mode === "group" ? 0 : -1}
variant={mode === "group" ? "secondary" : "tertiary"}
icon={<FeatherUsers />}
onClick={() => selectMode("group")}
onKeyDown={(event) => handleModeKeyDown(event, "group")}
>
{t(readyData.keys.groupModeKey)}
</Button>
) : null}
{readyData.allowedModes.includes("dm") ? (
<Button
ref={dmTabRef}
role="tab"
id="chat-channel-create-tab-dm"
aria-controls="chat-channel-create-panel-dm"
aria-selected={mode === "dm"}
tabIndex={mode === "dm" ? 0 : -1}
variant={mode === "dm" ? "secondary" : "tertiary"}
icon={<FeatherMessageCircle />}
onClick={() => selectMode("dm")}
onKeyDown={(event) => handleModeKeyDown(event, "dm")}
>
{t(readyData.keys.dmModeKey)}
</Button>
) : null}
</ButtonGroup>
) : null}
{mode === "group" ? (
<Card
id="chat-channel-create-panel-group"
role="tabpanel"
aria-labelledby="chat-channel-create-tab-group"
size="large"
data-ui-id="ui.chat.channelCreate.groupForm"
>
<TextInput
fillContainer
showLabel
label={t("chat.channelCreate.fields.name")}
helpText={t("chat.channelCreate.fields.nameHelp")}
error={localErrorKey === "chat.channelCreate.validation.groupNameRequired"}
message={localErrorKey ? t(localErrorKey) : undefined}
>
<TextInput.Input
value={name}
onChange={(event) => {
setName(event.target.value);
if (event.target.value.trim()) setLocalErrorKey(null);
}}
placeholder={t("chat.channelCreate.placeholders.name")}
maxLength={120}
autoFocus
data-ui-id="ui.chat.channelCreate.name"
/>
</TextInput>
<TextArea showLabel label={t("chat.channelCreate.fields.description")} helpText={t("chat.channelCreate.fields.descriptionHelp")}>
<TextArea.Input
value={description}
onChange={(event) => setDescription(event.target.value)}
placeholder={t("chat.channelCreate.placeholders.description")}
maxLength={4000}
data-ui-id="ui.chat.channelCreate.description"
/>
</TextArea>
<Card variant="neutral" data-ui-id="ui.chat.channelCreate.privacy">
<ButtonGroup align="space-between">
<ButtonGroup>
<FeatherHash aria-hidden="true" />
<span>{t(privacy === "private" ? "chat.channelCreate.privacy.private" : "chat.channelCreate.privacy.public")}</span>
</ButtonGroup>
<ChatSwitch
checked={privacy === "private"}
onCheckedChange={(checked) => setPrivacy(checked ? "private" : "public")}
aria-label={t("chat.channelCreate.fields.private")}
/>
</ButtonGroup>
<span>{t(privacy === "private" ? "chat.channelCreate.privacy.privateHelp" : "chat.channelCreate.privacy.publicHelp")}</span>
</Card>
<ButtonGroup align="stack" data-ui-id="ui.chat.channelCreate.members">
<strong>{t("chat.channelCreate.fields.members")}</strong>
<span>{t("chat.channelCreate.fields.membersHelp")}</span>
{readyData.userOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.usersEmptyKey)} body={t("chat.channelCreate.users.groupEmptyBody")} />
) : (
readyData.userOptions.map((user) => (
<Card key={user.userId} size="small" variant={selectedUserIds.has(user.userId) ? "information" : "default"}>
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar image={user.avatar.imageUrl ?? undefined} size="small">
{user.avatar.fallbackLabel}
</Avatar>
<span>{user.displayName}</span>
</ButtonGroup>
<Checkbox
checked={selectedUserIds.has(user.userId)}
label={user.email}
onCheckedChange={(checked) =>
setInitialUserIds((current) => (checked ? [...new Set([...current, user.userId])] : current.filter((id) => id !== user.userId)))
}
data-user-id={user.userId}
/>
</ButtonGroup>
</Card>
))
)}
</ButtonGroup>
<ButtonGroup align="stack" data-ui-id="ui.chat.channelCreate.groups">
<strong>{t("chat.channelCreate.fields.groups")}</strong>
<span>{t("chat.channelCreate.fields.groupsHelp")}</span>
{readyData.groupOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.groupsEmptyKey)} body={t("chat.channelCreate.groups.emptyBody")} />
) : (
readyData.groupOptions.map((group) => (
<Card key={group.groupId} size="small" variant={selectedGroupIds.has(group.groupId) ? "information" : "default"}>
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<strong>{group.name}</strong>
<span>
{group.description || t("chat.channelCreate.groups.noDescription")} ·{" "}
{t("chat.channelCreate.groups.memberCount", { count: group.memberCount })}
</span>
</ButtonGroup>
<Checkbox
checked={selectedGroupIds.has(group.groupId)}
label={group.name}
onCheckedChange={(checked) => {
setInitialGroupIds((current) => {
const next = checked ? [...new Set([...current, group.groupId])] : current.filter((id) => id !== group.groupId);
if (next.length === 0) setSyncGroupMembership(false);
return next;
});
}}
data-group-id={group.groupId}
/>
</ButtonGroup>
</Card>
))
)}
</ButtonGroup>
<Card variant="neutral" data-ui-id="ui.chat.channelCreate.groupSync">
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<strong>{t("chat.channelCreate.fields.groupSync")}</strong>
<span>{t("chat.channelCreate.fields.groupSyncHelp")}</span>
</ButtonGroup>
<ChatSwitch
checked={syncGroupMembership}
disabled={initialGroupIds.length === 0}
onCheckedChange={setSyncGroupMembership}
aria-label={t("chat.channelCreate.fields.groupSync")}
/>
</ButtonGroup>
</Card>
</Card>
) : (
<Card
id="chat-channel-create-panel-dm"
role="tabpanel"
aria-labelledby="chat-channel-create-tab-dm"
size="large"
data-ui-id="ui.chat.channelCreate.dmForm"
>
{readyData.userOptions.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.usersEmptyKey)} body={t("chat.channelCreate.users.dmEmptyBody")} />
) : (
<Select
value={peerUserId}
onValueChange={(value) => {
setPeerUserId(value);
setLocalErrorKey(null);
}}
showLabel
label={t("chat.channelCreate.fields.peer")}
helpText={t("chat.channelCreate.fields.peerHelp")}
placeholder={t("chat.channelCreate.placeholders.peer")}
triggerAriaLabel={t("chat.channelCreate.fields.peer")}
error={localErrorKey === "chat.channelCreate.validation.dmPeerRequired"}
errorText={localErrorKey ? t(localErrorKey) : undefined}
data-ui-id="ui.chat.channelCreate.peer"
>
{readyData.userOptions.map((user) => (
<Select.Item key={user.userId} value={user.userId}>
{user.displayName} · {user.email}
</Select.Item>
))}
</Select>
)}
</Card>
)}
</CreateShell>
);
}
@@ -0,0 +1,492 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherAtSign,
FeatherBell,
FeatherHash,
FeatherLock,
FeatherMessageCircle,
FeatherMessageSquare,
FeatherPin,
FeatherSearch,
FeatherUsers,
} from "@subframe/core";
import type {
ChatChannelListVM,
ChatChannelListView,
ChatChannelListRowVM,
ChatChannelNotificationPreference,
ChatDiscoverChannelRowVM,
} from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatSwitch } from "./ChatSwitch";
export type ChatChannelListActions = {
readonly onOpenChannel: (channelId: string, detailHref: string) => void;
readonly onQueryChange: (query: string) => void;
readonly onViewChange: (view: ChatChannelListView) => void;
readonly onShowArchivedChange: (showArchived: boolean) => void;
readonly onRetry: () => void | Promise<void>;
readonly onLoadMore?: (cursor: string) => void | Promise<void>;
readonly onCreateGroup?: (href: string) => void;
readonly onCreateDm?: (href: string) => void;
readonly onJoinChannel?: (channelId: string, joinHref: string) => void;
readonly onOpenMessageSearch?: (href: string) => void;
readonly onOpenMentions?: (href: string) => void;
readonly onSetPinned?: (channelId: string, pinned: boolean) => void;
readonly onSetNotificationPreference?: (channelId: string, preference: ChatChannelNotificationPreference) => void;
};
export type ChatChannelListPageProps = {
readonly vm: ChatChannelListVM;
readonly actions: ChatChannelListActions;
readonly joiningChannelId?: string | null;
readonly joinErrorKey?: string | null;
readonly preferenceErrorKey?: string | null;
readonly updatingPreferenceChannelId?: string | null;
};
const CHANNEL_LIST_VIEWS: readonly ChatChannelListView[] = ["all", "unread", "mentions", "pinned", "projects", "groups", "direct"];
function ChannelAvatar({ row }: { readonly row: ChatChannelListRowVM }): React.JSX.Element {
const fallbackIcon = row.kind === "project" ? <FeatherHash /> : row.kind === "group" ? <FeatherUsers /> : undefined;
return (
<Avatar image={row.avatar.imageUrl ?? undefined} color={row.kind === "project" ? "blue" : "neutral"}>
{fallbackIcon ?? row.avatar.fallbackLabel}
</Avatar>
);
}
function ChannelRow({
row,
onOpen,
onSetPinned,
onSetNotificationPreference,
isUpdating,
}: {
readonly row: ChatChannelListRowVM;
readonly onOpen: ChatChannelListActions["onOpenChannel"];
readonly onSetPinned?: ChatChannelListActions["onSetPinned"];
readonly onSetNotificationPreference?: ChatChannelListActions["onSetNotificationPreference"];
readonly isUpdating: boolean;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const accessibilityStatus = [
row.hasUnread ? t("chat.channelList.a11y.unread", { count: row.unreadCount }) : null,
row.hasMention ? t("chat.channelList.a11y.mention") : null,
row.isPrivate ? t("chat.channelList.private") : null,
row.isPinned ? t("chat.channelList.pinned") : null,
]
.filter((label): label is string => label !== null)
.join(", ");
return (
<Card data-channel-id={row.id}>
<button
type="button"
className="focus-visible:shadow-focus flex min-h-11 w-full cursor-pointer flex-col items-start gap-2 rounded-md border-0 bg-transparent p-0 text-left outline-none"
aria-label={t("chat.channelList.openAria", { channel: row.title, status: accessibilityStatus })}
onClick={() => onOpen(row.id, row.detailHref)}
data-ui-id="ui.chat.channelList.open"
>
<ButtonGroup align="space-between">
<ButtonGroup>
<ChannelAvatar row={row} />
<BadgeFeedback farbe="ghost-neutral" size="large">
{row.title}
</BadgeFeedback>
</ButtonGroup>
<ButtonGroup align="end">
{row.isPrivate ? (
<BadgeFeedback farbe="ghost-neutral" size="small" aria-label={t("chat.channelList.private")}>
<FeatherLock aria-hidden="true" />
</BadgeFeedback>
) : null}
{row.isPinned ? (
<BadgeFeedback farbe="ghost-neutral" size="small" aria-label={t("chat.channelList.pinned")}>
<FeatherPin aria-hidden="true" />
</BadgeFeedback>
) : null}
{row.hasMention ? (
<BadgeFeedback farbe="subtle-information" size="small">
<FeatherAtSign aria-hidden="true" />
</BadgeFeedback>
) : null}
{row.hasUnread ? (
<BadgeFeedback farbe="solid-brand-primary" size="small">
{formatters.number(row.unreadCount)}
</BadgeFeedback>
) : null}
</ButtonGroup>
</ButtonGroup>
{row.typingLabels.length > 0 ? (
<BadgeFeedback farbe="ghost-information">
{t("chat.channel.typing", { count: row.typingLabels.length, names: row.typingLabels.join(", ") })}
</BadgeFeedback>
) : row.lastMessage ? (
<span>
{row.lastMessage.systemEvent
? t(row.lastMessage.systemEvent.labelKey, row.lastMessage.systemEvent.values)
: `${row.lastMessage.authorLabel}: ${row.lastMessage.snippet}`}
</span>
) : row.subtitle ? (
<span>{row.subtitle}</span>
) : null}
</button>
<ButtonGroup>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(row.kindLabelKey)}
</BadgeFeedback>
{row.project ? (
<BadgeFeedback farbe="subtle-blue" size="small">
{row.project.number} · {row.project.stageLabel}
</BadgeFeedback>
) : null}
{row.isArchived ? (
<BadgeFeedback farbe="subtle-warning" size="small">
{t("chat.channelList.archived")}
</BadgeFeedback>
) : null}
{row.lastMessage ? (
<BadgeFeedback farbe="ghost-neutral" size="small">
{formatters.relativeDate(row.lastMessage.createdAtIso)}
</BadgeFeedback>
) : null}
{onSetPinned ? (
<Button
variant="tertiary"
icon={<FeatherPin />}
loading={isUpdating}
aria-label={t(row.isPinned ? "chat.channelList.actions.unpin" : "chat.channelList.actions.pin", { channel: row.title })}
onClick={(event) => {
event.stopPropagation();
onSetPinned(row.id, !row.isPinned);
}}
>
{t(row.isPinned ? "chat.channelList.actions.unpinShort" : "chat.channelList.actions.pinShort")}
</Button>
) : null}
{onSetNotificationPreference ? (
<Button
variant="tertiary"
icon={<FeatherBell />}
loading={isUpdating}
aria-label={t(row.isMuted ? "chat.channelList.actions.unmute" : "chat.channelList.actions.mute", { channel: row.title })}
onClick={(event) => {
event.stopPropagation();
onSetNotificationPreference(row.id, row.isMuted ? "all_messages" : "muted");
}}
>
{t(row.isMuted ? "chat.channelList.actions.unmuteShort" : "chat.channelList.actions.muteShort")}
</Button>
) : null}
</ButtonGroup>
</Card>
);
}
function DiscoverChannelRow({
row,
joining,
onJoin,
}: {
readonly row: ChatDiscoverChannelRowVM;
readonly joining: boolean;
readonly onJoin?: ChatChannelListActions["onJoinChannel"];
}): React.JSX.Element {
const { t } = useTranslation();
const canJoin = row.canJoin && row.joinHref !== null && Boolean(onJoin);
return (
<Card data-ui-id="ui.chat.channelList.discover.row" data-channel-id={row.id}>
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar image={row.avatar.imageUrl ?? undefined} color="neutral">
{row.avatar.fallbackLabel}
</Avatar>
<BadgeFeedback farbe="ghost-neutral" size="large">
{row.title}
</BadgeFeedback>
</ButtonGroup>
{canJoin ? (
<Button
variant="tertiary"
loading={joining}
disabled={joining}
aria-label={t("chat.channelList.discover.joinAria", { channel: row.title })}
onClick={() => onJoin?.(row.id, row.joinHref!)}
data-ui-id="ui.chat.channelList.discover.join"
>
{t("chat.channelList.discover.join")}
</Button>
) : null}
</ButtonGroup>
{row.description ? <span>{row.description}</span> : null}
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("chat.channelList.discover.memberCount", { count: row.memberCount })}
</BadgeFeedback>
</Card>
);
}
function ListShell({ children, headerActions }: { readonly children: React.ReactNode; readonly headerActions?: React.ReactNode }): React.JSX.Element {
const { t } = useTranslation();
return (
<PageShell uiId="ui.chat.channelList" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader icon={<FeatherMessageSquare className={PAGE_HEADER_ICON_CLASS} />} title={t("chat.nav.title")} actions={headerActions} />
<PageBody>{children}</PageBody>
</PageShell>
);
}
export function ChatChannelListPage({
vm,
actions,
joiningChannelId = null,
joinErrorKey = null,
preferenceErrorKey = null,
updatingPreferenceChannelId = null,
}: ChatChannelListPageProps): React.JSX.Element {
const { t } = useTranslation();
const isMobile = useChatMobileNavigation();
if (vm.status === "idle" || vm.status === "loading") {
return (
<ListShell>
<LoadingIndicatorSkeleton variant="list" role="status" aria-label={t("shared.loading")} data-ui-id="ui.chat.channelList.loading" />
</ListShell>
);
}
if (vm.status === "error") {
return (
<ListShell>
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
data-ui-id="ui.chat.channelList.error"
/>
</ListShell>
);
}
if (vm.status === "empty" || !vm.data) {
return (
<ListShell>
<EmptyState
outlined
title={t("chat.channelList.empty.headline")}
body={t("chat.channelList.empty.body")}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
/>
</ListShell>
);
}
const { filter, permissions, rows } = vm.data;
const hasActiveFilter = filter.query.trim().length > 0 || filter.view !== "all" || filter.showArchived;
const canShowCreateGroup = permissions.canCreateGroup && Boolean(actions.onCreateGroup);
const canShowCreateDm = permissions.canCreateDm && Boolean(actions.onCreateDm);
const canShowMessageSearch = permissions.canSearch && Boolean(actions.onOpenMessageSearch);
const canShowMentions = permissions.canViewMentions && Boolean(actions.onOpenMentions);
const emptyAction = hasActiveFilter ? (
<Button
variant="tertiary"
onClick={() => {
actions.onQueryChange("");
actions.onViewChange("all");
actions.onShowArchivedChange(false);
}}
>
{t("shared.reset")}
</Button>
) : canShowCreateGroup || canShowCreateDm ? (
<ButtonGroup>
{canShowCreateDm ? (
<Button variant="tertiary" icon={<FeatherMessageCircle />} onClick={() => actions.onCreateDm?.(vm.data.hrefs.newDm)}>
{t("chat.channelList.actions.newDm")}
</Button>
) : null}
{canShowCreateGroup ? (
<Button icon={<FeatherUsers />} onClick={() => actions.onCreateGroup?.(vm.data.hrefs.newChannel)}>
{t("chat.channelList.actions.newGroup")}
</Button>
) : null}
</ButtonGroup>
) : undefined;
const headerActions =
canShowMessageSearch || canShowMentions || (rows.length > 0 && (canShowCreateGroup || canShowCreateDm)) ? (
<ButtonGroup align="end">
{canShowMessageSearch ? (
<Button variant="tertiary" icon={<FeatherSearch />} onClick={() => actions.onOpenMessageSearch?.(vm.data.hrefs.search)}>
{t("chat.messageDiscovery.actions.search")}
</Button>
) : null}
{canShowMentions ? (
<Button variant="tertiary" icon={<FeatherAtSign />} onClick={() => actions.onOpenMentions?.(vm.data.hrefs.mentions)}>
{t("chat.messageDiscovery.actions.mentions")}
</Button>
) : null}
{canShowCreateDm && rows.length > 0 ? (
<Button variant="tertiary" icon={<FeatherMessageCircle />} onClick={() => actions.onCreateDm?.(vm.data.hrefs.newDm)}>
{t("chat.channelList.actions.newDm")}
</Button>
) : null}
{canShowCreateGroup && rows.length > 0 ? (
<Button icon={<FeatherUsers />} onClick={() => actions.onCreateGroup?.(vm.data.hrefs.newChannel)}>
{t("chat.channelList.actions.newGroup")}
</Button>
) : null}
</ButtonGroup>
) : null;
return (
<ListShell headerActions={headerActions}>
<ButtonGroup align="stack">
<SearchInput
fillContainer
hideShortcut
disabled={!permissions.canSearch}
placeholder={t("chat.searchPlaceholder")}
value={filter.query}
onChange={(event) => actions.onQueryChange(event.target.value)}
data-ui-id="ui.chat.channelList.search"
/>
<Select
variant="filled"
className="[&_[role=combobox]_span]:text-text-neutral-secondary"
value={filter.view}
onValueChange={(value) => actions.onViewChange(value as ChatChannelListView)}
triggerAriaLabel={t("shared.viewMode")}
>
{CHANNEL_LIST_VIEWS.map((view) => (
<Select.Item key={view} value={view}>
{t(`chat.channelList.view.${view}`)}
</Select.Item>
))}
</Select>
{permissions.canViewArchived ? (
<ButtonGroup>
<ChatSwitch checked={filter.showArchived} onCheckedChange={actions.onShowArchivedChange} aria-label={t("chat.channelList.showArchived")} />
<BadgeFeedback farbe="ghost-neutral" size="small">
{t("chat.channelList.showArchived")}
</BadgeFeedback>
</ButtonGroup>
) : null}
</ButtonGroup>
{rows.length === 0 ? (
<EmptyState
outlined
variant={hasActiveFilter ? "no-results" : "default"}
title={t(hasActiveFilter ? vm.data.noResultsHeadlineKey : vm.data.emptyHeadlineKey)}
body={t(hasActiveFilter ? vm.data.noResultsBodyKey : vm.data.emptyBodyKey)}
action={emptyAction}
data-ui-id="ui.chat.channelList.empty"
/>
) : (
<ButtonGroup align="stack" data-ui-id="ui.chat.channelList.rows">
{rows.map((row) => (
<ChannelRow
key={row.id}
row={row}
onOpen={actions.onOpenChannel}
onSetPinned={actions.onSetPinned}
onSetNotificationPreference={actions.onSetNotificationPreference}
isUpdating={updatingPreferenceChannelId === row.id}
/>
))}
</ButtonGroup>
)}
{vm.data.nextCursor && actions.onLoadMore ? (
<ButtonGroup align="center">
<Button variant="tertiary" onClick={() => void actions.onLoadMore?.(vm.data.nextCursor!)}>
{t("shared.loadMore")}
</Button>
</ButtonGroup>
) : null}
{joinErrorKey ? <EmptyState outlined variant="error" title={t(joinErrorKey)} data-ui-id="ui.chat.channelList.discover.error" /> : null}
{preferenceErrorKey ? <EmptyState outlined variant="error" title={t(preferenceErrorKey)} data-ui-id="ui.chat.channelList.preferences.error" /> : null}
{permissions.canDiscover && vm.data.discoverRows.length > 0 ? (
<ButtonGroup align="stack" data-ui-id="ui.chat.channelList.discover">
<BadgeFeedback farbe="ghost-neutral" size="large">
{t(vm.data.discoverHeadlineKey)}
</BadgeFeedback>
{vm.data.discoverRows.map((row) => (
<DiscoverChannelRow key={row.id} row={row} joining={joiningChannelId === row.id} onJoin={actions.onJoinChannel} />
))}
</ButtonGroup>
) : null}
{isMobile && (canShowMessageSearch || canShowMentions || canShowCreateDm || canShowCreateGroup) ? (
<nav
className="border-border-default bg-surface-neutral-primary sticky bottom-0 z-10 flex w-full flex-wrap items-center gap-2 border-t border-solid pt-2 pb-[max(0.75rem,env(safe-area-inset-bottom))]"
aria-label={t("chat.nav.title")}
data-ui-id="ui.chat.mobileNavigation"
>
{canShowMessageSearch ? (
<Button size="large" variant="tertiary" icon={<FeatherSearch />} onClick={() => actions.onOpenMessageSearch?.(vm.data.hrefs.search)}>
{t("chat.messageDiscovery.actions.search")}
</Button>
) : null}
{canShowMentions ? (
<Button size="large" variant="tertiary" icon={<FeatherAtSign />} onClick={() => actions.onOpenMentions?.(vm.data.hrefs.mentions)}>
{t("chat.messageDiscovery.actions.mentions")}
</Button>
) : null}
{canShowCreateDm ? (
<Button size="large" variant="tertiary" icon={<FeatherMessageCircle />} onClick={() => actions.onCreateDm?.(vm.data.hrefs.newDm)}>
{t("chat.channelList.actions.newDm")}
</Button>
) : null}
{canShowCreateGroup ? (
<Button size="large" icon={<FeatherUsers />} onClick={() => actions.onCreateGroup?.(vm.data.hrefs.newChannel)}>
{t("chat.channelList.actions.newGroup")}
</Button>
) : null}
</nav>
) : null}
</ListShell>
);
}
function useChatMobileNavigation(): boolean {
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
const update = () => setIsMobile(window.innerWidth > 0 && window.innerWidth < 768);
update();
window.addEventListener("resize", update);
return () => window.removeEventListener("resize", update);
}, []);
return isMobile;
}
@@ -0,0 +1,155 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { buildChatChannelSettingsVM, type ChatChannelSettingsMemberInput } from "@hivegrid/view-models";
import { ChatChannelSettingsPage, type ChatChannelSettingsActions } from "./ChatChannelSettingsPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join("/")}` : key),
}),
}));
function user(userId: string) {
return {
userId,
displayName: `User ${userId}`,
email: `${userId}@example.test`,
avatar: { imageUrl: null, fallbackLabel: userId.slice(0, 2).toUpperCase() },
};
}
function member(userId: string, role: "admin" | "member" = "member"): ChatChannelSettingsMemberInput {
return { user: user(userId), role };
}
function actions(overrides: Partial<ChatChannelSettingsActions> = {}): ChatChannelSettingsActions {
return {
onBack: vi.fn(),
onRetry: vi.fn(),
onAddMember: vi.fn(),
onChangeRole: vi.fn(),
onRemoveMember: vi.fn(),
onPrivacyChange: vi.fn(),
onLeave: vi.fn(),
onArchive: vi.fn(),
...overrides,
};
}
function groupVm() {
return buildChatChannelSettingsVM({
currentUserId: "viewer",
channel: {
id: "chat_group",
kind: "group",
title: "Montage Nord",
description: "Interne Abstimmung",
isPrivate: false,
isArchived: false,
project: null,
},
members: [member("viewer", "admin"), member("admin-2", "admin"), member("member-1")],
tenantUsers: [user("viewer"), user("admin-2"), user("member-1"), user("candidate")],
permissions: {
canManageMembers: true,
canManageAdmins: true,
canChangePrivacy: true,
canLeave: true,
canManageManualGuests: false,
canArchive: true,
},
});
}
describe("AK-P15b chat channel settings interim UI", () => {
beforeEach(() => vi.clearAllMocks());
it("delegates privacy, membership, role, and leave actions", () => {
const onPrivacyChange = vi.fn();
const onAddMember = vi.fn();
const onChangeRole = vi.fn();
const onRemoveMember = vi.fn();
const onLeave = vi.fn();
const onArchive = vi.fn();
render(
<MemoryRouter>
<ChatChannelSettingsPage
vm={groupVm()}
actions={actions({ onPrivacyChange, onAddMember, onChangeRole, onRemoveMember, onLeave, onArchive })}
/>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("switch", { name: "chat.channelSettings.privacy.private" }));
expect(onPrivacyChange).toHaveBeenCalledWith("private");
fireEvent.click(screen.getByRole("combobox", { name: "chat.channelSettings.candidates.placeholder" }));
fireEvent.click(screen.getByRole("option", { name: "User candidate" }));
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.actions.addMember" }));
expect(onAddMember).toHaveBeenCalledWith("candidate");
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.actions.promote" }));
expect(onChangeRole).toHaveBeenCalledWith("member-1", "admin");
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.actions.removeMember:User member-1" }));
expect(onRemoveMember).toHaveBeenCalledWith("member-1");
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.actions.leave" }));
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.confirm.leave.confirm" }));
expect(onLeave).toHaveBeenCalledOnce();
});
it("renders direct-message settings as explicit read-only state", () => {
const vm = buildChatChannelSettingsVM({
currentUserId: "viewer",
channel: {
id: "chat_dm",
kind: "dm",
title: "Mara Klein",
description: null,
isPrivate: true,
isArchived: false,
project: null,
},
members: [member("viewer"), member("peer")],
tenantUsers: [user("viewer"), user("peer")],
permissions: {
canManageMembers: false,
canManageAdmins: false,
canChangePrivacy: false,
canLeave: false,
canManageManualGuests: false,
canArchive: false,
},
});
render(
<MemoryRouter>
<ChatChannelSettingsPage vm={vm} actions={actions()} />
</MemoryRouter>
);
expect(screen.getByText("chat.channelSettings.dm.readOnly")).toBeInTheDocument();
expect(screen.queryByRole("switch")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "chat.channelSettings.actions.archive" })).not.toBeInTheDocument();
});
it("requires confirmation before archiving a group channel", () => {
const onArchive = vi.fn();
render(
<MemoryRouter>
<ChatChannelSettingsPage vm={groupVm()} actions={actions({ onArchive })} />
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.actions.archive" }));
expect(onArchive).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "chat.channelSettings.confirm.archive.confirm" }));
expect(onArchive).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,311 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Description as DialogDescription, Title as DialogTitle } from "@radix-ui/react-dialog";
import {
FeatherArchive,
FeatherArrowLeft,
FeatherLock,
FeatherLogOut,
FeatherSettings,
FeatherShield,
FeatherTrash2,
FeatherUnlock,
FeatherUserPlus,
} from "@subframe/core";
import type { ChatChannelSettingsMemberRole, ChatChannelSettingsVM } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { Select } from "~/ui/components/Select";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatSwitch } from "./ChatSwitch";
export type ChatChannelSettingsActions = Readonly<{
onBack: () => void;
onRetry: () => void | Promise<void>;
onAddMember: (userId: string) => void | Promise<void>;
onChangeRole: (userId: string, role: ChatChannelSettingsMemberRole) => void | Promise<void>;
onRemoveMember: (userId: string) => void | Promise<void>;
onPrivacyChange: (privacy: "public" | "private") => void | Promise<void>;
onLeave: () => void | Promise<void>;
onArchive: () => void | Promise<void>;
}>;
export type ChatChannelSettingsPageProps = Readonly<{
vm: ChatChannelSettingsVM;
actions: ChatChannelSettingsActions;
busy?: boolean;
actionErrorKey?: string | null;
}>;
export function ChatChannelSettingsPage({ vm, actions, busy = false, actionErrorKey = null }: ChatChannelSettingsPageProps): React.JSX.Element {
const { t } = useTranslation();
const [candidateUserId, setCandidateUserId] = useState("");
const [confirmAction, setConfirmAction] = useState<"archive" | "leave" | null>(null);
const readyData = vm.status === "ready" ? vm.data : null;
const headerActions = (
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={actions.onBack} disabled={busy}>
{t("chat.channelSettings.actions.back")}
</Button>
);
if (vm.status === "idle" || vm.status === "loading") {
return (
<SettingsShell actions={headerActions}>
<LoadingIndicatorSkeleton
variant="card"
role="status"
aria-label={t("chat.channelSettings.members.loading")}
data-ui-id="ui.chat.channelSettings.loading"
/>
</SettingsShell>
);
}
if (vm.status === "error") {
return (
<SettingsShell actions={headerActions}>
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
data-ui-id="ui.chat.channelSettings.error"
/>
</SettingsShell>
);
}
if (vm.status === "empty" || !readyData) {
return (
<SettingsShell actions={headerActions}>
<EmptyState outlined title={t("chat.channelSettings.empty.title")} body={t("chat.channelSettings.empty.body")} />
</SettingsShell>
);
}
const canAddMember = readyData.permissions.canManageGroupMembers || readyData.permissions.canManageManualGuests;
return (
<SettingsShell actions={headerActions}>
{actionErrorKey ? (
<Alert
variant="error"
notDismissible
title={t("chat.channelSettings.errors.actionTitle")}
description={t(actionErrorKey)}
data-ui-id="ui.chat.channelSettings.actionError"
/>
) : null}
<Card size="large" data-ui-id="ui.chat.channelSettings.summary">
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{readyData.channel.title}</span>
{readyData.channel.description ? (
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{readyData.channel.description}</span>
) : null}
</ButtonGroup>
<BadgeFeedback farbe={readyData.channel.isArchived ? "subtle-neutral" : "subtle-brand-primary"}>
{t(`chat.channel.kind.${readyData.channel.kind}`)}
</BadgeFeedback>
</ButtonGroup>
</Card>
{readyData.infoKey ? <Alert variant="information" notDismissible title={t(readyData.infoKey)} /> : null}
{readyData.channel.kind === "group" ? (
<Card size="large" data-ui-id="ui.chat.channelSettings.privacy">
<ButtonGroup align="space-between">
<ButtonGroup>
{readyData.channel.privacy === "private" ? <FeatherLock aria-hidden="true" /> : <FeatherUnlock aria-hidden="true" />}
<ButtonGroup align="stack">
<strong>{t("chat.channelSettings.privacy.title")}</strong>
<span>{t(`chat.channelSettings.privacy.${readyData.channel.privacy}Help`)}</span>
</ButtonGroup>
</ButtonGroup>
<ChatSwitch
checked={readyData.channel.privacy === "private"}
disabled={busy || !readyData.permissions.canChangeGroupPrivacy}
onCheckedChange={(checked) => void actions.onPrivacyChange(checked ? "private" : "public")}
aria-label={t("chat.channelSettings.privacy.private")}
data-ui-id="ui.chat.channelSettings.privacyToggle"
/>
</ButtonGroup>
</Card>
) : null}
<Card size="large" data-ui-id="ui.chat.channelSettings.members">
<ButtonGroup align="space-between">
<ButtonGroup align="stack">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("chat.channelSettings.members.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("chat.channelSettings.members.count", { count: readyData.members.length })}
</span>
</ButtonGroup>
<FeatherShield aria-hidden="true" />
</ButtonGroup>
{canAddMember && readyData.candidateUsers.length > 0 ? (
<ButtonGroup align="start" data-ui-id="ui.chat.channelSettings.addMember">
<Select
className="min-w-64"
value={candidateUserId}
onValueChange={setCandidateUserId}
placeholder={t("chat.channelSettings.candidates.placeholder")}
triggerAriaLabel={t("chat.channelSettings.candidates.placeholder")}
>
{readyData.candidateUsers.map((candidate) => (
<Select.Item key={candidate.userId} value={candidate.userId}>
{candidate.displayName}
</Select.Item>
))}
</Select>
<Button
variant="secondary"
icon={<FeatherUserPlus />}
disabled={!candidateUserId || busy}
onClick={() => {
if (!candidateUserId) return;
void actions.onAddMember(candidateUserId);
}}
data-ui-id="ui.chat.channelSettings.addMemberSubmit"
>
{t("chat.channelSettings.actions.addMember")}
</Button>
</ButtonGroup>
) : null}
{readyData.members.length === 0 ? (
<EmptyState outlined title={t(readyData.keys.membersEmptyKey)} />
) : (
readyData.members.map((member) => (
<Card key={member.userId} size="small" variant={member.isCurrentUser ? "information" : "default"}>
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar image={member.avatar.imageUrl ?? undefined} size="small">
{member.avatar.fallbackLabel}
</Avatar>
<ButtonGroup align="stack">
<strong>{member.displayName}</strong>
<span>{member.email}</span>
</ButtonGroup>
</ButtonGroup>
<ButtonGroup>
<BadgeFeedback farbe={member.role === "admin" ? "subtle-brand-primary" : "subtle-neutral"} size="small">
{t(member.roleLabelKey)}
</BadgeFeedback>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t(member.sourceLabelKey)}
</BadgeFeedback>
{member.actions.canPromoteToAdmin ? (
<Button size="small" variant="tertiary" disabled={busy} onClick={() => void actions.onChangeRole(member.userId, "admin")}>
{t("chat.channelSettings.actions.promote")}
</Button>
) : null}
{member.actions.canDemoteFromAdmin ? (
<Button size="small" variant="tertiary" disabled={busy} onClick={() => void actions.onChangeRole(member.userId, "member")}>
{t("chat.channelSettings.actions.demote")}
</Button>
) : null}
{member.actions.canRemoveFromGroup || member.actions.canRemoveManualGuest ? (
<Button
size="small"
variant="destructive"
icon={<FeatherTrash2 />}
disabled={busy}
onClick={() => void actions.onRemoveMember(member.userId)}
aria-label={t("chat.channelSettings.actions.removeMember", { member: member.displayName })}
/>
) : null}
</ButtonGroup>
</ButtonGroup>
</Card>
))
)}
</Card>
{readyData.leave.canLeave || readyData.leave.blockedReasonKey || readyData.permissions.canArchive ? (
<Card size="large" data-ui-id="ui.chat.channelSettings.channelActions">
<ButtonGroup align="stack">
<span className="text-heading-2 font-heading-2 text-text-neutral-primary">{t("chat.channelSettings.channelActions.title")}</span>
{readyData.leave.blockedReasonKey ? <Alert variant="warning" notDismissible title={t(readyData.leave.blockedReasonKey)} /> : null}
<ButtonGroup>
{readyData.leave.canLeave ? (
<Button variant="secondary" icon={<FeatherLogOut />} disabled={busy} onClick={() => setConfirmAction("leave")}>
{t("chat.channelSettings.actions.leave")}
</Button>
) : null}
{readyData.permissions.canArchive ? (
<Button variant="destructive" icon={<FeatherArchive />} disabled={busy} onClick={() => setConfirmAction("archive")}>
{t("chat.channelSettings.actions.archive")}
</Button>
) : null}
</ButtonGroup>
</ButtonGroup>
</Card>
) : null}
<Dialog open={confirmAction !== null} onOpenChange={(open: boolean) => (open ? undefined : setConfirmAction(null))}>
<Dialog.Content
className="w-[420px] max-w-[90vw] p-4"
aria-label={t(`chat.channelSettings.confirm.${confirmAction ?? "leave"}.title`)}
data-ui-id="ui.chat.channelSettings.confirm"
>
<ButtonGroup align="stack">
<DialogTitle className="text-heading-0 font-heading-0 text-text-neutral-primary">
{t(`chat.channelSettings.confirm.${confirmAction ?? "leave"}.title`)}
</DialogTitle>
<DialogDescription className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t(`chat.channelSettings.confirm.${confirmAction ?? "leave"}.body`)}
</DialogDescription>
</ButtonGroup>
<ButtonGroup align="end">
<Button variant="tertiary" disabled={busy} onClick={() => setConfirmAction(null)}>
{t("shared.cancel")}
</Button>
<Button
variant="destructive"
loading={busy}
onClick={() => {
if (confirmAction === "archive") void actions.onArchive();
if (confirmAction === "leave") void actions.onLeave();
}}
>
{t(`chat.channelSettings.confirm.${confirmAction ?? "leave"}.confirm`)}
</Button>
</ButtonGroup>
</Dialog.Content>
</Dialog>
</SettingsShell>
);
}
function SettingsShell({ children, actions }: { readonly children: React.ReactNode; readonly actions?: React.ReactNode }): React.JSX.Element {
const { t } = useTranslation();
return (
<PageShell uiId="ui.chat.channelSettings" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherSettings className={PAGE_HEADER_ICON_CLASS} />}
title={t("chat.channelSettings.title")}
subtitle={t("chat.channelSettings.subtitle")}
actions={actions}
uiId="ui.chat.channelSettings.header"
/>
<PageBody>{children}</PageBody>
</PageShell>
);
}
@@ -0,0 +1,73 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { createChatDetailInterimFixturePage, createChatIndexInterimFixturePage, createMockRegistry } from "@hivegrid/ui-mock";
import { ChatChannelDetailPage } from "./ChatChannelDetailPage";
import { ChatChannelListPage } from "./ChatChannelListPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({ date: (value: string) => value, number: (value: number) => String(value), relativeDate: (value: string) => value }),
}));
describe("AK-P15b UI hot-swap route/action contract", () => {
it("runs the real index and detail action contracts with ui-mock replacement VMs", () => {
const indexPage = createChatIndexInterimFixturePage();
const detailPage = createChatDetailInterimFixturePage();
const registry = createMockRegistry([indexPage, detailPage]);
const index = registry.get(indexPage.route);
const detail = registry.get(detailPage.route);
if (index?.state.status !== "ready" || detail?.state.status !== "ready") throw new Error("chat.errors.integrityFailure");
const onOpenChannel = vi.fn();
const indexView = render(
<MemoryRouter>
<ChatChannelListPage
vm={index.state.data.viewModel}
actions={{
onOpenChannel,
onQueryChange: vi.fn(),
onViewChange: vi.fn(),
onShowArchivedChange: vi.fn(),
onRetry: vi.fn(),
}}
/>
</MemoryRouter>
);
const firstChannel = index.state.data.viewModel.status === "ready" ? index.state.data.viewModel.data.rows[0] : null;
if (!firstChannel) throw new Error("chat.errors.integrityFailure");
const openButton = indexView.container.querySelector('[data-ui-id="ui.chat.channelList.open"]');
expect(openButton).toBeInstanceOf(HTMLButtonElement);
fireEvent.click(openButton!);
expect(onOpenChannel).toHaveBeenCalledWith(firstChannel.id, firstChannel.detailHref);
indexView.unmount();
const onSend = vi.fn();
render(
<MemoryRouter>
<ChatChannelDetailPage
vm={detail.state.data.viewModel}
draft="Hot swap reply"
actions={{
onBack: vi.fn(),
onDraftChange: vi.fn(),
onSend,
onRetryMessage: vi.fn(),
onDiscardMessage: vi.fn(),
onMessageVisibilityChange: vi.fn(),
onRetryConnection: vi.fn(),
onLoadOlder: vi.fn(),
onOpenSettings: vi.fn(),
}}
/>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "shared.send" }));
expect(onSend).toHaveBeenCalledWith("Hot swap reply");
});
});
@@ -0,0 +1,894 @@
// @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();
});
});
@@ -0,0 +1,69 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { ChatMentionAutocomplete } from "./ChatMentionAutocomplete";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
describe("ChatMentionAutocomplete", () => {
it("renders grouped accessible options and delegates pointer selection", () => {
const onSelect = vi.fn();
const onActiveIndexChange = vi.fn();
render(
<ChatMentionAutocomplete
open
loading={false}
activeIndex={1}
listboxId="mention-list"
vm={{
total: 2,
groups: [
{
kind: "user",
labelKey: "chat.mention.groups.users",
items: [
{ kind: "user", id: "user_1", label: "Ada", detail: "ada@example.test", href: null },
{ kind: "user", id: "user_2", label: "Mara", detail: null, href: null },
],
},
],
}}
actions={{ onSelect, onActiveIndexChange }}
/>
);
expect(screen.getByRole("listbox", { name: "chat.mention.label" })).toBeInTheDocument();
expect(screen.getAllByRole("option")[1]).toHaveAttribute("aria-selected", "true");
fireEvent.mouseEnter(screen.getAllByRole("option")[0]!);
expect(onActiveIndexChange).toHaveBeenCalledWith(0);
fireEvent.click(screen.getByRole("option", { name: /Ada/ }));
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ kind: "user", id: "user_1" }));
});
it("announces loading and empty states", () => {
const { rerender } = render(
<ChatMentionAutocomplete
open
loading
activeIndex={0}
listboxId="mention-list"
vm={null}
actions={{ onSelect: vi.fn(), onActiveIndexChange: vi.fn() }}
/>
);
expect(screen.getByLabelText("chat.mention.loading")).toBeInTheDocument();
rerender(
<ChatMentionAutocomplete
open
loading={false}
activeIndex={0}
listboxId="mention-list"
vm={{ total: 0, groups: [] }}
actions={{ onSelect: vi.fn(), onActiveIndexChange: vi.fn() }}
/>
);
expect(screen.getByText("chat.mention.empty")).toBeInTheDocument();
});
});
@@ -0,0 +1,85 @@
import { useTranslation } from "react-i18next";
import type { ChatMentionAutocompleteVM, ChatMentionSuggestionVM } from "@hivegrid/view-models";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
export function ChatMentionAutocomplete({
vm,
open,
loading,
activeIndex,
listboxId,
actions,
}: {
readonly vm: ChatMentionAutocompleteVM | null;
readonly open: boolean;
readonly loading: boolean;
readonly activeIndex: number;
readonly listboxId: string;
readonly actions: {
readonly onSelect: (suggestion: ChatMentionSuggestionVM) => void;
readonly onActiveIndexChange: (index: number) => void;
};
}): React.JSX.Element | null {
const { t } = useTranslation();
if (!open) return null;
const items = vm?.groups.flatMap((group) => group.items) ?? [];
let itemOffset = 0;
return (
<Card size="small" contentOverflow="wrap" data-ui-id="ui.chat.mentionAutocomplete">
<span id={`${listboxId}-help`} className="sr-only">
{t("chat.mention.help")}
</span>
<div id={listboxId} role="listbox" aria-label={t("chat.mention.label")} aria-describedby={`${listboxId}-help`} aria-busy={loading}>
{loading ? (
<LoadingIndicatorSkeleton variant="list" aria-label={t("chat.mention.loading")} />
) : items.length === 0 ? (
<EmptyState outlined title={t("chat.mention.empty")} />
) : (
<ButtonGroup align="stack">
{vm?.groups.map((group) => {
const startIndex = itemOffset;
itemOffset += group.items.length;
return (
<div key={group.kind} role="group" aria-labelledby={`${listboxId}-${group.kind}`} className="w-full">
<span id={`${listboxId}-${group.kind}`} className="text-caption-bold font-caption-bold text-text-neutral-secondary">
{t(group.labelKey)}
</span>
<ButtonGroup align="stack">
{group.items.map((item, index) => {
const absoluteIndex = startIndex + index;
const selected = absoluteIndex === activeIndex;
return (
<Button
key={`${item.kind}:${item.id}`}
id={`${listboxId}-option-${absoluteIndex}`}
role="option"
tabIndex={-1}
aria-selected={selected}
variant={selected ? "secondary" : "ghost"}
onMouseEnter={() => actions.onActiveIndexChange(absoluteIndex)}
onMouseDown={(event) => event.preventDefault()}
onClick={() => actions.onSelect(item)}
>
<span className="flex min-w-0 flex-1 items-center justify-between gap-3 text-left">
<span className="truncate">{item.label}</span>
{item.detail ? <span className="text-text-neutral-secondary truncate">{item.detail}</span> : null}
</span>
</Button>
);
})}
</ButtonGroup>
</div>
);
})}
</ButtonGroup>
)}
</div>
</Card>
);
}
@@ -0,0 +1,86 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { ChatMessageDiscoveryPage, type ChatMessageDiscoveryActions } from "./ChatMessageDiscoveryPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${JSON.stringify(values)}` : key),
}),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({ date: (value: string) => `date:${value}` }),
}));
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
function actions(): ChatMessageDiscoveryActions {
return {
onBack: vi.fn(),
onOpenResult: vi.fn(),
onQueryChange: vi.fn(),
onSwitchMode: vi.fn(),
onLoadMore: vi.fn(),
onRetry: vi.fn(),
};
}
describe("ChatMessageDiscoveryPage", () => {
it("renders search results and exposes keyboard-safe actions", () => {
const callbacks = actions();
const vm = buildChatMessageDiscoveryVM({
mode: "search",
query: "heat",
hrefs,
nextCursor: "cursor_1",
rows: [
{
id: "message_1",
chatId: "chat_1",
channelKind: "group",
channelTitle: "Montage Nord",
authorLabel: "Ada Lovelace",
authorAvatar: { imageUrl: null, fallbackLabel: "AL" },
body: "Heat pump update",
createdAtIso: "2026-07-16T11:00:00.000Z",
detailHref: "/demo/chat/chat_1?message=message_1",
isThreadReply: true,
},
],
});
render(<ChatMessageDiscoveryPage vm={vm} actions={callbacks} />);
expect(screen.getByRole("heading", { name: "chat.messageDiscovery.search.title" })).toBeTruthy();
fireEvent.change(screen.getByRole("searchbox"), { target: { value: "pump" } });
expect(callbacks.onQueryChange).toHaveBeenCalledWith("pump");
const result = screen.getByRole("link");
fireEvent.keyDown(result, { key: "Enter" });
expect(callbacks.onOpenResult).toHaveBeenCalledWith(expect.objectContaining({ id: "message_1" }));
fireEvent.click(screen.getByRole("button", { name: "shared.loadMore" }));
expect(callbacks.onLoadMore).toHaveBeenCalledWith("cursor_1");
fireEvent.click(screen.getByRole("button", { name: "chat.messageDiscovery.actions.mentions" }));
expect(callbacks.onSwitchMode).toHaveBeenCalledWith("/demo/chat/mentions");
});
it("shows a distinct prompt before searching and a no-results state after a query", () => {
const callbacks = actions();
const { rerender } = render(
<ChatMessageDiscoveryPage vm={buildChatMessageDiscoveryVM({ mode: "search", query: "", rows: [], hrefs })} actions={callbacks} />
);
expect(screen.getByText("chat.messageDiscovery.search.emptyTitle")).toBeTruthy();
rerender(<ChatMessageDiscoveryPage vm={buildChatMessageDiscoveryVM({ mode: "search", query: "missing", rows: [], hrefs })} actions={callbacks} />);
expect(screen.getByText("chat.messageDiscovery.search.noResultsTitle")).toBeTruthy();
});
it("renders the mentions aggregate without a search field", () => {
render(<ChatMessageDiscoveryPage vm={buildChatMessageDiscoveryVM({ mode: "mentions", rows: [], hrefs })} actions={actions()} />);
expect(screen.getByRole("heading", { name: "chat.messageDiscovery.mentions.title" })).toBeTruthy();
expect(screen.queryByRole("searchbox")).toBeNull();
expect(screen.getByText("chat.messageDiscovery.mentions.emptyTitle")).toBeTruthy();
});
});
@@ -0,0 +1,189 @@
import { useTranslation } from "react-i18next";
import { FeatherAtSign, FeatherChevronLeft, FeatherMessageSquare, FeatherSearch } from "@subframe/core";
import type { ChatMessageDiscoveryRowVM, ChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { SearchInput } from "~/ui/components/SearchInput";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
export type ChatMessageDiscoveryActions = Readonly<{
onBack: (href: string) => void;
onOpenResult: (row: ChatMessageDiscoveryRowVM) => void;
onQueryChange: (query: string) => void;
onSwitchMode: (href: string) => void;
onLoadMore?: (cursor: string) => void | Promise<void>;
onRetry: () => void | Promise<void>;
}>;
export function ChatMessageDiscoveryPage({ vm, actions }: { readonly vm: ChatMessageDiscoveryVM; readonly actions: ChatMessageDiscoveryActions }) {
const { t } = useTranslation();
if (vm.status === "idle" || vm.status === "loading") {
return (
<DiscoveryShell title={t("chat.nav.title")}>
<LoadingIndicatorSkeleton variant="list" role="status" aria-label={t("shared.loading")} />
</DiscoveryShell>
);
}
if (vm.status === "error") {
return (
<DiscoveryShell title={t("chat.nav.title")}>
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={
<Button variant="tertiary" onClick={() => void actions.onRetry()}>
{t("shared.retry")}
</Button>
}
/>
</DiscoveryShell>
);
}
if (vm.status === "empty" || !vm.data) {
return (
<DiscoveryShell title={t("chat.nav.title")}>
<EmptyState outlined title={t("chat.messageDiscovery.mentions.emptyTitle")} body={t("chat.messageDiscovery.mentions.emptyBody")} />
</DiscoveryShell>
);
}
const data = vm.data;
const isEmptySearch = data.mode === "search" && data.query.length === 0;
const emptyTitleKey = isEmptySearch ? data.keys.emptyTitleKey : data.keys.noResultsTitleKey;
const emptyBodyKey = isEmptySearch ? data.keys.emptyBodyKey : data.keys.noResultsBodyKey;
const switchHref = data.mode === "search" ? data.hrefs.mentions : data.hrefs.search;
const switchLabelKey = data.mode === "search" ? "chat.messageDiscovery.actions.mentions" : "chat.messageDiscovery.actions.search";
return (
<DiscoveryShell
title={t(data.keys.titleKey)}
subtitle={t(data.keys.subtitleKey)}
icon={data.mode === "search" ? <FeatherSearch className={PAGE_HEADER_ICON_CLASS} /> : <FeatherAtSign className={PAGE_HEADER_ICON_CLASS} />}
actions={
<ButtonGroup align="end">
<Button variant="tertiary" onClick={() => actions.onSwitchMode(switchHref)}>
{t(switchLabelKey)}
</Button>
<Button variant="tertiary" icon={<FeatherChevronLeft />} onClick={() => actions.onBack(data.hrefs.chat)}>
{t("chat.messageDiscovery.actions.back")}
</Button>
</ButtonGroup>
}
>
{data.mode === "search" ? (
<SearchInput
fillContainer
hideShortcut
autoFocus
placeholder={t("chat.messageDiscovery.search.placeholder")}
value={data.query}
onChange={(event) => actions.onQueryChange(event.target.value)}
data-ui-id="ui.chat.messageDiscovery.search"
/>
) : null}
{data.rows.length === 0 ? (
<EmptyState
outlined
variant={!isEmptySearch && data.mode === "search" ? "no-results" : "default"}
title={t(emptyTitleKey)}
body={t(emptyBodyKey)}
data-ui-id="ui.chat.messageDiscovery.empty"
/>
) : (
<ButtonGroup align="stack" data-ui-id="ui.chat.messageDiscovery.results">
{data.rows.map((row) => (
<DiscoveryRow key={row.id} row={row} onOpen={actions.onOpenResult} />
))}
</ButtonGroup>
)}
{data.nextCursor && actions.onLoadMore ? (
<ButtonGroup align="center">
<Button variant="tertiary" onClick={() => void actions.onLoadMore?.(data.nextCursor!)}>
{t("shared.loadMore")}
</Button>
</ButtonGroup>
) : null}
</DiscoveryShell>
);
}
function DiscoveryRow({ row, onOpen }: { readonly row: ChatMessageDiscoveryRowVM; readonly onOpen: (row: ChatMessageDiscoveryRowVM) => void }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<Card
role="link"
tabIndex={0}
aria-label={t("chat.messageDiscovery.result.openAria", { channel: row.channelTitle, author: row.authorLabel })}
onClick={() => onOpen(row)}
onKeyDown={(event) => {
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
onOpen(row);
}}
data-message-id={row.id}
>
<ButtonGroup align="space-between">
<ButtonGroup>
<Avatar size="small" image={row.authorAvatar.imageUrl ?? undefined}>
{row.authorAvatar.fallbackLabel}
</Avatar>
<BadgeFeedback farbe="ghost-neutral" size="large">
{row.authorLabel}
</BadgeFeedback>
<BadgeFeedback farbe="subtle-neutral" size="small">
{row.channelTitle}
</BadgeFeedback>
<BadgeFeedback farbe="ghost-neutral" size="small">
{t(row.channelKindLabelKey)}
</BadgeFeedback>
{row.isThreadReply ? (
<BadgeFeedback farbe="ghost-neutral" size="small">
{t("chat.messageDiscovery.result.threadReply")}
</BadgeFeedback>
) : null}
</ButtonGroup>
<BadgeFeedback farbe="ghost-neutral" size="small">
{formatters.date(row.createdAtIso, { dateStyle: "medium", timeStyle: "short" })}
</BadgeFeedback>
</ButtonGroup>
<ButtonGroup>
<span>{row.snippet}</span>
</ButtonGroup>
</Card>
);
}
function DiscoveryShell({
title,
subtitle,
icon = <FeatherMessageSquare className={PAGE_HEADER_ICON_CLASS} />,
actions,
children,
}: {
readonly title: string;
readonly subtitle?: string;
readonly icon?: React.ReactNode;
readonly actions?: React.ReactNode;
readonly children: React.ReactNode;
}) {
return (
<PageShell uiId="ui.chat.messageDiscovery" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader icon={icon} title={title} subtitle={subtitle} actions={actions} />
<PageBody>{children}</PageBody>
</PageShell>
);
}
@@ -0,0 +1,61 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { buildChatChannelListVM } from "@hivegrid/view-models";
import { ChatChannelListPage } from "./ChatChannelListPage";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({ date: (value: string) => value, number: (value: number) => String(value) }),
}));
describe("chat message discovery reachability", () => {
it("opens cross-channel search and mentions from the member chat index", () => {
const openSearch = vi.fn();
const openMentions = vi.fn();
const vm = buildChatChannelListVM({
rows: [],
discoverRows: [],
filter: { query: "", view: "all", showArchived: false },
permissions: {
canWrite: true,
canCreateGroup: false,
canCreateDm: false,
canDiscover: true,
canViewMentions: true,
canSearch: true,
canViewArchived: true,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new",
newDm: "/demo/chat/new?mode=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat/archived",
},
totals: { unread: 0, mentions: 0 },
});
render(
<ChatChannelListPage
vm={vm}
actions={{
onOpenChannel: vi.fn(),
onQueryChange: vi.fn(),
onViewChange: vi.fn(),
onShowArchivedChange: vi.fn(),
onRetry: vi.fn(),
onOpenMessageSearch: openSearch,
onOpenMentions: openMentions,
}}
/>
);
fireEvent.click(screen.getByRole("button", { name: "chat.messageDiscovery.actions.search" }));
fireEvent.click(screen.getByRole("button", { name: "chat.messageDiscovery.actions.mentions" }));
expect(openSearch).toHaveBeenCalledWith("/demo/chat/search");
expect(openMentions).toHaveBeenCalledWith("/demo/chat/mentions");
});
});
@@ -0,0 +1,291 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router";
import { Description as DialogDescription, Title as DialogTitle } from "@radix-ui/react-dialog";
import { FeatherEdit3, FeatherFile, FeatherImage, FeatherMessageSquare, FeatherPin, FeatherSmile, FeatherTrash2 } from "@subframe/core";
import type { ChatAttachmentVM, ChatFeatureMessageVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { renderSanitizedChatMarkdown } from "~/utils/html-sanitizer";
import { Alert } from "~/ui/components/Alert";
import { Avatar } from "~/ui/components/Avatar";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { Dialog } from "~/ui/components/Dialog";
import { TextArea } from "~/ui/components/TextArea";
const QUICK_REACTIONS = ["👍", "❤️", "🎉"] as const;
function attachmentIcon(attachment: ChatAttachmentVM): React.JSX.Element {
if (attachment.kind === "image") return <FeatherImage />;
if (attachment.kind === "voice") return <FeatherMessageSquare />;
return <FeatherFile />;
}
function ThreadMessageAttachments({ attachments }: { readonly attachments: readonly ChatAttachmentVM[] }): React.JSX.Element | null {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
if (attachments.length === 0) return null;
return (
<ButtonGroup align="stack" data-ui-id="ui.chat.messageFeature.attachments">
{attachments.map((attachment) =>
attachment.scanStatus === "blocked" ? (
<Alert key={attachment.id} variant="error" title={t("chat.attachments.blocked")} notDismissible />
) : attachment.scanStatus === "pending" ? (
<Alert key={attachment.id} variant="neutral" title={attachment.fileName} description={t("chat.attachments.pending")} notDismissible />
) : (
<Card key={attachment.id} size="small" contentOverflow="wrap">
{attachment.kind === "image" && attachment.previewHref ? (
<a href={attachment.downloadHref} target="_blank" rel="noreferrer">
<img
src={attachment.previewHref}
alt={attachment.altText ?? attachment.fileName}
className="max-h-64 w-full rounded-md object-contain"
loading="lazy"
/>
</a>
) : null}
{attachment.kind === "voice" ? (
// Voice Notes intentionally have no transcript in AK-P15b v1.
// eslint-disable-next-line jsx-a11y/media-has-caption
<audio controls preload="metadata" src={attachment.downloadHref} className="w-full">
<a href={attachment.downloadHref}>{attachment.fileName}</a>
</audio>
) : null}
<a href={attachment.downloadHref} target="_blank" rel="noreferrer">
<ButtonGroup>
<BadgeFeedback farbe="ghost-neutral">{attachmentIcon(attachment)}</BadgeFeedback>
<span>{attachment.fileName}</span>
<BadgeFeedback farbe="ghost-neutral" size="small">
{formatters.number(attachment.sizeBytes, { style: "unit", unit: "byte", unitDisplay: "narrow" })}
</BadgeFeedback>
</ButtonGroup>
</a>
</Card>
)
)}
</ButtonGroup>
);
}
export function ChatMessageFeatureCard({
message,
featureErrorKey,
actions,
}: {
readonly message: ChatFeatureMessageVM;
readonly featureErrorKey?: string;
readonly actions: {
readonly onToggleReaction: (messageId: string, emoji: string, active: boolean) => void;
readonly onTogglePin: (messageId: string, pinned: boolean) => void;
readonly onEditMessage?: (messageId: string, body: string) => void;
readonly onDeleteMessage?: (messageId: string) => void;
readonly onRetryFeature?: (messageId: string) => void;
};
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [editOpen, setEditOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [editDraft, setEditDraft] = useState(message.bodyMarkdown ?? "");
const renderedBody = message.bodyMarkdown ? replaceMentionTokensWithLabels(message.bodyMarkdown, message.mentions) : null;
return (
<section id={`message-${message.id}`} tabIndex={-1} className="scroll-mt-24 rounded-lg outline-none target:ring-2 target:ring-brand-primary">
<Card data-message-id={message.id} data-ui-id="ui.chat.messageFeature.message">
<ButtonGroup align="stack">
<ButtonGroup>
<Avatar size="small" image={message.authorAvatarUrl ?? undefined}>
{initials(message.authorLabel)}
</Avatar>
<span>{message.authorLabel}</span>
<BadgeFeedback farbe="ghost-neutral" size="small">
{formatters.date(message.createdAtIso, { hour: "2-digit", minute: "2-digit" })}
</BadgeFeedback>
{message.pinned ? (
<BadgeFeedback farbe="subtle-information" size="small">
<FeatherPin aria-hidden="true" /> {t("chat.message.pinned")}
</BadgeFeedback>
) : null}
</ButtonGroup>
{message.deleted ? (
<Alert variant="neutral" title={t("chat.message.deleted")} notDismissible />
) : renderedBody ? (
<div data-ui-id="ui.chat.messageFeature.body" dangerouslySetInnerHTML={{ __html: renderSanitizedChatMarkdown(renderedBody) }} />
) : null}
{!message.deleted && message.mentions.length > 0 ? (
<ButtonGroup aria-label={t("chat.mention.label")}>
{message.mentions.map((mention) =>
mention.href ? (
<Link key={`${mention.kind}:${mention.id}`} to={mention.href} aria-label={mention.label}>
<BadgeFeedback farbe="subtle-information">@{mention.label}</BadgeFeedback>
</Link>
) : (
<BadgeFeedback key={`${mention.kind}:${mention.id}`} farbe="subtle-information">
@{mention.label}
</BadgeFeedback>
)
)}
</ButtonGroup>
) : null}
{!message.deleted ? <ThreadMessageAttachments attachments={message.attachments} /> : null}
{featureErrorKey ? (
<ButtonGroup align="stack" data-ui-id="ui.chat.messageFeature.error">
<Alert variant="error" title={t(featureErrorKey)} notDismissible />
{actions.onRetryFeature ? (
<Button variant="tertiary" size="small" onClick={() => actions.onRetryFeature?.(message.id)}>
{t("shared.retry")}
</Button>
) : null}
</ButtonGroup>
) : null}
{message.reactions.length > 0 ? (
<ButtonGroup aria-label={t("chat.reaction.summaryAria")}>
{message.reactions.map((reaction) => (
<Button
key={reaction.emoji}
variant={reaction.reactedByViewer ? "secondary" : "tertiary"}
size="small"
onClick={() => actions.onToggleReaction(message.id, reaction.emoji, !reaction.reactedByViewer)}
disabled={!message.canReact}
>
{reaction.emoji} {reaction.count}
</Button>
))}
</ButtonGroup>
) : null}
{message.canReact || message.canPin || message.canEdit || message.canDelete ? (
<ButtonGroup>
{message.canReact
? QUICK_REACTIONS.map((emoji) => {
const active = message.reactions.some((reaction) => reaction.emoji === emoji && reaction.reactedByViewer);
return (
<Button
key={emoji}
variant="ghost"
size="small"
icon={<FeatherSmile />}
aria-label={t(active ? "chat.reaction.remove" : "chat.reaction.add", { emoji })}
onClick={() => actions.onToggleReaction(message.id, emoji, !active)}
>
{emoji}
</Button>
);
})
: null}
{message.canPin ? (
<Button
variant="tertiary"
size="small"
icon={<FeatherPin />}
onClick={() => actions.onTogglePin(message.id, !message.pinned)}
>
{t(message.pinned ? "chat.pinned.unpin" : "chat.pinned.pin")}
</Button>
) : null}
{message.canEdit && actions.onEditMessage ? (
<Button
variant="tertiary"
size="small"
icon={<FeatherEdit3 />}
onClick={() => {
setEditDraft(message.bodyMarkdown ?? "");
setEditOpen(true);
}}
>
{t("chat.message.edit")}
</Button>
) : null}
{message.canDelete && actions.onDeleteMessage ? (
<Button variant="tertiary" size="small" icon={<FeatherTrash2 />} onClick={() => setDeleteOpen(true)}>
{t("chat.message.delete")}
</Button>
) : null}
</ButtonGroup>
) : null}
</ButtonGroup>
</Card>
<Dialog open={editOpen} onOpenChange={(open: boolean) => setEditOpen(open)}>
<Dialog.Content className="w-[520px] max-w-[90vw] p-4">
<ButtonGroup align="stack">
<DialogTitle className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("chat.message.editTitle")}</DialogTitle>
<TextArea label={t("chat.message.editTitle")} showLabel={false}>
<TextArea.Input value={editDraft} placeholder={t("chat.message.editPlaceholder")} onChange={(event) => setEditDraft(event.target.value)} />
</TextArea>
<ButtonGroup>
<Button variant="tertiary" onClick={() => setEditOpen(false)}>{t("chat.message.cancel")}</Button>
<Button
variant="primary"
onClick={() => {
actions.onEditMessage?.(message.id, editDraft);
setEditOpen(false);
}}
disabled={editDraft.trim().length === 0 || editDraft === message.bodyMarkdown}
>
{t("chat.message.save")}
</Button>
</ButtonGroup>
</ButtonGroup>
</Dialog.Content>
</Dialog>
<Dialog open={deleteOpen} onOpenChange={(open: boolean) => setDeleteOpen(open)}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-4">
<ButtonGroup align="stack">
<DialogTitle className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("chat.message.deleteConfirmTitle")}</DialogTitle>
<DialogDescription className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("chat.message.deleteConfirmBody")}
</DialogDescription>
<ButtonGroup>
<Button variant="tertiary" onClick={() => setDeleteOpen(false)}>{t("chat.message.cancel")}</Button>
<Button
variant="destructive"
onClick={() => {
actions.onDeleteMessage?.(message.id);
setDeleteOpen(false);
}}
>
{t("chat.message.delete")}
</Button>
</ButtonGroup>
</ButtonGroup>
</Dialog.Content>
</Dialog>
</section>
);
}
function replaceMentionTokensWithLabels(
markdown: string,
mentions: ChatFeatureMessageVM["mentions"]
): string {
const labels = new Map(mentions.map((mention) => [`${mention.kind}\u0000${mention.id}`, mention.label]));
return markdown.replace(/<@(user|project|contact|company):([A-Za-z0-9._-]{1,500})>/gu, (_token, kind: string, id: string) => {
const label = labels.get(`${kind}\u0000${id}`) ?? "@";
return `@${escapeMarkdownText(label)}`;
});
}
function escapeMarkdownText(value: string): string {
return value.replace(/([\\`*_{}\[\]()<>#+\-.!|])/gu, "\\$1");
}
function initials(label: string): string {
return (
label
.trim()
.split(/\s+/)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("") || "?"
);
}
@@ -0,0 +1,185 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { buildChatPinnedMessagesVM, buildChatThreadVM } from "@hivegrid/view-models";
import { ChatPinnedMessagesPage } from "./ChatPinnedMessagesPage";
import { ChatThreadPage } from "./ChatThreadPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => (values ? `${key}:${Object.values(values).join("/")}` : key),
}),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({ date: (value: string) => `date:${value}`, number: (value: number) => String(value) }),
}));
const message = {
id: "message_1",
authorLabel: "Mara Klein",
authorAvatarUrl: null,
bodyMarkdown: "Bitte **prüfen**",
createdAtIso: "2026-07-16T08:00:00.000Z",
deleted: false,
mentions: [],
attachments: [
{
id: "message_1:file_1",
fileId: "file_1",
kind: "file",
fileName: "montageplan.pdf",
mimeType: "application/pdf",
sizeBytes: 1024,
downloadHref: "/demo/files/file_1/content/original",
previewHref: null,
altText: null,
durationSeconds: null,
scanStatus: "clean",
},
],
reactions: [{ emoji: "👍", count: 2, reactedByViewer: true }],
pinned: true,
canReact: true,
canPin: true,
canEdit: true,
canDelete: true,
} as const;
describe("AK-P15b thread and pinned interim screens", () => {
it("sends a reply and delegates reaction and pin actions", () => {
const onDraftChange = vi.fn();
const onSendReply = vi.fn();
const onToggleReaction = vi.fn();
const onTogglePin = vi.fn();
const onRetryFeature = vi.fn();
const onEditMessage = vi.fn();
const onDeleteMessage = vi.fn();
const vm = buildChatThreadVM({
chatId: "chat_1",
threadId: "message_1",
channelTitle: "Montage Nord",
backHref: "/demo/chat/chat_1",
parent: message,
replies: [],
replyCount: 0,
canReply: true,
});
render(
<MemoryRouter>
<ChatThreadPage
vm={vm}
draft="Antwort"
busy={false}
errorKey={null}
featureErrorKeys={{ message_1: "chat.errors.invalidInput" }}
actions={{
onBack: vi.fn(),
onDraftChange,
onSendReply,
onToggleReaction,
onTogglePin,
onEditMessage,
onDeleteMessage,
onRetryFeature,
onRetry: vi.fn(),
}}
/>
</MemoryRouter>
);
fireEvent.change(screen.getByRole("combobox", { name: "chat.thread.replyLabel" }), { target: { value: "Neu" } });
expect(onDraftChange).toHaveBeenCalledWith("Neu", 3);
fireEvent.click(screen.getByRole("button", { name: "chat.thread.sendReply" }));
expect(onSendReply).toHaveBeenCalledWith("Antwort");
fireEvent.click(screen.getByRole("button", { name: "chat.reaction.remove:👍" }));
expect(onToggleReaction).toHaveBeenCalledWith("message_1", "👍", false);
fireEvent.click(screen.getByRole("button", { name: "chat.pinned.unpin" }));
expect(onTogglePin).toHaveBeenCalledWith("message_1", false);
expect(screen.getByText("chat.errors.invalidInput")).toBeInTheDocument();
expect(screen.getByText("montageplan.pdf")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
expect(onRetryFeature).toHaveBeenCalledWith("message_1");
});
it("shows pinned rows and unpins only after an explicit action", () => {
const onUnpin = vi.fn();
const vm = buildChatPinnedMessagesVM({
chatId: "chat_1",
channelTitle: "Montage Nord",
backHref: "/demo/chat/chat_1",
rows: [
{
message,
pinnedAtIso: "2026-07-16T09:00:00.000Z",
pinnedByLabel: "Raffael Sheikh",
note: null,
messageHref: "/demo/chat/chat_1?message=message_1#message-message_1",
canUnpin: true,
},
],
});
render(
<MemoryRouter>
<ChatPinnedMessagesPage vm={vm} busyMessageId={null} errorKey={null} actions={{ onBack: vi.fn(), onUnpin, onRetry: vi.fn() }} />
</MemoryRouter>
);
expect(screen.getByText("chat.pinned.by:Raffael Sheikh")).toBeInTheDocument();
fireEvent.click(screen.getAllByRole("button", { name: "chat.pinned.unpin" }).at(-1)!);
expect(onUnpin).toHaveBeenCalledWith("message_1");
});
it("confirms thread-message edits and deletes before delegating them", () => {
const onEditMessage = vi.fn();
const onDeleteMessage = vi.fn();
const vm = buildChatThreadVM({
chatId: "chat_1",
threadId: "message_1",
channelTitle: "Montage Nord",
backHref: "/demo/chat/chat_1",
parent: message,
replies: [],
replyCount: 0,
canReply: true,
});
render(
<MemoryRouter>
<ChatThreadPage
vm={vm}
draft=""
busy={false}
errorKey={null}
actions={{
onBack: vi.fn(),
onDraftChange: vi.fn(),
onSendReply: vi.fn(),
onToggleReaction: vi.fn(),
onTogglePin: vi.fn(),
onEditMessage,
onDeleteMessage,
onRetry: vi.fn(),
}}
/>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("button", { name: "chat.message.edit" }));
const editDialog = screen.getByRole("dialog");
expect(within(editDialog).getByRole("heading", { name: "chat.message.editTitle" })).toBeInTheDocument();
fireEvent.change(within(editDialog).getByRole("textbox"), { target: { value: "Aktualisiert" } });
fireEvent.click(within(editDialog).getByRole("button", { name: "chat.message.save" }));
expect(onEditMessage).toHaveBeenCalledWith("message_1", "Aktualisiert");
fireEvent.click(screen.getByRole("button", { name: "chat.message.delete" }));
const deleteDialog = screen.getByRole("dialog");
expect(within(deleteDialog).getByRole("heading", { name: "chat.message.deleteConfirmTitle" })).toBeInTheDocument();
fireEvent.click(within(deleteDialog).getByRole("button", { name: "chat.message.delete" }));
expect(onDeleteMessage).toHaveBeenCalledWith("message_1");
});
});
@@ -0,0 +1,109 @@
import { Link } from "react-router";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherPin } from "@subframe/core";
import type { ChatPinnedMessagesVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatMessageFeatureCard } from "./ChatMessageFeatureCard";
export function ChatPinnedMessagesPage({
vm,
busyMessageId,
errorKey,
featureErrorKeys,
actions,
}: {
readonly vm: ChatPinnedMessagesVM;
readonly busyMessageId: string | null;
readonly errorKey: string | null;
readonly featureErrorKeys?: Readonly<Record<string, string>>;
readonly actions: {
readonly onBack: (href: string) => void;
readonly onUnpin: (messageId: string) => void;
readonly onRetryFeature?: (messageId: string) => void;
readonly onRetry: () => void;
};
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const data = vm.status === "ready" ? vm.data : null;
return (
<PageShell uiId="ui.chat.pinned" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherPin className={PAGE_HEADER_ICON_CLASS} />}
title={data ? t("chat.pinned.title", { channel: data.channelTitle }) : t("chat.pinned.titleFallback")}
actions={
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={() => data && actions.onBack(data.backHref)} disabled={!data}>
{t("shared.back")}
</Button>
}
/>
<PageBody>
{vm.status === "loading" || vm.status === "idle" ? (
<LoadingIndicatorSkeleton variant="list" aria-label={t("shared.loading")} />
) : vm.status === "error" ? (
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={<Button onClick={actions.onRetry}>{t("shared.retry")}</Button>}
/>
) : !data || data.rows.length === 0 ? (
<EmptyState outlined title={t(data?.emptyHeadlineKey ?? "chat.pinned.empty.headline")} body={t(data?.emptyBodyKey ?? "chat.pinned.empty.body")} />
) : (
<ButtonGroup align="stack">
{errorKey ? <Alert variant="error" title={t(errorKey)} notDismissible /> : null}
{data.rows.map((row) => (
<Card key={row.message.id} data-ui-id="ui.chat.pinned.row">
<ButtonGroup align="stack">
<ButtonGroup>
<BadgeFeedback farbe="subtle-information" size="small">
{t("chat.pinned.by", { user: row.pinnedByLabel })}
</BadgeFeedback>
<BadgeFeedback farbe="ghost-neutral" size="small">
{formatters.date(row.pinnedAtIso, { dateStyle: "medium", timeStyle: "short" })}
</BadgeFeedback>
</ButtonGroup>
{row.note ? <span>{row.note}</span> : null}
<ChatMessageFeatureCard
message={row.message}
featureErrorKey={featureErrorKeys?.[row.message.id]}
actions={{
onToggleReaction: () => undefined,
onTogglePin: (messageId, pinned) => pinned || actions.onUnpin(messageId),
onRetryFeature: actions.onRetryFeature,
}}
/>
<ButtonGroup>
<Link to={row.messageHref}>{t("chat.pinned.openMessage")}</Link>
{row.canUnpin ? (
<Button
variant="tertiary"
size="small"
icon={<FeatherPin />}
onClick={() => actions.onUnpin(row.message.id)}
disabled={busyMessageId === row.message.id}
loading={busyMessageId === row.message.id}
>
{t("chat.pinned.unpin")}
</Button>
) : null}
</ButtonGroup>
</ButtonGroup>
</Card>
))}
</ButtonGroup>
)}
</PageBody>
</PageShell>
);
}
@@ -0,0 +1,137 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import type { ComponentProps, ReactNode } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { buildChatChannelListVM } from "@hivegrid/view-models";
import { describe, expect, it, vi } from "vitest";
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),
relativeDate: (value: string) => value,
}),
}));
vi.mock("@subframe/core", () => ({
FeatherAtSign: () => <span />,
FeatherHash: () => <span />,
FeatherLock: () => <span />,
FeatherMessageCircle: () => <span />,
FeatherMessageSquare: () => <span />,
FeatherPin: () => <span />,
FeatherUsers: () => <span />,
}));
vi.mock("~/ui/components/Avatar", () => ({ Avatar: ({ children }: { children?: ReactNode }) => <span>{children}</span> }));
vi.mock("~/ui/components/BadgeFeedback", () => ({ BadgeFeedback: ({ children }: { children?: ReactNode }) => <span>{children}</span> }));
vi.mock("~/ui/components/Button", () => ({
Button: ({ children, loading: _loading, icon: _icon, ...props }: ComponentProps<"button"> & { loading?: boolean; icon?: ReactNode }) => (
<button {...props}>{children}</button>
),
}));
vi.mock("~/ui/components/ButtonGroup", () => ({ ButtonGroup: ({ children }: { children?: ReactNode }) => <div>{children}</div> }));
vi.mock("~/ui/components/Card", () => ({ Card: ({ children, ...props }: ComponentProps<"div">) => <div {...props}>{children}</div> }));
vi.mock("~/ui/components/EmptyState", () => ({
EmptyState: ({ title, body, action }: { title?: ReactNode; body?: ReactNode; action?: ReactNode }) => (
<div>
{title}
{body}
{action}
</div>
),
}));
vi.mock("~/ui/components/LoadingIndicatorSkeleton", () => ({ LoadingIndicatorSkeleton: (props: ComponentProps<"div">) => <div {...props} /> }));
vi.mock("~/ui/components/SearchInput", () => ({
SearchInput: ({ fillContainer: _fill, hideShortcut: _shortcut, ...props }: ComponentProps<"input"> & { fillContainer?: boolean; hideShortcut?: boolean }) => (
<input type="search" {...props} />
),
}));
vi.mock("~/ui/components/Select", () => ({
Select: Object.assign(
({ children }: { children?: ReactNode }) => <div>{children}</div>,
{ Item: ({ children }: { children?: ReactNode }) => <span>{children}</span> }
),
}));
vi.mock("~/ui/components/Switch", () => ({ Switch: (props: ComponentProps<"input">) => <input type="checkbox" {...props} /> }));
vi.mock("../shared/PageShell", () => ({
PAGE_HEADER_ICON_CLASS: "",
PageShell: ({ children }: { children?: ReactNode }) => <main>{children}</main>,
PageHeader: ({ title, actions }: { title?: ReactNode; actions?: ReactNode }) => (
<header>
{title}
{actions}
</header>
),
PageBody: ({ children }: { children?: ReactNode }) => <section>{children}</section>,
}));
const actions = (onJoinChannel: ChatChannelListActions["onJoinChannel"]): ChatChannelListActions => ({
onOpenChannel: vi.fn(),
onQueryChange: vi.fn(),
onViewChange: vi.fn(),
onShowArchivedChange: vi.fn(),
onRetry: vi.fn(),
onJoinChannel,
});
const vm = buildChatChannelListVM({
rows: [],
discoverRows: [
{
id: "chat_public",
title: "Montage Nord",
description: "Offener Austausch",
avatar: { imageUrl: null, fallbackLabel: "MN" },
memberCount: 7,
isJoined: false,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
},
],
filter: { query: "", view: "all", showArchived: false },
permissions: {
canWrite: true,
canCreateGroup: false,
canCreateDm: false,
canDiscover: true,
canViewMentions: false,
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 },
});
describe("public channel discovery interim UI", () => {
it("shows public groups as join-only rows and delegates the join intent", () => {
const onJoinChannel = vi.fn();
const { rerender } = render(<ChatChannelListPage vm={vm} actions={actions(onJoinChannel)} />);
expect(screen.getByText("chat.channelList.discover.headline")).toBeInTheDocument();
expect(screen.getByText("Offener Austausch")).toBeInTheDocument();
expect(screen.getByText("chat.channelList.discover.memberCount:7")).toBeInTheDocument();
expect(screen.queryByRole("link", { name: /Montage Nord/ })).not.toBeInTheDocument();
const joinButton = screen.getByRole("button", { name: "chat.channelList.discover.joinAria:Montage Nord" });
fireEvent.click(joinButton);
expect(onJoinChannel).toHaveBeenCalledWith("chat_public", "/demo/chat");
rerender(<ChatChannelListPage vm={vm} joiningChannelId="chat_public" actions={actions(onJoinChannel)} />);
expect(screen.getByRole("button", { name: "chat.channelList.discover.joinAria:Montage Nord" })).toBeDisabled();
});
});
@@ -0,0 +1,42 @@
import type { ButtonHTMLAttributes } from "react";
import { cn } from "~/lib/utils";
export type ChatSwitchProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onChange" | "role"> &
Readonly<{
checked: boolean;
onCheckedChange: (checked: boolean) => void;
}>;
/** Chat-local accessible switch; avoids changing the generated Subframe primitive. */
export function ChatSwitch({ checked, onCheckedChange, className, disabled, ...props }: ChatSwitchProps): React.JSX.Element {
return (
<button
{...props}
type="button"
role="switch"
aria-checked={checked}
disabled={disabled}
onClick={() => onCheckedChange(!checked)}
className={cn(
"focus-visible:shadow-focus inline-flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-md border-0 bg-transparent outline-none disabled:cursor-default disabled:opacity-50",
className
)}
>
<span
aria-hidden="true"
className={cn(
"rounded-round flex h-6 w-10 items-center border border-solid px-0.5 transition-colors",
checked ? "border-brand-brand-border-solid-default bg-brand-brand-surface-solid-default" : "border-border-strong bg-surface-neutral-primary"
)}
>
<span
className={cn(
"rounded-round h-4 w-4 transition-transform",
checked ? "bg-icon-neutral-on-solid translate-x-4" : "bg-icon-neutral-tertiary translate-x-0"
)}
/>
</span>
</button>
);
}
@@ -0,0 +1,207 @@
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { FeatherArrowLeft, FeatherMessageSquare, FeatherSend } from "@subframe/core";
import type { ChatMentionAutocompleteVM, ChatMentionSuggestionVM, ChatThreadVM } from "@hivegrid/view-models";
import { Alert } from "~/ui/components/Alert";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { ButtonGroup } from "~/ui/components/ButtonGroup";
import { Card } from "~/ui/components/Card";
import { EmptyState } from "~/ui/components/EmptyState";
import { LoadingIndicatorSkeleton } from "~/ui/components/LoadingIndicatorSkeleton";
import { TextArea } from "~/ui/components/TextArea";
import { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
import { ChatMessageFeatureCard } from "./ChatMessageFeatureCard";
import { ChatMentionAutocomplete } from "./ChatMentionAutocomplete";
export type ChatOptimisticThreadReply = Readonly<{
clientMessageId: string;
authorLabel: string;
bodyMarkdown: string;
createdAtIso: string;
deliveryState: "sending" | "sent" | "failed";
failureReasonKey: string | null;
}>;
export function ChatThreadPage({
vm,
draft,
busy,
errorKey,
featureErrorKeys,
mentionAutocomplete,
optimisticReplies = [],
actions,
}: {
readonly vm: ChatThreadVM;
readonly draft: string;
readonly busy: boolean;
readonly errorKey: string | null;
readonly featureErrorKeys?: Readonly<Record<string, string>>;
readonly optimisticReplies?: readonly ChatOptimisticThreadReply[];
readonly mentionAutocomplete?: {
readonly vm: ChatMentionAutocompleteVM | null;
readonly open: boolean;
readonly loading: boolean;
readonly activeIndex: number;
readonly listboxId: string;
};
readonly actions: {
readonly onBack: (href: string) => void;
readonly onDraftChange: (value: string, caret: number) => void;
readonly onSendReply: (value: string) => void;
readonly onToggleReaction: (messageId: string, emoji: string, active: boolean) => void;
readonly onTogglePin: (messageId: string, pinned: boolean) => void;
readonly onEditMessage: (messageId: string, body: string) => void;
readonly onDeleteMessage: (messageId: string) => void;
readonly onMentionActiveIndexChange?: (index: number) => void;
readonly onMentionSelect?: (suggestion: ChatMentionSuggestionVM) => number | null;
readonly onMentionKeyDown?: (key: "ArrowDown" | "ArrowUp" | "Enter" | "Escape") => boolean;
readonly onRetryReply?: (clientMessageId: string) => void;
readonly onDiscardReply?: (clientMessageId: string) => void;
readonly onRetryFeature?: (messageId: string) => void;
readonly onRetry: () => void;
};
}): React.JSX.Element {
const { t } = useTranslation();
const data = vm.status === "ready" ? vm.data : null;
const composerRef = useRef<HTMLTextAreaElement | null>(null);
function selectMention(suggestion: ChatMentionSuggestionVM): void {
const nextCaret = actions.onMentionSelect?.(suggestion) ?? null;
if (nextCaret === null) return;
requestAnimationFrame(() => {
composerRef.current?.focus();
composerRef.current?.setSelectionRange(nextCaret, nextCaret);
});
}
function sendDraft(): void {
const body = draft.trim();
if (!body || busy) return;
actions.onSendReply(body);
requestAnimationFrame(() => composerRef.current?.focus());
}
return (
<PageShell uiId="ui.chat.thread" className="mobile:[&_button]:min-h-11 mobile:[&_button]:min-w-11">
<PageHeader
icon={<FeatherMessageSquare className={PAGE_HEADER_ICON_CLASS} />}
title={data ? t("chat.thread.title", { channel: data.channelTitle }) : t("chat.thread.titleFallback")}
subtitle={data ? t("chat.thread.replyCount", { count: data.replyCount }) : undefined}
actions={
<Button variant="tertiary" icon={<FeatherArrowLeft />} onClick={() => data && actions.onBack(data.backHref)} disabled={!data}>
{t("shared.back")}
</Button>
}
/>
<PageBody>
{vm.status === "loading" || vm.status === "idle" ? (
<LoadingIndicatorSkeleton variant="list" aria-label={t("shared.loading")} />
) : vm.status === "error" ? (
<EmptyState
outlined
variant="error"
title={t("shared.error")}
body={t(vm.error.messageKey)}
action={<Button onClick={actions.onRetry}>{t("shared.retry")}</Button>}
/>
) : !data ? (
<EmptyState outlined title={t("chat.thread.empty.headline")} body={t("chat.thread.empty.body")} />
) : (
<ButtonGroup align="stack">
{errorKey ? <Alert variant="error" title={t(errorKey)} notDismissible /> : null}
<ChatMessageFeatureCard message={data.parent} featureErrorKey={featureErrorKeys?.[data.parent.id]} actions={actions} />
{data.replies.length === 0 && optimisticReplies.length === 0 ? (
<EmptyState outlined title={t(data.emptyRepliesHeadlineKey)} body={t(data.emptyRepliesBodyKey)} />
) : (
<>
{data.replies.map((reply) => (
<ChatMessageFeatureCard key={reply.id} message={reply} featureErrorKey={featureErrorKeys?.[reply.id]} actions={actions} />
))}
{optimisticReplies.map((reply) => (
<Card
key={reply.clientMessageId}
id={`message-local-${reply.clientMessageId}`}
variant={reply.deliveryState === "failed" ? "default" : "information"}
data-delivery-state={reply.deliveryState}
data-ui-id="ui.chat.thread.optimisticReply"
>
<ButtonGroup align="space-between">
<strong>{reply.authorLabel}</strong>
<BadgeFeedback farbe={reply.deliveryState === "failed" ? "subtle-negative" : "subtle-neutral"} size="small" role="status">
{t(`chat.message.delivery.${reply.deliveryState}`)}
</BadgeFeedback>
</ButtonGroup>
<p>{reply.bodyMarkdown}</p>
{reply.deliveryState === "failed" ? (
<ButtonGroup align="end" role="alert">
<span>{t(reply.failureReasonKey ?? "chat.message.sendFailed")}</span>
<Button variant="tertiary" onClick={() => actions.onRetryReply?.(reply.clientMessageId)}>
{t("shared.retry")}
</Button>
<Button variant="ghost" onClick={() => actions.onDiscardReply?.(reply.clientMessageId)}>
{t("shared.remove")}
</Button>
</ButtonGroup>
) : null}
</Card>
))}
</>
)}
{data.canReply ? (
<ButtonGroup align="stack">
<TextArea label={t("chat.thread.replyLabel")} showLabel>
<TextArea.Input
ref={composerRef}
value={draft}
placeholder={t(data.composerPlaceholderKey)}
onChange={(event) => actions.onDraftChange(event.target.value, event.target.selectionStart ?? event.target.value.length)}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
if (
actions.onMentionKeyDown &&
["ArrowDown", "ArrowUp", "Enter", "Escape"].includes(event.key) &&
actions.onMentionKeyDown(event.key as "ArrowDown" | "ArrowUp" | "Enter" | "Escape")
) {
event.preventDefault();
return;
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
sendDraft();
}
}}
role="combobox"
aria-autocomplete="list"
aria-expanded={mentionAutocomplete?.open ?? false}
aria-controls={mentionAutocomplete?.open ? mentionAutocomplete.listboxId : undefined}
aria-activedescendant={
mentionAutocomplete?.open && !mentionAutocomplete.loading && (mentionAutocomplete.vm?.total ?? 0) > 0
? `${mentionAutocomplete.listboxId}-option-${mentionAutocomplete.activeIndex}`
: undefined
}
/>
</TextArea>
{mentionAutocomplete ? (
<ChatMentionAutocomplete
{...mentionAutocomplete}
actions={{
onSelect: selectMention,
onActiveIndexChange: actions.onMentionActiveIndexChange ?? (() => undefined),
}}
/>
) : null}
<Button variant="primary" icon={<FeatherSend />} onClick={sendDraft} disabled={busy || draft.trim().length === 0} loading={busy}>
{t("chat.thread.sendReply")}
</Button>
</ButtonGroup>
) : (
<Alert variant="neutral" title={t("chat.composer.permissionDenied")} notDismissible />
)}
</ButtonGroup>
)}
</PageBody>
</PageShell>
);
}
@@ -0,0 +1,7 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`AK-P15b team chat interim visual baseline > renders the channel index and detail surfaces from ~/ui 1`] = `
"<div><main data-ui-id="ui.chat.interim.visualBaseline"><div class="flex w-full flex-col items-start mobile:[&amp;_button]:min-h-11 mobile:[&amp;_button]:min-w-11" data-ui-id="ui.chat.channelList"><div class="flex w-full items-start gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:flex-col mobile:px-4"><div class="flex grow shrink-0 basis-0 flex-col items-start gap-1"><div class="flex items-center gap-2"><span class="text-heading- font-heading- text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><h1 class="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">chat.nav.title</h1></div></div></div><div class="flex w-full flex-col gap-6 p-6 mobile:p-4"><div class="group/e0379327 flex w-full items-center gap-2 flex-col"><div class="group/75a35ed3 flex w-full cursor-pointer flex-col items-start justify-center gap-4 h-9 min-w-0 max-w-none" data-ui-id="ui.chat.channelList.search"><div class="hidden flex-col items-start gap-3"></div><label class="flex h-9 w-full flex-none cursor-text items-center gap-2.5 rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 group-hover/75a35ed3:bg-surface-neutral-secondary group-focus-within/75a35ed3:bg-surface-neutral-secondary group-focus-within/75a35ed3:shadow-focus min-w-0 max-w-none"><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><input class="grow shrink-0 basis-0 self-stretch border-0 bg-transparent text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle" style="box-shadow: none;" placeholder="chat.searchPlaceholder" type="search" value=""><div class="items-center gap-1 rounded-sm group-focus-within/75a35ed3:hidden hidden"><div class="group/97bdb082 flex min-h-[20px] items-center justify-center rounded-sm border border-solid border-surface-feedback-subtle-neutral bg-surface-feedback-subtle-neutral px-1 py-0.5"><span class="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-on-subtle">Strg K</span></div></div><span class="hidden text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary animate-spin icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><div class="hidden h-5 w-5 flex-none items-center justify-center rounded-round cursor-pointer hover:bg-surface-neutral-tertiary"><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></div></label></div><div class="group/bb88f90b flex w-full min-w-[192px] max-w-[320px] cursor-pointer flex-col items-start gap-4 [&amp;_[role=combobox]_span]:text-text-neutral-secondary"><div class="hidden flex-col items-start gap-3"></div><div class="flex w-full flex-col items-start gap-4 rounded-[4px]"><div class="flex w-full flex-col items-start rounded-sm border border-solid border-border-strong group-hover/bb88f90b:border group-hover/bb88f90b:border-solid group-hover/bb88f90b:border-brand-brand-border-solid-hover group-hover/bb88f90b:bg-surface-neutral-secondary group-focus-within/bb88f90b:bg-surface-neutral-secondary group-focus-within/bb88f90b:shadow-focus bg-surface-neutral-secondary"><button class="select-module_trigger__L7Z7z group/7ce1d396 flex h-9 w-full min-w-0 items-center justify-between gap-2 overflow-hidden px-3 py-3 text-left" type="button" role="combobox" aria-controls="radix-_r_0_" aria-expanded="false" aria-autocomplete="none" dir="ltr" data-state="closed" aria-label="shared.viewMode"><span class="group/21c51472 min-w-0 truncate whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary select-module_value__4AkUy"><span style="pointer-events: none;"><span class="group/c3085a74 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-tertiary h-auto grow shrink-0 basis-0">chat.channelList.view.all</span></span></span><span class="flex-none text-body-default-medium-0 font-body-default-medium-0 text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></button></div></div></div><div class="group/e0379327 flex w-full items-center gap-2"><button aria-label="chat.channelList.showArchived" type="button" role="switch" aria-checked="false" class="focus-visible:shadow-focus inline-flex h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-md border-0 bg-transparent outline-none disabled:cursor-default disabled:opacity-50"><span aria-hidden="true" class="rounded-round flex h-6 w-10 items-center border border-solid px-0.5 transition-colors border-border-strong bg-surface-neutral-primary"><span class="rounded-round h-4 w-4 transition-transform bg-icon-neutral-teLine truncated
</div></div></div><h2 id="radix-_r_2_" style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"></h2><h2 id="radix-_r_5_" style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"></h2></div><div><div class="group/e0379327 flex w-full items-center gap-2 justify-end scroll-mt-24" id="message-message-raffael-1" data-message-id="message-raffael-1" tabindex="-1"><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md px-4 py-4 shadow-sm min-w-0 [overflow-wrap:anywhere] border border-solid border-border-information-subtle bg-surface-feedback-subtle-information" data-delivery-state="sent" data-transport-source="http_ack"><div class="group/e0379327 flex w-full items-center gap-2"><span>Raffael Sheikh</span><div class="group/896531e4 flex items-center gap-2 rounded-round h-5 bg-transparent px-0 py-0"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-neutral-on-subtle"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-on-subtle">2026-07-15T09:31:00.000Z</span></div></div><div data-ui-id="ui.chat.channelDetail.messageBody"><p>Perfekt, danke!</p>
</div><div class="group/896531e4 flex items-center gap-2 rounded-round h-5 bg-transparent px-0 py-0" data-ui-id="ui.chat.channelDetail.readReceipt" data-read-count="0" data-recipient-count="3"><div class="flex h-1 w-1 flex-none flex-col items-start gap-2 rounded-round bg-icon-neutral-on-subtle"></div><span class="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-on-subtle">chat.message.read.aggregate:0/3</span></div></div></div><h2 id="radix-_r_8_" style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"></h2><h2 id="radix-_r_b_" style="position: absolute; border: 0px; width: 1px; height: 1px; padding: 0px; margin: -1px; overflow: hidden; clip: rect(0px, 0px, 0px, 0px); white-space: nowrap; word-wrap: normal;"></h2></div></div></section></div></div><div class="group/3a65613d flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-information-subtle bg-surface-feedback-subtle-information px-4 py-5 relative" data-ui-id="ui.chat.channelDetail.typing"><div class="flex w-full items-start gap-3"><span class="text-heading-0 font-heading-0 text-icon-feedback-information icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-positive icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-warning icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-negative icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><div class="flex grow shrink-0 basis-0 flex-col items-start gap-2"><span class="w-full whitespace-pre-wrap text-text-feedback-information text-body-small-medium-0 font-body-small-medium-0">chat.channel.typing:1/Mara Klein</span></div></div><div class="hidden items-start justify-center absolute top-3 right-3"><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></div></div><section class="mobile:sticky mobile:bottom-0 mobile:z-10 mobile:-mx-4 mobile:bg-surface-neutral-primary mobile:px-4 mobile:pb-[max(1rem,env(safe-area-inset-bottom))] mobile:pt-2" data-ui-id="ui.chat.channelDetail.composerDock"><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 shadow-sm" data-ui-id="ui.chat.channelDetail.composer"><label class="group/4ec05ee8 flex w-full min-w-[192px] max-w-[576px] cursor-pointer flex-col items-start gap-1"><div class="flex w-full flex-col items-start gap-4"><div class="hidden flex-col items-start gap-3"></div><div class="flex w-full grow shrink-0 basis-0 flex-col items-start rounded-sm border border-solid border-border-strong bg-surface-neutral-primary group-hover/4ec05ee8:border group-hover/4ec05ee8:border-solid group-hover/4ec05ee8:border-brand-brand-border-solid-hover group-hover/4ec05ee8:bg-surface-neutral-secondary group-focus-within/4ec05ee8:border-2 group-focus-within/4ec05ee8:border-solid group-focus-within/4ec05ee8:border-brand-brand-border-solid-default group-focus-within/4ec05ee8:bg-surface-neutral-secondary"><textarea class="min-h-[96px] w-full border-none bg-transparent px-3 py-2 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle" placeholder="chat.composer.placeholder" maxlength="4000" aria-label="chat.composer.placeholder" role="combobox" aria-autocomplete="list" aria-expanded="false"></textarea></div><span class="hidden text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">chat.composer.tooLong:4000</span></div></label><div class="group/e0379327 flex w-full items-center gap-2 justify-between [&amp;>*]:rounded-md mobile:flex-wrap"><div class="group/e0379327 flex w-full items-center gap-2 mobile:flex-wrap"></div><button class="group/3b777358 flex h-9 cursor-pointer items-center justify-center gap-3 rounded-md border-none bg-brand-brand-surface-solid-default px-4 py-2.5 text-left hover:bg-brand-brand-surface-solid-hover active:bg-brand-brand-surface-solid-active focus-within:shadow-focus disabled:cursor-default disabled:bg-surface-neutral-disabled disabled:pointer-events-none hover:disabled:cursor-default hover:disabled:bg-surface-neutral-disabled active:disabled:cursor-default active:disabled:bg-surface-neutral-disabled mobile:min-h-11" type="button" disabled=""><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neLine truncated
`;
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { readMergedLocaleNamespace } from "~/utils/testing/repoPaths";
type ChatAuditTranslations = {
chat: {
audit: {
description: string;
dmBanner: string;
actions: Record<string, string>;
administration: Record<string, string>;
members: { title: string; role: Record<string, string> };
confirm: { archive: Record<string, string>; remove: Record<string, string> };
};
};
};
function readTranslations(locale: "de" | "de-formal" | "en"): ChatAuditTranslations {
return readMergedLocaleNamespace<ChatAuditTranslations>(locale, "translations");
}
describe("AK-P15b chat admin audit translations", () => {
it("keeps cleanup and force-member copy complete in every shipped locale", () => {
const catalogs = [readTranslations("de"), readTranslations("de-formal"), readTranslations("en")];
for (const catalog of catalogs) {
const audit = catalog.chat.audit;
expect(audit.description).toBeTruthy();
expect(audit.dmBanner).toBeTruthy();
expect(Object.keys(audit.actions).sort()).toEqual(["archive", "archiveLabel", "demote", "promote", "removeMemberLabel"]);
expect(Object.keys(audit.members.role).sort()).toEqual(["admin", "member"]);
expect(Object.keys(audit.confirm.archive).sort()).toEqual(["body", "bodyNamed", "title"]);
expect(Object.keys(audit.confirm.remove).sort()).toEqual(["body", "title"]);
}
});
it("uses formal German address in destructive-action explanations", () => {
const informal = readTranslations("de").chat.audit;
const formal = readTranslations("de-formal").chat.audit;
expect(informal.confirm.archive.body).toContain("deiner");
expect(formal.confirm.archive.body).toContain("Ihrer");
expect(informal.administration.readOnlyDescription).toContain("Du");
expect(formal.administration.readOnlyDescription).toContain("Sie");
});
});
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { readMergedLocaleNamespace } from "~/utils/testing/repoPaths";
type ChatCreateTranslations = {
chat: {
channelList: { actions: { newDm: string; newGroup: string } };
channelCreate: {
title: string;
subtitle: string;
fields: { membersHelp: string; peerHelp: string };
users: { loading: string; empty: string };
permissions: { none: string; noneBody: string };
validation: Record<string, string>;
};
};
};
function readTranslations(locale: "de" | "de-formal" | "en"): ChatCreateTranslations {
return readMergedLocaleNamespace<ChatCreateTranslations>(locale, "translations");
}
describe("AK-P15b chat create translations", () => {
it("ships complete German and English base copy for the create surface", () => {
const de = readTranslations("de");
const en = readTranslations("en");
expect(de.chat.channelList.actions).toMatchObject({ newDm: "Neue Direktnachricht", newGroup: "Neuer Channel" });
expect(en.chat.channelList.actions).toMatchObject({ newDm: "New direct message", newGroup: "New channel" });
expect(de.chat.channelCreate.users.loading).toMatch(/geladen/);
expect(en.chat.channelCreate.users.loading).toMatch(/Loading/);
expect(Object.keys(de.chat.channelCreate.validation)).toEqual(Object.keys(en.chat.channelCreate.validation));
});
it("uses formal address in the German formal overlay", () => {
const formal = readTranslations("de-formal");
expect(formal.chat.channelCreate.subtitle).toContain("Sie");
expect(formal.chat.channelCreate.fields.membersHelp).toContain("Sie");
expect(formal.chat.channelCreate.fields.peerHelp).toContain("Wählen Sie");
expect(formal.chat.channelCreate.permissions.none).toContain("Sie");
expect(formal.chat.channelCreate.permissions.noneBody).toContain("Ihnen");
});
});
@@ -0,0 +1,71 @@
import { createChatDetailInterimFixturePage, createChatIndexInterimFixturePage } from "@hivegrid/ui-mock";
import { MemoryRouter } from "react-router";
import { ChatChannelDetailPage } from "./ChatChannelDetailPage";
import { ChatChannelListPage } from "./ChatChannelListPage";
export const CHAT_INTERIM_VISUAL_SCREENS = ["index", "detail"] as const;
export type ChatInterimVisualScreen = (typeof CHAT_INTERIM_VISUAL_SCREENS)[number];
const noOp = (): void => undefined;
/** Shared AD-28 fixture for markup snapshots and Chromium pixel baselines. */
export function ChatInterimVisualFixture({
screen,
enableNavigation = false,
}: {
readonly screen: ChatInterimVisualScreen;
readonly enableNavigation?: boolean;
}): React.JSX.Element {
if (screen === "index") {
const page = createChatIndexInterimFixturePage();
if (page.state.status !== "ready") throw new Error("chat.errors.integrityFailure");
return (
<MemoryRouter>
<ChatChannelListPage
vm={page.state.data.viewModel}
actions={{
onOpenChannel: noOp,
onQueryChange: noOp,
onViewChange: noOp,
onShowArchivedChange: noOp,
onRetry: noOp,
...(enableNavigation
? {
onCreateGroup: noOp,
onCreateDm: noOp,
onOpenMessageSearch: noOp,
onOpenMentions: noOp,
}
: {}),
}}
/>
</MemoryRouter>
);
}
const page = createChatDetailInterimFixturePage();
if (page.state.status !== "ready") throw new Error("chat.errors.integrityFailure");
return (
<MemoryRouter>
<ChatChannelDetailPage
vm={page.state.data.viewModel}
draft=""
actions={{
onBack: noOp,
onDraftChange: noOp,
onSend: noOp,
onRetryMessage: noOp,
onDiscardMessage: noOp,
onMessageVisibilityChange: noOp,
onRetryConnection: noOp,
onLoadOlder: noOp,
onOpenSettings: noOp,
}}
/>
</MemoryRouter>
);
}
@@ -0,0 +1,41 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import React from "react";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { CHAT_INTERIM_VISUAL_SCREENS, ChatInterimVisualFixture } from "./chat-interim.visual-fixture";
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) => value,
dateTime: (value: string) => `date:${value}`,
relativeDate: (value: string) => `relative:${value}`,
}),
}));
describe("AK-P15b team chat interim visual baseline", () => {
it("renders the channel index and detail surfaces from ~/ui", () => {
render(
<main data-ui-id="ui.chat.interim.visualBaseline">
{CHAT_INTERIM_VISUAL_SCREENS.map((screen) => (
<ChatInterimVisualFixture key={screen} screen={screen} />
))}
</main>
);
expect(document.querySelectorAll("[data-ui-id='ui.chat.channelList']")).toHaveLength(1);
expect(document.querySelectorAll("[data-ui-id='ui.chat.channelDetail']")).toHaveLength(1);
const stableMarkup = document.body.innerHTML.replace(/<svg\b[^>]*>[\s\S]*?<\/svg>/gu, '<svg data-visual-icon="true"></svg>');
expect(stableMarkup).toMatchSnapshot();
});
});
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { readMergedLocaleNamespace } from "~/utils/testing/repoPaths";
type MessageDiscoveryTranslations = {
chat: {
messageDiscovery: {
search: Record<string, string>;
mentions: Record<string, string>;
actions: Record<string, string>;
result: Record<string, string>;
};
};
};
function readTranslations(locale: "de" | "de-formal" | "en"): MessageDiscoveryTranslations {
return readMergedLocaleNamespace<MessageDiscoveryTranslations>(locale, "translations");
}
describe("AK-P15b message discovery translations", () => {
it("ships the same complete search and mentions contract in every locale", () => {
const reference = readTranslations("en").chat.messageDiscovery;
for (const locale of ["de", "de-formal", "en"] as const) {
const translations = readTranslations(locale).chat.messageDiscovery;
expect(Object.keys(translations.search)).toEqual(Object.keys(reference.search));
expect(Object.keys(translations.mentions)).toEqual(Object.keys(reference.mentions));
expect(Object.keys(translations.actions)).toEqual(Object.keys(reference.actions));
expect(Object.keys(translations.result)).toEqual(Object.keys(reference.result));
for (const group of Object.values(translations)) {
for (const value of Object.values(group)) expect(value.trim()).not.toBe("");
}
expect(translations.result.openAria).toContain("{{author}}");
expect(translations.result.openAria).toContain("{{channel}}");
}
});
it("uses formal address in the German formal search copy", () => {
const formal = readTranslations("de-formal").chat.messageDiscovery;
expect(formal.search.subtitle).toContain("Sie");
expect(formal.search.emptyBody).toContain("Geben Sie");
});
});
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { readMergedLocaleNamespace } from "~/utils/testing/repoPaths";
const DISCOVERY_KEYS = ["headline", "join", "joinAria", "memberCount_one", "memberCount_other"] as const;
type DiscoveryTranslations = {
chat: {
channelList: {
discover: Record<(typeof DISCOVERY_KEYS)[number], string>;
};
};
};
function readTranslations(locale: "de" | "de-formal" | "en"): DiscoveryTranslations {
return readMergedLocaleNamespace<DiscoveryTranslations>(locale, "translations");
}
describe("AK-P15b public channel discovery translations", () => {
it("ships the join contract in every supported locale", () => {
for (const locale of ["de", "de-formal", "en"] as const) {
const discover = readTranslations(locale).chat.channelList.discover;
expect(Object.keys(discover)).toEqual(DISCOVERY_KEYS);
for (const value of Object.values(discover)) expect(value.trim()).not.toBe("");
expect(discover.joinAria).toContain("{{channel}}");
expect(discover.memberCount_one).toContain("{{count}}");
expect(discover.memberCount_other).toContain("{{count}}");
}
});
});
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { readMergedLocaleNamespace } from "~/utils/testing/repoPaths";
const SYSTEM_EVENT_KEYS = [
"groupCreated",
"projectCreated",
"projectLeaderChanged",
"projectLeaderChangedFrom",
"memberWriteAccessGranted",
"memberWriteAccessRevoked",
"memberAdded",
"memberRemoved",
"channelPrivacyPublic",
"channelPrivacyPrivate",
"channelArchived",
"taskCreated",
"generic",
] as const;
type ChatSystemTranslations = {
chat: {
channel: { newSystemMessageAnnouncement: string };
systemEvent: Record<(typeof SYSTEM_EVENT_KEYS)[number], string>;
};
};
function readTranslations(locale: "de" | "de-formal" | "en"): ChatSystemTranslations {
return readMergedLocaleNamespace<ChatSystemTranslations>(locale, "translations");
}
describe("AK-P15b chat system-message translations", () => {
it("ships the complete system-event contract in every supported locale", () => {
for (const locale of ["de", "de-formal", "en"] as const) {
const translations = readTranslations(locale);
expect(Object.keys(translations.chat.systemEvent)).toEqual(SYSTEM_EVENT_KEYS);
expect(translations.chat.channel.newSystemMessageAnnouncement).toContain("{{message}}");
for (const value of Object.values(translations.chat.systemEvent)) expect(value.trim()).not.toBe("");
}
});
it("keeps interpolation placeholders aligned across locales", () => {
const locales = [readTranslations("de"), readTranslations("de-formal"), readTranslations("en")];
for (const key of SYSTEM_EVENT_KEYS) {
const placeholderSets = locales.map((locale) => placeholders(locale.chat.systemEvent[key]));
expect(placeholderSets[1]).toEqual(placeholderSets[0]);
expect(placeholderSets[2]).toEqual(placeholderSets[0]);
}
});
});
function placeholders(value: string): string[] {
return [...value.matchAll(/{{\s*([^}\s]+)\s*}}/g)].map((match) => match[1] ?? "").sort();
}