fix(webui): preserve native touch menus with message link actions
This commit is contained in:
1 parent
b08c9da8de
commit
4693bba81f
18 files changed
+291
-65
No files matched your search
+8
-5
@@ -457,11 +457,14 @@ 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 or
|
||||||
press Shift+F10 while it is focused, or touch and hold it. There is no persistent
|
press Shift+F10 while it is focused. Touch and hold keeps the browser's native
|
||||||
action button beside the link. Scrolling or a short tap does not open the menu.
|
link menu. For in-app actions on touch devices, open the message's existing
|
||||||
You can copy the link, open it in a browser tab, or preview it beside the current
|
**Message actions → View links** entry. It lists only the web links rendered in
|
||||||
conversation.
|
that message, not URLs inside code blocks or file references. Choose a link to
|
||||||
|
copy it, open it externally, or preview it beside the current conversation.
|
||||||
|
There is no persistent action button beside each link and no custom long-press
|
||||||
|
gesture to interfere with scrolling or text selection.
|
||||||
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.
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
CircleAlert,
|
CircleAlert,
|
||||||
Clock3,
|
Clock3,
|
||||||
Copy,
|
Copy,
|
||||||
|
Link2,
|
||||||
Quote,
|
Quote,
|
||||||
Wrench,
|
Wrench,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
@@ -131,6 +132,7 @@ interface MessageBlockMenuActionsProps {
|
|||||||
isTurnStreaming?: boolean;
|
isTurnStreaming?: boolean;
|
||||||
onForkFromHere?: () => void;
|
onForkFromHere?: () => void;
|
||||||
activity?: MessageBlockMenuActivity;
|
activity?: MessageBlockMenuActivity;
|
||||||
|
onViewLinks?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Actions and metadata shown after opening a visual message block's context panel. */
|
/** Actions and metadata shown after opening a visual message block's context panel. */
|
||||||
@@ -139,6 +141,7 @@ export function MessageBlockMenuActions({
|
|||||||
isTurnStreaming = false,
|
isTurnStreaming = false,
|
||||||
onForkFromHere,
|
onForkFromHere,
|
||||||
activity,
|
activity,
|
||||||
|
onViewLinks,
|
||||||
}: MessageBlockMenuActionsProps) {
|
}: MessageBlockMenuActionsProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const content = message.role === "assistant"
|
const content = message.role === "assistant"
|
||||||
@@ -274,6 +277,10 @@ export function MessageBlockMenuActions({
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
{onViewLinks ? <button type="button" data-message-links-trigger onClick={onViewLinks}
|
||||||
|
className="flex min-h-[var(--message-block-control-size)] w-full items-center gap-2 rounded-control px-2 py-1.5 text-[13px] text-muted-foreground hover:bg-muted/70 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||||
|
<Link2 className="h-3.5 w-3.5" aria-hidden />{t("webPreview.viewLinks")}
|
||||||
|
</button> : null}
|
||||||
<FallbackResponseSources
|
<FallbackResponseSources
|
||||||
sources={message.role === "assistant" ? message.responseSources : undefined}
|
sources={message.role === "assistant" ? message.responseSources : undefined}
|
||||||
className="min-h-[var(--message-block-control-size)] gap-1"
|
className="min-h-[var(--message-block-control-size)] gap-1"
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { useContext, useLayoutEffect, useRef, useState, type RefObject } from "react";
|
||||||
|
import { ArrowLeft, ChevronRight, Link2 } from "lucide-react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
import { WebPreviewContext } from "@/components/WebLink";
|
||||||
|
import { floatingItemClassName, floatingItemFocusClassName } from "@/components/ui/floating-surface";
|
||||||
|
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||||
|
import { parseWebLink } from "@/lib/web-preview";
|
||||||
|
|
||||||
|
interface MessageWebLink { href: string; title: string }
|
||||||
|
|
||||||
|
/** Read only links actually rendered in this message, not code samples or file references. */
|
||||||
|
export function useMessageWebLinks(root: RefObject<HTMLElement>, open: boolean) {
|
||||||
|
const [links, setLinks] = useState<MessageWebLink[]>([]);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const element = root.current;
|
||||||
|
if (!open || !element) return;
|
||||||
|
const collect = () => {
|
||||||
|
const unique = new Map<string, MessageWebLink>();
|
||||||
|
element.querySelectorAll<HTMLAnchorElement>("[data-assistant-selectable] a[data-web-link]").forEach((anchor) => {
|
||||||
|
const href = anchor.getAttribute("href") ?? "";
|
||||||
|
const url = parseWebLink(href);
|
||||||
|
if (url && !unique.has(url.href)) {
|
||||||
|
unique.set(url.href, { href, title: anchor.textContent?.trim() || href });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
setLinks(Array.from(unique.values()));
|
||||||
|
};
|
||||||
|
collect();
|
||||||
|
// Markdown is lazy-loaded; collect again when its real links appear/change.
|
||||||
|
const observer = new MutationObserver(collect);
|
||||||
|
observer.observe(element, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["href"] });
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [root, open]);
|
||||||
|
return links;
|
||||||
|
}
|
||||||
|
|
||||||
|
const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} w-full min-h-11 text-start hover:bg-muted/70`;
|
||||||
|
|
||||||
|
/** A drill-in inside the existing message popover, not another floating layer. */
|
||||||
|
export function MessageLinksMenu({ links, onBack, onClose }: {
|
||||||
|
links: MessageWebLink[];
|
||||||
|
onBack: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const openPreview = useContext(WebPreviewContext);
|
||||||
|
const [selected, setSelected] = useState<string | null>(links.length === 1 ? links[0].href : null);
|
||||||
|
const active = links.find((link) => link.href === selected);
|
||||||
|
const backRef = useRef<HTMLButtonElement>(null);
|
||||||
|
useLayoutEffect(() => { backRef.current?.focus({ preventScroll: true }); }, [selected]);
|
||||||
|
return <div className="w-60 max-w-full">
|
||||||
|
<button ref={backRef} type="button" className={itemClassName} aria-label={t("webPreview.back")}
|
||||||
|
onClick={() => active && links.length > 1 ? setSelected(null) : onBack()}>
|
||||||
|
<ArrowLeft aria-hidden /><span>{t("webPreview.viewLinks")}</span>
|
||||||
|
</button>
|
||||||
|
{active ? <MessageLinkActions key={active.href} link={active} onClose={onClose}
|
||||||
|
onPreview={openPreview ? () => { onClose(); openPreview(active.href); } : undefined} />
|
||||||
|
: <div className="border-t border-border/45 pt-1">
|
||||||
|
{links.map((link) => <button type="button" key={link.href} className={itemClassName} onClick={() => setSelected(link.href)}>
|
||||||
|
<Link2 className="text-muted-foreground" aria-hidden />
|
||||||
|
<span className="min-w-0 flex-1 truncate">{link.title}</span><ChevronRight className="text-muted-foreground" aria-hidden />
|
||||||
|
</button>)}
|
||||||
|
</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function MessageLinkActions({ link, onClose, onPreview }: {
|
||||||
|
link: MessageWebLink;
|
||||||
|
onClose: () => void;
|
||||||
|
onPreview?: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
|
||||||
|
const mounted = useRef(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
mounted.current = true;
|
||||||
|
return () => { mounted.current = false; };
|
||||||
|
}, []);
|
||||||
|
const copy = async () => {
|
||||||
|
const success = await copyTextToClipboard(link.href);
|
||||||
|
if (mounted.current) setFeedback(success ? "copied" : "copyFailed");
|
||||||
|
};
|
||||||
|
return <div className="border-t border-border/45 pt-1">
|
||||||
|
<p className="max-h-24 overflow-y-auto px-2.5 py-2 text-xs text-muted-foreground [overflow-wrap:anywhere]" dir="auto">{link.href}</p>
|
||||||
|
{onPreview ? <button type="button" className={itemClassName} onClick={onPreview}>{t("webPreview.open")}</button> : null}
|
||||||
|
<a className={itemClassName} href={link.href} target="_blank" rel="noreferrer noopener" onClick={onClose}>{t("webPreview.external")}</a>
|
||||||
|
<button type="button" className={itemClassName} onClick={() => { void copy(); }}>{t("webPreview.copy")}</button>
|
||||||
|
{feedback ? <p role="status" className="px-2.5 py-1.5 text-xs text-muted-foreground">{t(`webPreview.${feedback}`)}</p> : null}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -34,20 +34,13 @@ function WebsiteLink({ href, children, className, ...props }: ComponentPropsWith
|
|||||||
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
|
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
|
||||||
const interactedOutside = useRef(false);
|
const interactedOutside = useRef(false);
|
||||||
const generation = useRef(0);
|
const generation = useRef(0);
|
||||||
const press = useRef<{ id: number; x: number; y: number; timer: number } | null>(null);
|
const pointerType = useRef("");
|
||||||
const suppressClick = useRef(false);
|
|
||||||
|
|
||||||
const cancelPress = () => {
|
|
||||||
if (press.current) window.clearTimeout(press.current.timer);
|
|
||||||
press.current = null;
|
|
||||||
};
|
|
||||||
useEffect(() => () => {
|
useEffect(() => () => {
|
||||||
cancelPress();
|
|
||||||
generation.current += 1;
|
generation.current += 1;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const changeOpen = (next: boolean) => {
|
const changeOpen = (next: boolean) => {
|
||||||
cancelPress();
|
|
||||||
generation.current += 1;
|
generation.current += 1;
|
||||||
setOpen(next);
|
setOpen(next);
|
||||||
};
|
};
|
||||||
@@ -70,38 +63,25 @@ function WebsiteLink({ href, children, className, ...props }: ComponentPropsWith
|
|||||||
<Menu.Anchor virtualRef={anchor} />
|
<Menu.Anchor virtualRef={anchor} />
|
||||||
<span className="inline max-w-full"
|
<span className="inline max-w-full"
|
||||||
onContextMenu={(event) => {
|
onContextMenu={(event) => {
|
||||||
event.preventDefault(); event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
// Touch keeps the browser's native link preview/copy/share menu. Older
|
||||||
|
// WebKit exposes contextmenu as a MouseEvent, so remember the last pointer.
|
||||||
|
const type = (event.nativeEvent as PointerEvent).pointerType || pointerType.current;
|
||||||
|
if (type === "touch" || (!type && window.matchMedia("(pointer: coarse)").matches)) return;
|
||||||
|
event.preventDefault();
|
||||||
openAt(event.clientX, event.clientY);
|
openAt(event.clientX, event.clientY);
|
||||||
}}
|
}}
|
||||||
onKeyDown={(event) => {
|
onKeyDown={(event) => {
|
||||||
suppressClick.current = false;
|
|
||||||
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
|
||||||
event.preventDefault(); event.stopPropagation();
|
event.preventDefault(); event.stopPropagation();
|
||||||
const bounds = link.current!.getBoundingClientRect();
|
const bounds = link.current!.getBoundingClientRect();
|
||||||
openAt(bounds.left, bounds.bottom);
|
openAt(bounds.left, bounds.bottom);
|
||||||
}}
|
}}
|
||||||
onPointerDown={(event) => {
|
onPointerDown={(event) => {
|
||||||
suppressClick.current = false;
|
pointerType.current = event.pointerType;
|
||||||
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();
|
|
||||||
}}>
|
}}>
|
||||||
<a {...props} ref={link} href={href} target="_blank" rel="noreferrer noopener"
|
<a {...props} ref={link} data-web-link href={href} target="_blank" rel="noreferrer noopener"
|
||||||
className={cn(className, "[-webkit-touch-callout:none]")}>{children}</a>
|
className={className}>{children}</a>
|
||||||
</span>
|
</span>
|
||||||
{feedback === "copied" ? <span role="status" className="sr-only">{t("webPreview.copied")}</span> : null}
|
{feedback === "copied" ? <span role="status" className="sr-only">{t("webPreview.copied")}</span> : null}
|
||||||
<Menu.Portal container={portal ?? undefined}>
|
<Menu.Portal container={portal ?? undefined}>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||||
import { MoreHorizontal } from "lucide-react";
|
import { MoreHorizontal } from "lucide-react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
|
import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
|
||||||
|
import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu";
|
||||||
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
|
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
|
||||||
import {
|
import {
|
||||||
AgentActivityCluster,
|
AgentActivityCluster,
|
||||||
@@ -355,6 +356,7 @@ interface ThreadDisplayUnitProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MessageBlockMenuProps {
|
interface MessageBlockMenuProps {
|
||||||
|
messageRoot: RefObject<HTMLElement>;
|
||||||
message: UIMessage;
|
message: UIMessage;
|
||||||
isTurnStreaming: boolean;
|
isTurnStreaming: boolean;
|
||||||
contextBlockKey: string;
|
contextBlockKey: string;
|
||||||
@@ -372,6 +374,7 @@ interface MessageBlockMenuProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function MessageBlockMenu({
|
function MessageBlockMenu({
|
||||||
|
messageRoot,
|
||||||
message,
|
message,
|
||||||
isTurnStreaming,
|
isTurnStreaming,
|
||||||
contextBlockKey,
|
contextBlockKey,
|
||||||
@@ -385,6 +388,9 @@ function MessageBlockMenu({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const contentRef = useRef<HTMLDivElement>(null);
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||||
|
const links = useMessageWebLinks(messageRoot, open);
|
||||||
|
const [linksShown, setLinksShown] = useState(false);
|
||||||
|
useEffect(() => { if (!open) setLinksShown(false); }, [open]);
|
||||||
const [triggerHeight, setTriggerHeight] = useState(28);
|
const [triggerHeight, setTriggerHeight] = useState(28);
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
const trigger = triggerRef.current;
|
const trigger = triggerRef.current;
|
||||||
@@ -466,12 +472,15 @@ function MessageBlockMenu({
|
|||||||
"shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:shadow-[0_2px_10px_rgba(0,0,0,0.24)]",
|
"shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:shadow-[0_2px_10px_rgba(0,0,0,0.24)]",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<MessageBlockMenuActions
|
{linksShown && links.length > 0 ? <MessageLinksMenu links={links}
|
||||||
|
onBack={() => { setLinksShown(false); contentRef.current?.focus({ preventScroll: true }); }}
|
||||||
|
onClose={() => onOpenChange(false)} /> : <MessageBlockMenuActions
|
||||||
message={message}
|
message={message}
|
||||||
isTurnStreaming={isTurnStreaming}
|
isTurnStreaming={isTurnStreaming}
|
||||||
onForkFromHere={onForkFromHere}
|
onForkFromHere={onForkFromHere}
|
||||||
activity={activity}
|
activity={activity}
|
||||||
/>
|
onViewLinks={links.length > 0 ? () => setLinksShown(true) : undefined}
|
||||||
|
/>}
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
);
|
);
|
||||||
@@ -570,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
|||||||
]);
|
]);
|
||||||
const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? (
|
const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? (
|
||||||
<MessageBlockMenu
|
<MessageBlockMenu
|
||||||
|
messageRoot={elementRef}
|
||||||
message={unit.message}
|
message={unit.message}
|
||||||
isTurnStreaming={isTurnStreaming}
|
isTurnStreaming={isTurnStreaming}
|
||||||
contextBlockKey={contextBlockKey}
|
contextBlockKey={contextBlockKey}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "About website previews"
|
"websiteInfo": "About website previews"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "View links",
|
||||||
|
"back": "Back",
|
||||||
"original": "Original link",
|
"original": "Original link",
|
||||||
"actions": "Link actions",
|
"actions": "Link actions",
|
||||||
"open": "Preview website",
|
"open": "Preview website",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "Acerca de las vistas previas web"
|
"websiteInfo": "Acerca de las vistas previas web"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "Ver enlaces",
|
||||||
|
"back": "Atrás",
|
||||||
"original": "Enlace original",
|
"original": "Enlace original",
|
||||||
"actions": "Acciones del enlace",
|
"actions": "Acciones del enlace",
|
||||||
"open": "Vista previa del sitio",
|
"open": "Vista previa del sitio",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "À propos des aperçus web"
|
"websiteInfo": "À propos des aperçus web"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "Voir les liens",
|
||||||
|
"back": "Retour",
|
||||||
"original": "Lien d’origine",
|
"original": "Lien d’origine",
|
||||||
"actions": "Actions du lien",
|
"actions": "Actions du lien",
|
||||||
"open": "Aperçu du site",
|
"open": "Aperçu du site",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "Tentang pratinjau situs"
|
"websiteInfo": "Tentang pratinjau situs"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "Lihat tautan",
|
||||||
|
"back": "Kembali",
|
||||||
"original": "Tautan asli",
|
"original": "Tautan asli",
|
||||||
"actions": "Tindakan tautan",
|
"actions": "Tindakan tautan",
|
||||||
"open": "Pratinjau situs",
|
"open": "Pratinjau situs",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "ウェブプレビューについて"
|
"websiteInfo": "ウェブプレビューについて"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "リンクを表示",
|
||||||
|
"back": "戻る",
|
||||||
"original": "元のリンク",
|
"original": "元のリンク",
|
||||||
"actions": "リンク操作",
|
"actions": "リンク操作",
|
||||||
"open": "ウェブサイトをプレビュー",
|
"open": "ウェブサイトをプレビュー",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "웹 미리보기 정보"
|
"websiteInfo": "웹 미리보기 정보"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "링크 보기",
|
||||||
|
"back": "뒤로",
|
||||||
"original": "원래 링크",
|
"original": "원래 링크",
|
||||||
"actions": "링크 작업",
|
"actions": "링크 작업",
|
||||||
"open": "웹사이트 미리보기",
|
"open": "웹사이트 미리보기",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "Sobre as prévias de sites"
|
"websiteInfo": "Sobre as prévias de sites"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "Ver links",
|
||||||
|
"back": "Voltar",
|
||||||
"original": "Link original",
|
"original": "Link original",
|
||||||
"actions": "Ações do link",
|
"actions": "Ações do link",
|
||||||
"open": "Pré-visualizar site",
|
"open": "Pré-visualizar site",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "Giới thiệu về xem trước trang web"
|
"websiteInfo": "Giới thiệu về xem trước trang web"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "Xem liên kết",
|
||||||
|
"back": "Quay lại",
|
||||||
"original": "Liên kết gốc",
|
"original": "Liên kết gốc",
|
||||||
"actions": "Thao tác liên kết",
|
"actions": "Thao tác liên kết",
|
||||||
"open": "Xem trước trang web",
|
"open": "Xem trước trang web",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "关于网页预览"
|
"websiteInfo": "关于网页预览"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "查看链接",
|
||||||
|
"back": "返回",
|
||||||
"original": "原始链接",
|
"original": "原始链接",
|
||||||
"actions": "链接操作",
|
"actions": "链接操作",
|
||||||
"open": "预览网页",
|
"open": "预览网页",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
"websiteInfo": "關於網頁預覽"
|
"websiteInfo": "關於網頁預覽"
|
||||||
},
|
},
|
||||||
"webPreview": {
|
"webPreview": {
|
||||||
|
"viewLinks": "查看連結",
|
||||||
|
"back": "返回",
|
||||||
"original": "原始連結",
|
"original": "原始連結",
|
||||||
"actions": "連結操作",
|
"actions": "連結操作",
|
||||||
"open": "預覽網頁",
|
"open": "預覽網頁",
|
||||||
|
|||||||
@@ -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\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());
|
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||||
fireEvent.keyDown(window, { key: "Escape" });
|
fireEvent.keyDown(window, { key: "Escape" });
|
||||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||||
fireEvent.contextMenu(screen.getByRole("link", { name: "Website" }));
|
// The same pane is reachable with taps only, without intercepting a native
|
||||||
fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" }));
|
// 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" }));
|
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
|
||||||
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument());
|
||||||
await screen.findByText("Preview of notes.txt");
|
await screen.findByText("Preview of notes.txt");
|
||||||
|
|||||||
@@ -145,45 +145,44 @@ describe("web link actions", () => {
|
|||||||
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
|
||||||
expect(link).not.toHaveFocus();
|
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();
|
vi.useFakeTimers();
|
||||||
const onClick = vi.fn();
|
const onClick = vi.fn();
|
||||||
render(<WebLink href="https://example.com/" onClick={onClick}>Example</WebLink>);
|
render(<WebLink href="https://example.com/" onClick={onClick}>Example</WebLink>);
|
||||||
const link = screen.getByRole("link", { name: "Example" });
|
const link = screen.getByRole("link", { name: "Example" });
|
||||||
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 150 });
|
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 150 });
|
||||||
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
|
await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
|
||||||
expect(screen.getByRole("menu")).toBeInTheDocument();
|
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" });
|
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(fireEvent.click(link)).toBe(true);
|
||||||
expect(onClick).toHaveBeenCalledTimes(1);
|
expect(onClick).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
it.each(["move", "cancel", "leave", "short tap", "second finger"])("cancels touch hold on %s", async (reason) => {
|
it("still supports a mouse and keyboard after touch on a hybrid device", () => {
|
||||||
vi.useFakeTimers();
|
|
||||||
render(<WebLink href="https://example.com/">Example</WebLink>);
|
render(<WebLink href="https://example.com/">Example</WebLink>);
|
||||||
const link = screen.getByRole("link", { name: "Example" });
|
const link = screen.getByRole("link", { name: "Example" });
|
||||||
fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 100 });
|
fireEvent.pointerDown(link, { pointerType: "touch" });
|
||||||
if (reason === "move") fireEvent.pointerMove(link, { pointerId: 1, clientX: 100, clientY: 125 });
|
fireEvent.pointerDown(link, { pointerType: "mouse", button: 2 });
|
||||||
else if (reason === "cancel") fireEvent.pointerCancel(link);
|
expect(fireEvent.contextMenu(link)).toBe(false);
|
||||||
else if (reason === "leave") fireEvent.pointerLeave(link);
|
expect(screen.getByRole("menu")).toBeInTheDocument();
|
||||||
else if (reason === "short tap") fireEvent.pointerUp(link);
|
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
|
||||||
else fireEvent.pointerDown(link, { pointerId: 2, pointerType: "touch", isPrimary: false, button: 0 });
|
fireEvent.pointerDown(link, { pointerType: "touch" });
|
||||||
await act(async () => { await vi.advanceTimersByTimeAsync(700); });
|
fireEvent.keyDown(link, { key: "F10", shiftKey: true });
|
||||||
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
|
expect(screen.getByRole("menu")).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
it("cancels pending holds and discards an open menu when its URL changes", async () => {
|
it("leaves a coarse-pointer context menu native even without a preceding pointer event", () => {
|
||||||
vi.useFakeTimers();
|
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 view = (href: string) => <WebLink href={href}>Example</WebLink>;
|
||||||
const { rerender } = render(view("https://example.com/old"));
|
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" }));
|
fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }));
|
||||||
expect(screen.getByRole("menu")).toBeInTheDocument();
|
expect(screen.getByRole("menu")).toBeInTheDocument();
|
||||||
rerender(view("https://example.com/third"));
|
rerender(view("https://example.com/third"));
|
||||||
|
|||||||
Reference in new issue
Block a user