GitPane.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /* eslint-disable max-lines -- GitPane 当前集中承载来源切换、diff 懒加载、展开状态和文件变更查找联动;后续拆分需按 Git 面板功能边界单独推进。 */
  2. import { useCallback, useEffect, useMemo, useRef, useState } from "react";
  3. import { useVirtualizer } from "@tanstack/react-virtual";
  4. import type { GitChangeSourceId, GitDiffResult } from "@zcode/shared";
  5. import { TID_GIT_PANE } from "@zcode/shared";
  6. import { cn } from "@/components/lib/utils.js";
  7. import { Button } from "@/components/ui/button.js";
  8. import { FileTextIcon, RefreshCw } from "lucide-react";
  9. import {
  10. Select,
  11. SelectContent,
  12. SelectItem,
  13. SelectTrigger,
  14. SelectValue,
  15. } from "@/components/ui/select.js";
  16. import { type GitPaneFileChange, type GitPaneRepositoryState } from "@/hooks/useGitRepository.js";
  17. import { useServices } from "@/hooks/useServices.js";
  18. import { useFileContextActions } from "@/hooks/useFileContextActions.js";
  19. import { useWorkspaceOpenInEditorTarget } from "@/hooks/useWorkspaceOpenInEditorTarget.js";
  20. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  21. import { joinFilePath, isAbsoluteFilePath } from "@/lib/path.js";
  22. import {
  23. getDiffCacheKey,
  24. getErrorMessage,
  25. getGitPaneDiffFindContent,
  26. getSourceMessageId,
  27. } from "@/GitPane/helpers.js";
  28. import { GitPaneChangeCard } from "@/GitPaneChangeCard.js";
  29. import { getFileChangeFindState } from "@/GitPane/fileChangeFindSearch.js";
  30. import { logger } from "@/logger.js";
  31. import { useZCodeStore } from "@/store/StoreProvider.js";
  32. import { resolveTheme } from "@/useTheme.js";
  33. import { getWorkspaceFileRelativePath } from "@/workspace-file-tree/model.js";
  34. interface GitDiffLoadState {
  35. loading: boolean;
  36. diff: GitDiffResult | null;
  37. }
  38. const GIT_PANE_CHANGE_ROW_ESTIMATE_PX = 32;
  39. const GIT_PANE_CHANGE_ROW_OVERSCAN = 14;
  40. export function GitPane({
  41. workspacePath,
  42. gitState,
  43. isDesktop,
  44. selectedSourceId,
  45. fileChangeFindActiveIndex,
  46. fileChangeFindNavigationRequestId,
  47. fileChangeFindQuery,
  48. onFileChangeFindMatchCountChange,
  49. onSelectSource,
  50. onClose: _onClose,
  51. onRefresh,
  52. onRevealFileInTree,
  53. workspaceIdentity,
  54. workspaceRemoteSessionId,
  55. }: {
  56. workspacePath: string;
  57. workspaceIdentity?: string;
  58. workspaceRemoteSessionId?: string;
  59. gitState: GitPaneRepositoryState;
  60. isDesktop?: boolean;
  61. selectedSourceId: GitChangeSourceId;
  62. fileChangeFindActiveIndex: number;
  63. fileChangeFindNavigationRequestId: number;
  64. fileChangeFindQuery: string;
  65. onFileChangeFindMatchCountChange: (count: number) => void;
  66. onSelectSource: (sourceId: GitChangeSourceId) => void;
  67. onClose: () => void;
  68. onRefresh: () => void;
  69. onRevealFileInTree?: (path: string) => void;
  70. }) {
  71. const { gitService } = useServices();
  72. const { intl } = useZCodeIntl();
  73. const theme = useZCodeStore((state) => state.theme);
  74. const codePreviewSettings = useZCodeStore((state) => state.codePreviewSettings);
  75. const workspaceOpenTarget = useWorkspaceOpenInEditorTarget({
  76. workspacePath,
  77. workspaceIdentity,
  78. workspaceRemoteSessionId,
  79. });
  80. const fileActions = useFileContextActions({
  81. canOpenLocalFileManager: Boolean(isDesktop),
  82. isRemoteWorkspace:
  83. Boolean(workspaceRemoteSessionId || workspaceIdentity?.trim()) ||
  84. workspaceOpenTarget.isRemoteWorkspace,
  85. remoteTarget: workspaceOpenTarget.remoteTarget,
  86. workspaceIdentity,
  87. });
  88. const resolvedTheme = resolveTheme(theme);
  89. const [expandedPath, setExpandedPath] = useState<string | null>(null);
  90. const [diffStateByKey, setDiffStateByKey] = useState<Record<string, GitDiffLoadState>>({});
  91. const diffGenerationRef = useRef(0);
  92. const pendingDiffKeysRef = useRef(new Set<string>());
  93. const changeListScrollRef = useRef<HTMLDivElement | null>(null);
  94. const defaultSourceOption = gitState.sourceOptions[0]!;
  95. const currentSourceOption =
  96. gitState.sourceOptions.find((option) => option.id === selectedSourceId) ?? defaultSourceOption;
  97. const currentDataset = gitState.datasets[currentSourceOption.id] ?? gitState.datasets.unstaged;
  98. const currentChanges = useMemo(
  99. () => currentDataset.sections.flatMap((section) => section.changes),
  100. [currentDataset],
  101. );
  102. const normalizedFileChangeFindQuery = fileChangeFindQuery.trim();
  103. const emptyStateCopy = useMemo(() => {
  104. if (currentSourceOption.id === "last-turn") {
  105. return {
  106. title: intl.formatMessage({ id: "git.empty.lastTurnTitle" }),
  107. description: intl.formatMessage({
  108. id: "git.empty.lastTurnDescription",
  109. }),
  110. };
  111. }
  112. if (gitState.loading) {
  113. return {
  114. title: intl.formatMessage({ id: "common.loading" }),
  115. description: intl.formatMessage({ id: "git.loading.description" }),
  116. };
  117. }
  118. if (gitState.error) {
  119. return {
  120. title: intl.formatMessage({ id: "git.error.title" }),
  121. description: intl.formatMessage(
  122. { id: "git.error.description" },
  123. { message: gitState.error },
  124. ),
  125. };
  126. }
  127. if (!gitState.summary.isGitAvailable) {
  128. return {
  129. title: intl.formatMessage({ id: "git.empty.gitUnavailableTitle" }),
  130. description: intl.formatMessage({
  131. id: "git.empty.gitUnavailableDescription",
  132. }),
  133. };
  134. }
  135. if (!gitState.summary.isRepository) {
  136. return {
  137. title: intl.formatMessage({ id: "git.empty.notRepositoryTitle" }),
  138. description: intl.formatMessage({
  139. id: "git.empty.notRepositoryDescription",
  140. }),
  141. };
  142. }
  143. return {
  144. title: intl.formatMessage({ id: "git.empty.title" }),
  145. description: intl.formatMessage({ id: "git.empty.description" }),
  146. };
  147. }, [
  148. currentSourceOption.id,
  149. gitState.error,
  150. gitState.loading,
  151. gitState.summary.isGitAvailable,
  152. gitState.summary.isRepository,
  153. intl,
  154. ]);
  155. useEffect(() => {
  156. diffGenerationRef.current += 1;
  157. pendingDiffKeysRef.current.clear();
  158. setDiffStateByKey({});
  159. }, [gitState.revision, workspacePath]);
  160. useEffect(() => {
  161. if (!expandedPath) {
  162. return;
  163. }
  164. if (!currentChanges.some((change) => change.path === expandedPath)) {
  165. setExpandedPath(null);
  166. }
  167. }, [currentChanges, expandedPath]);
  168. const loadDiffForChange = useCallback(
  169. (change: GitPaneFileChange, sourceId: GitChangeSourceId) => {
  170. if (sourceId === "last-turn" || change.diff) {
  171. return;
  172. }
  173. const cacheKey = getDiffCacheKey(sourceId, change.path);
  174. if (pendingDiffKeysRef.current.has(cacheKey) || diffStateByKey[cacheKey]?.diff) {
  175. return;
  176. }
  177. pendingDiffKeysRef.current.add(cacheKey);
  178. setDiffStateByKey((current) => ({
  179. ...current,
  180. [cacheKey]: {
  181. loading: true,
  182. diff: current[cacheKey]?.diff ?? null,
  183. },
  184. }));
  185. const generation = diffGenerationRef.current;
  186. void gitService
  187. .getDiff({
  188. workspacePath,
  189. path: change.path,
  190. sourceId,
  191. })
  192. .then((diff) => {
  193. if (diffGenerationRef.current !== generation) {
  194. return;
  195. }
  196. // 大文件 diff 卡顿问题需要先确认“卡在拉取还是卡在渲染”。
  197. // 这里记录每次展开拿到的 diff 规模,便于从日志快速定位是否命中 fallback 条件。
  198. // 文件变更查找会批量预加载 diff;这类逐文件规模日志只适合开发排查。
  199. // 走 debug 可避免生产桌面日志被搜索行为刷大,同时保留定位大 diff 卡顿的线索。
  200. logger.debug("[GitPane] diff 已加载", {
  201. workspacePath,
  202. sourceId,
  203. path: change.path,
  204. availability: diff.availability,
  205. beforeChars: diff.beforeContent?.length ?? 0,
  206. afterChars: diff.afterContent?.length ?? 0,
  207. });
  208. setDiffStateByKey((current) => ({
  209. ...current,
  210. [cacheKey]: {
  211. loading: false,
  212. diff,
  213. },
  214. }));
  215. })
  216. .catch((error: unknown) => {
  217. if (diffGenerationRef.current !== generation) {
  218. return;
  219. }
  220. const message = getErrorMessage(error);
  221. logger.warn("[GitPane] 读取文件 diff 失败", {
  222. workspacePath,
  223. sourceId,
  224. path: change.path,
  225. error: message,
  226. });
  227. setDiffStateByKey((current) => ({
  228. ...current,
  229. [cacheKey]: {
  230. loading: false,
  231. diff: {
  232. path: change.path,
  233. availability: "unavailable",
  234. patch: null,
  235. beforeContent: null,
  236. afterContent: null,
  237. summary: message,
  238. },
  239. },
  240. }));
  241. })
  242. .finally(() => {
  243. pendingDiffKeysRef.current.delete(cacheKey);
  244. });
  245. },
  246. [diffStateByKey, gitService, workspacePath],
  247. );
  248. useEffect(() => {
  249. if (!expandedPath) {
  250. return;
  251. }
  252. const expandedChange = currentChanges.find((change) => change.path === expandedPath);
  253. if (!expandedChange) {
  254. return;
  255. }
  256. loadDiffForChange(expandedChange, currentDataset.id);
  257. }, [currentChanges, currentDataset.id, expandedPath, loadDiffForChange]);
  258. const fileChangeFindTargets = useMemo(
  259. () =>
  260. currentChanges.map((change) => {
  261. const diffState =
  262. change.diff ??
  263. diffStateByKey[getDiffCacheKey(currentDataset.id, change.path)]?.diff ??
  264. null;
  265. return {
  266. path: change.path,
  267. content: getGitPaneDiffFindContent(diffState),
  268. };
  269. }),
  270. [currentChanges, currentDataset.id, diffStateByKey],
  271. );
  272. const fileChangeFindState = useMemo(
  273. () =>
  274. getFileChangeFindState(fileChangeFindTargets, fileChangeFindQuery, fileChangeFindActiveIndex),
  275. [fileChangeFindActiveIndex, fileChangeFindQuery, fileChangeFindTargets],
  276. );
  277. const activeFileChangeFindMatch = fileChangeFindState.activeMatch;
  278. const changeRowVirtualizer = useVirtualizer({
  279. count: currentChanges.length,
  280. getItemKey: (index) => {
  281. const change = currentChanges[index];
  282. return change ? `${currentDataset.id}:${change.path}` : `${currentDataset.id}:${index}`;
  283. },
  284. getScrollElement: () => changeListScrollRef.current,
  285. estimateSize: () => GIT_PANE_CHANGE_ROW_ESTIMATE_PX,
  286. overscan: GIT_PANE_CHANGE_ROW_OVERSCAN,
  287. });
  288. const virtualChangeRows = changeRowVirtualizer.getVirtualItems();
  289. useEffect(() => {
  290. onFileChangeFindMatchCountChange(fileChangeFindState.total);
  291. }, [fileChangeFindState.total, onFileChangeFindMatchCountChange]);
  292. useEffect(() => {
  293. // Review 面板打开时会把数百个未跟踪文件同步挂载,CDP trace 里 click
  294. // 事件因此出现 600ms+ long task。这里只挂载可视行;展开 diff 后高度变化时重测,
  295. // 避免后续虚拟行继续沿用折叠态高度。
  296. changeRowVirtualizer.measure();
  297. }, [changeRowVirtualizer, currentDataset.id, expandedPath]);
  298. useEffect(() => {
  299. if (!normalizedFileChangeFindQuery) {
  300. return;
  301. }
  302. // 文件变更查找需要命中折叠文件里的内容。
  303. // diff 默认是展开时懒加载的,所以查找时先把当前来源的 diff 补齐,再用同一套 patch 数据计算全局命中。
  304. for (const change of currentChanges) {
  305. loadDiffForChange(change, currentDataset.id);
  306. }
  307. }, [currentChanges, currentDataset.id, loadDiffForChange, normalizedFileChangeFindQuery]);
  308. useEffect(() => {
  309. if (!activeFileChangeFindMatch) {
  310. return;
  311. }
  312. const activeChange = currentChanges.find(
  313. (change) => change.path === activeFileChangeFindMatch.path,
  314. );
  315. if (!activeChange) {
  316. return;
  317. }
  318. if (expandedPath !== activeFileChangeFindMatch.path) {
  319. // 当前命中可能位于折叠文件内。
  320. // 先展开目标文件,再由文本高亮 hook 在真实 DOM 渲染后滚动到命中行。
  321. setExpandedPath(activeFileChangeFindMatch.path);
  322. }
  323. loadDiffForChange(activeChange, currentDataset.id);
  324. }, [
  325. activeFileChangeFindMatch,
  326. currentChanges,
  327. currentDataset.id,
  328. expandedPath,
  329. fileChangeFindNavigationRequestId,
  330. loadDiffForChange,
  331. ]);
  332. useEffect(() => {
  333. if (!activeFileChangeFindMatch) {
  334. return;
  335. }
  336. const activeMatchIndex = currentChanges.findIndex(
  337. (change) => change.path === activeFileChangeFindMatch.path,
  338. );
  339. if (activeMatchIndex < 0) {
  340. return;
  341. }
  342. changeRowVirtualizer.scrollToIndex(activeMatchIndex, { align: "center" });
  343. }, [
  344. activeFileChangeFindMatch,
  345. changeRowVirtualizer,
  346. currentChanges,
  347. fileChangeFindNavigationRequestId,
  348. ]);
  349. const handleSelectSource = (nextSourceId: string) => {
  350. logger.info(`[GitPane] 切换来源 workspace=${workspacePath} source=${nextSourceId}`);
  351. onSelectSource(nextSourceId as GitChangeSourceId);
  352. setExpandedPath(null);
  353. };
  354. const handleExpandChange = (change: GitPaneFileChange, nextOpen: boolean) => {
  355. logger.info(
  356. `[GitPane] 切换文件展开 workspace=${workspacePath} source=${currentSourceOption.id} path=${change.path} expanded=${nextOpen}`,
  357. );
  358. setExpandedPath(nextOpen ? change.path : null);
  359. if (nextOpen) {
  360. loadDiffForChange(change, currentDataset.id);
  361. }
  362. };
  363. const resolveChangePath = useCallback(
  364. (change: GitPaneFileChange) =>
  365. isAbsoluteFilePath(change.path) ? change.path : joinFilePath(workspacePath, change.path),
  366. [workspacePath],
  367. );
  368. const handleCopyAbsolutePath = useCallback(
  369. (change: GitPaneFileChange) => {
  370. void fileActions.copyAbsolutePath({ path: resolveChangePath(change) });
  371. },
  372. [fileActions, resolveChangePath],
  373. );
  374. const handleCopyRelativePath = useCallback(
  375. (change: GitPaneFileChange) => {
  376. void fileActions.copyRelativePath({
  377. path: resolveChangePath(change),
  378. relativePath: getWorkspaceFileRelativePath(workspacePath, resolveChangePath(change)),
  379. });
  380. },
  381. [fileActions, resolveChangePath, workspacePath],
  382. );
  383. const handleRevealChangeInFileManager = useCallback(
  384. (change: GitPaneFileChange) => {
  385. void fileActions.revealInFileManager({
  386. path: resolveChangePath(change),
  387. deleted: change.kind === "deleted",
  388. kind: "file",
  389. });
  390. },
  391. [fileActions, resolveChangePath],
  392. );
  393. const handleRevealChangeInFileTree = useCallback(
  394. (change: GitPaneFileChange) => {
  395. onRevealFileInTree?.(resolveChangePath(change));
  396. },
  397. [onRevealFileInTree, resolveChangePath],
  398. );
  399. const contextMenuLabels = useMemo(
  400. () => ({
  401. copyAbsolutePath: intl.formatMessage({ id: "fileActions.copyAbsolutePath" }),
  402. copyRelativePath: intl.formatMessage({ id: "fileActions.copyRelativePath" }),
  403. revealInFileManager: intl.formatMessage({ id: "git.changeContext.revealInFileManager" }),
  404. revealInFileTree: intl.formatMessage({ id: "git.changeContext.revealInFileTree" }),
  405. }),
  406. [intl],
  407. );
  408. return (
  409. <section data-testid={TID_GIT_PANE} className="flex h-full min-h-0 flex-col bg-background">
  410. <div className="flex items-center justify-between gap-3 p-3">
  411. <Select value={currentSourceOption.id} onValueChange={handleSelectSource}>
  412. <SelectTrigger className="max-w-full" size="lg">
  413. <SelectValue />
  414. </SelectTrigger>
  415. <SelectContent align="start">
  416. {gitState.sourceOptions.map((option) => (
  417. <SelectItem key={option.id} value={option.id} disabled={option.disabled}>
  418. {intl.formatMessage({ id: getSourceMessageId(option.id) })}
  419. </SelectItem>
  420. ))}
  421. </SelectContent>
  422. </Select>
  423. <div className="flex items-center gap-2">
  424. <Button
  425. type="button"
  426. variant="ghost"
  427. size="lg"
  428. disabled={gitState.loading}
  429. onClick={onRefresh}
  430. >
  431. <RefreshCw className={cn("size-3.5", gitState.loading && "animate-spin")} />
  432. {intl.formatMessage({ id: "git.action.refresh" })}
  433. </Button>
  434. </div>
  435. </div>
  436. <div className="min-h-0 flex-1">
  437. {currentChanges.length > 0 ? (
  438. <div ref={changeListScrollRef} className="h-full min-h-0 w-full overflow-auto">
  439. <div
  440. className="relative w-full min-w-0"
  441. style={{ height: `${changeRowVirtualizer.getTotalSize()}px` }}
  442. >
  443. {virtualChangeRows.map((virtualRow) => {
  444. const change = currentChanges[virtualRow.index];
  445. if (!change) {
  446. return null;
  447. }
  448. const isExpanded = expandedPath === change.path;
  449. const diffCacheKey = getDiffCacheKey(currentDataset.id, change.path);
  450. const cachedDiffState = diffStateByKey[diffCacheKey];
  451. const diffState = change.diff ?? cachedDiffState?.diff ?? null;
  452. const isDiffLoading =
  453. isExpanded && !change.diff && (!cachedDiffState || cachedDiffState.loading);
  454. return (
  455. <div
  456. key={virtualRow.key}
  457. ref={changeRowVirtualizer.measureElement}
  458. className="absolute left-0 w-full min-w-0"
  459. data-git-pane-change-virtual-row
  460. data-index={virtualRow.index}
  461. // transform 定位会让行内 sticky 文件名失效,展开大 diff 后标题不再置顶。
  462. // 改用 top 偏移保留虚拟滚动布局,同时让 sticky 继续以滚动容器为参照。
  463. style={{ top: `${virtualRow.start}px` }}
  464. >
  465. <GitPaneChangeCard
  466. change={change}
  467. contextMenuLabels={contextMenuLabels}
  468. diffState={diffState}
  469. isDiffLoading={isDiffLoading}
  470. isExpanded={isExpanded}
  471. canRevealInFileManager={fileActions.canRevealInFileManager({
  472. path: resolveChangePath(change),
  473. deleted: change.kind === "deleted",
  474. })}
  475. codePreviewSettings={codePreviewSettings}
  476. resolvedTheme={resolvedTheme}
  477. onCopyAbsolutePath={handleCopyAbsolutePath}
  478. onCopyRelativePath={handleCopyRelativePath}
  479. onOpenChange={handleExpandChange}
  480. onRevealInFileManager={handleRevealChangeInFileManager}
  481. onRevealInFileTree={
  482. onRevealFileInTree ? handleRevealChangeInFileTree : undefined
  483. }
  484. />
  485. </div>
  486. );
  487. })}
  488. </div>
  489. </div>
  490. ) : (
  491. <div className="flex h-full flex-col items-center justify-center px-6 text-center">
  492. <FileTextIcon className="size-8 text-foreground-subtlest" />
  493. <p className="mt-3 text-ui-base font-medium text-foreground">{emptyStateCopy.title}</p>
  494. <p className="mt-1 text-ui-base text-foreground-subtle">{emptyStateCopy.description}</p>
  495. </div>
  496. )}
  497. </div>
  498. </section>
  499. );
  500. }