import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent, } from "react"; import type { GitRepositorySummary } from "@zcode/shared"; import { Button } from "@/components/ui/button.js"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command.js"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover.js"; import { cn } from "@/components/lib/utils.js"; import { GitBranchCreateDialog, GitBranchSwitchAssistDialog, } from "@/git-branch-switcher/GitBranchDialogs.js"; import { GitGraphDialog } from "@/git-graph/GitGraphDialog.js"; import { useGitBranchSwitcher } from "@/hooks/useGitBranchSwitcher.js"; import { useZCodeIntl } from "@/i18n/IntlProvider.js"; import { matchesGitBranchSearch, resolveGitBranchTriggerLabel, } from "@/git-branch-switcher/display.js"; import { isCoarseTouchDevice, shouldRestoreChatInputFocusAfterPickerClose, } from "@/lib/pickerFocus.js"; import { ChevronDownIcon, GitBranchIcon, GitGraph, LoaderIcon, PlusIcon, } from "lucide-react"; interface GitBranchSwitcherProps { workspacePath: string; gitSummary: GitRepositorySummary; dirtyFileCount: number; onRefreshGit: () => void; className?: string; triggerClassName?: string; popoverClassName?: string; branchListClassName?: string; markAsWorkspaceHeaderBranch?: boolean; compactForRemoteControl?: boolean; popoverSide?: "top" | "bottom" | "left" | "right"; avoidPopoverCollisions?: boolean; showFooterActions?: boolean; } export function GitBranchSwitcher({ workspacePath, gitSummary, dirtyFileCount, onRefreshGit, className, triggerClassName, popoverClassName, branchListClassName, markAsWorkspaceHeaderBranch = false, compactForRemoteControl = false, popoverSide = "top", avoidPopoverCollisions = true, showFooterActions = true, }: GitBranchSwitcherProps) { const { intl, locale } = useZCodeIntl(); const numberFormatter = new Intl.NumberFormat(locale); const commandListRef = useRef(null); const [gitGraphDialogOpen, setGitGraphDialogOpen] = useState(false); const { open, setOpen, createDialogOpen, setCreateDialogOpen, createBranchName, setCreateBranchName, commitMessage, setCommitMessage, commitError, switchAssistStep, switchAssistState, branchesResult, loadingBranches, mutationPending, switchBranch, createBranchAndSwitch, openSwitchCommitDialog, closeSwitchAssistDialog, commitAndSwitchBranch, } = useGitBranchSwitcher({ workspacePath, currentBranchName: gitSummary.branchName, headRefType: gitSummary.headRefType, onRefreshGit, }); const isVisible = gitSummary.isGitAvailable && gitSummary.isRepository; const displayedCurrentBranchName = branchesResult?.currentBranchName ?? gitSummary.branchName; const triggerLabel = useMemo( () => resolveGitBranchTriggerLabel({ headRefType: gitSummary.headRefType, currentBranchName: displayedCurrentBranchName, detachedLabel: intl.formatMessage({ id: "git.head.detached" }), fallbackLabel: intl.formatMessage({ id: "git.branchSwitcher.label" }), }), [displayedCurrentBranchName, gitSummary.headRefType, intl], ); const currentBranchDirtyLabel = useMemo( () => dirtyFileCount > 0 ? intl.formatMessage( { id: "git.branchSwitcher.currentDirty" }, { count: numberFormatter.format(dirtyFileCount) }, ) : null, [dirtyFileCount, intl, numberFormatter], ); const switchAssistCurrentBranchLabel = useMemo(() => { if (!switchAssistState) { return triggerLabel; } return resolveGitBranchTriggerLabel({ headRefType: gitSummary.headRefType, currentBranchName: switchAssistState.currentBranchName, detachedLabel: intl.formatMessage({ id: "git.head.detached" }), fallbackLabel: intl.formatMessage({ id: "git.branchSwitcher.label" }), }); }, [gitSummary.headRefType, intl, switchAssistState, triggerLabel]); const branchSearchFilter = useCallback( (value: string, search: string) => matchesGitBranchSearch(value, search) ? 1 : 0, [], ); useEffect(() => { if (!open || !branchesResult?.branches.length) { return; } const frameId = window.requestAnimationFrame(() => { const selectedItem = commandListRef.current?.querySelector( '[data-branch-current="true"]', ) ?? null; selectedItem?.scrollIntoView({ block: "nearest" }); }); return () => { window.cancelAnimationFrame(frameId); }; }, [branchesResult, open]); const handleContentKeyDown = useCallback( (event: KeyboardEvent) => { if (event.key !== "Tab") { return; } const highlightedItem = event.currentTarget.querySelector( '[data-slot="command-item"][data-selected="true"]:not([data-disabled=true])', ) ?? event.currentTarget.querySelector( '[data-slot="command-item"]:not([data-disabled=true])', ); if (!highlightedItem) { return; } event.preventDefault(); highlightedItem.click(); }, [], ); if (!isVisible) { return null; } return ( <>
{ event.preventDefault(); if (isCoarseTouchDevice()) { // 手机触控设备打开分支列表时,自动聚焦搜索框会拉起系统键盘遮挡列表。 // 移动端保留触发器焦点,用户需要搜索时再手动点输入框;桌面端继续自动进入搜索。 return; } const target = event.currentTarget; if (!(target instanceof HTMLElement)) { return; } const searchInput = target.querySelector( '[data-slot="command-input"]', ); searchInput?.focus(); }} onCloseAutoFocus={(event) => { event.preventDefault(); if ( !shouldRestoreChatInputFocusAfterPickerClose({ isCoarseTouchDevice: isCoarseTouchDevice(), }) ) { return; } const input = document.querySelector( '[data-testid="chat-input"]', ); input?.focus(); }} > {loadingBranches ? intl.formatMessage({ id: "common.loading" }) : intl.formatMessage({ id: "git.branchSwitcher.empty" })} {(branchesResult?.branches ?? []).map((branch) => { const isCurrent = branch.name === displayedCurrentBranchName; return ( { void switchBranch(branch.name); }} >
{branch.name}
{isCurrent && currentBranchDirtyLabel ? (

{currentBranchDirtyLabel}

) : null}
); })}
{showFooterActions ? (
) : null}
{ setCreateDialogOpen(nextOpen); if (!nextOpen) { setCreateBranchName(""); } }} onBranchNameChange={setCreateBranchName} onCancel={() => { setCreateDialogOpen(false); setCreateBranchName(""); }} onSubmit={() => { void createBranchAndSwitch(); }} /> { void commitAndSwitchBranch(); }} /> ); }