feat(webui): preview Markdown files with a source toggle
This commit is contained in:
1 parent
742ea48df3
commit
0869c928a2
18 files changed
+182
-17
No files matched your search
@@ -9,6 +9,7 @@ interface FilePreviewPanelProps {
|
||||
token: string;
|
||||
loadPreview?: (path: string) => Promise<FilePreviewPayload>;
|
||||
initialPreview?: FilePreviewPayload;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
}
|
||||
|
||||
export function FilePreviewPanel({
|
||||
@@ -17,6 +18,7 @@ export function FilePreviewPanel({
|
||||
token,
|
||||
loadPreview,
|
||||
initialPreview,
|
||||
onOpenFilePreview,
|
||||
}: FilePreviewPanelProps) {
|
||||
const [state, setState] = useState<FilePreviewPanelState>(() => initialPreview
|
||||
? { status: "ready", payload: initialPreview } : { status: "loading" });
|
||||
@@ -55,6 +57,7 @@ export function FilePreviewPanel({
|
||||
}, [path, sessionKey, loadPreview]);
|
||||
|
||||
const reportImageError = useCallback(() => setState({ status: "error" }), []);
|
||||
return <FilePreviewPanelView path={path} state={state} imageOpen={imageOpen}
|
||||
return <FilePreviewPanelView key={`${sessionKey}:${path}`} path={path} state={state} imageOpen={imageOpen}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onImageOpenChange={setImageOpen} onImageError={reportImageError} />;
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AlertCircle } from "lucide-react";
|
||||
|
||||
import { CodeBlock } from "@/components/CodeBlock";
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { ImageLightbox } from "@/components/ImageLightbox";
|
||||
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
|
||||
import type { FilePreviewPayload } from "@/lib/types";
|
||||
@@ -11,14 +14,18 @@ export type FilePreviewPanelState =
|
||||
| { status: "error"; message?: string; routeMissing?: boolean }
|
||||
| { status: "ready"; payload: FilePreviewPayload };
|
||||
|
||||
export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange, onImageError }: {
|
||||
export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange, onImageError, onOpenFilePreview }: {
|
||||
path: string;
|
||||
state: FilePreviewPanelState;
|
||||
imageOpen: boolean;
|
||||
onImageOpenChange: (open: boolean) => void;
|
||||
onImageError: () => void;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState<"preview" | "source">("preview");
|
||||
const markdown = state.status === "ready" && state.payload.kind !== "image"
|
||||
&& state.payload.language === "markdown";
|
||||
const displayPath = state.status === "ready" ? state.payload.display_path : path;
|
||||
const { name } = splitFilePath(displayPath);
|
||||
const fileName = name || displayPath;
|
||||
@@ -32,7 +39,14 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
|
||||
return (
|
||||
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
|
||||
<div data-file-preview-scroll tabIndex={0}
|
||||
{markdown ? (
|
||||
<div className="flex shrink-0 items-center justify-end px-4 py-2">
|
||||
<SegmentedControl value={mode} onChange={setMode} ariaLabel={t("filePreview.displayMode")}
|
||||
options={[{ value: "preview", label: t("filePreview.preview") }, { value: "source", label: t("filePreview.source") }]}
|
||||
itemClassName="px-3 [@media(pointer:coarse)]:min-h-9" />
|
||||
</div>
|
||||
) : null}
|
||||
<div key={mode} data-file-preview-scroll tabIndex={0}
|
||||
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
|
||||
{state.status === "loading" ? (
|
||||
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
|
||||
@@ -77,7 +91,12 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
<CodeBlock
|
||||
{markdown && mode === "preview" ? (
|
||||
<MarkdownText documentPath={state.payload.path} onOpenFilePreview={onOpenFilePreview}
|
||||
className="px-5 pb-6 pt-1 text-sm [overflow-wrap:anywhere] sm:px-6 [&>:first-child]:mt-0">
|
||||
{state.payload.content}
|
||||
</MarkdownText>
|
||||
) : <CodeBlock
|
||||
language={state.payload.language}
|
||||
code={state.payload.content}
|
||||
chrome="none"
|
||||
@@ -86,7 +105,7 @@ export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange
|
||||
wrapLongLines={false}
|
||||
viewportHighlight
|
||||
className="min-h-full"
|
||||
/>
|
||||
/>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -15,6 +15,7 @@ interface MarkdownTextProps {
|
||||
streaming?: boolean;
|
||||
preserveStreamingLayout?: boolean;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
documentPath?: string;
|
||||
}
|
||||
|
||||
const loadMarkdownRenderer = () => import("@/components/MarkdownTextRenderer");
|
||||
@@ -27,6 +28,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
|
||||
streaming,
|
||||
preserveStreamingLayout,
|
||||
onOpenFilePreview,
|
||||
documentPath,
|
||||
}: {
|
||||
source: string;
|
||||
className?: string;
|
||||
@@ -34,6 +36,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
|
||||
streaming: boolean;
|
||||
preserveStreamingLayout: boolean;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
documentPath?: string;
|
||||
}) {
|
||||
return (
|
||||
<LazyMarkdownRenderer
|
||||
@@ -42,6 +45,7 @@ const MemoizedMarkdownRenderer = memo(function MemoizedMarkdownRenderer({
|
||||
streaming={streaming}
|
||||
preserveStreamingLayout={preserveStreamingLayout}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
documentPath={documentPath}
|
||||
>
|
||||
{source}
|
||||
</LazyMarkdownRenderer>
|
||||
@@ -80,6 +84,7 @@ export function MarkdownText({
|
||||
streaming = false,
|
||||
preserveStreamingLayout = false,
|
||||
onOpenFilePreview,
|
||||
documentPath,
|
||||
}: MarkdownTextProps) {
|
||||
const renderedSource = children;
|
||||
const renderPhase = streaming ? "streaming" : "complete";
|
||||
@@ -111,6 +116,7 @@ export function MarkdownText({
|
||||
streaming={streaming}
|
||||
preserveStreamingLayout={preserveStreamingLayout}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
documentPath={documentPath}
|
||||
/>
|
||||
</Suspense>
|
||||
</MarkdownRendererBoundary>
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
FileReferenceChip,
|
||||
isFilePatternReference,
|
||||
isLikelyFilePath,
|
||||
splitFilePath,
|
||||
} from "@/components/FileReferenceChip";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { inferMediaKind } from "@/lib/media";
|
||||
@@ -50,6 +51,8 @@ interface MarkdownTextRendererProps {
|
||||
streaming?: boolean;
|
||||
preserveStreamingLayout?: boolean;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
/** Read-only documents must not load embedded resources or use chat routing. */
|
||||
documentPath?: string;
|
||||
}
|
||||
|
||||
type MarkdownAstNode = {
|
||||
@@ -388,6 +391,29 @@ function fileReferenceFromLink(href: string | undefined): string | null {
|
||||
return isPreviewableFileTarget(target) ? target : null;
|
||||
}
|
||||
|
||||
function DocumentLink({ href, path, onOpen, children }: {
|
||||
href: string;
|
||||
path: string;
|
||||
onOpen?: (path: string) => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
// Fragment-only links must not replace the application's hash route.
|
||||
if (!href || href.startsWith("#")) return <>{children}</>;
|
||||
if (/^(https?:\/\/|mailto:)/i.test(href)) {
|
||||
return <WebLink href={href} className="text-blue-500 underline underline-offset-2 dark:text-blue-300">{children}</WebLink>;
|
||||
}
|
||||
if (/^[a-z][a-z\d+.-]*:/i.test(href) || href.startsWith("//")) return <>{children}</>;
|
||||
let target = href.split(/[?#]/, 1)[0];
|
||||
try { target = decodeURIComponent(target); } catch { return <>{children}</>; }
|
||||
if (!target) return <>{children}</>;
|
||||
// Resolve against the document, not the WebUI origin or the project root.
|
||||
// The gateway still resolves and authorizes the resulting path.
|
||||
const resolved = /^[\\/]|^[a-z]:[\\/]/i.test(target)
|
||||
? target : `${splitFilePath(path).directory}${target}`;
|
||||
return <FileReferenceChip path={nodeText(children) || target} previewPath={resolved}
|
||||
tooltipPath={resolved} onOpen={onOpen} />;
|
||||
}
|
||||
|
||||
function sessionReferenceHref(href: string): string | null {
|
||||
const prefix = href.startsWith("#session/")
|
||||
? "#session/"
|
||||
@@ -554,6 +580,7 @@ export default function MarkdownTextRenderer({
|
||||
streaming = false,
|
||||
preserveStreamingLayout = false,
|
||||
onOpenFilePreview,
|
||||
documentPath,
|
||||
}: MarkdownTextRendererProps) {
|
||||
const { t } = useTranslation();
|
||||
const [mathPlugin, setMathPlugin] = useState(() => loadedMathPlugin);
|
||||
@@ -588,7 +615,7 @@ export default function MarkdownTextRenderer({
|
||||
);
|
||||
}
|
||||
const raw = String(kids).replace(/\n$/, "");
|
||||
if (isLikelyFilePath(raw)) {
|
||||
if (!documentPath && isLikelyFilePath(raw)) {
|
||||
return (
|
||||
<InferredFileReferenceChip
|
||||
path={raw}
|
||||
@@ -663,6 +690,9 @@ export default function MarkdownTextRenderer({
|
||||
if (href === "streamdown:incomplete-link") {
|
||||
return <>{markdownChildren}</>;
|
||||
}
|
||||
if (documentPath) {
|
||||
return <DocumentLink href={href} path={documentPath} onOpen={onOpenFilePreview}>{markdownChildren}</DocumentLink>;
|
||||
}
|
||||
const sessionHref = sessionReferenceHref(href);
|
||||
if (sessionHref) {
|
||||
return (
|
||||
@@ -764,7 +794,7 @@ export default function MarkdownTextRenderer({
|
||||
);
|
||||
},
|
||||
li({ children: markdownChildren, className: itemClassName }) {
|
||||
const link = inlineLinkPreviewFromChildren(markdownChildren);
|
||||
const link = !documentPath && inlineLinkPreviewFromChildren(markdownChildren);
|
||||
if (link) {
|
||||
return (
|
||||
<li className={cn("list-none pl-0", itemClassName)}>
|
||||
@@ -837,6 +867,9 @@ export default function MarkdownTextRenderer({
|
||||
const source = typeof src === "string" ? src : "";
|
||||
if (!source) return null;
|
||||
const label = typeof alt === "string" ? alt : "";
|
||||
if (documentPath) {
|
||||
return <DocumentLink href={source} path={documentPath} onOpen={onOpenFilePreview}>{label || source}</DocumentLink>;
|
||||
}
|
||||
const kind = markdownAttachmentKind(source, label);
|
||||
return (
|
||||
<AttachmentTile
|
||||
@@ -850,7 +883,7 @@ export default function MarkdownTextRenderer({
|
||||
);
|
||||
},
|
||||
}),
|
||||
[highlightCode, onOpenFilePreview, t],
|
||||
[highlightCode, onOpenFilePreview, documentPath, t],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -2134,6 +2134,7 @@ export function ThreadShell({
|
||||
token={token}
|
||||
loadPreview={filePreviews.load}
|
||||
initialPreview={filePreviews.peek(activePreview.value)}
|
||||
onOpenFilePreview={openFilePreview}
|
||||
/>
|
||||
) : <WebPreviewPanel key={activePreview.id} url={activePreview.value} />}
|
||||
</PreviewPane>
|
||||
|
||||
@@ -8,20 +8,22 @@ import type { AutomationUpdatePayload, SessionAutomationJob, UIMessage } from "@
|
||||
import { StatePicker, type ComponentExample } from "./example";
|
||||
|
||||
function FilePreview() {
|
||||
const [mode, setMode] = useState<"text" | "image" | "truncated" | "loading" | "error" | "route_missing">("text");
|
||||
const [mode, setMode] = useState<"markdown" | "text" | "image" | "truncated" | "loading" | "error" | "route_missing">("markdown");
|
||||
const [imageOpen, setImageOpen] = useState(false);
|
||||
const path = mode === "image" ? "nanobot.png" : "greeting.ts";
|
||||
const path = mode === "image" ? "nanobot.png" : mode === "markdown" || mode === "truncated" ? "REPORT.md" : "greeting.ts";
|
||||
const state: FilePreviewPanelState = mode === "loading" ? { status: "loading" }
|
||||
: mode === "error" || mode === "route_missing" ? { status: "error", routeMissing: mode === "route_missing" }
|
||||
: { status: "ready", payload: mode === "image"
|
||||
? { kind: "image", path, display_path: path, project_path: "/workspace", size: 24_576, mime_type: "image/png", data_url: "/brand/nanobot_icon_512.png" }
|
||||
: { path, display_path: path, project_path: "/workspace", size: 128, language: "typescript", truncated: mode === "truncated",
|
||||
content: 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } };
|
||||
: { path, display_path: path, project_path: "/workspace", size: 128, language: path.endsWith(".md") ? "markdown" : "typescript", truncated: mode === "truncated",
|
||||
content: path.endsWith(".md")
|
||||
? '# Skills 迁移报告\n\n已完成迁移,**原文件保持不变**。\n\n## 验证结果\n\n| 项目 | 结果 |\n| --- | --- |\n| 文件数量 | 1,199 个 |\n| 校验 | SHA-256 一致 |\n\n- [x] 保留原目录\n- [x] 检查引用\n\n## 下一步\n\n打开技能目录,确认所需服务已连接。\n\n```sh\nls skills/\n```\n\n\n'
|
||||
: 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } };
|
||||
return <div className="space-y-4">
|
||||
<StatePicker label="文件预览状态" value={mode} options={["text", "image", "truncated", "loading", "error", "route_missing"]}
|
||||
<StatePicker label="文件预览状态" value={mode} options={["markdown", "text", "image", "truncated", "loading", "error", "route_missing"]}
|
||||
onChange={(next) => { setMode(next); setImageOpen(false); }} />
|
||||
<div className="flex h-80 flex-col overflow-hidden rounded-control border">
|
||||
<FilePreviewPanelView path={path} state={state} imageOpen={imageOpen} onImageOpenChange={setImageOpen}
|
||||
<div className="flex h-[32rem] flex-col overflow-hidden rounded-control border">
|
||||
<FilePreviewPanelView key={path} path={path} state={state} imageOpen={imageOpen} onImageOpenChange={setImageOpen}
|
||||
onImageError={() => { setMode("error"); setImageOpen(false); }} />
|
||||
</div>
|
||||
</div>;
|
||||
|
||||
@@ -2437,6 +2437,9 @@
|
||||
"gatewayPath": "Paths refer to the gateway machine."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Display mode",
|
||||
"preview": "Preview",
|
||||
"source": "Source",
|
||||
"aria": "File preview",
|
||||
"breadcrumb": "File path",
|
||||
"close": "Close file preview",
|
||||
|
||||
@@ -2238,6 +2238,9 @@
|
||||
"gatewayPath": "Las rutas pertenecen al equipo del gateway."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Modo de visualización",
|
||||
"preview": "Vista previa",
|
||||
"source": "Código fuente",
|
||||
"aria": "Vista previa de archivo",
|
||||
"breadcrumb": "Ruta del archivo",
|
||||
"close": "Cerrar vista previa de archivo",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "Les chemins désignent la machine de la passerelle."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Mode d’affichage",
|
||||
"preview": "Aperçu",
|
||||
"source": "Source",
|
||||
"aria": "Aperçu du fichier",
|
||||
"breadcrumb": "Chemin du fichier",
|
||||
"close": "Fermer l’aperçu du fichier",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "Jalur merujuk ke komputer gateway."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Mode tampilan",
|
||||
"preview": "Pratinjau",
|
||||
"source": "Sumber",
|
||||
"aria": "Pratinjau file",
|
||||
"breadcrumb": "Jalur file",
|
||||
"close": "Tutup pratinjau file",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "パスはゲートウェイのマシンを指します。"
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "表示モード",
|
||||
"preview": "プレビュー",
|
||||
"source": "ソース",
|
||||
"aria": "ファイルプレビュー",
|
||||
"breadcrumb": "ファイルパス",
|
||||
"close": "ファイルプレビューを閉じる",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "경로는 게이트웨이 컴퓨터를 가리킵니다."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "표시 방식",
|
||||
"preview": "미리 보기",
|
||||
"source": "원문",
|
||||
"aria": "파일 미리보기",
|
||||
"breadcrumb": "파일 경로",
|
||||
"close": "파일 미리보기 닫기",
|
||||
|
||||
@@ -2251,6 +2251,9 @@
|
||||
"gatewayPath": "Os caminhos se referem à máquina do gateway."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Modo de exibição",
|
||||
"preview": "Prévia",
|
||||
"source": "Código-fonte",
|
||||
"aria": "Pré-visualização de arquivo",
|
||||
"breadcrumb": "Caminho do arquivo",
|
||||
"close": "Fechar pré-visualização de arquivo",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "Đường dẫn thuộc máy chạy gateway."
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "Chế độ hiển thị",
|
||||
"preview": "Xem trước",
|
||||
"source": "Mã nguồn",
|
||||
"aria": "Xem trước tệp",
|
||||
"breadcrumb": "Đường dẫn tệp",
|
||||
"close": "Đóng xem trước tệp",
|
||||
|
||||
@@ -2437,6 +2437,9 @@
|
||||
"gatewayPath": "路径指向网关所在的机器。"
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "显示方式",
|
||||
"preview": "预览",
|
||||
"source": "原文",
|
||||
"aria": "文件预览",
|
||||
"breadcrumb": "文件路径",
|
||||
"close": "关闭文件预览",
|
||||
|
||||
@@ -2237,6 +2237,9 @@
|
||||
"gatewayPath": "路徑指向閘道所在的電腦。"
|
||||
},
|
||||
"filePreview": {
|
||||
"displayMode": "顯示方式",
|
||||
"preview": "預覽",
|
||||
"source": "原文",
|
||||
"aria": "檔案預覽",
|
||||
"breadcrumb": "檔案路徑",
|
||||
"close": "關閉檔案預覽",
|
||||
|
||||
@@ -168,13 +168,82 @@ describe("FilePreviewPanel", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
await screen.findByTestId("mock-code-block");
|
||||
await screen.findByRole("heading", { name: "Notes" });
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => {
|
||||
await setAppLanguage("zh-CN");
|
||||
});
|
||||
|
||||
expect(screen.getByRole("button", { name: "预览" })).toHaveAttribute("aria-pressed", "true");
|
||||
expect(screen.getByRole("button", { name: "原文" })).toBeInTheDocument();
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("defaults old Markdown payloads to preview and switches to exact source without another read", async () => {
|
||||
const content = "# Report\n\n**Done**\n\n| Item | Status |\n| --- | --- |\n| Copy | OK |\n";
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({ path: "/workspace/REPORT.md", display_path: "REPORT.md",
|
||||
language: "markdown", content, truncated: true });
|
||||
render(<FilePreviewPanel sessionKey="a" path="REPORT.md" token="test" />);
|
||||
await screen.findByRole("heading", { name: "Report" });
|
||||
expect(screen.getByRole("table")).toHaveTextContent("CopyOK");
|
||||
const notice = "Preview is truncated because this file is large.";
|
||||
expect(screen.getByText(notice)).toBeInTheDocument();
|
||||
const source = screen.getByRole("button", { name: "Source" });
|
||||
source.focus();
|
||||
fireEvent.click(source);
|
||||
expect(source).toHaveFocus();
|
||||
expect(source).toHaveAttribute("aria-pressed", "true");
|
||||
expect(screen.getByTestId("mock-code-block").textContent).toBe(content);
|
||||
expect(CodeBlock).toHaveBeenLastCalledWith(expect.objectContaining({
|
||||
code: content, chrome: "none", showLineNumbers: true, wrapLongLines: false, viewportHighlight: true,
|
||||
}), expect.anything());
|
||||
expect(screen.getByText(notice)).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Preview" }));
|
||||
await screen.findByRole("heading", { name: "Report" });
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("resets the display for another file or session but keeps source on credential renewal", async () => {
|
||||
const payload = { path: "/workspace/notes.md", display_path: "notes.md", language: "markdown",
|
||||
content: "# Notes", truncated: false };
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue(payload);
|
||||
const view = (path: string, sessionKey = "a", token = "old") =>
|
||||
<FilePreviewPanel sessionKey={sessionKey} path={path} token={token} />;
|
||||
const { rerender } = render(view("notes.md"));
|
||||
await screen.findByRole("heading", { name: "Notes" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Source" }));
|
||||
rerender(view("notes.md", "a", "new"));
|
||||
expect(screen.getByRole("button", { name: "Source" })).toHaveAttribute("aria-pressed", "true");
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
rerender(view("other.md"));
|
||||
await screen.findByRole("heading", { name: "Notes" });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Source" }));
|
||||
rerender(view("other.md", "b"));
|
||||
await screen.findByRole("heading", { name: "Notes" });
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("keeps document resources inert and opens relative links through the session preview callback", async () => {
|
||||
const open = vi.fn();
|
||||
vi.mocked(fetchFilePreview).mockResolvedValue({ path: "/workspace/reports/REPORT.mdx", display_path: "reports/REPORT.mdx",
|
||||
language: "markdown", truncated: false, content: [
|
||||
"# Report", "[Local](../notes%20one.md)", "",
|
||||
"- Reference — [Website](https://example.com)", "[Section](#details)", "[Chat](#/chat/websocket:other)",
|
||||
"[Unsafe](javascript:alert(1))", '<img src="https://example.com/raw.png" onerror="alert(1)">',
|
||||
'<iframe src="https://example.com/frame"></iframe>', '<script>alert(1)</script>',
|
||||
"`skills/cron/SKILL.md`", "<CustomComponent />",
|
||||
].join("\n\n") });
|
||||
const { container } = render(<FilePreviewPanel sessionKey="a" path="reports/REPORT.mdx" token="test" onOpenFilePreview={open} />);
|
||||
await screen.findByRole("heading", { name: "Report" });
|
||||
expect(container.querySelector("img, iframe, script, video, audio")).toBeNull();
|
||||
expect(screen.getByRole("link", { name: "Chart" })).toHaveAttribute("href", "https://example.com/chart.png");
|
||||
expect(screen.getByRole("link", { name: "Website" })).toHaveAttribute("rel", "noreferrer noopener");
|
||||
expect(screen.queryByRole("link", { name: /Section|Chat|Unsafe/ })).not.toBeInTheDocument();
|
||||
expect(container.querySelector("code")?.textContent).toBe("skills/cron/SKILL.md");
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "/workspace/reports/../notes one.md" }));
|
||||
expect(open).toHaveBeenCalledWith("/workspace/reports/../notes one.md");
|
||||
expect(fetchFilePreview).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user