Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(frontend): Add view mode toggle (old/diff/new) to file changes viewer (#13519)

Vasco Schiavo8f87ef59c72f
diff --git a/frontend/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx b/frontend/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx
new file mode 100644
index 0000000000..d91e1088c4
--- /dev/null
+++ b/frontend/__tests__/components/features/diff-viewer/file-diff-viewer.test.tsx
@@ -0,0 +1,165 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { FileDiffViewer } from "#/components/features/diff-viewer/file-diff-viewer";
+
+const MOCK_DIFF = { original: "old content", modified: "new content" };
+const MOCK_MD_DIFF = {
+ original: "# Old Heading",
+ modified: "# New Heading\n\nSome **bold** text",
+};
+
+let mockDiff = MOCK_DIFF;
+let mockIsSuccess = true;
+let mockIsLoading = false;
+
+vi.mock("#/hooks/query/use-unified-git-diff", () => ({
+ useUnifiedGitDiff: () => ({
+ data: mockDiff,
+ isLoading: mockIsLoading,
+ isSuccess: mockIsSuccess,
+ isRefetching: false,
+ }),
+}));
+
+vi.mock("@monaco-editor/react", () => ({
+ DiffEditor: (props: Record<string, unknown>) => (
+ <div data-testid="file-diff-viewer" data-original={props.original} data-modified={props.modified} />
+ ),
+ Editor: (props: Record<string, unknown>) => (
+ <div data-testid="file-single-viewer" data-value={props.value} />
+ ),
+}));
+
+vi.mock("#/components/features/markdown/markdown-renderer", () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => (
+ <div data-testid="markdown-renderer">{content}</div>
+ ),
+}));
+
+const expand = async (user: ReturnType<typeof userEvent.setup>) => {
+ await user.click(screen.getByTestId("collapse"));
+};
+
+describe("FileDiffViewer", () => {
+ beforeEach(() => {
+ mockDiff = MOCK_DIFF;
+ mockIsSuccess = true;
+ mockIsLoading = false;
+ });
+
+ it("starts collapsed with no view mode buttons", () => {
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ expect(screen.queryByTestId("view-mode-old")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("view-mode-diff")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("view-mode-new")).not.toBeInTheDocument();
+ });
+
+ it("shows view mode buttons when expanded", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+
+ expect(screen.getByTestId("view-mode-old")).toBeInTheDocument();
+ expect(screen.getByTestId("view-mode-diff")).toBeInTheDocument();
+ expect(screen.getByTestId("view-mode-new")).toBeInTheDocument();
+ });
+
+ it("shows diff editor by default when expanded", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+
+ expect(screen.getByTestId("file-diff-viewer")).toBeInTheDocument();
+ expect(screen.queryByTestId("file-single-viewer")).not.toBeInTheDocument();
+ });
+
+ it("switches to single editor on 'new' mode", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+ await user.click(screen.getByTestId("view-mode-new"));
+
+ expect(screen.getByTestId("file-single-viewer")).toBeInTheDocument();
+ expect(screen.getByTestId("file-single-viewer")).toHaveAttribute("data-value", "new content");
+ expect(screen.queryByTestId("file-diff-viewer")).not.toBeInTheDocument();
+ });
+
+ it("switches to single editor on 'old' mode", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+ await user.click(screen.getByTestId("view-mode-old"));
+
+ expect(screen.getByTestId("file-single-viewer")).toBeInTheDocument();
+ expect(screen.getByTestId("file-single-viewer")).toHaveAttribute("data-value", "old content");
+ });
+
+ it("returns to diff editor when switching back to 'diff' mode", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+ await user.click(screen.getByTestId("view-mode-new"));
+ await user.click(screen.getByTestId("view-mode-diff"));
+
+ expect(screen.getByTestId("file-diff-viewer")).toBeInTheDocument();
+ expect(screen.queryByTestId("file-single-viewer")).not.toBeInTheDocument();
+ });
+
+ it("renders markdown preview for .md files in 'new' mode", async () => {
+ mockDiff = MOCK_MD_DIFF;
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="README.md" type="M" />);
+
+ await expand(user);
+ await user.click(screen.getByTestId("view-mode-new"));
+
+ expect(screen.getByTestId("markdown-preview")).toBeInTheDocument();
+ expect(screen.getByTestId("markdown-renderer")).toHaveTextContent(/New Heading/);
+ expect(screen.getByTestId("markdown-renderer")).toHaveTextContent(/bold/);
+ expect(screen.queryByTestId("file-single-viewer")).not.toBeInTheDocument();
+ });
+
+ it("renders markdown preview for .md files in 'old' mode", async () => {
+ mockDiff = MOCK_MD_DIFF;
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="README.md" type="M" />);
+
+ await expand(user);
+ await user.click(screen.getByTestId("view-mode-old"));
+
+ expect(screen.getByTestId("markdown-renderer")).toHaveTextContent(MOCK_MD_DIFF.original);
+ });
+
+ it("shows diff editor for .md files in 'diff' mode", async () => {
+ mockDiff = MOCK_MD_DIFF;
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="README.md" type="M" />);
+
+ await expand(user);
+
+ expect(screen.getByTestId("file-diff-viewer")).toBeInTheDocument();
+ expect(screen.queryByTestId("markdown-preview")).not.toBeInTheDocument();
+ });
+
+ it("highlights the active view mode button", async () => {
+ const user = userEvent.setup();
+ render(<FileDiffViewer path="src/index.ts" type="M" />);
+
+ await expand(user);
+
+ expect(screen.getByTestId("view-mode-diff").className).toContain("bg-neutral-600");
+ expect(screen.getByTestId("view-mode-old").className).not.toContain("bg-neutral-600");
+
+ await user.click(screen.getByTestId("view-mode-old"));
+
+ expect(screen.getByTestId("view-mode-old").className).toContain("bg-neutral-600");
+ expect(screen.getByTestId("view-mode-diff").className).not.toContain("bg-neutral-600");
+ });
+});
diff --git a/frontend/src/components/features/diff-viewer/editor-container.test.tsx b/frontend/src/components/features/diff-viewer/editor-container.test.tsx
new file mode 100644
index 0000000000..6204bf56ab
--- /dev/null
+++ b/frontend/src/components/features/diff-viewer/editor-container.test.tsx
@@ -0,0 +1,44 @@
+import { render, screen } from "@testing-library/react";
+import { describe, it, expect } from "vitest";
+import { EditorContainer } from "./editor-container";
+
+describe("EditorContainer", () => {
+ it("renders children", () => {
+ render(
+ <EditorContainer height={400}>
+ <div data-testid="child" />
+ </EditorContainer>,
+ );
+ expect(screen.getByTestId("child")).toBeInTheDocument();
+ });
+
+ it("renders with the editor-container test id", () => {
+ render(
+ <EditorContainer height={300}>
+ <div data-testid="inner" />
+ </EditorContainer>,
+ );
+ expect(screen.getByTestId("editor-container")).toBeInTheDocument();
+ });
+
+ it("sets the --editor-height CSS variable based on height prop", () => {
+ render(
+ <EditorContainer height={500}>
+ <div data-testid="inner" />
+ </EditorContainer>,
+ );
+ const container = screen.getByTestId("editor-container");
+ expect(container.style.getPropertyValue("--editor-height")).toBe("500px");
+ });
+
+ it("applies border and overflow styles", () => {
+ render(
+ <EditorContainer height={400}>
+ <div data-testid="inner" />
+ </EditorContainer>,
+ );
+ const container = screen.getByTestId("editor-container");
+ expect(container.className).toContain("border");
+ expect(container.className).toContain("overflow-hidden");
+ });
+});
diff --git a/frontend/src/components/features/diff-viewer/editor-container.tsx b/frontend/src/components/features/diff-viewer/editor-container.tsx
new file mode 100644
index 0000000000..ffc9114d76
--- /dev/null
+++ b/frontend/src/components/features/diff-viewer/editor-container.tsx
@@ -0,0 +1,18 @@
+import React from "react";
+
+interface EditorContainerProps {
+ height: number;
+ children: React.ReactNode;
+}
+
+export function EditorContainer({ height, children }: EditorContainerProps) {
+ return (
+ <div
+ data-testid="editor-container"
+ className="w-full border border-neutral-600 overflow-hidden h-[var(--editor-height)]"
+ style={{ "--editor-height": `${height}px` } as React.CSSProperties}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/frontend/src/components/features/diff-viewer/file-diff-viewer.tsx b/frontend/src/components/features/diff-viewer/file-diff-viewer.tsx
index ca5ddc61bf..11e9761ce1 100644
--- a/frontend/src/components/features/diff-viewer/file-diff-viewer.tsx
+++ b/frontend/src/components/features/diff-viewer/file-diff-viewer.tsx
@@ -1,33 +1,41 @@
-import { DiffEditor, Monaco } from "@monaco-editor/react";
+import { DiffEditor, Editor, Monaco } from "@monaco-editor/react";
import React from "react";
import { editor as editor_t } from "monaco-editor";
-import { LuFileDiff, LuFileMinus, LuFilePlus } from "react-icons/lu";
+import {
+ LuFileDiff,
+ LuFileMinus,
+ LuFilePlus,
+ LuHistory,
+ LuGitCompareArrows,
+ LuFileCheck,
+} from "react-icons/lu";
import { IconType } from "react-icons/lib";
import { GitChangeStatus } from "#/api/open-hands.types";
import { getLanguageFromPath } from "#/utils/get-language-from-path";
import { cn } from "#/utils/utils";
import ChevronUp from "#/icons/chveron-up.svg?react";
import { useUnifiedGitDiff } from "#/hooks/query/use-unified-git-diff";
-
-interface LoadingSpinnerProps {
- className?: string;
-}
-
-// TODO: Move out of this file and replace the current spinner with this one
-function LoadingSpinner({ className }: LoadingSpinnerProps) {
- return (
- <div className="flex items-center justify-center">
- <div
- className={cn(
- "animate-spin rounded-full border-4 border-gray-200 border-t-blue-500",
- className,
- )}
- role="status"
- aria-label="Loading"
- />
- </div>
- );
-}
+import { MarkdownRenderer } from "#/components/features/markdown/markdown-renderer";
+import { Typography } from "#/ui/typography";
+import { LoadingSpinner } from "./loading-spinner";
+import { EditorContainer } from "./editor-container";
+
+type ViewMode = "diff" | "old" | "new";
+
+const VIEW_MODES: { mode: ViewMode; icon: IconType }[] = [
+ { mode: "old", icon: LuHistory },
+ { mode: "diff", icon: LuGitCompareArrows },
+ { mode: "new", icon: LuFileCheck },
+];
+
+const SHARED_EDITOR_OPTIONS: editor_t.IEditorOptions = {
+ renderValidationDecorations: "off",
+ readOnly: true,
+ scrollBeyondLastLine: false,
+ minimap: { enabled: false },
+ automaticLayout: true,
+ scrollbar: { alwaysConsumeMouseWheel: false },
+};
const STATUS_MAP: Record<GitChangeStatus, string | IconType> = {
A: LuFilePlus,
@@ -37,6 +45,28 @@ const STATUS_MAP: Record<GitChangeStatus, string | IconType> = {
U: "Untracked",
};
+const beforeMount = (monaco: Monaco) => {
+ monaco.editor.defineTheme("custom-diff-theme", {
+ base: "vs-dark",
+ inherit: true,
+ rules: [
+ { token: "comment", foreground: "6a9955" },
+ { token: "keyword", foreground: "569cd6" },
+ { token: "string", foreground: "ce9178" },
+ { token: "number", foreground: "b5cea8" },
+ ],
+ colors: {
+ "diffEditor.insertedTextBackground": "#014b01AA",
+ "diffEditor.removedTextBackground": "#750000AA",
+ "diffEditor.insertedLineBackground": "#003f00AA",
+ "diffEditor.removedLineBackground": "#5a0000AA",
+ "diffEditor.border": "#444444",
+ "editorUnnecessaryCode.border": "#00000000",
+ "editorUnnecessaryCode.opacity": "#00000077",
+ },
+ });
+};
+
export interface FileDiffViewerProps {
path: string;
type: GitChangeStatus;
@@ -45,7 +75,9 @@ export interface FileDiffViewerProps {
export function FileDiffViewer({ path, type }: FileDiffViewerProps) {
const [isCollapsed, setIsCollapsed] = React.useState(true);
const [editorHeight, setEditorHeight] = React.useState(400);
+ const [viewMode, setViewMode] = React.useState<ViewMode>("diff");
const diffEditorRef = React.useRef<editor_t.IStandaloneDiffEditor>(null);
+ const singleEditorRef = React.useRef<editor_t.IStandaloneCodeEditor>(null);
const isAdded = type === "A" || type === "U";
const isDeleted = type === "D";
@@ -55,7 +87,6 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {
const parts = path.split(/\s+/).slice(1);
return parts[parts.length - 1];
}
-
return path;
}, [path, type]);
@@ -70,69 +101,106 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {
enabled: !isCollapsed,
});
- // Function to update editor height based on content
const updateEditorHeight = React.useCallback(() => {
- if (diffEditorRef.current) {
- const originalEditor = diffEditorRef.current.getOriginalEditor();
- const modifiedEditor = diffEditorRef.current.getModifiedEditor();
-
- if (originalEditor && modifiedEditor) {
- // Get the content height from both editors and use the larger one
- const originalHeight = originalEditor.getContentHeight();
- const modifiedHeight = modifiedEditor.getContentHeight();
- const contentHeight = Math.max(originalHeight, modifiedHeight);
-
- // Add a small buffer to avoid scrollbar
- setEditorHeight(contentHeight + 20);
- }
+ if (!diffEditorRef.current) return;
+ const originalEditor = diffEditorRef.current.getOriginalEditor();
+ const modifiedEditor = diffEditorRef.current.getModifiedEditor();
+ if (originalEditor && modifiedEditor) {
+ setEditorHeight(
+ Math.max(
+ originalEditor.getContentHeight(),
+ modifiedEditor.getContentHeight(),
+ ) + 20,
+ );
}
}, []);
- const beforeMount = (monaco: Monaco) => {
- monaco.editor.defineTheme("custom-diff-theme", {
- base: "vs-dark",
- inherit: true,
- rules: [
- { token: "comment", foreground: "6a9955" },
- { token: "keyword", foreground: "569cd6" },
- { token: "string", foreground: "ce9178" },
- { token: "number", foreground: "b5cea8" },
- ],
- colors: {
- "diffEditor.insertedTextBackground": "#014b01AA", // Stronger green background
- "diffEditor.removedTextBackground": "#750000AA", // Stronger red background
- "diffEditor.insertedLineBackground": "#003f00AA", // Dark green for added lines
- "diffEditor.removedLineBackground": "#5a0000AA", // Dark red for removed lines
- "diffEditor.border": "#444444", // Border between diff editors
-
- "editorUnnecessaryCode.border": "#00000000", // No border for unnecessary code
- "editorUnnecessaryCode.opacity": "#00000077", // Slightly faded
- },
- });
- };
+ const updateSingleEditorHeight = React.useCallback(() => {
+ if (singleEditorRef.current) {
+ setEditorHeight(singleEditorRef.current.getContentHeight() + 20);
+ }
+ }, []);
- const handleEditorDidMount = (editor: editor_t.IStandaloneDiffEditor) => {
+ const handleDiffEditorMount = (editor: editor_t.IStandaloneDiffEditor) => {
diffEditorRef.current = editor;
updateEditorHeight();
+ editor.getOriginalEditor().onDidContentSizeChange(updateEditorHeight);
+ editor.getModifiedEditor().onDidContentSizeChange(updateEditorHeight);
+ };
- const originalEditor = editor.getOriginalEditor();
- const modifiedEditor = editor.getModifiedEditor();
-
- originalEditor.onDidContentSizeChange(updateEditorHeight);
- modifiedEditor.onDidContentSizeChange(updateEditorHeight);
+ const handleSingleEditorMount = (editor: editor_t.IStandaloneCodeEditor) => {
+ singleEditorRef.current = editor;
+ updateSingleEditorHeight();
+ editor.onDidContentSizeChange(updateSingleEditorHeight);
};
const status = (type === "U" ? STATUS_MAP.A : STATUS_MAP[type]) || "?";
-
- let statusIcon: React.ReactNode;
- if (typeof status === "string") {
- statusIcon = <span>{status}</span>;
- } else {
- const StatusIcon = status; // now it's recognized as a component
- statusIcon = <StatusIcon className="w-5 h-5" />;
- }
+ const statusIcon =
+ typeof status === "string" ? (
+ <Typography.Text>{status}</Typography.Text>
+ ) : (
+ React.createElement(status, { className: "w-5 h-5" })
+ );
const isFetchingData = isLoading || isRefetching;
+ const language = getLanguageFromPath(filePath);
+ const isMarkdownFile = language === "markdown";
+ const singleViewContent =
+ viewMode === "old" ? (diff?.original ?? "") : (diff?.modified ?? "");
+
+ const renderContent = () => {
+ if (viewMode === "diff") {
+ return (
+ <EditorContainer height={editorHeight}>
+ <DiffEditor
+ data-testid="file-diff-viewer"
+ className="w-full h-full"
+ language={language}
+ original={isAdded ? "" : (diff?.original ?? "")}
+ modified={isDeleted ? "" : (diff?.modified ?? "")}
+ theme="custom-diff-theme"
+ onMount={handleDiffEditorMount}
+ beforeMount={beforeMount}
+ options={{
+ ...SHARED_EDITOR_OPTIONS,
+ renderSideBySide: !isAdded && !isDeleted,
+ hideUnchangedRegions: { enabled: true },
+ }}
+ />
+ </EditorContainer>
+ );
+ }
+
+ if (isMarkdownFile) {
+ return (
+ <div
+ className="w-full border border-neutral-600 overflow-auto p-4 bg-neutral-900 prose prose-invert max-w-none"
+ data-testid="markdown-preview"
+ >
+ <MarkdownRenderer
+ content={singleViewContent}
+ includeStandard
+ includeHeadings
+ />
+ </div>
+ );
+ }
+
+ return (
+ <EditorContainer height={editorHeight}>
+ <Editor
+ data-testid="file-single-viewer"
+ className="w-full h-full"
+ language={language}
+ value={singleViewContent}
+ theme="custom-diff-theme"
+ beforeMount={beforeMount}
+ onMount={handleSingleEditorMount}
+ options={SHARED_EDITOR_OPTIONS}
+ />
+ </EditorContainer>
+ );
+ };
return (
<div data-testid="file-diff-viewer-outer" className="w-full flex flex-col">
@@ -144,9 +212,31 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {
onClick={() => setIsCollapsed((prev) => !prev)}
>
<span className="text-sm w-full text-content flex items-center gap-2">
- {isFetchingData && <LoadingSpinner className="w-5 h-5" />}
- {!isFetchingData && statusIcon}
+ {isFetchingData ? <LoadingSpinner className="w-5 h-5" /> : statusIcon}
<strong className="w-full truncate">{filePath}</strong>
+ {!isCollapsed && (
+ <span
+ className="flex items-center gap-0.5 shrink-0"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {VIEW_MODES.map(({ mode, icon: Icon }) => (
+ <button
+ key={mode}
+ data-testid={`view-mode-${mode}`}
+ type="button"
+ onClick={() => setViewMode(mode)}
+ className={cn(
+ "p-1 rounded transition-colors cursor-pointer",
+ viewMode === mode
+ ? "bg-neutral-600 text-white"
+ : "text-neutral-400 hover:bg-neutral-700 hover:text-neutral-200",
+ )}
+ >
+ <Icon className="w-4 h-4" />
+ </button>
+ ))}
+ </span>
+ )}
<button data-testid="collapse" type="button">
<ChevronUp
className={cn(
@@ -157,40 +247,8 @@ export function FileDiffViewer({ path, type }: FileDiffViewerProps) {
</button>
</span>
</div>
- {isSuccess && !isCollapsed && (
- <div
- className="w-full border border-neutral-600 overflow-hidden rounded-b-xl"
- style={{ height: `${editorHeight}px` }}
- >
- <DiffEditor
- data-testid="file-diff-viewer"
- className="w-full h-full"
- language={getLanguageFromPath(filePath)}
- original={isAdded ? "" : diff.original}
- modified={isDeleted ? "" : diff.modified}
- theme="custom-diff-theme"
- onMount={handleEditorDidMount}
- beforeMount={beforeMount}
- options={{
- renderValidationDecorations: "off",
- readOnly: true,
- renderSideBySide: !isAdded && !isDeleted,
- scrollBeyondLastLine: false,
- minimap: {
- enabled: false,
- },
- hideUnchangedRegions: {
- enabled: true,
- },
- automaticLayout: true,
- scrollbar: {
- // Make scrollbar less intrusive
- alwaysConsumeMouseWheel: false,
- },
- }}
- />
- </div>
- )}
+
+ {isSuccess && !isCollapsed && renderContent()}
</div>
);
}
diff --git a/frontend/src/components/features/diff-viewer/loading-spinner.tsx b/frontend/src/components/features/diff-viewer/loading-spinner.tsx
new file mode 100644
index 0000000000..29ea58def7
--- /dev/null
+++ b/frontend/src/components/features/diff-viewer/loading-spinner.tsx
@@ -0,0 +1,20 @@
+import { cn } from "#/utils/utils";
+
+export interface LoadingSpinnerProps {
+ className?: string;
+}
+
+export function LoadingSpinner({ className }: LoadingSpinnerProps) {
+ return (
+ <div className="flex items-center justify-center">
+ <div
+ className={cn(
+ "animate-spin rounded-full border-4 border-gray-200 border-t-blue-500",
+ className,
+ )}
+ role="status"
+ aria-label="Loading"
+ />
+ </div>
+ );
+}