fix(webui): preserve native touch menus with message link actions

This commit is contained in:
Xubin Ren committed 2026-09-24 15:17:05 +08:00
1 parent b08c9da8de
commit 4693bba81f
18 files changed
+291 -65

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useRef } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { WebLink, WebPreviewContext } from "@/components/WebLink";
import { useMessageWebLinks } from "@/components/MessageLinksMenu";
import { copyTextToClipboard } from "@/lib/clipboard";
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn(async () => true) }));
afterEach(() => { cleanup(); vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true); });
function view(content: string, openPreview?: (url: string) => void) {
return <WebPreviewContext.Provider value={openPreview}>
<ThreadMessages messages={[{ id: "links", role: "assistant", content, createdAt: 1 }]} />
</WebPreviewContext.Provider>;
}
async function openLinks() {
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
fireEvent.click(await screen.findByRole("button", { name: "View links" }));
return screen.getByRole("dialog", { name: "Message actions" });
}
describe("message link actions", () => {
it("collects rendered links, deduplicates destinations and ignores code, images and file references", async () => {
render(view("[First](https://example.com/) and [Again](https://example.com).\n\n[Second](https://example.org/demo)\n\nhttps://example.net/plain\n\n`https://code.invalid/inline`\n\n```text\nhttps://code.invalid/block\n```\n\n![Image](https://image.invalid/pic.png)\n\n[notes.txt](notes.txt)"));
await screen.findByRole("link", { name: "First" });
const menu = await openLinks();
expect(within(menu).getAllByRole("button").map(button => button.textContent)).toEqual(["View links", "First", "Second", "https://example.net/plain"]);
expect(within(menu).queryByRole("button", { name: "Again" })).not.toBeInTheDocument();
expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible();
expect(within(menu).getByRole("button", { name: "https://example.net/plain" })).toBeVisible();
fireEvent.click(within(menu).getByRole("button", { name: "First" }));
expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("href", "https://example.com/");
expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener");
expect(within(menu).queryByRole("button", { name: "Preview website" })).not.toBeInTheDocument();
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible();
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible();
});
it("does not show an entry for a message without a rendered web link", async () => {
render(view("No links here. `https://example.com/code` [Mail](mailto:test@example.com) [Unsafe](javascript:alert)"));
await screen.findByText(/No links here/);
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.queryByRole("button", { name: "View links" })).not.toBeInTheDocument();
});
it("opens the single link's actions directly and closes the message menu on preview", async () => {
const preview = vi.fn();
render(view("[Website](https://example.com/demo?q=one#two)", preview));
await screen.findByRole("link", { name: /Website/ });
const menu = await openLinks();
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.click(within(menu).getByRole("button", { name: "Preview website" }));
expect(preview).toHaveBeenCalledWith("https://example.com/demo?q=one#two");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
expect(screen.getByRole("button", { name: "View links" })).toBeVisible();
});
it("provides copy feedback and retry without losing the selected link", async () => {
vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
render(view("[Website](https://example.com/demo)"));
await screen.findByRole("link", { name: /Website/ });
const menu = await openLinks();
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
expect(await screen.findByRole("status")).toHaveTextContent("Could not copy link");
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied"));
expect(copyTextToClipboard).toHaveBeenLastCalledWith("https://example.com/demo");
fireEvent.keyDown(menu, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Message actions" })).toHaveFocus();
});
it("ignores late copy feedback after going back", async () => {
let finish!: (result: boolean) => void;
vi.mocked(copyTextToClipboard).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(view("[Old](https://example.com/old)"));
await screen.findByRole("link", { name: /Old/ });
const menu = await openLinks();
fireEvent.click(within(menu).getByRole("button", { name: "Copy link" }));
fireEvent.click(within(menu).getByRole("button", { name: "Back" }));
await act(async () => finish(true));
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible();
});
it("tracks newly rendered or changed links only within the owning message", async () => {
function LiveMessage({ href }: { href: string | null }) {
const root = useRef<HTMLDivElement>(null);
const links = useMessageWebLinks(root, true);
return <><WebLink href="https://elsewhere.invalid/">Another message</WebLink>
<div ref={root}>
<WebLink href="https://activity.invalid/">An activity link, not part of the reply</WebLink>
<div data-assistant-selectable>{href ? <WebLink href={href}>Current link</WebLink> : null}</div>
</div>
<output>{links.map(link => link.href).join(",")}</output></>;
}
const { rerender } = render(<LiveMessage href={null} />);
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender(<LiveMessage href="https://example.com/old" />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/old$/));
rerender(<LiveMessage href="https://example.com/new" />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/new$/));
rerender(<LiveMessage href={null} />);
await waitFor(() => expect(screen.getByRole("status")).toBeEmptyDOMElement());
});
});
@@ -283,8 +283,13 @@ describe("temporary chat navigation", () => {
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
fireEvent.keyDown(window, { key: "Escape" });
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
// The same pane is reachable with taps only, without intercepting a native
// touch context menu or adding a button next to every rendered link.
fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
fireEvent.click(await screen.findByRole("button", { name: "View links" }));
fireEvent.click(await screen.findByRole("button", { name: "Preview website" }));
await screen.findByTestId("web-preview-panel");
expect(screen.queryByRole("dialog", { name: "Message actions" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
await screen.findByText("Preview of notes.txt");
+24 -25
View File
@@ -145,45 +145,44 @@ describe("web link actions", () => {
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
expect(link).not.toHaveFocus();
});
it("opens on a touch hold and suppresses the following ghost click, but keeps the next tap usable", async () => {
it("leaves touch holds, native context menus and subsequent taps to the browser", async () => {
vi.useFakeTimers();
const onClick = vi.fn();
render(<WebLink href="https://example.com/" onClick={onClick}>Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 150 });
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(screen.getByRole("menu")).toBeInTheDocument();
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
expect(fireEvent.contextMenu(link)).toBe(true);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
expect(link.className).not.toContain("touch-callout");
fireEvent.pointerUp(link, { pointerId: 1, pointerType: "touch" });
expect(fireEvent.click(link)).toBe(false);
expect(onClick).not.toHaveBeenCalled();
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
await act(async () => { await vi.advanceTimersByTimeAsync(300); });
fireEvent.pointerDown(link, { pointerId: 2, pointerType: "touch", isPrimary: true, button: 0 });
fireEvent.pointerUp(link, { pointerId: 2, pointerType: "touch" });
expect(fireEvent.click(link)).toBe(true);
expect(onClick).toHaveBeenCalledTimes(1);
});
it.each(["move", "cancel", "leave", "short tap", "second finger"])("cancels touch hold on %s", async (reason) => {
vi.useFakeTimers();
it("still supports a mouse and keyboard after touch on a hybrid device", () => {
render(<WebLink href="https://example.com/">Example</WebLink>);
const link = screen.getByRole("link", { name: "Example" });
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 100 });
if (reason === "move") fireEvent.pointerMove(link, { pointerId: 1, clientX: 100, clientY: 125 });
else if (reason === "cancel") fireEvent.pointerCancel(link);
else if (reason === "leave") fireEvent.pointerLeave(link);
else if (reason === "short tap") fireEvent.pointerUp(link);
else fireEvent.pointerDown(link, { pointerId: 2, pointerType: "touch", isPrimary: false, button: 0 });
await act(async () => { await vi.advanceTimersByTimeAsync(700); });
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
fireEvent.pointerDown(link, { pointerType: "touch" });
fireEvent.pointerDown(link, { pointerType: "mouse", button: 2 });
expect(fireEvent.contextMenu(link)).toBe(false);
expect(screen.getByRole("menu")).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
fireEvent.pointerDown(link, { pointerType: "touch" });
fireEvent.keyDown(link, { key: "F10", shiftKey: true });
expect(screen.getByRole("menu")).toBeInTheDocument();
});
it("cancels pending holds and discards an open menu when its URL changes", async () => {
vi.useFakeTimers();
it("leaves a coarse-pointer context menu native even without a preceding pointer event", () => {
const original = window.matchMedia;
const media = vi.spyOn(window, "matchMedia").mockImplementation(query => ({ ...original(query), matches: query === "(pointer: coarse)" }));
render(<WebLink href="https://example.com/">Example</WebLink>);
expect(fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }))).toBe(true);
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
media.mockRestore();
});
it("discards an open menu when its URL changes", () => {
const view = (href: string) => <WebLink href={href}>Example</WebLink>;
const { rerender } = render(view("https://example.com/old"));
fireEvent.pointerDown(screen.getByRole("link", { name: "Example" }), { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0 });
rerender(view("https://example.com/new"));
await act(async () => { await vi.advanceTimersByTimeAsync(700); });
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
expect(screen.getByRole("menu")).toBeInTheDocument();
rerender(view("https://example.com/third"));