GitBranchSwitcher.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useRef,
  6. useState,
  7. type KeyboardEvent,
  8. } from "react";
  9. import type { GitRepositorySummary } from "@zcode/shared";
  10. import { Button } from "@/components/ui/button.js";
  11. import {
  12. Command,
  13. CommandEmpty,
  14. CommandGroup,
  15. CommandInput,
  16. CommandItem,
  17. CommandList,
  18. } from "@/components/ui/command.js";
  19. import {
  20. Popover,
  21. PopoverContent,
  22. PopoverTrigger,
  23. } from "@/components/ui/popover.js";
  24. import { cn } from "@/components/lib/utils.js";
  25. import {
  26. GitBranchCreateDialog,
  27. GitBranchSwitchAssistDialog,
  28. } from "@/git-branch-switcher/GitBranchDialogs.js";
  29. import { GitGraphDialog } from "@/git-graph/GitGraphDialog.js";
  30. import { useGitBranchSwitcher } from "@/hooks/useGitBranchSwitcher.js";
  31. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  32. import {
  33. matchesGitBranchSearch,
  34. resolveGitBranchTriggerLabel,
  35. } from "@/git-branch-switcher/display.js";
  36. import {
  37. isCoarseTouchDevice,
  38. shouldRestoreChatInputFocusAfterPickerClose,
  39. } from "@/lib/pickerFocus.js";
  40. import {
  41. ChevronDownIcon,
  42. GitBranchIcon,
  43. GitGraph,
  44. LoaderIcon,
  45. PlusIcon,
  46. } from "lucide-react";
  47. interface GitBranchSwitcherProps {
  48. workspacePath: string;
  49. gitSummary: GitRepositorySummary;
  50. dirtyFileCount: number;
  51. onRefreshGit: () => void;
  52. className?: string;
  53. triggerClassName?: string;
  54. popoverClassName?: string;
  55. branchListClassName?: string;
  56. markAsWorkspaceHeaderBranch?: boolean;
  57. compactForRemoteControl?: boolean;
  58. popoverSide?: "top" | "bottom" | "left" | "right";
  59. avoidPopoverCollisions?: boolean;
  60. showFooterActions?: boolean;
  61. }
  62. export function GitBranchSwitcher({
  63. workspacePath,
  64. gitSummary,
  65. dirtyFileCount,
  66. onRefreshGit,
  67. className,
  68. triggerClassName,
  69. popoverClassName,
  70. branchListClassName,
  71. markAsWorkspaceHeaderBranch = false,
  72. compactForRemoteControl = false,
  73. popoverSide = "top",
  74. avoidPopoverCollisions = true,
  75. showFooterActions = true,
  76. }: GitBranchSwitcherProps) {
  77. const { intl, locale } = useZCodeIntl();
  78. const numberFormatter = new Intl.NumberFormat(locale);
  79. const commandListRef = useRef<HTMLDivElement | null>(null);
  80. const [gitGraphDialogOpen, setGitGraphDialogOpen] = useState(false);
  81. const {
  82. open,
  83. setOpen,
  84. createDialogOpen,
  85. setCreateDialogOpen,
  86. createBranchName,
  87. setCreateBranchName,
  88. commitMessage,
  89. setCommitMessage,
  90. commitError,
  91. switchAssistStep,
  92. switchAssistState,
  93. branchesResult,
  94. loadingBranches,
  95. mutationPending,
  96. switchBranch,
  97. createBranchAndSwitch,
  98. openSwitchCommitDialog,
  99. closeSwitchAssistDialog,
  100. commitAndSwitchBranch,
  101. } = useGitBranchSwitcher({
  102. workspacePath,
  103. currentBranchName: gitSummary.branchName,
  104. headRefType: gitSummary.headRefType,
  105. onRefreshGit,
  106. });
  107. const isVisible = gitSummary.isGitAvailable && gitSummary.isRepository;
  108. const displayedCurrentBranchName =
  109. branchesResult?.currentBranchName ?? gitSummary.branchName;
  110. const triggerLabel = useMemo(
  111. () =>
  112. resolveGitBranchTriggerLabel({
  113. headRefType: gitSummary.headRefType,
  114. currentBranchName: displayedCurrentBranchName,
  115. detachedLabel: intl.formatMessage({ id: "git.head.detached" }),
  116. fallbackLabel: intl.formatMessage({ id: "git.branchSwitcher.label" }),
  117. }),
  118. [displayedCurrentBranchName, gitSummary.headRefType, intl],
  119. );
  120. const currentBranchDirtyLabel = useMemo(
  121. () =>
  122. dirtyFileCount > 0
  123. ? intl.formatMessage(
  124. { id: "git.branchSwitcher.currentDirty" },
  125. { count: numberFormatter.format(dirtyFileCount) },
  126. )
  127. : null,
  128. [dirtyFileCount, intl, numberFormatter],
  129. );
  130. const switchAssistCurrentBranchLabel = useMemo(() => {
  131. if (!switchAssistState) {
  132. return triggerLabel;
  133. }
  134. return resolveGitBranchTriggerLabel({
  135. headRefType: gitSummary.headRefType,
  136. currentBranchName: switchAssistState.currentBranchName,
  137. detachedLabel: intl.formatMessage({ id: "git.head.detached" }),
  138. fallbackLabel: intl.formatMessage({ id: "git.branchSwitcher.label" }),
  139. });
  140. }, [gitSummary.headRefType, intl, switchAssistState, triggerLabel]);
  141. const branchSearchFilter = useCallback(
  142. (value: string, search: string) =>
  143. matchesGitBranchSearch(value, search) ? 1 : 0,
  144. [],
  145. );
  146. useEffect(() => {
  147. if (!open || !branchesResult?.branches.length) {
  148. return;
  149. }
  150. const frameId = window.requestAnimationFrame(() => {
  151. const selectedItem =
  152. commandListRef.current?.querySelector<HTMLElement>(
  153. '[data-branch-current="true"]',
  154. ) ?? null;
  155. selectedItem?.scrollIntoView({ block: "nearest" });
  156. });
  157. return () => {
  158. window.cancelAnimationFrame(frameId);
  159. };
  160. }, [branchesResult, open]);
  161. const handleContentKeyDown = useCallback(
  162. (event: KeyboardEvent<HTMLDivElement>) => {
  163. if (event.key !== "Tab") {
  164. return;
  165. }
  166. const highlightedItem =
  167. event.currentTarget.querySelector<HTMLElement>(
  168. '[data-slot="command-item"][data-selected="true"]:not([data-disabled=true])',
  169. ) ??
  170. event.currentTarget.querySelector<HTMLElement>(
  171. '[data-slot="command-item"]:not([data-disabled=true])',
  172. );
  173. if (!highlightedItem) {
  174. return;
  175. }
  176. event.preventDefault();
  177. highlightedItem.click();
  178. },
  179. [],
  180. );
  181. if (!isVisible) {
  182. return null;
  183. }
  184. return (
  185. <>
  186. <div
  187. data-workspace-header-branch={markAsWorkspaceHeaderBranch ? "true" : undefined}
  188. className={cn("flex items-center px-1 pt-2", className)}
  189. >
  190. <Popover open={open} onOpenChange={setOpen}>
  191. <PopoverTrigger asChild>
  192. <Button
  193. type="button"
  194. variant="ghost"
  195. size={"default"}
  196. disabled={mutationPending}
  197. aria-label={intl.formatMessage({
  198. id: "git.branchSwitcher.trigger.ariaLabel",
  199. })}
  200. className={cn(
  201. "min-w-0 rounded-full text-ui-base/relaxed",
  202. // Bugfix: 手机远控聊天页底部空间很窄,分支名会挤压输入工具栏;远控模式只保留图标入口。
  203. compactForRemoteControl
  204. ? "size-8 px-0"
  205. : "max-w-full pl-3 pr-2",
  206. triggerClassName,
  207. )}
  208. >
  209. <GitBranchIcon
  210. data-branch-switcher-primary-icon="true"
  211. className="size-4 text-foreground-subtle"
  212. />
  213. {!compactForRemoteControl ? (
  214. <>
  215. <span className="min-w-0 max-w-25 truncate text-left">{triggerLabel}</span>
  216. {loadingBranches || mutationPending ? (
  217. <LoaderIcon
  218. data-branch-switcher-trailing-icon="true"
  219. className="size-3.5 animate-spin text-foreground-subtle"
  220. />
  221. ) : (
  222. <ChevronDownIcon
  223. data-branch-switcher-trailing-icon="true"
  224. className="size-3.5 text-foreground-subtle"
  225. />
  226. )}
  227. </>
  228. ) : null}
  229. </Button>
  230. </PopoverTrigger>
  231. <PopoverContent
  232. align="start"
  233. side={popoverSide}
  234. avoidCollisions={avoidPopoverCollisions}
  235. className={cn("w-80 gap-0 bg-menu p-0", popoverClassName)}
  236. onOpenAutoFocus={(event) => {
  237. event.preventDefault();
  238. if (isCoarseTouchDevice()) {
  239. // 手机触控设备打开分支列表时,自动聚焦搜索框会拉起系统键盘遮挡列表。
  240. // 移动端保留触发器焦点,用户需要搜索时再手动点输入框;桌面端继续自动进入搜索。
  241. return;
  242. }
  243. const target = event.currentTarget;
  244. if (!(target instanceof HTMLElement)) {
  245. return;
  246. }
  247. const searchInput = target.querySelector<HTMLElement>(
  248. '[data-slot="command-input"]',
  249. );
  250. searchInput?.focus();
  251. }}
  252. onCloseAutoFocus={(event) => {
  253. event.preventDefault();
  254. if (
  255. !shouldRestoreChatInputFocusAfterPickerClose({
  256. isCoarseTouchDevice: isCoarseTouchDevice(),
  257. })
  258. ) {
  259. return;
  260. }
  261. const input = document.querySelector<HTMLElement>(
  262. '[data-testid="chat-input"]',
  263. );
  264. input?.focus();
  265. }}
  266. >
  267. <Command
  268. className="bg-transparent p-0 text-foreground"
  269. filter={branchSearchFilter}
  270. onKeyDown={handleContentKeyDown}
  271. >
  272. <CommandInput
  273. placeholder={intl.formatMessage({
  274. id: "git.branchSwitcher.searchPlaceholder",
  275. })}
  276. className="h-8"
  277. />
  278. <CommandList ref={commandListRef} className={cn("max-h-72", branchListClassName)}>
  279. <CommandEmpty className="px-4 py-5 text-foreground-subtle">
  280. {loadingBranches
  281. ? intl.formatMessage({ id: "common.loading" })
  282. : intl.formatMessage({ id: "git.branchSwitcher.empty" })}
  283. </CommandEmpty>
  284. <CommandGroup
  285. heading={intl.formatMessage({
  286. id: "git.branchSwitcher.section.branches",
  287. })}
  288. className="space-y-0.5 p-1 **:[[cmdk-group-heading]]:px-3 **:[[cmdk-group-heading]]:py-2 **:[[cmdk-group-heading]]:text-ui-base **:[[cmdk-group-heading]]:font-medium **:[[cmdk-group-heading]]:text-foreground-subtle"
  289. >
  290. {(branchesResult?.branches ?? []).map((branch) => {
  291. const isCurrent =
  292. branch.name === displayedCurrentBranchName;
  293. return (
  294. <CommandItem
  295. key={branch.name}
  296. value={branch.name}
  297. data-checked={isCurrent ? "true" : undefined}
  298. data-branch-current={isCurrent ? "true" : undefined}
  299. disabled={mutationPending}
  300. className={cn(
  301. "items-start gap-3 rounded-lg px-3 py-2 text-ui-base",
  302. )}
  303. onSelect={() => {
  304. void switchBranch(branch.name);
  305. }}
  306. >
  307. <GitBranchIcon className="mt-0.5 size-4 text-foreground-subtle" />
  308. <div className="min-w-0 flex-1 flex flex-col gap-1 text-left">
  309. <div className="truncate text-ui-base font-medium text-foreground">
  310. {branch.name}
  311. </div>
  312. {isCurrent && currentBranchDirtyLabel ? (
  313. <p className="pt-0.5 text-ui-base text-foreground-subtle">
  314. {currentBranchDirtyLabel}
  315. </p>
  316. ) : null}
  317. </div>
  318. </CommandItem>
  319. );
  320. })}
  321. </CommandGroup>
  322. </CommandList>
  323. </Command>
  324. {showFooterActions ? (
  325. <div className="border-t border-border p-1">
  326. <Button
  327. type="button"
  328. variant="ghost"
  329. size="lg"
  330. className="w-full justify-start px-2 text-foreground hover:bg-menu-hover hover:text-foreground"
  331. disabled={mutationPending}
  332. onClick={() => {
  333. setOpen(false);
  334. setCreateDialogOpen(true);
  335. }}
  336. >
  337. <PlusIcon className="size-4 text-foreground-subtle" />
  338. {intl.formatMessage({
  339. id: "git.branchSwitcher.createAction",
  340. })}
  341. </Button>
  342. <Button
  343. type="button"
  344. variant="ghost"
  345. size="lg"
  346. className="w-full justify-start px-2 text-foreground hover:bg-menu-hover hover:text-foreground"
  347. onClick={() => {
  348. setOpen(false);
  349. setGitGraphDialogOpen(true);
  350. }}
  351. >
  352. <GitGraph className="size-4 text-foreground-subtle" />
  353. {intl.formatMessage({ id: "gitGraph.menuAction" })}
  354. </Button>
  355. </div>
  356. ) : null}
  357. </PopoverContent>
  358. </Popover>
  359. </div>
  360. <GitBranchCreateDialog
  361. open={createDialogOpen}
  362. branchName={createBranchName}
  363. mutationPending={mutationPending}
  364. onOpenChange={(nextOpen) => {
  365. setCreateDialogOpen(nextOpen);
  366. if (!nextOpen) {
  367. setCreateBranchName("");
  368. }
  369. }}
  370. onBranchNameChange={setCreateBranchName}
  371. onCancel={() => {
  372. setCreateDialogOpen(false);
  373. setCreateBranchName("");
  374. }}
  375. onSubmit={() => {
  376. void createBranchAndSwitch();
  377. }}
  378. />
  379. <GitGraphDialog
  380. open={gitGraphDialogOpen}
  381. workspacePath={workspacePath}
  382. onOpenChange={setGitGraphDialogOpen}
  383. />
  384. <GitBranchSwitchAssistDialog
  385. step={switchAssistStep}
  386. state={switchAssistState}
  387. currentBranchLabel={switchAssistCurrentBranchLabel}
  388. commitMessage={commitMessage}
  389. commitError={commitError}
  390. mutationPending={mutationPending}
  391. onClose={closeSwitchAssistDialog}
  392. onOpenCommit={openSwitchCommitDialog}
  393. onCommitMessageChange={setCommitMessage}
  394. onSubmit={() => {
  395. void commitAndSwitchBranch();
  396. }}
  397. />
  398. </>
  399. );
  400. }