π OpenHands: AI-Driven Development
Fix: branch/repo dropdown reset on click (#12501)
Abhay Mishrab8a608c45e42
diff --git a/frontend/__tests__/components/features/home/git-branch-dropdown.test.tsx b/frontend/__tests__/components/features/home/git-branch-dropdown.test.tsxnew file mode 100644index 0000000000..151dde9a58--- /dev/null+++ b/frontend/__tests__/components/features/home/git-branch-dropdown.test.tsx@@ -0,0 +1,186 @@+import { render, screen, waitFor } from "@testing-library/react";+import { describe, expect, vi, beforeEach, it } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import userEvent from "@testing-library/user-event";+import { GitBranchDropdown } from "../../../../src/components/features/home/git-branch-dropdown/git-branch-dropdown";+import { Branch } from "#/types/git";++// Mock the branch data hook+const mockUseBranchData = vi.fn();+vi.mock("#/hooks/query/use-branch-data", () => ({+ useBranchData: (...args: unknown[]) => mockUseBranchData(...args),+}));++const MOCK_BRANCHES: Branch[] = [+ { name: "main", commit_sha: "abc123", protected: true },+ { name: "develop", commit_sha: "def456", protected: false },+ { name: "feature/test", commit_sha: "ghi789", protected: false },+];++const mockOnBranchSelect = vi.fn();++const renderDropdown = (+ props: Partial<Parameters<typeof GitBranchDropdown>[0]> = {},+) => {+ // Default mock return value+ mockUseBranchData.mockReturnValue({+ branches: MOCK_BRANCHES,+ isLoading: false,+ isError: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ isSearchLoading: false,+ });++ return render(+ <GitBranchDropdown+ repository="user/repo"+ provider="github"+ selectedBranch={null}+ onBranchSelect={mockOnBranchSelect}+ // eslint-disable-next-line react/jsx-props-no-spreading+ {...props}+ />,+ {+ wrapper: ({ children }) => (+ <QueryClientProvider+ client={+ new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ }+ >+ {children}+ </QueryClientProvider>+ ),+ },+ );+};++describe("GitBranchDropdown", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe("dropdown behavior", () => {+ it("should open dropdown when input is clicked", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-branch-dropdown-input");+ await userEvent.click(input);++ // Dropdown should be open (menu should be visible)+ await waitFor(() => {+ expect(+ screen.getByTestId("git-branch-dropdown-menu"),+ ).toBeInTheDocument();+ });+ });++ it("should keep dropdown open when clicking input while already open", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-branch-dropdown-input");++ // First click - open dropdown+ await userEvent.click(input);+ await waitFor(() => {+ expect(+ screen.getByTestId("git-branch-dropdown-menu"),+ ).toBeInTheDocument();+ });++ // Second click on input - should stay open (not close)+ await userEvent.click(input);++ // Dropdown should still be open+ await waitFor(() => {+ expect(+ screen.getByTestId("git-branch-dropdown-menu"),+ ).toBeInTheDocument();+ });+ });++ it("should preserve typed text when clicking input while typing", async () => {+ renderDropdown();++ const input = screen.getByTestId(+ "git-branch-dropdown-input",+ ) as HTMLInputElement;++ // Click to open and type+ await userEvent.click(input);+ await userEvent.type(input, "feat");++ expect(input.value).toBe("feat");++ // Click on input again (should not reset text)+ await userEvent.click(input);++ // Text should be preserved+ expect(input.value).toBe("feat");+ });+ });++ describe("cursor position preservation", () => {+ it("should allow editing in the middle of input text", async () => {+ renderDropdown();++ const input = screen.getByTestId(+ "git-branch-dropdown-input",+ ) as HTMLInputElement;++ // Click and type initial text+ await userEvent.click(input);+ await userEvent.type(input, "hello");++ expect(input.value).toBe("hello");++ // Move cursor to position 2 and type+ input.setSelectionRange(2, 2);+ await userEvent.type(input, "X");++ // The character should be inserted (exact position may vary based on browser behavior)+ expect(input.value).toContain("X");+ });+ });++ describe("input synchronization", () => {+ it("should show selected branch name in input when provided", async () => {+ const selectedBranch = MOCK_BRANCHES[0];+ renderDropdown({ selectedBranch });++ const input = screen.getByTestId(+ "git-branch-dropdown-input",+ ) as HTMLInputElement;++ await waitFor(() => {+ expect(input.value).toBe(selectedBranch.name);+ });+ });+ });++ describe("branch selection", () => {+ it("should call onBranchSelect when a branch is selected", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-branch-dropdown-input");+ await userEvent.click(input);++ // Wait for dropdown to open and show branches+ await waitFor(() => {+ expect(screen.getByText("main")).toBeInTheDocument();+ });++ // Click on a branch+ await userEvent.click(screen.getByText("develop"));++ expect(mockOnBranchSelect).toHaveBeenCalledWith(MOCK_BRANCHES[1]);+ });+ });+});diff --git a/frontend/__tests__/components/features/home/git-repo-dropdown.test.tsx b/frontend/__tests__/components/features/home/git-repo-dropdown.test.tsxnew file mode 100644index 0000000000..f4d99e4fb5--- /dev/null+++ b/frontend/__tests__/components/features/home/git-repo-dropdown.test.tsx@@ -0,0 +1,234 @@+import { render, screen, waitFor } from "@testing-library/react";+import { describe, expect, vi, beforeEach, it } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import userEvent from "@testing-library/user-event";+import { GitRepoDropdown } from "../../../../src/components/features/home/git-repo-dropdown/git-repo-dropdown";+import { GitRepository } from "#/types/git";++// Mock the repository data hook+const mockUseRepositoryData = vi.fn();+vi.mock(+ "#/components/features/home/git-repo-dropdown/use-repository-data",+ () => ({+ useRepositoryData: (...args: unknown[]) => mockUseRepositoryData(...args),+ }),+);++// Mock the URL search hook+const mockUseUrlSearch = vi.fn();+vi.mock("#/components/features/home/git-repo-dropdown/use-url-search", () => ({+ useUrlSearch: (...args: unknown[]) => mockUseUrlSearch(...args),+}));++// Mock useConfig+vi.mock("#/hooks/query/use-config", () => ({+ useConfig: () => ({ data: null }),+}));++// Mock useHomeStore+vi.mock("#/stores/home-store", () => ({+ useHomeStore: () => ({ recentRepositories: [] }),+}));++const MOCK_REPOSITORIES: GitRepository[] = [+ {+ id: "1",+ full_name: "user/repo-one",+ git_provider: "github",+ is_public: true,+ },+ {+ id: "2",+ full_name: "user/repo-two",+ git_provider: "github",+ is_public: true,+ },+ {+ id: "3",+ full_name: "org/feature-repo",+ git_provider: "github",+ is_public: false,+ },+];++const mockOnChange = vi.fn();++const setupDefaultMocks = (+ repositoryDataOverrides: Partial<+ ReturnType<typeof mockUseRepositoryData>+ > = {},+) => {+ mockUseRepositoryData.mockReturnValue({+ repositories: MOCK_REPOSITORIES,+ selectedRepository: null,+ isLoading: false,+ isError: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ isSearchLoading: false,+ ...repositoryDataOverrides,+ });++ mockUseUrlSearch.mockReturnValue({+ urlSearchResults: [],+ isUrlSearchLoading: false,+ });+};++const renderDropdown = (+ props: Partial<Parameters<typeof GitRepoDropdown>[0]> = {},+ repositoryDataOverrides: Partial<+ ReturnType<typeof mockUseRepositoryData>+ > = {},+) => {+ // Set up mocks with optional overrides+ setupDefaultMocks(repositoryDataOverrides);++ return render(+ <GitRepoDropdown+ provider="github"+ onChange={mockOnChange}+ // eslint-disable-next-line react/jsx-props-no-spreading+ {...props}+ />,+ {+ wrapper: ({ children }) => (+ <QueryClientProvider+ client={+ new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ }+ >+ {children}+ </QueryClientProvider>+ ),+ },+ );+};++describe("GitRepoDropdown", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe("dropdown behavior", () => {+ it("should open dropdown when input is clicked", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-repo-dropdown");+ await userEvent.click(input);++ // Dropdown should be open (menu should be visible)+ await waitFor(() => {+ expect(+ screen.getByTestId("git-repo-dropdown-menu"),+ ).toBeInTheDocument();+ });+ });++ it("should keep dropdown open when clicking input while already open", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-repo-dropdown");++ // First click - open dropdown+ await userEvent.click(input);+ await waitFor(() => {+ expect(+ screen.getByTestId("git-repo-dropdown-menu"),+ ).toBeInTheDocument();+ });++ // Second click on input - should stay open (not close)+ await userEvent.click(input);++ // Dropdown should still be open+ await waitFor(() => {+ expect(+ screen.getByTestId("git-repo-dropdown-menu"),+ ).toBeInTheDocument();+ });+ });++ it("should preserve typed text when clicking input while typing", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;++ // Click to open and type+ await userEvent.click(input);+ await userEvent.type(input, "repo");++ expect(input.value).toBe("repo");++ // Click on input again (should not reset text)+ await userEvent.click(input);++ // Text should be preserved+ expect(input.value).toBe("repo");+ });+ });++ describe("cursor position preservation", () => {+ it("should allow editing in the middle of input text", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;++ // Click and type initial text+ await userEvent.click(input);+ await userEvent.type(input, "hello");++ expect(input.value).toBe("hello");++ // Move cursor to position 2 and type+ input.setSelectionRange(2, 2);+ await userEvent.type(input, "X");++ // The character should be inserted (exact position may vary based on browser behavior)+ expect(input.value).toContain("X");+ });+ });++ describe("input synchronization", () => {+ it("should show selected repository name in input when provided", async () => {+ const selectedRepository = MOCK_REPOSITORIES[0];++ renderDropdown(+ { value: selectedRepository.full_name },+ { selectedRepository },+ );++ const input = screen.getByTestId("git-repo-dropdown") as HTMLInputElement;++ await waitFor(() => {+ expect(input.value).toBe(selectedRepository.full_name);+ });+ });+ });++ describe("repository selection", () => {+ it("should call onChange when a repository is selected", async () => {+ renderDropdown();++ const input = screen.getByTestId("git-repo-dropdown");+ await userEvent.click(input);++ // Wait for dropdown to open and show repositories+ await waitFor(() => {+ expect(screen.getByText("user/repo-one")).toBeInTheDocument();+ });++ // Click on a repository+ await userEvent.click(screen.getByText("user/repo-two"));++ expect(mockOnChange).toHaveBeenCalledWith(MOCK_REPOSITORIES[1]);+ });+ });+});diff --git a/frontend/src/components/features/home/git-branch-dropdown/git-branch-dropdown.tsx b/frontend/src/components/features/home/git-branch-dropdown/git-branch-dropdown.tsxindex eb99283dd1..112ada032f 100644--- a/frontend/src/components/features/home/git-branch-dropdown/git-branch-dropdown.tsx+++ b/frontend/src/components/features/home/git-branch-dropdown/git-branch-dropdown.tsx@@ -87,16 +87,6 @@ export function GitBranchDropdown({[onBranchSelect],);- // Handle input value change- const handleInputValueChange = useCallback(- ({ inputValue: newInputValue }: { inputValue?: string }) => {- if (newInputValue !== undefined) {- setInputValue(newInputValue);- }- },- [],- );-// Handle menu scroll for infinite loadingconst handleMenuScroll = useCallback((event: React.UIEvent<HTMLUListElement>) => {@@ -128,8 +118,14 @@ export function GitBranchDropdown({onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {handleBranchSelect(newSelectedItem || null);},- onInputValueChange: handleInputValueChange,inputValue,+ // Override Downshift's default input-click behavior to avoid closing/reopening+ // the menu, which would reset scroll position and break search continuity.+ stateReducer: (state, actionAndChanges) =>+ actionAndChanges.type === useCombobox.stateChangeTypes.InputClick &&+ state.isOpen+ ? { ...actionAndChanges.changes, isOpen: true }+ : actionAndChanges.changes,});// Reset branch selection when repository changes@@ -176,12 +172,12 @@ export function GitBranchDropdown({// Initialize input value when selectedBranch changes (but not when user is typing)useEffect(() => {- if (selectedBranch && !isOpen && inputValue !== selectedBranch.name) {+ if (selectedBranch && !isOpen) {setInputValue(selectedBranch.name);- } else if (!selectedBranch && !isOpen && inputValue) {+ } else if (!selectedBranch && !isOpen) {setInputValue("");}- }, [selectedBranch, isOpen, inputValue]);+ }, [selectedBranch, isOpen]);const isLoadingState = isLoading || isSearchLoading || isFetchingNextPage;@@ -207,6 +203,10 @@ export function GitBranchDropdown({"disabled:bg-[#363636] disabled:cursor-not-allowed disabled:opacity-60","pl-7 pr-16 text-sm font-normal leading-5", // Space for clear and toggle buttons),+ // Direct onChange for cursor position preservation+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => {+ setInputValue(e.target.value);+ },})}data-testid="git-branch-dropdown-input"/>diff --git a/frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx b/frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsxindex 442a65a318..d86277f96d 100644--- a/frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx+++ b/frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx@@ -184,14 +184,6 @@ export function GitRepoDropdown({setInputValue("");}, [handleSelectionChange]);- // Handle input value change- const handleInputValueChange = useCallback(- ({ inputValue: newInputValue }: { inputValue?: string }) => {- setInputValue(newInputValue || "");- },- [],- );-// Handle scroll to bottom for paginationconst handleMenuScroll = useCallback((event: React.UIEvent<HTMLUListElement>) => {@@ -220,8 +212,14 @@ export function GitRepoDropdown({onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {handleSelectionChange(newSelectedItem);},- onInputValueChange: handleInputValueChange,inputValue,+ // Override Downshift's default input-click behavior to avoid closing/reopening+ // the menu, which would reset scroll position and break search continuity.+ stateReducer: (state, actionAndChanges) =>+ actionAndChanges.type === useCombobox.stateChangeTypes.InputClick &&+ state.isOpen+ ? { ...actionAndChanges.changes, isOpen: true }+ : actionAndChanges.changes,});// Sync localSelectedItem with external value prop@@ -237,6 +235,8 @@ export function GitRepoDropdown({useEffect(() => {if (selectedRepository && !isOpen) {setInputValue(selectedRepository.full_name);+ } else if (!selectedRepository && !isOpen) {+ setInputValue("");}}, [selectedRepository, isOpen]);@@ -335,6 +335,10 @@ export function GitRepoDropdown({"disabled:bg-[#363636] disabled:cursor-not-allowed disabled:opacity-60","pl-7 pr-16 text-sm font-normal leading-5", // Space for clear and toggle buttons),+ // Direct onChange for cursor position preservation+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => {+ setInputValue(e.target.value);+ },})}data-testid="git-repo-dropdown"/>