feat(webui): add isolated website previews and link actions
This commit is contained in:
1 parent
05bee21b10
commit
fccf415283
19 files changed
+626
-13
No files matched your search
@@ -15,6 +15,7 @@ import { Streamdown, type Components, type StreamdownProps } from "streamdown";
|
||||
|
||||
import { AttachmentTile } from "@/components/AttachmentTile";
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { WebLink } from "@/components/WebLink";
|
||||
import {
|
||||
INLINE_TOKEN_HIGHLIGHT_COLOR,
|
||||
InlineTokenHighlight,
|
||||
@@ -451,7 +452,7 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {
|
||||
: link.title;
|
||||
|
||||
return (
|
||||
<a
|
||||
<WebLink
|
||||
href={link.href}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
@@ -487,7 +488,7 @@ function InlineLinkPreviewRow({ link }: { link: InlineLinkPreview }) {
|
||||
<span className="min-w-0 [overflow-wrap:anywhere] leading-normal sm:truncate">
|
||||
{label}
|
||||
</span>
|
||||
</a>
|
||||
</WebLink>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -672,7 +673,7 @@ export default function MarkdownTextRenderer({
|
||||
return <>{markdownChildren}</>;
|
||||
}
|
||||
return (
|
||||
<a
|
||||
<WebLink
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
@@ -680,7 +681,7 @@ export default function MarkdownTextRenderer({
|
||||
{...props}
|
||||
>
|
||||
{markdownChildren}
|
||||
</a>
|
||||
</WebLink>
|
||||
);
|
||||
},
|
||||
// Streamdown decorates emphasis with spans by default. Preserve native
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { createContext, useContext, useEffect, useState, type ComponentPropsWithoutRef } from "react";
|
||||
import { Copy, ExternalLink, MoreHorizontal, PanelRight } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { copyTextToClipboard } from "@/lib/clipboard";
|
||||
import { parseWebLink } from "@/lib/web-preview";
|
||||
|
||||
export const WebPreviewContext = createContext<((url: string) => void) | undefined>(undefined);
|
||||
|
||||
export function WebLink({ href = "", children, ...props }: ComponentPropsWithoutRef<"a">) {
|
||||
const { t } = useTranslation();
|
||||
const openPreview = useContext(WebPreviewContext);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [feedback, setFeedback] = useState("");
|
||||
useEffect(() => {
|
||||
if (!feedback) return;
|
||||
const timer = window.setTimeout(() => setFeedback(""), 4000);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [feedback]);
|
||||
const url = parseWebLink(href);
|
||||
const anchor = <a {...props} href={href} target="_blank" rel="noreferrer noopener">{children}</a>;
|
||||
if (!url) {
|
||||
// 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) ? anchor : <>{children}</>;
|
||||
}
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={setOpen}>
|
||||
<span className="inline max-w-full" onContextMenu={(event) => {
|
||||
event.preventDefault(); event.stopPropagation(); setOpen(true);
|
||||
}} onKeyDown={(event) => {
|
||||
if ((event.shiftKey && event.key === "F10") || event.key === "ContextMenu") {
|
||||
event.preventDefault(); event.stopPropagation(); setOpen(true);
|
||||
}
|
||||
}}>
|
||||
{anchor}
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button type="button" aria-label={t("webPreview.actions")} title={t("webPreview.actions")}
|
||||
className="ml-0.5 inline-flex h-6 w-6 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">
|
||||
<MoreHorizontal className="h-3.5 w-3.5" aria-hidden />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
</span>
|
||||
<DropdownMenuContent align="start">
|
||||
<DropdownMenuLabel className="max-w-64 truncate">{url.host}</DropdownMenuLabel>
|
||||
{openPreview ? <DropdownMenuItem onSelect={() => openPreview(url.href)}>
|
||||
<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();
|
||||
setFeedback("");
|
||||
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>
|
||||
{feedback ? <div role="status" className="px-2.5 py-1.5 text-xs text-muted-foreground">{feedback}</div> : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useState, type CSSProperties, type PointerEvent } from "react";
|
||||
import { ExternalLink, RotateCw, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { isLoopbackHost } from "@/lib/network";
|
||||
import { isNativeRuntime } from "@/lib/runtime";
|
||||
import { parseWebLink, webPreviewRestriction } from "@/lib/web-preview";
|
||||
|
||||
interface WebPreviewPanelProps {
|
||||
url: string;
|
||||
desktopWidth?: number;
|
||||
onResizeStart?: (event: PointerEvent<HTMLButtonElement>) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function WebPreviewPanel({ url: value, desktopWidth = 544, onResizeStart, onClose }: WebPreviewPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const [revision, setRevision] = useState(0);
|
||||
const url = parseWebLink(value);
|
||||
const restriction = url ? webPreviewRestriction(url, new URL(window.location.href), isNativeRuntime(),
|
||||
"credentialless" in HTMLIFrameElement.prototype) : "invalid";
|
||||
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
|
||||
return (
|
||||
<aside aria-label={t("webPreview.title")} data-testid="web-preview-panel" data-file-preview-panel
|
||||
style={{ "--file-preview-width": `${desktopWidth}px`, "--file-preview-slot-width": `${desktopWidth}px` } as CSSProperties}
|
||||
className="absolute inset-y-0 right-0 z-30 flex w-full flex-col border-l border-border/70 bg-background pb-[env(safe-area-inset-bottom)] shadow-2xl md:relative md:z-auto md:w-[var(--file-preview-slot-width)] md:min-w-0 md:shrink-0 md:pb-0 md:shadow-none">
|
||||
{onResizeStart ? <button type="button" aria-label={t("webPreview.resize")}
|
||||
className="absolute inset-y-0 left-0 z-20 hidden w-2 cursor-col-resize touch-none hover:bg-border/50 md:block"
|
||||
onPointerDown={onResizeStart} /> : null}
|
||||
<div className="flex shrink-0 items-center gap-1 border-b border-border/60 px-3 py-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium" title={url?.origin}>{t("webPreview.original")}</p>
|
||||
<p className="truncate text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
|
||||
</div>
|
||||
{!restriction ? <button type="button" className={buttonClass} onClick={() => setRevision((n) => n + 1)} title={t("webPreview.refresh")} aria-label={t("webPreview.refresh")}>
|
||||
<RotateCw className="h-4 w-4" aria-hidden />
|
||||
</button> : null}
|
||||
{url ? <a className={buttonClass} href={url.href} target="_blank" rel="noreferrer noopener" title={t("webPreview.external")} aria-label={t("webPreview.external")}>
|
||||
<ExternalLink className="h-4 w-4" aria-hidden />
|
||||
</a> : null}
|
||||
<button type="button" className={buttonClass} onClick={onClose} title={t("webPreview.close")} aria-label={t("webPreview.close")}><X className="h-4 w-4" aria-hidden /></button>
|
||||
</div>
|
||||
<div className="shrink-0 space-y-1 border-b border-border/60 px-4 py-3 text-xs leading-relaxed text-muted-foreground">
|
||||
<p>{t("webPreview.isolated")}</p>
|
||||
<p>{t("webPreview.blockedHint")}</p>
|
||||
{url && isLoopbackHost(url.hostname) ? <p>{t("webPreview.loopback")}</p> : null}
|
||||
</div>
|
||||
{restriction ? <div role="status" className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6 text-center text-sm text-muted-foreground">
|
||||
{t(`webPreview.${restriction}`)}
|
||||
</div> : <iframe key={`${value}:${revision}`} title={t("webPreview.frame", { host: url!.host })}
|
||||
{...{ credentialless: "" }} sandbox="allow-scripts" referrerPolicy="no-referrer"
|
||||
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; payment 'none'; fullscreen 'none'; display-capture 'none'; usb 'none'; serial 'none'; hid 'none'"
|
||||
src={url!.href} className="min-h-0 w-full flex-1 border-0 bg-white" />}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,9 @@ import { useTranslation } from "react-i18next";
|
||||
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
||||
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
|
||||
import { FileActionsProvider } from "@/components/FileActions";
|
||||
import { WebPreviewContext } from "@/components/WebLink";
|
||||
import { WebPreviewPanel } from "@/components/WebPreviewPanel";
|
||||
import { parseWebLink } from "@/lib/web-preview";
|
||||
import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||
@@ -713,7 +716,7 @@ export function ThreadShell({
|
||||
} | null>(null);
|
||||
const [heroGreetingKey, setHeroGreetingKey] = useState(randomHeroGreetingKey);
|
||||
const [submittedViewportTurnId, setSubmittedViewportTurnId] = useState<string | null>(null);
|
||||
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth } =
|
||||
const { state: previewState, setPath: setFilePreviewPath, setWidth: setFilePreviewWidth, setWebUrl } =
|
||||
useFilePreviewState(previewSessionKey, filePreviewStore);
|
||||
const [closingPreview, setClosingPreview] = useState<{ key: string; path: string } | null>(null);
|
||||
const filePreviewClosing = closingPreview?.key === previewSessionKey;
|
||||
@@ -1544,18 +1547,36 @@ export function ThreadShell({
|
||||
},
|
||||
}), [filePreviewClosing, filePreviewPath, openFilePreview, resolveFileMetadata]);
|
||||
|
||||
const openWebPreview = useCallback((url: string) => {
|
||||
const parsed = parseWebLink(url);
|
||||
if (!parsed) return;
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
if (filePreviewCloseTimerRef.current !== null) {
|
||||
window.clearTimeout(filePreviewCloseTimerRef.current);
|
||||
filePreviewCloseTimerRef.current = null;
|
||||
}
|
||||
setClosingPreview(null);
|
||||
setWebUrl(parsed.href);
|
||||
}, [setWebUrl]);
|
||||
|
||||
const closeWebPreview = useCallback(() => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
setWebUrl(null);
|
||||
}, [setWebUrl]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filePreviewPath || !headerActive) return;
|
||||
if ((!filePreviewPath && !previewState.webUrl) || !headerActive) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
|
||||
// Let a dialog/menu above the pane consume Escape without closing this preview.
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
|
||||
event.preventDefault();
|
||||
handleCloseFilePreview();
|
||||
if (previewState.webUrl) closeWebPreview();
|
||||
else handleCloseFilePreview();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [filePreviewPath, headerActive, handleCloseFilePreview]);
|
||||
}, [filePreviewPath, previewState.webUrl, headerActive, handleCloseFilePreview, closeWebPreview]);
|
||||
|
||||
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
@@ -1568,12 +1589,15 @@ export function ThreadShell({
|
||||
const originalBodyCursor = document.body.style.cursor;
|
||||
const originalBodyUserSelect = document.body.style.userSelect;
|
||||
const originalPanelTransition = panel?.style.transition ?? "";
|
||||
const frameElement = panel?.querySelector("iframe");
|
||||
const originalFramePointerEvents = frameElement?.style.pointerEvents ?? "";
|
||||
let nextWidth = filePreviewWidthRef.current;
|
||||
let frame: number | null = null;
|
||||
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
if (panel) panel.style.transition = "none";
|
||||
if (frameElement) frameElement.style.pointerEvents = "none";
|
||||
|
||||
const applyWidth = (clientX: number) => {
|
||||
nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth);
|
||||
@@ -1597,6 +1621,7 @@ export function ThreadShell({
|
||||
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
|
||||
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
|
||||
if (panel) panel.style.transition = originalPanelTransition;
|
||||
if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents;
|
||||
if (commit) setFilePreviewWidth(nextWidth);
|
||||
document.body.style.cursor = originalBodyCursor;
|
||||
document.body.style.userSelect = originalBodyUserSelect;
|
||||
@@ -1615,7 +1640,7 @@ export function ThreadShell({
|
||||
}, [setFilePreviewWidth]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!filePreviewPath) return;
|
||||
if (!filePreviewPath && !previewState.webUrl) return;
|
||||
const clampToShell = () => {
|
||||
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
|
||||
const maxWidth = maxFilePreviewWidth(shellWidth);
|
||||
@@ -1629,7 +1654,7 @@ export function ThreadShell({
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", clampToShell);
|
||||
};
|
||||
}, [filePreviewPath]);
|
||||
}, [filePreviewPath, previewState.webUrl]);
|
||||
|
||||
const handleForkFromMessage = useCallback(
|
||||
async (beforeUserIndex: number) => {
|
||||
@@ -1833,6 +1858,7 @@ export function ThreadShell({
|
||||
resolve={previewSessionKey ? resolveFilePreviewAvailability : undefined}
|
||||
>
|
||||
<FileActionsProvider value={previewSessionKey ? fileActions : undefined}>
|
||||
<WebPreviewContext.Provider value={previewSessionKey ? openWebPreview : undefined}>
|
||||
<ThreadViewport
|
||||
ref={viewportRef}
|
||||
messages={displayMessages}
|
||||
@@ -1861,6 +1887,7 @@ export function ThreadShell({
|
||||
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
||||
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
||||
/>
|
||||
</WebPreviewContext.Provider>
|
||||
</FileActionsProvider>
|
||||
</FilePreviewAvailabilityProvider>
|
||||
</div>
|
||||
@@ -1890,6 +1917,15 @@ export function ThreadShell({
|
||||
onClose={handleCloseFilePreview}
|
||||
/>
|
||||
) : null}
|
||||
{previewState.webUrl && previewSessionKey ? (
|
||||
<WebPreviewPanel
|
||||
key={`${previewSessionKey}:${previewState.webUrl}`}
|
||||
url={previewState.webUrl}
|
||||
desktopWidth={filePreviewWidth}
|
||||
onResizeStart={handleFilePreviewResizeStart}
|
||||
onClose={closeWebPreview}
|
||||
/>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user