The composer read the mention limit from the room runtime by itself and dropped a failure: mentions went off with nothing shown, and the retry beside it existed only for the file limits, so a room without uploads had none. The attachments client, which already owns that runtime on the page, now gives both limits as one result with one failure and the one existing retry. Its three readers of the file limits share one decoder.
178 lines
11 KiB
TypeScript
178 lines
11 KiB
TypeScript
import { expect, test, vi } from "vitest";
|
|
import { act, createElement, useLayoutEffect } from "react";
|
|
import { createRoot } from "react-dom/client";
|
|
import { renderToStaticMarkup } from "react-dom/server";
|
|
import { DOMImplementation } from "@xmldom/xmldom";
|
|
import { ChannelAttachments } from "../src/client/channel/attachments";
|
|
import { ChannelConversation as ConversationView } from "../src/client/channel/components/ChannelConversation";
|
|
import * as hosting from "../src/client/channel/hosting";
|
|
import type { ChannelMessage, ProfilePage } from "../src/client/channel/protocol";
|
|
import { useProfileDirectory } from "../src/client/channel/use-channel";
|
|
import { setCopy } from "../src/client/ui/copy";
|
|
|
|
function conversationProps(times: number[]) {
|
|
setCopy({ lang: "en" });
|
|
const messages: ChannelMessage[] = times.map((time, index) => ({ id: `message-${index}`, seq: index + 1,
|
|
userId: "author", text: `Message ${index + 1}`, time, attachments: [] }));
|
|
return {
|
|
domainId: "site", roomId: "room", roomName: "Room", messages, users: [], profiles: new Map(),
|
|
queryProfiles: async () => ({ profiles: [], total: 0, nextCursor: null }), selfUserId: "self", authorized: true, canSend: true,
|
|
sending: false, hidden: false, available: true, attachments: {} as never, attachmentsAvailable: false,
|
|
history: { hasMore: false, atLatest: true }, loadingHistory: false, onHistory: async () => {},
|
|
onLatest: async () => {}, onSend: async () => {}, interaction: null,
|
|
};
|
|
}
|
|
|
|
function historyMarkup(times: number[]) {
|
|
return renderToStaticMarkup(createElement(ConversationView, conversationProps(times)));
|
|
}
|
|
|
|
test("the first loaded day has an absolute date and message metadata exposes the full timestamp", () => {
|
|
const date = new Date(2020, 0, 1, 20, 0, 12);
|
|
const html = historyMarkup([date.getTime(), date.getTime() + 30_000]);
|
|
expect(html.match(/class="c3-message-date"/g)).toHaveLength(1);
|
|
expect(html).toContain(date.toLocaleDateString("en", { dateStyle: "long" }));
|
|
const timestamp = date.toLocaleString("en", { dateStyle: "long", timeStyle: "long" });
|
|
expect(html).toContain(`title="${timestamp}" aria-label="${timestamp}"`);
|
|
expect(html).toContain('c3-message c3-reaction-message is-continuation');
|
|
const continuation = html.split('is-continuation')[1];
|
|
expect(continuation).toContain('<div class="visually-hidden"><strong>');
|
|
expect(continuation).toContain(new Date(date.getTime() + 30_000).toISOString());
|
|
});
|
|
|
|
test("same-author messages break at local midnight, while a UTC date boundary alone does not", () => {
|
|
const previousZone = process.env.TZ;
|
|
process.env.TZ = "America/New_York";
|
|
try {
|
|
const midnight = [new Date(2020, 0, 1, 23, 59, 30).getTime(), new Date(2020, 0, 2, 0, 0, 30).getTime()];
|
|
expect(historyMarkup(midnight).match(/class="c3-message-date"/g)).toHaveLength(2);
|
|
expect(historyMarkup(midnight)).not.toContain('is-continuation');
|
|
const utcMidnight = [Date.parse("2020-01-02T23:59:30Z"), Date.parse("2020-01-03T00:00:30Z")];
|
|
expect(historyMarkup(utcMidnight).match(/class="c3-message-date"/g)).toHaveLength(1);
|
|
expect(historyMarkup(utcMidnight)).toContain('is-continuation');
|
|
} finally {
|
|
if (previousZone === undefined) delete process.env.TZ; else process.env.TZ = previousZone;
|
|
}
|
|
});
|
|
|
|
test("prepending history keeps one divider per local day", () => {
|
|
const first = new Date(2020, 0, 1, 20).getTime(), earlier = new Date(2019, 11, 31, 20).getTime();
|
|
expect(historyMarkup([first, first + 30_000]).match(/class="c3-message-date"/g)).toHaveLength(1);
|
|
expect(historyMarkup([first - 30_000, first, first + 30_000]).match(/class="c3-message-date"/g)).toHaveLength(1);
|
|
expect(historyMarkup([earlier, first, first + 30_000]).match(/class="c3-message-date"/g)).toHaveLength(2);
|
|
});
|
|
|
|
test.each(["mentions", "attachments", "mentions without files"])("the composer reports and retries a failed limits read: %s", async failure => {
|
|
const attachmentsAvailable = failure !== "mentions without files";
|
|
const mentions = vi.fn(() => 2);
|
|
const files = vi.fn(() => JSON.stringify({ maxFileBytes: 100, maxAttachmentsPerMessage: 2, maxRetainedBytes: 200,
|
|
maxRetainedFiles: 2, maxInlineImageBytes: 100, maxInlineImageEdge: 10 }));
|
|
vi.spyOn(hosting, "loadRoomHosting").mockResolvedValue({ initializeRuntime: async () => {},
|
|
message_mention_limit: mentions, attachment_limits: files } as unknown as Awaited<ReturnType<typeof hosting.loadRoomHosting>>);
|
|
const props = { ...conversationProps([1]), attachmentsAvailable, attachments: new ChannelAttachments(vi.fn(), vi.fn()),
|
|
users: [{ id: "author", name: "Ada", version: "a".repeat(64) }] };
|
|
const page = new DOMImplementation().createDocument("http://www.w3.org/1999/xhtml", "div");
|
|
Object.assign(page, { addEventListener: vi.fn(), removeEventListener: vi.fn() });
|
|
const create = page.createElement.bind(page);
|
|
const createNS = page.createElementNS.bind(page);
|
|
const element = { addEventListener() {}, removeEventListener() {}, querySelector: () => null, matches: () => false, style: { setProperty() {} } };
|
|
vi.spyOn(page, "createElement").mockImplementation(name => Object.assign(create(name), element));
|
|
vi.spyOn(page, "createElementNS").mockImplementation((ns, name) => Object.assign(createNS(ns, name), element));
|
|
const listen = vi.fn(), container = Object.assign(page.documentElement!, { addEventListener: listen });
|
|
vi.stubGlobal("window", { document: page, HTMLIFrameElement: class {} });
|
|
vi.stubGlobal("document", page);
|
|
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
|
const root = createRoot(container as unknown as HTMLElement);
|
|
const button = (label: string) => Array.from(container.getElementsByTagName("button")).find(node => node.getAttribute("aria-label") === label);
|
|
try {
|
|
if (failure === "attachments") {
|
|
const previous = new ChannelAttachments(vi.fn(), vi.fn());
|
|
await act(() => root.render(createElement(ConversationView, { ...props, attachments: previous })));
|
|
expect(button("Add files")?.hasAttribute("aria-disabled")).toBe(false);
|
|
}
|
|
(failure === "attachments" ? files : mentions).mockImplementationOnce(() => { throw new Error("unavailable"); });
|
|
await act(() => root.render(createElement(ConversationView, props)));
|
|
expect(container.textContent).toContain("Mentions and files are unavailable");
|
|
expect(button("Mention Ada")?.hasAttribute("disabled")).toBe(true);
|
|
expect(button("Add files")?.getAttribute("aria-disabled")).toBe(attachmentsAvailable ? "true" : undefined);
|
|
const retry = button("Retry");
|
|
expect(retry).toBeDefined();
|
|
const click = listen.mock.calls.find(([type, , capture]) => type === "click" && !capture)![1];
|
|
await act(() => click({ type: "click", target: retry, button: 0 }));
|
|
expect(button("Retry")).toBeUndefined();
|
|
expect(container.textContent).not.toContain("Mentions and files are unavailable");
|
|
expect(button("Mention Ada")?.hasAttribute("disabled")).toBe(false);
|
|
expect(button("Add files")?.hasAttribute("aria-disabled")).toBe(attachmentsAvailable ? false : undefined);
|
|
if (!attachmentsAvailable) expect(files).not.toHaveBeenCalled();
|
|
} finally { await act(() => root.unmount()); vi.restoreAllMocks(); vi.unstubAllGlobals(); }
|
|
});
|
|
|
|
test("profile pages retry the failed cursor and retire a pending read when the query changes", async () => {
|
|
const view = Object.assign(new EventTarget(), { HTMLIFrameElement: class {} });
|
|
const ownerDocument = Object.assign(new EventTarget(), { nodeType: 9, defaultView: view });
|
|
vi.stubGlobal("window", Object.assign(view, { document: ownerDocument }));
|
|
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
|
const root = createRoot(Object.assign(new EventTarget(), { nodeType: 1, tagName: "DIV", ownerDocument }) as unknown as HTMLElement);
|
|
let reply!: (page: ProfilePage) => void, reject!: (reason: Error) => void;
|
|
const read = vi.fn<Parameters<typeof useProfileDirectory>[0]>(() => new Promise((resolve, fail) => { reply = resolve; reject = fail; }));
|
|
let directory!: ReturnType<typeof useProfileDirectory>;
|
|
const committed = vi.fn();
|
|
function Reader({ query, known }: { query: { query?: string } | null; known?: { id: string }[] }) {
|
|
directory = useProfileDirectory(read, query, known);
|
|
useLayoutEffect(() => { committed(directory); });
|
|
return null;
|
|
}
|
|
const render = (query: { query?: string } | null, known?: { id: string }[]) => act(() => root.render(createElement(Reader, { query, known })));
|
|
const load = () => act(() => { void directory.load(); });
|
|
const page = (nextCursor: string | null, ...ids: string[]): ProfilePage => ({
|
|
profiles: ids.map(id => ({ id, name: id, avatar: null, version: "a".repeat(64) })), total: ids.length, nextCursor,
|
|
});
|
|
try {
|
|
await render({}, [{ id: "live" }]);
|
|
await load();
|
|
await act(() => reject(new Error("request_timeout")));
|
|
expect(directory).toMatchObject({ failed: true, loading: false, next: undefined, ids: ["live"] });
|
|
await load();
|
|
await act(() => reply(page("b", "live", "b")));
|
|
await load();
|
|
await act(() => reject(new Error("disconnected")));
|
|
expect(directory).toMatchObject({ failed: true, loading: false, next: "b", ids: ["live", "b"] });
|
|
await load();
|
|
await load();
|
|
expect(read.mock.calls.map(([query]) => query)).toStrictEqual([{}, {}, { after: "b" }, { after: "b" }]);
|
|
expect(read.mock.lastCall![1]?.aborted).toBe(false);
|
|
expect(directory).toMatchObject({ loading: true, failed: false });
|
|
await act(() => reply(page(null, "b", "c")));
|
|
expect(directory).toMatchObject({ loading: false, failed: false, next: null, ids: ["live", "b", "c"] });
|
|
|
|
await render({ query: "a" });
|
|
await load();
|
|
const late = reply, signal = read.mock.lastCall![1]!;
|
|
await render({ query: "ab" });
|
|
expect(signal.aborted).toBe(true);
|
|
await load();
|
|
const replacement = read.mock.lastCall!;
|
|
await act(() => late(page("old", "a")));
|
|
expect(directory).toMatchObject({ ids: [], next: undefined, loading: true, failed: false });
|
|
await load();
|
|
expect(read.mock.lastCall).toBe(replacement);
|
|
expect(replacement[0]).toStrictEqual({ query: "ab" });
|
|
await act(() => reply(page("ab", "ab")));
|
|
expect(directory).toMatchObject({ ids: ["ab"], next: "ab", loading: false });
|
|
await load();
|
|
const closing = read.mock.lastCall!;
|
|
expect(closing[0]).toStrictEqual({ query: "ab", after: "ab" });
|
|
committed.mockClear();
|
|
await render(null);
|
|
expect(committed.mock.calls[0]?.[0]).toMatchObject({ ids: [], next: undefined, loading: false, failed: false });
|
|
expect(closing[1]?.aborted).toBe(true);
|
|
await act(() => reject(new Error("aborted")));
|
|
await load();
|
|
expect(read.mock.lastCall).toBe(closing);
|
|
expect(directory).toMatchObject({ ids: [], next: undefined, loading: false, failed: false });
|
|
} finally {
|
|
await act(() => root.unmount());
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|