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,259 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import {
buildChatChannelListVM,
type ChatChannelListFilterState,
type ChatChannelListRowInput,
type ChatChannelListVM,
type ChatDiscoverChannelRowVM,
} from "@hivegrid/view-models";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ChatChannelListPageProps } from "~/components/screens/chat/ChatChannelListPage";
const mocks = vi.hoisted(() => ({
loaderData: undefined as unknown,
pageProps: undefined as ChatChannelListPageProps | undefined,
navigate: vi.fn(),
revalidate: vi.fn(),
fetcher: {
data: undefined as unknown,
state: "idle" as "idle" | "loading" | "submitting",
load: vi.fn(),
submit: vi.fn(),
},
getTranslations: vi.fn(),
loadChatContext: vi.fn(),
loadMemberChatChannels: vi.fn(),
}));
vi.mock("react-router", () => ({
useLoaderData: () => mocks.loaderData,
useNavigate: () => mocks.navigate,
useRevalidator: () => ({ revalidate: mocks.revalidate }),
useFetcher: () => mocks.fetcher,
}));
vi.mock("~/components/screens/chat/ChatChannelListPage", () => ({
ChatChannelListPage: (props: ChatChannelListPageProps) => {
mocks.pageProps = props;
const rows = props.vm.status === "ready" ? props.vm.data.rows : [];
const discoverRows = props.vm.status === "ready" ? props.vm.data.discoverRows : [];
const cursor = props.vm.status === "ready" ? props.vm.data.nextCursor : null;
return (
<div>
<output data-testid="channel-rows">{rows.map((row) => `${row.id}:${row.unreadCount}`).join(",")}</output>
<output data-testid="channel-query">{props.vm.status === "ready" ? props.vm.data.filter.query : ""}</output>
<output data-testid="join-error">{props.joinErrorKey ?? ""}</output>
{cursor && props.actions.onLoadMore ? <button onClick={() => void props.actions.onLoadMore?.(cursor)}>load-more</button> : null}
{discoverRows.map((row) =>
row.joinHref && props.actions.onJoinChannel ? (
<button key={row.id} onClick={() => props.actions.onJoinChannel?.(row.id, row.joinHref!)}>
join-{row.id}
</button>
) : null
)}
</div>
);
},
}));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
vi.mock("~/modules/chat/routes/chatAccess.server", () => ({ loadChatContext: (...args: unknown[]) => mocks.loadChatContext(...args) }));
vi.mock("~/modules/chat/services/ChatService.server", () => ({
loadMemberChatChannels: (...args: unknown[]) => mocks.loadMemberChatChannels(...args),
joinPublicChatChannel: vi.fn(),
updateOwnChatChannelPreferences: vi.fn(),
}));
vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf_1" }) }));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: vi.fn() }));
import ChatChannelListRoute from "./chat._index";
const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false };
function row(id: string, unreadCount = 0): ChatChannelListRowInput {
return {
id,
kind: "group",
title: id,
subtitle: null,
detailHref: `/demo/chat/${id}`,
avatar: { imageUrl: null, fallbackLabel: id.slice(0, 1) },
project: null,
lastMessage: null,
typingLabels: [],
unreadCount,
hasMention: unreadCount > 1,
isPinned: false,
isPrivate: false,
notificationPreference: "all_messages",
archivedAtIso: null,
memberCount: 2,
canManage: false,
};
}
function page(
rows: readonly ChatChannelListRowInput[],
nextCursor: string | null,
filter = DEFAULT_FILTER,
discoverRows: readonly ChatDiscoverChannelRowVM[] = []
): ChatChannelListVM {
return buildChatChannelListVM({
rows,
discoverRows,
filter,
permissions: {
canWrite: false,
canCreateGroup: false,
canCreateDm: false,
canDiscover: discoverRows.length > 0,
canViewMentions: false,
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=1",
},
totals: { unread: rows.reduce((total, entry) => total + entry.unreadCount, 0), mentions: 0 },
nextCursor,
});
}
function routeData(vm: ChatChannelListVM, pageCursor: string | null = null) {
return { title: "Chat", tenantSlug: "demo", pageCursor, vm };
}
describe("chat channel list route pagination", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.fetcher.data = undefined;
mocks.fetcher.state = "idle";
mocks.loaderData = routeData(page([row("chat_1", 1)], "cursor_2"));
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
mocks.loadChatContext.mockResolvedValue({ tenantId: "tenant_1", userId: "user_1", permissions: [] });
mocks.loadMemberChatChannels.mockResolvedValue(page([row("chat_2")], null));
});
afterEach(() => vi.useRealTimers());
it("loads another page without navigation, appends in order, deduplicates, and adopts its cursor", async () => {
const view = render(<ChatChannelListRoute />);
expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_1:1");
fireEvent.click(screen.getByRole("button", { name: "load-more" }));
expect(mocks.fetcher.load).toHaveBeenCalledWith("/demo/chat?cursor=cursor_2");
mocks.fetcher.state = "loading";
view.rerender(<ChatChannelListRoute />);
mocks.fetcher.data = routeData(page([row("chat_1", 3), row("chat_2", 2)], null), "cursor_2");
mocks.fetcher.state = "idle";
view.rerender(<ChatChannelListRoute />);
await waitFor(() => expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_1:3,chat_2:2"));
expect(screen.queryByRole("button", { name: "load-more" })).not.toBeInTheDocument();
});
it("resets appended rows and ignores an old in-flight page when the server filter changes", async () => {
const view = render(<ChatChannelListRoute />);
fireEvent.click(screen.getByRole("button", { name: "load-more" }));
mocks.fetcher.state = "loading";
view.rerender(<ChatChannelListRoute />);
const unreadFilter = { query: "", view: "unread" as const, showArchived: false };
mocks.loaderData = routeData(page([row("chat_unread", 4)], null, unreadFilter));
view.rerender(<ChatChannelListRoute />);
mocks.fetcher.data = routeData(page([row("chat_stale", 9)], null), "cursor_2");
mocks.fetcher.state = "idle";
view.rerender(<ChatChannelListRoute />);
await waitFor(() => expect(screen.getByTestId("channel-rows")).toHaveTextContent("chat_unread:4"));
expect(screen.getByTestId("channel-rows")).not.toHaveTextContent("chat_stale");
});
it("does not let a late loader response overwrite a newer local search query", () => {
vi.useFakeTimers();
const view = render(<ChatChannelListRoute />);
act(() => mocks.pageProps?.actions.onQueryChange("abc"));
act(() => vi.advanceTimersByTime(250));
act(() => mocks.pageProps?.actions.onQueryChange("abcd"));
mocks.loaderData = routeData(page([row("chat_old")], null, { ...DEFAULT_FILTER, query: "abc" }));
view.rerender(<ChatChannelListRoute />);
expect(screen.getByTestId("channel-query")).toHaveTextContent("abcd");
mocks.loaderData = routeData(page([row("chat_new")], null, { ...DEFAULT_FILTER, query: "abcd" }));
view.rerender(<ChatChannelListRoute />);
expect(screen.getByTestId("channel-query")).toHaveTextContent("abcd");
vi.useRealTimers();
});
it.each(["abc ", "x".repeat(250)])("releases local query protection when the normalized loader value returns", (rawQuery) => {
vi.useFakeTimers();
const normalizedQuery = rawQuery.trim().slice(0, 200);
const view = render(<ChatChannelListRoute />);
act(() => mocks.pageProps?.actions.onQueryChange(rawQuery));
act(() => vi.advanceTimersByTime(250));
mocks.loaderData = routeData(page([row("chat_match")], null, { ...DEFAULT_FILTER, query: normalizedQuery }));
view.rerender(<ChatChannelListRoute />);
expect(screen.getByTestId("channel-query")).toHaveTextContent(normalizedQuery);
mocks.loaderData = routeData(page([row("chat_back")], null, { ...DEFAULT_FILTER, query: "back" }));
view.rerender(<ChatChannelListRoute />);
expect(screen.getByTestId("channel-query")).toHaveTextContent("back");
});
it("submits a CSRF-protected join intent for a discoverable public group", () => {
mocks.loaderData = routeData(
page([row("chat_1")], null, DEFAULT_FILTER, [
{
id: "chat_public",
title: "Montage Nord",
description: null,
avatar: { imageUrl: null, fallbackLabel: "MN" },
memberCount: 4,
isJoined: false,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
},
])
);
render(<ChatChannelListRoute />);
fireEvent.click(screen.getByRole("button", { name: "join-chat_public" }));
expect(mocks.fetcher.submit).toHaveBeenCalledOnce();
const [formData, options] = mocks.fetcher.submit.mock.calls[0] as [FormData, { method: string; action: string }];
expect(Object.fromEntries(formData.entries())).toEqual({ intent: "join", chatId: "chat_public", csrf: "csrf_1" });
expect(options).toEqual({ method: "post", action: "/demo/chat" });
});
it("optimistically applies a personal pin and submits the desired state", async () => {
render(<ChatChannelListRoute />);
act(() => mocks.pageProps?.actions.onSetPinned?.("chat_1", true));
expect(mocks.fetcher.submit).toHaveBeenCalledOnce();
const [formData, options] = mocks.fetcher.submit.mock.calls[0] as [FormData, { method: string }];
expect(Object.fromEntries(formData.entries())).toMatchObject({
intent: "set-pin",
chatId: "chat_1",
isPinned: "true",
csrf: "csrf_1",
});
expect(formData.get("requestId")).toEqual(expect.any(String));
expect(options).toEqual({ method: "post" });
await waitFor(() => expect(mocks.pageProps?.vm.status === "ready" ? mocks.pageProps.vm.data.rows[0]?.isPinned : false).toBe(true));
});
});