refactor(webui): keep website actions in compact context menus
This commit is contained in:
1 parent
c2edd5632e
commit
b08c9da8de
5 files changed
+214
-70
No files matched your search
+4
-2
@@ -458,8 +458,10 @@ private, trusted network.
|
|||||||
### Links and website previews
|
### Links and website previews
|
||||||
|
|
||||||
HTTP(S) links in replies have a **Link actions** menu: right-click the link,
|
HTTP(S) links in replies have a **Link actions** menu: right-click the link,
|
||||||
press Shift+F10 while it is focused, or use its ellipsis button. You can copy the
|
press Shift+F10 while it is focused, or touch and hold it. There is no persistent
|
||||||
link, open it in a browser tab, or preview it beside the current conversation.
|
action button beside the link. Scrolling or a short tap does not open the menu.
|
||||||
|
You can copy the link, open it in a browser tab, or preview it beside the current
|
||||||
|
conversation.
|
||||||
Ordinary clicks still open links in a browser tab. File and session links keep
|
Ordinary clicks still open links in a browser tab. File and session links keep
|
||||||
their own behavior.
|
their own behavior.
|
||||||
|
|
||||||
|
|||||||
@@ -453,7 +453,6 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<WebLink
|
<WebLink
|
||||||
layout="row"
|
|
||||||
href={link.href}
|
href={link.href}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noreferrer noopener"
|
rel="noreferrer noopener"
|
||||||
|
|||||||
@@ -1,67 +1,126 @@
|
|||||||
import { createContext, useContext, useEffect, useState, type ComponentPropsWithoutRef } from "react";
|
import { createContext, useContext, useEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
|
||||||
import { Copy, ExternalLink, MoreHorizontal, PanelRight } from "lucide-react";
|
import * as Menu from "@radix-ui/react-menu";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClassName, floatingSurfaceMotionClassName } from "@/components/ui/floating-surface";
|
||||||
|
import { useFloatingPortal } from "@/components/ui/floating-portal";
|
||||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||||
import { parseWebLink } from "@/lib/web-preview";
|
import { parseWebLink } from "@/lib/web-preview";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);
|
export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);
|
||||||
|
|
||||||
export function WebLink({ href = "", children, layout = "inline", className, ...props }: ComponentPropsWithoutRef<"a"> & { layout?: "inline" | "row" }) {
|
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} cursor-default`;
|
||||||
|
|
||||||
|
export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutRef<"a">) {
|
||||||
|
const url = parseWebLink(href);
|
||||||
|
if (url) return <WebsiteLink key={href} {...props} href={href}>{children}</WebsiteLink>;
|
||||||
|
// Keep the renderer's relative media/document and mail links unchanged.
|
||||||
|
const relative = !/^[a-z][a-z\d+.-]*:/i.test(href)
|
||||||
|
&& !href.includes("\\") && !Array.from(href).some((char) => char.charCodeAt(0) < 32);
|
||||||
|
return relative || /^(mailto:|tel:|#)/i.test(href)
|
||||||
|
? <a {...props} href={href} target="_blank" rel="noreferrer noopener">{children}</a> : <>{children}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Keep links as links; secondary actions share the compact file-reference surface. */
|
||||||
|
function WebsiteLink({ href, children, className, ...props }: ComponentPropsWithoutRef<"a"> & { href: string }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const openPreview = useContext(WebPreviewContext);
|
const openPreview = useContext(WebPreviewContext);
|
||||||
|
const portal = useFloatingPortal();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [feedback, setFeedback] = useState("");
|
const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
|
||||||
useEffect(() => {
|
const link = useRef<HTMLAnchorElement>(null);
|
||||||
if (!feedback) return;
|
const point = useRef({ x: 0, y: 0 });
|
||||||
const timer = window.setTimeout(() => setFeedback(""), 4000);
|
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
|
||||||
return () => window.clearTimeout(timer);
|
const interactedOutside = useRef(false);
|
||||||
}, [feedback]);
|
const generation = useRef(0);
|
||||||
const url = parseWebLink(href);
|
const press = useRef<{ id: number; x: number; y: number; timer: number } | null>(null);
|
||||||
const anchor = <a {...props} className={cn(className, layout === "row" && "min-w-0 flex-1")} href={href} target="_blank" rel="noreferrer noopener">{children}</a>;
|
const suppressClick = useRef(false);
|
||||||
if (!url) {
|
|
||||||
// Keep the renderer's relative media/document and mail links unchanged.
|
const cancelPress = () => {
|
||||||
const relative = !/^[a-z][a-z\d+.-]*:/i.test(href)
|
if (press.current) window.clearTimeout(press.current.timer);
|
||||||
&& !href.includes("\\") && !Array.from(href).some((char) => char.charCodeAt(0) < 32);
|
press.current = null;
|
||||||
return relative || /^(mailto:|tel:|#)/i.test(href) ? anchor : <>{children}</>;
|
};
|
||||||
}
|
useEffect(() => () => {
|
||||||
return (
|
cancelPress();
|
||||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
generation.current += 1;
|
||||||
<span className={cn("max-w-full", layout === "row" ? "inline-flex w-full min-w-0 items-center" : "inline")} onContextMenu={(event) => {
|
}, []);
|
||||||
event.preventDefault(); event.stopPropagation(); setOpen(true);
|
|
||||||
}} onKeyDown={(event) => {
|
const changeOpen = (next: boolean) => {
|
||||||
if ((event.shiftKey && event.key === "F10") || event.key === "ContextMenu") {
|
cancelPress();
|
||||||
event.preventDefault(); event.stopPropagation(); setOpen(true);
|
generation.current += 1;
|
||||||
}
|
setOpen(next);
|
||||||
|
};
|
||||||
|
const openAt = (x: number, y: number) => {
|
||||||
|
point.current = { x, y };
|
||||||
|
interactedOutside.current = false;
|
||||||
|
setFeedback(null);
|
||||||
|
changeOpen(true);
|
||||||
|
};
|
||||||
|
const copy = async () => {
|
||||||
|
const current = generation.current;
|
||||||
|
const copied = await copyTextToClipboard(href);
|
||||||
|
// Late clipboard results must not dismiss a new menu or report another URL.
|
||||||
|
if (current !== generation.current) return;
|
||||||
|
setFeedback(copied ? "copied" : "copyFailed");
|
||||||
|
if (copied) changeOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return <Menu.Root open={open} onOpenChange={changeOpen}>
|
||||||
|
<Menu.Anchor virtualRef={anchor} />
|
||||||
|
<span className="inline max-w-full"
|
||||||
|
onContextMenu={(event) => {
|
||||||
|
event.preventDefault(); event.stopPropagation();
|
||||||
|
openAt(event.clientX, event.clientY);
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
suppressClick.current = false;
|
||||||
|
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
||||||
|
event.preventDefault(); event.stopPropagation();
|
||||||
|
const bounds = link.current!.getBoundingClientRect();
|
||||||
|
openAt(bounds.left, bounds.bottom);
|
||||||
|
}}
|
||||||
|
onPointerDown={(event) => {
|
||||||
|
suppressClick.current = false;
|
||||||
|
cancelPress();
|
||||||
|
if (event.pointerType !== "touch" || !event.isPrimary || event.button !== 0) return;
|
||||||
|
const { pointerId: id, clientX: x, clientY: y } = event;
|
||||||
|
press.current = { id, x, y, timer: window.setTimeout(() => {
|
||||||
|
suppressClick.current = true;
|
||||||
|
openAt(x, y);
|
||||||
|
}, 600) };
|
||||||
|
}}
|
||||||
|
onPointerMove={(event) => {
|
||||||
|
const current = press.current;
|
||||||
|
if (current && (event.pointerId !== current.id || Math.hypot(event.clientX - current.x, event.clientY - current.y) > 10)) cancelPress();
|
||||||
|
}}
|
||||||
|
onPointerUp={cancelPress} onPointerCancel={cancelPress} onPointerLeave={cancelPress}
|
||||||
|
onClickCapture={(event) => {
|
||||||
|
if (!suppressClick.current) return;
|
||||||
|
suppressClick.current = false;
|
||||||
|
event.preventDefault(); event.stopPropagation();
|
||||||
}}>
|
}}>
|
||||||
{anchor}
|
<a {...props} ref={link} href={href} target="_blank" rel="noreferrer noopener"
|
||||||
<DropdownMenuTrigger asChild>
|
className={cn(className, "[-webkit-touch-callout:none]")}>{children}</a>
|
||||||
<button type="button" aria-label={t("webPreview.actions")} title={t("webPreview.actions")}
|
</span>
|
||||||
className="ml-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md align-middle text-muted-foreground/70 hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
{feedback === "copied" ? <span role="status" className="sr-only">{t("webPreview.copied")}</span> : null}
|
||||||
<MoreHorizontal className="h-3.5 w-3.5" aria-hidden />
|
<Menu.Portal container={portal ?? undefined}>
|
||||||
</button>
|
<Menu.Content aria-label={t("webPreview.actions")} align="start" sideOffset={4} collisionPadding={12}
|
||||||
</DropdownMenuTrigger>
|
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 rounded-control p-1 [&_[role=menuitem]]:py-1.5 [@media(pointer:coarse)]:[&_[role=menuitem]]:min-h-11")}
|
||||||
</span>
|
onContextMenu={(event) => { event.preventDefault(); event.stopPropagation(); }}
|
||||||
<DropdownMenuContent align="start">
|
onClick={(event) => event.stopPropagation()}
|
||||||
<DropdownMenuLabel className="max-w-64 truncate">{url.host}</DropdownMenuLabel>
|
onInteractOutside={() => { interactedOutside.current = true; }}
|
||||||
{openPreview ? <DropdownMenuItem onSelect={() => openPreview(url.href)}>
|
onCloseAutoFocus={(event) => {
|
||||||
<PanelRight className="h-4 w-4" aria-hidden />{t("webPreview.open")}
|
|
||||||
</DropdownMenuItem> : null}
|
|
||||||
<DropdownMenuItem asChild>
|
|
||||||
<a href={url.href} target="_blank" rel="noreferrer noopener">
|
|
||||||
<ExternalLink className="h-4 w-4" aria-hidden />{t("webPreview.external")}
|
|
||||||
</a>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem onSelect={(event) => {
|
|
||||||
// Keep the menu/focus alive until the clipboard fallback finishes.
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
setFeedback("");
|
if (!interactedOutside.current) link.current?.focus();
|
||||||
void copyTextToClipboard(url.href).then((copied) => setFeedback(t(copied ? "webPreview.copied" : "webPreview.copyFailed")));
|
}}>
|
||||||
}}><Copy className="h-4 w-4" aria-hidden />{t("webPreview.copy")}</DropdownMenuItem>
|
{openPreview ? <Menu.Item className={itemClassName} onSelect={() => openPreview(href)}>{t("webPreview.open")}</Menu.Item> : null}
|
||||||
{feedback ? <div role="status" className="px-2.5 py-1.5 text-xs text-muted-foreground">{feedback}</div> : null}
|
<Menu.Item asChild className={itemClassName}>
|
||||||
</DropdownMenuContent>
|
<a href={href} target="_blank" rel="noreferrer noopener">{t("webPreview.external")}</a>
|
||||||
</DropdownMenu>
|
</Menu.Item>
|
||||||
);
|
<Menu.Item className={itemClassName} onSelect={(event) => { event.preventDefault(); void copy(); }}>{t("webPreview.copy")}</Menu.Item>
|
||||||
|
{feedback === "copyFailed" ? <div role="status" className="max-w-64 px-2.5 py-1.5 text-xs text-muted-foreground">{t("webPreview.copyFailed")}</div> : null}
|
||||||
|
</Menu.Content>
|
||||||
|
</Menu.Portal>
|
||||||
|
</Menu.Root>;
|
||||||
}
|
}
|
||||||
@@ -158,13 +158,16 @@ describe("temporary chat navigation", () => {
|
|||||||
act(() => TestSocket.current.open());
|
act(() => TestSocket.current.open());
|
||||||
await selectTopic("Regular topic");
|
await selectTopic("Regular topic");
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
|
||||||
const content = await screen.findByText("Preview of notes.txt");
|
await screen.findByText("Preview of notes.txt");
|
||||||
|
const panel = screen.getByTestId("file-preview-panel");
|
||||||
const fullPreviewRequests = () => vi.mocked(fetch).mock.calls.filter(([url]) =>
|
const fullPreviewRequests = () => vi.mocked(fetch).mock.calls.filter(([url]) =>
|
||||||
String(url).includes("/file-preview?path=") && !String(url).includes("probe=") && !String(url).includes("metadata="));
|
String(url).includes("/file-preview?path=") && !String(url).includes("probe=") && !String(url).includes("metadata="));
|
||||||
expect(fullPreviewRequests()).toHaveLength(1);
|
expect(fullPreviewRequests()).toHaveLength(1);
|
||||||
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });
|
await act(async () => { await vi.advanceTimersByTimeAsync(15_000); });
|
||||||
expect(fetchBootstrap).toHaveBeenCalledTimes(2);
|
expect(fetchBootstrap).toHaveBeenCalledTimes(2);
|
||||||
expect(screen.getByText("Preview of notes.txt")).toBe(content);
|
// Lazy syntax highlighting can replace text spans independently of token refresh.
|
||||||
|
expect(screen.getByTestId("file-preview-panel")).toBe(panel);
|
||||||
|
expect(screen.getByText("Preview of notes.txt")).toBeInTheDocument();
|
||||||
expect(fullPreviewRequests()).toHaveLength(1);
|
expect(fullPreviewRequests()).toHaveLength(1);
|
||||||
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
fireEvent.click(screen.getByRole("button", { name: "second.txt" }));
|
||||||
await screen.findByText("Preview of second.txt");
|
await screen.findByText("Preview of second.txt");
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
|
// @vitest-environment-options {"settings":{"disableIframePageLoading":true}}
|
||||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { WebLink, WebPreviewContext } from "@/components/WebLink";
|
import { WebLink, WebPreviewContext } from "@/components/WebLink";
|
||||||
@@ -19,6 +19,8 @@ beforeEach(() => {
|
|||||||
Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", { configurable: true, value: false });
|
Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", { configurable: true, value: false });
|
||||||
});
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.useRealTimers();
|
||||||
if (credentialless) Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", credentialless);
|
if (credentialless) Object.defineProperty(HTMLIFrameElement.prototype, "credentialless", credentialless);
|
||||||
else Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
|
else Reflect.deleteProperty(HTMLIFrameElement.prototype, "credentialless");
|
||||||
});
|
});
|
||||||
@@ -76,21 +78,23 @@ describe("web preview boundaries", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("web link actions", () => {
|
describe("web link actions", () => {
|
||||||
it("reserves room for actions beside a full-width link row without changing inline links", () => {
|
it("keeps the primary link without a persistent action button or extra tab stop", () => {
|
||||||
const { rerender } = render(<WebLink layout="row" href="https://example.com/">Long website title</WebLink>);
|
render(<WebLink href="https://example.com/">Long website title</WebLink>);
|
||||||
const link = screen.getByRole("link", { name: "Long website title" });
|
const link = screen.getByRole("link", { name: "Long website title" });
|
||||||
expect(link.parentElement).toHaveClass("inline-flex", "w-full");
|
expect(link).toHaveAttribute("href", "https://example.com/");
|
||||||
expect(link).toHaveClass("min-w-0", "flex-1");
|
expect(link).toHaveAttribute("target", "_blank");
|
||||||
expect(screen.getByRole("button", { name: "Link actions" })).toHaveClass("shrink-0");
|
expect(link).toHaveAttribute("rel", "noreferrer noopener");
|
||||||
rerender(<WebLink href="https://example.com/">Long website title</WebLink>);
|
expect(screen.queryByRole("button")).not.toBeInTheDocument();
|
||||||
expect(link.parentElement).toHaveClass("inline");
|
expect(fireEvent.click(link)).toBe(true);
|
||||||
expect(link).not.toHaveClass("flex-1");
|
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
it("opens a shared right-click menu without loading any website beforehand", async () => {
|
it("opens a shared right-click menu without loading any website beforehand", async () => {
|
||||||
const open = vi.fn();
|
const open = vi.fn();
|
||||||
const { container } = render(<WebPreviewContext.Provider value={open}><WebLink href="https://example.com/?a=b#c">Example</WebLink></WebPreviewContext.Provider>);
|
const { container } = render(<WebPreviewContext.Provider value={open}><WebLink href="https://example.com/?a=b#c">Example</WebLink></WebPreviewContext.Provider>);
|
||||||
expect(container.querySelector("iframe")).toBeNull();
|
expect(container.querySelector("iframe")).toBeNull();
|
||||||
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
|
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
|
||||||
|
expect(screen.getAllByRole("menuitem")).toHaveLength(3);
|
||||||
|
expect(screen.queryByText("example.com")).not.toBeInTheDocument();
|
||||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
||||||
expect(open).toHaveBeenCalledWith("https://example.com/?a=b#c");
|
expect(open).toHaveBeenCalledWith("https://example.com/?a=b#c");
|
||||||
});
|
});
|
||||||
@@ -99,14 +103,91 @@ describe("web link actions", () => {
|
|||||||
fireEvent.keyDown(screen.getByRole("link", { name: "Example" }), { key: "F10", shiftKey: true });
|
fireEvent.keyDown(screen.getByRole("link", { name: "Example" }), { key: "F10", shiftKey: true });
|
||||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
|
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
|
||||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied"));
|
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied"));
|
||||||
expect(screen.getByRole("menu")).toBeInTheDocument();
|
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||||
|
expect(screen.getByRole("link", { name: "Example" })).toHaveFocus();
|
||||||
expect(copyTextToClipboard).toHaveBeenCalledWith("https://example.com/?q=one#two");
|
expect(copyTextToClipboard).toHaveBeenCalledWith("https://example.com/?q=one#two");
|
||||||
expect(screen.queryByRole("menuitem", { name: "Preview website" })).not.toBeInTheDocument();
|
expect(screen.queryByRole("menuitem", { name: "Preview website" })).not.toBeInTheDocument();
|
||||||
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
|
vi.mocked(copyTextToClipboard).mockResolvedValue(false);
|
||||||
await userEvent.setup().keyboard("{Escape}");
|
fireEvent.keyDown(screen.getByRole("link", { name: "Example" }), { key: "ContextMenu" });
|
||||||
await userEvent.setup().click(screen.getByRole("button", { name: "Link actions" }));
|
|
||||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
|
fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));
|
||||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Could not copy link"));
|
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Could not copy link"));
|
||||||
|
expect(screen.getByRole("menu")).toBeInTheDocument();
|
||||||
|
vi.mocked(copyTextToClipboard).mockResolvedValue(true);
|
||||||
|
fireEvent.click(screen.getByRole("menuitem", { name: "Copy link" }));
|
||||||
|
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||||
|
});
|
||||||
|
it("ignores a late copy completion after the user reopens the menu", async () => {
|
||||||
|
let finish!: (result: boolean) => void;
|
||||||
|
vi.mocked(copyTextToClipboard).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
|
||||||
|
render(<WebLink href="https://example.com/">Example</WebLink>);
|
||||||
|
const link = screen.getByRole("link", { name: "Example" });
|
||||||
|
fireEvent.contextMenu(link);
|
||||||
|
fireEvent.click(screen.getByRole("menuitem", { name: "Copy link" }));
|
||||||
|
await userEvent.setup().keyboard("{Escape}");
|
||||||
|
fireEvent.contextMenu(link);
|
||||||
|
await act(async () => finish(true));
|
||||||
|
expect(screen.getByRole("menu")).toBeInTheDocument();
|
||||||
|
expect(screen.queryByRole("status")).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
it("closes with Escape and restores focus, without stealing an outside click", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<><WebLink href="https://example.com/">Example</WebLink><button>Elsewhere</button></>);
|
||||||
|
const link = screen.getByRole("link", { name: "Example" });
|
||||||
|
fireEvent.keyDown(link, { key: "F10", shiftKey: true });
|
||||||
|
await user.keyboard("{Escape}");
|
||||||
|
await waitFor(() => expect(link).toHaveFocus());
|
||||||
|
fireEvent.contextMenu(link);
|
||||||
|
// Radix's modal menu disables hit testing on underlying controls. A real
|
||||||
|
// outside pointer first dismisses the menu rather than activating that control.
|
||||||
|
// Its document listener is deferred until the opening pointer event finishes.
|
||||||
|
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||||
|
fireEvent.pointerDown(document.body, { pointerType: "mouse", button: 0 });
|
||||||
|
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 () => {
|
||||||
|
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();
|
||||||
|
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();
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
it("cancels pending holds and discards an open menu when its URL changes", async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
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"));
|
||||||
|
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
it("does not add web actions for mail, files or executable addresses", () => {
|
it("does not add web actions for mail, files or executable addresses", () => {
|
||||||
render(<><WebLink href="mailto:test@example.com">Mail</WebLink><WebLink href="javascript:alert(1)">Unsafe</WebLink><WebLink href="file:///notes">File</WebLink></>);
|
render(<><WebLink href="mailto:test@example.com">Mail</WebLink><WebLink href="javascript:alert(1)">Unsafe</WebLink><WebLink href="file:///notes">File</WebLink></>);
|
||||||
|
|||||||
Reference in new issue
Block a user