From b35bf882b5592872f6a91dfbee7f28c42877d86d Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:56:02 +0200 Subject: [PATCH] refactor(vcs): split Git Log into per-component modules (#3761) GitLog.tsx (3,129 lines) moves along its component seams into src/features/vcs/log/ (shared, logHooks, commitMenu, CommitMessage, GraphCell, ColumnHeaders, CommitRow, CommitList, FilterBar, BranchesPanel, CommitDetails). Declaration bodies, CSS, text and the lazy entry are unchanged; imports point at the new modules without re-export shims. Part of #3589 Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- src/features/vcs/GitLog.tsx | 2892 +---------------- .../vcs/__tests__/gitLogRefLabels.test.tsx | 4 +- src/features/vcs/__tests__/historyOps.test.ts | 6 +- .../vcs/__tests__/logBranches.test.tsx | 6 +- .../__tests__/logGraphCorrectness.test.tsx | 12 +- src/features/vcs/__tests__/logPanes.test.tsx | 14 +- .../vcs/__tests__/logUiFeatures.test.tsx | 13 +- src/features/vcs/log/BranchesPanel.tsx | 312 ++ src/features/vcs/log/ColumnHeaders.tsx | 243 ++ src/features/vcs/log/CommitDetails.tsx | 578 ++++ src/features/vcs/log/CommitList.tsx | 622 ++++ src/features/vcs/log/CommitMessage.tsx | 173 + src/features/vcs/log/CommitRow.tsx | 201 ++ src/features/vcs/log/FilterBar.tsx | 502 +++ src/features/vcs/log/GraphCell.tsx | 161 + src/features/vcs/log/commitMenu.ts | 116 + src/features/vcs/log/logHooks.tsx | 35 + src/features/vcs/log/shared.ts | 37 + 18 files changed, 3030 insertions(+), 2897 deletions(-) create mode 100644 src/features/vcs/log/BranchesPanel.tsx create mode 100644 src/features/vcs/log/ColumnHeaders.tsx create mode 100644 src/features/vcs/log/CommitDetails.tsx create mode 100644 src/features/vcs/log/CommitList.tsx create mode 100644 src/features/vcs/log/CommitMessage.tsx create mode 100644 src/features/vcs/log/CommitRow.tsx create mode 100644 src/features/vcs/log/FilterBar.tsx create mode 100644 src/features/vcs/log/GraphCell.tsx create mode 100644 src/features/vcs/log/commitMenu.ts create mode 100644 src/features/vcs/log/logHooks.tsx create mode 100644 src/features/vcs/log/shared.ts diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx index c02b20f78..ca80fb787 100644 --- a/src/features/vcs/GitLog.tsx +++ b/src/features/vcs/GitLog.tsx @@ -1,159 +1,35 @@ -import { writeClipboardText } from "@/platform/clipboard"; -import { useBookmarkPopups } from "@/features/search/bookmarks/store"; -import { commitBookmarkPath } from "./logBookmarks"; -import { copySelectionOnKeyDown } from "@/ui/selectableText"; -import { branchesByRepo, commitKey, commitRepo, graphCommit, type RepoCommit } from "./multiRoot"; -/** Git tool window: Log (graph, filters, commit details) and Console tabs. */ -import { IssueText } from "./issueLinks"; -import { BranchFilterPopup } from "./BranchFilterPopup"; -import { - Fragment, - memo, - useCallback, - useContext, - useEffect, - useLayoutEffect, - useMemo, - useRef, - useState, - type KeyboardEvent, - type MouseEvent as ReactMouseEvent, - type ReactNode, -} from "react"; -import clsx from "clsx"; -import { useVirtualizer } from "@tanstack/react-virtual"; -import type { Branch, ChangedFile, Commit } from "@/bindings"; +import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; -import { executeAction } from "@/platform/actions"; -import { setContext } from "@/platform/context"; -import { maybeEditorService, useGitLogChecks, type EditorInput } from "@/workbench/contributions"; -import { - EmptyState, - Icon, - IconButton, - Menu, - SearchField, - SplitGroup, - SplitHandle, - SplitPanel, - Spinner, - Popup, - TOOLTIP_DELAY, - Tabs, - Tree, - fileIconName, - showContextMenu, - type MenuItem, - type TreeHandle, - T, - copyText, - hideNativeScrollbar, - lazyComponent, - lockDragCursor, - Scrollbar, -} from "@/ui"; -import { hasPrimaryModifier } from "@/platform/keymap"; -import { laneColor, reachableFrom, type GraphRow, type GraphSegment } from "./graph"; -import { nextSpeedMatch } from "./logSearch"; -import { presentLogGraph } from "./logPresentation"; +import { useWorkflowSettings } from "@/platform/workflowSettings"; +import { EmptyState, IconButton, SplitGroup, SplitHandle, SplitPanel, T, Tabs } from "@/ui"; +import { copySelectionOnKeyDown } from "@/ui/selectableText"; +import clsx from "clsx"; +import { useContext, useEffect, useLayoutEffect, useRef } from "react"; +import { LocalChangesView, StashContent, tabItems, useStashTabCounts } from "./CommitView"; +import styles from "./GitLog.module.css"; +import { WorktreesPanel } from "./gitMenuDialogs"; +import { gitTabs, shownTab } from "./gitTabs"; +import { BranchesPanel } from "./log/BranchesPanel"; +import { CommitDetails } from "./log/CommitDetails"; +import { CommitList } from "./log/CommitList"; +import { FilterBar } from "./log/FilterBar"; +import { useLogRepositories, useReadOnlyLog } from "./log/logHooks"; +import { LogIdContext } from "./logContext"; +import { invalidateLogDetails } from "./logDetails"; +import { useLogOptions } from "./logOptions"; +import { LogScope } from "./LogScope"; import { closeLogTab, - extendCommitSelection, - goToChild, - goToParent, initLogBranchFilter, - isMine, - loadMore, logState, - loadNewer, - ME, - dateRangeLabel, refsSignature, reloadLog, - openLogTab, - recentLogFilters, - recentFilterValues, - toggleCommitBookmark, - selectCommit, selectGitTab, - selectedCommits, - setLogBranches, - setLogFilters, - toggleCommitSelection, - toggleRepository, - updateLogOptions, useGitLog, - PAGE, } from "./logStore"; -import { logOptions, refLabels, useLogOptions, type LogOptions } from "./logOptions"; -import { KIND_COLOR, dirName, fileCount, formatTime, relTo, renameFrom, type EffectiveKind } from "./model"; +import { branchesByRepo } from "./multiRoot"; import { clearConsole, useVcsConsole } from "./ops"; -import { currentRepo, currentRepoRoot, loadBranches, repoName, useVcs } from "./store"; -import { canDeleteBranch, loadFavoriteBranches, useFavoriteBranches } from "./branchOps"; -import { branchMenu, inRepo, tagMenu } from "./branchMenu"; -import { BranchSync } from "./BranchSync"; -import { - branchFolderKeys, - branchGroupKeys, - buildBranchTree, - buildRepositoryBranchTree, - filterBranchTree, - isFavoriteBranch, - type BranchTreeNode, -} from "./branches"; -import { chooseDateRange, chooseMany } from "./dialogs"; -import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree"; -import { DIFF_KIND, diffInput, vcsDiffInFront } from "./diffInput"; -import { - absolutePath, - filesUnder, - flatFileNodes, - showChangesDiff, - toLogChanges, - useLogChanges, - withLineStats, - type LogChange, -} from "./logChanges"; -import { canUpdateBranch, useBranchesPane, type BranchTarget } from "./logPaneActions"; -import styles from "./GitLog.module.css"; -import { tx } from "@/platform/i18n"; -import { useWorkflowSettings } from "@/platform/workflowSettings"; -import { gitTabs, shownTab } from "./gitTabs"; -import { LocalChangesView, StashContent, tabItems, useStashTabCounts } from "./CommitView"; -import { WorktreesPanel } from "./gitMenuDialogs"; -import { chooseLogPaths } from "./PathFilterDialog"; -import { goToRef } from "./logStore"; -import { LogIdContext } from "./logContext"; -import { LogScope } from "./LogScope"; -import { browseRepositoryAt, openExternalLog } from "./RevisionBrowser"; -import { invalidateLogDetails, loadLogDetails, useCommitDetails } from "./logDetails"; - -const ROW = 26; -const LANE = 14; -interface LogColumn { - id: string; - title: string; - width: number; - render(commit: Commit): ReactNode; -} -const LogMergePreview = lazyComponent(() => import("./GitMergeDiff").then((m) => m.GitMergeDiff)); -const LogDiffPreview = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor)); - -function useLogRepositories() { - const scope = useContext(LogIdContext); - const tab = useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog))); - const roots = useVcs((s) => s.roots); - const repo = tab?.repo; - const repositories = tab?.repositories; - const key = (repositories?.length ? repositories : repo ? [repo] : roots).join("\0"); - // eslint-disable-next-line react-hooks/exhaustive-deps - return useMemo(() => (repositories?.length ? repositories : repo ? [repo] : roots), [key]); -} - -function useReadOnlyLog() { - const scope = useContext(LogIdContext); - return useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog))?.readOnly === true); -} +import { loadBranches, useVcs } from "./store"; /** The Git window's tabs (they depend on the commit interface) and the one shown. */ function useGitTabs() { @@ -356,2732 +232,6 @@ export function LogView() { ); } -// --- branches --------------------------------------------------------------- - -function branchDetail(n: BranchTreeNode): ReactNode { - const b = n.branch; - if (!b) return undefined; - if (!b.current && b.behind <= 0 && b.ahead <= 0) return undefined; - return ( - - {b.current && {tx("current")}} - - - ); -} - -export function BranchesPanel() { - const scope = useContext(LogIdContext); - const shown = useGitLog((s) => s.shownLog); - const active = !scope || scope === shown; - const logGeneration = useGitLog((s) => s.generation); - const selectedBranches = useVcs((s) => s.branches); - const repositories = useLogRepositories(); - const readOnly = useReadOnlyLog(); - const version = useVcs((s) => s.version); - const [allBranches, setAllBranches] = useState>({}); - const [allTags, setAllTags] = useState>({}); - const currentRepository = currentRepo(); - const branches = useMemo( - () => - repositories.length === 1 && repositories[0] !== currentRepository - ? (allBranches[repositories[0]!] ?? []) - : selectedBranches, - [repositories, currentRepository, allBranches, selectedBranches], - ); - const root = useVcs((s) => s.root); - const branchesLoaded = useVcs((s) => s.branchesLoaded); - const current = useVcs((s) => s.branch?.head ?? null); - const favorites = useFavoriteBranches((s) => s.names); - const filterBranches = useGitLog((s) => s.filters.branches); - const filterRepositories = useGitLog((s) => s.filters.repositories); - const [query, setQuery] = useState(""); - const [tags, setTags] = useState([]); - useEffect(() => loadFavoriteBranches(), [root]); - // Branches reload when refs move (fetch, new tag…): the tags are re-read with them. - useEffect(() => { - let live = true; - call(commands.vcsTags(repositories[0] ?? currentRepo())).then( - (t) => live && setTags(t), - () => live && setTags([]), - ); - return () => { - live = false; - }; - }, [root, branches, repositories]); - useEffect(() => { - let live = true; - void branchesByRepo(repositories) - .then((value) => live && setAllBranches(value)) - .catch(() => undefined); - void Promise.all(repositories.map(async (r) => [r, await call(commands.vcsTags(r))] as const)) - .then((value) => live && setAllTags(Object.fromEntries(value))) - .catch(() => undefined); - return () => { - live = false; - }; - }, [repositories, version, logGeneration]); - const allRoots = useMemo(() => { - if (repositories.length < 2) return buildBranchTree(branches, favorites, tags); - return buildRepositoryBranchTree( - repositories.map((repo) => ({ - root: repo, - name: repoName(repo), - branches: allBranches[repo] ?? [], - tags: allTags[repo] ?? [], - })), - favorites, - ); - }, [repositories, allBranches, allTags, branches, favorites, tags]); - const roots = useMemo(() => filterBranchTree(allRoots, query), [allRoots, query]); - // While searching every match is shown expanded. - const searchExpanded = useMemo(() => (query.trim() ? new Set(branchGroupKeys(roots)) : undefined), [roots, query]); - // Highlighted rows: a click only selects (IDEA), and only a double click or - // Enter switches the log, so the selection is the pane's own state. It still - // follows the filter when something else changes it (Show Log, the filter bar). - const filterKeys = useMemo( - () => - filterBranches.flatMap((b) => { - if (b === "HEAD") return ["head"]; - if (repositories.length < 2) return [`b:${b}`]; - return (filterRepositories?.length ? filterRepositories : repositories).map((r) => `${r}:b:${b}`); - }), - [filterBranches, filterRepositories, repositories], - ); - const filterKey = filterKeys.join("\n"); - const [shownKey, setShownKey] = useState(filterKey); - const [selected, setSelected] = useState>(() => new Set(filterKeys)); - if (shownKey !== filterKey) { - // The filter changed elsewhere (Show Log, the filter bar): highlight it. - setShownKey(filterKey); - setSelected(new Set(filterKeys)); - } - // Refs in tree order, for Copy: full refs, so the folder path comes along - // (`feat/x`, `origin/main`). - const refs = useMemo(() => { - const out: { key: string; ref: string; branch?: Branch; repo?: string }[] = []; - const walk = (nodes: readonly BranchTreeNode[]) => { - for (const n of nodes) { - if (n.ref) out.push({ key: n.key, ref: n.ref, branch: n.branch, repo: n.repo }); - walk(n.children ?? []); - } - }; - walk(allRoots); - return out; - }, [allRoots]); - const targets = useMemo( - (): BranchTarget[] => - refs.filter((r) => selected.has(r.key)).map(({ ref, branch, repo }) => ({ ref, branch, repo })), - [refs, selected], - ); - useEffect(() => { - if (!active) return; - useBranchesPane.setState({ selected: targets }); - return () => useBranchesPane.setState({ selected: [] }); - }, [targets, active]); - const target = targets[0] ?? undefined; - const favorite = !!target?.branch && isFavoriteBranch(target.branch, favorites); - const onKeyDownCapture = (e: KeyboardEvent) => { - if ((e.key !== "c" && e.key !== "C") || !hasPrimaryModifier(e) || e.altKey || e.shiftKey) return; - // The branch search keeps the browser's own copy. - if ((e.target as HTMLElement).closest("input, textarea")) return; - const names = targets.map((r) => r.ref); - if (!names.length) return; - e.preventDefault(); - e.stopPropagation(); - void copyText(names.join("\n")); - }; - return ( -
-
- - {!readOnly && ( - <> - - - canDeleteBranch(t))} - /> - - - - - )} - (readOnly ? void reloadLog({ preserve: true }) : void loadBranches())} - /> -
-
-
- -
- - key={`${root ?? ""}:${branchesLoaded}`} - roots={roots} - getKey={(n) => n.key} - getLabel={(n) => (n.kind === "head" || n.kind === "group" ? tx(n.label) : n.label)} - getChildren={(n) => n.children} - isExpandable={(n) => !!n.children} - defaultExpanded={[ - ...branchGroupKeys(allRoots), - "g:local", - "g:remote", - ...roots.flatMap((r) => r.children?.filter((c) => c.kind === "remote").map((c) => c.key) ?? []), - ...(current ? branchFolderKeys(roots, current) : []), - ]} - expanded={searchExpanded} - getIcon={(n) => - n.kind === "head" - ? "commit" - : n.kind === "tag" - ? "tag" - : n.branch?.current - ? "current-branch" - : n.kind === "branch" - ? n.favorite - ? "star" - : "branch" - : "folder" - } - getDetail={branchDetail} - selected={selected} - onSelectionChange={(sel) => setSelected(sel)} - onActivate={(n) => { - // IDEA: double click (or Enter) switches the log to that ref, or to every - // selected one when it is part of a multi-selection; checking out stays in the context menu. - if (!n.ref) return; - const sel = selected.has(n.key) ? targets.filter((r) => r.repo === n.repo).map((r) => r.ref) : [n.ref]; - setLogFilters({ branches: sel, repositories: n.repo ? [n.repo] : [] }); - }} - onContextMenu={(n, _sel, e) => { - if (readOnly) { - if (!n?.ref) return; - e.preventDefault(); - showContextMenu(e, [ - { label: "Show in Git Log", run: () => setLogBranches([n.ref!]) }, - { label: "Copy", run: () => void copyText(n.ref!) }, - ]); - return; - } - // The menu acts on the whole selection when the right-clicked branch is part of it. - const picked: BranchTarget[] = - n && selected.has(n.key) ? targets : n?.ref ? [{ ref: n.ref, branch: n.branch, repo: n.repo }] : []; - const menu = n?.branch - ? branchMenu( - n.branch, - n.repo ? (useVcs.getState().heads[n.repo]?.head ?? null) : current, - () => {}, - picked, - ) - : n?.kind === "tag" - ? tagMenu(n.ref!) - : n?.kind === "remote" || (n?.kind === "group" && n.key.endsWith("g:remote")) - ? REMOTES_MENU - : []; - // Delete scopes each selected target itself and must preserve the original focus. - const items = n?.repo - ? menu.flatMap((item) => - n.branch && "label" in item && item.label === "Delete" ? [item] : inRepo(n.repo!, [item]), - ) - : menu; - if (!items.length) return; - e.preventDefault(); - showContextMenu(e, items); - }} - empty={ - query.trim() ? ( - - No matching branches - - ) : undefined - } - aria-label="Branches" - className={styles.branchTree} - /> -
-
- ); -} - -/** IDEA: the Remote node and each remote of the Branches pane offer Manage Remotes…. */ -const REMOTES_MENU: MenuItem[] = [{ label: "Manage Remotes…", run: () => void executeAction("vcs.manageRemotes") }]; - -// --- filters ---------------------------------------------------------------- - -const DAY = 86_400_000; -/** Keyboard moves through several files quickly: preview the one the selection settles on. */ -const PREVIEW_DELAY = 120; - -function fileNodeAt(nodes: readonly FileTreeNode[], key: string): FileTreeNode | null { - for (const n of nodes) { - if (n.key === key) return n.file ? n : null; - if (!n.file) { - const hit = fileNodeAt(n.children, key); - if (hit) return hit; - } - } - return null; -} -const DATE_OPTIONS: { label: string; days: number }[] = [ - { label: "Last 24 Hours", days: 1 }, - { label: "Last 7 Days", days: 7 }, - { label: "Last 30 Days", days: 30 }, - { label: "Last Year", days: 365 }, -]; - -/** - * A toolbar button's dropdown, anchored to the button: a second click on it closes the menu - * instead of reopening it, as in IDEA. Returns the opener and the element to render. - */ -function useDropdownMenu() { - const [menu, setMenu] = useState<{ anchor: HTMLElement; items: MenuItem[] } | null>(null); - const open = (anchor: HTMLElement | ReactMouseEvent, items: MenuItem[]) => { - const el = "currentTarget" in anchor ? anchor.currentTarget : anchor; - setMenu((m) => (m?.anchor === el ? null : { anchor: el, items })); - }; - const dropdown = menu && setMenu(null)} />; - return [open, dropdown] as const; -} - -interface LogFilter { - label: string; - value: string | null; - onOpen: (anchor: HTMLElement) => void; - onClear: () => void; -} - -function FilterButton({ label, value, onOpen, onClear, hidden }: LogFilter & { hidden?: boolean }) { - return ( - - ); -} - -function FilterBar() { - const scope = useContext(LogIdContext); - const shown = useGitLog((s) => s.shownLog); - const active = !scope || scope === shown; - const logGeneration = useGitLog((s) => s.generation); - const filters = useGitLog((s) => s.filters); - const commits = useGitLog((s) => s.commits); - const selectedBranches = useVcs((s) => s.branches); - const [branches, setBranches] = useState(selectedBranches); - const version = useVcs((s) => s.version); - const root = useVcs((s) => s.root); - const repositories = useLogRepositories(); - const readOnly = useReadOnlyLog(); - const bookmarks = useGitLog((s) => s.bookmarks); - const showBranches = useLogOptions((s) => s.showBranches); - useEffect(() => { - let live = true; - const roots = filters.repositories?.length ? filters.repositories : repositories; - void branchesByRepo(roots) - .then((all) => { - if (live) - setBranches([ - ...new Map( - Object.values(all) - .flat() - .map((b) => [b.name, b]), - ).values(), - ]); - }) - .catch(() => undefined); - return () => { - live = false; - }; - }, [repositories, filters.repositories, version, logGeneration]); - const [text, setText] = useState(filters.text); - const [branchAnchor, setBranchAnchor] = useState(null); - const [menuBelow, dropdown] = useDropdownMenu(); - // Filters that do not fit move behind a chevron, like a toolbar's overflow. - const groupRef = useRef(null); - const [hiddenFrom, setHiddenFrom] = useState(Infinity); - useLayoutEffect(() => { - const group = groupRef.current; - if (!group) return; - const measure = () => { - const items = [...group.children] as HTMLElement[]; - const i = items.findIndex((el) => el.offsetLeft + el.offsetWidth > group.clientWidth + 1); - setHiddenFrom(i < 0 ? Infinity : i); - }; - measure(); - const ro = new ResizeObserver(measure); - ro.observe(group); - for (const el of group.children) ro.observe(el); - return () => ro.disconnect(); - }, [filters, repositories.length]); - - // Keep the field in sync when filters change elsewhere (Show History, reveal). - const [seen, setSeen] = useState(filters); - if (seen !== filters) { - setSeen(filters); - setText(filters.text); - } - - useEffect(() => { - if (!active || text === filters.text) return; - const t = setTimeout(() => setLogFilters({ text }), 300); - return () => clearTimeout(t); - }, [text, filters.text, active]); - - const branchNames = () => branches.filter((b) => !b.name.endsWith("/HEAD")).map((b) => b.name); - - const selectBranches = async () => { - setBranchAnchor(null); - const r = await chooseMany({ - title: "Filter by Branch", - options: [ - ...new Set([ - "HEAD", - ...branchNames(), - ...recentFilterValues("branches").flat(), - ...recentFilterValues("range").filter((s): s is string => !!s), - ]), - ], - initial: filters.branches, - customLabel: "Branches, patterns, exclusions or ranges (comma-separated):", - }); - if (r) setLogBranches(r); - }; - - const openUser = async (anchor: HTMLElement) => { - const roots = filters.repositories?.length - ? filters.repositories - : repositories.length - ? repositories - : [currentRepo()]; - const users = await Promise.all(roots.map((repo) => call(commands.vcsLogUsers(repo)).catch(() => [] as string[]))); - const authors = [...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) => - a.localeCompare(b), - ); - menuBelow(anchor, [ - ...recentFilterValues("authors").map((authors) => ({ - label: authors.join(", "), - run: () => setLogFilters({ authors }), - })), - { label: ME, checked: filters.authors.includes(ME), run: () => setLogFilters({ authors: [ME] }) }, - ...(authors.length ? [{ kind: "separator" as const }] : []), - ...authors.slice(0, 30).map((a) => ({ - label: a, - checked: filters.authors.includes(a), - run: () => setLogFilters({ authors: [a] }), - })), - { kind: "separator" }, - { - label: "Select…", - run: async () => { - const r = await chooseMany({ - title: "Filter by User", - options: [ME, ...authors], - initial: filters.authors, - customLabel: "Other names or emails (comma-separated):", - }); - if (r) setLogFilters({ authors: r }); - }, - }, - ]); - }; - - const openDate = (anchor: HTMLElement) => - menuBelow(anchor, [ - ...recentFilterValues("date") - .filter((date) => date != null) - .map((date) => ({ label: date.label, run: () => setLogFilters({ date }) })), - ...DATE_OPTIONS.map((o) => ({ - label: o.label, - checked: filters.date?.label === o.label, - run: () => setLogFilters({ date: { after: Date.now() - o.days * DAY, before: null, label: o.label } }), - })), - { kind: "separator" }, - { - label: "Select…", - run: async () => { - const r = await chooseDateRange(); - if (r) setLogFilters({ date: { ...r, label: dateRangeLabel(r.after, r.before) } }); - }, - }, - ]); - - const openPaths = (anchor: HTMLElement) => - menuBelow(anchor, [ - ...recentFilterValues("paths") - .filter((paths) => paths?.length) - .map((paths) => ({ label: paths!.join(", "), run: () => setLogFilters({ paths, path: null }) })), - { - label: "Select Folders…", - run: async () => { - const paths = await chooseLogPaths( - repositories.length ? repositories : root ? [root] : [], - filters.paths ?? (filters.path ? [filters.path] : []), - readOnly, - ); - if (paths) setLogFilters({ path: null, paths }); - }, - }, - ]); - - const logFilters: LogFilter[] = [ - ...(repositories.length > 1 - ? [ - { - label: "Repository", - value: filters.repositories?.map(repoName).join(", ") || null, - onOpen: (anchor: HTMLElement) => - menuBelow( - anchor, - repositories.map((repo) => ({ - label: repoName(repo), - checked: filters.repositories?.includes(repo) ?? false, - run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }), - })), - ), - onClear: () => setLogFilters({ repositories: [] }), - }, - ] - : []), - { - label: "Branch", - value: filters.range || filters.branches.join(", ") || null, - onOpen: (anchor: HTMLElement) => setBranchAnchor((open) => (open === anchor ? null : anchor)), - onClear: () => setLogBranches([]), - }, - { - label: "User", - value: filters.authors.join(", ") || null, - onOpen: openUser, - onClear: () => setLogFilters({ authors: [] }), - }, - { - label: "Date", - value: filters.date?.label ?? null, - onOpen: openDate, - onClear: () => setLogFilters({ date: null }), - }, - { - label: "Paths", - value: filters.paths?.length - ? filters.paths.map((p) => (root ? relTo(root, p) : p)).join(", ") - : filters.path - ? (root ? relTo(root, filters.path) : filters.path) || "." - : null, - onOpen: openPaths, - onClear: () => setLogFilters({ path: null, paths: [] }), - }, - ]; - - return ( -
- {!showBranches && ( - - )} - setLogFilters({ regex }), - }, - { - id: "case", - icon: "case", - title: "Match Case", - pressed: filters.matchCase, - onToggle: (matchCase) => setLogFilters({ matchCase }), - }, - ]} - /> - - {logFilters.map((f, i) => ( - - {hiddenFrom < logFilters.length && ( - { - const anchor = e.currentTarget; - menuBelow( - anchor, - logFilters.slice(hiddenFrom).map((f) => ({ - label: f.value ? `${tx(f.label)}: ${f.value}` : f.label, - run: () => f.onOpen(anchor), - })), - ); - }} - /> - )} - {dropdown} - {branchAnchor && ( - setBranchAnchor(null)} - onSelect={(branch) => { - setLogBranches([branch]); - setBranchAnchor(null); - }} - onSelectMany={() => void selectBranches()} - /> - )} - - - menuBelow( - e, - Object.entries(bookmarks).map(([key, summary]) => ({ - label: summary, - run: () => { - const split = key.lastIndexOf("\0"); - void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined); - }, - })), - ) - } - /> - - menuBelow(e, [ - { - label: "In Tool Window", - run: () => { - openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`); - }, - }, - { - label: "In Editor", - run: () => { - openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor"); - }, - }, - { label: "External Repository…", run: openExternalLog }, - ]) - } - /> - - menuBelow( - e, - recentLogFilters().map((filters) => ({ - label: - [ - filters.range, - filters.branches.join(", "), - filters.authors.join(", "), - filters.text, - filters.path, - filters.paths?.join(", "), - filters.date?.label, - ] - .filter(Boolean) - .join(" · ") || tx("All commits"), - run: () => setLogFilters(filters), - })), - ) - } - /> - void reloadLog({ preserve: true })} /> - menuBelow(e, graphOptionsMenu(useLogOptions.getState()))} - /> - menuBelow(e, viewOptionsMenu(useLogOptions.getState()))} - /> - -
- ); -} - -const toggle = (label: string, o: LogOptions, key: keyof LogOptions): MenuItem => ({ - label, - checked: !!o[key], - run: () => updateLogOptions({ [key]: !o[key] }), -}); - -/** IDEA's Git Log › Graph Options (sort, first parent / no merges, linear branches). */ -export function graphOptionsMenu(o: LogOptions): MenuItem[] { - return [ - { kind: "header", label: "Sort" }, - { label: "By Commit Date", checked: o.sort === "date", run: () => updateLogOptions({ sort: "date" }) }, - { label: "Topologically", checked: o.sort === "topo", run: () => updateLogOptions({ sort: "topo" }) }, - { - label: "Incoming Commits First", - checked: o.sort === "standard", - run: () => updateLogOptions({ sort: "standard" }), - }, - { kind: "separator" }, - { kind: "header", label: "Options" }, - toggle("First Parent", o, "firstParent"), - toggle("No Merges", o, "noMerges"), - { - label: "Linearize Merges", - checked: o.linearizeMerges, - run: () => - updateLogOptions({ linearizeMerges: !o.linearizeMerges, ...(!o.linearizeMerges ? { sort: "standard" } : {}) }), - }, - { kind: "separator" }, - { kind: "header", label: "Branch Actions" }, - { kind: "action", action: "vcs.log.collapseLinear" }, - { kind: "action", action: "vcs.log.expandLinear" }, - ]; -} - -/** IDEA's Git Log › View Options (what rows show and highlight). */ -export function viewOptionsMenu(o: LogOptions): MenuItem[] { - return [ - { kind: "header", label: "Show" }, - toggle("Compact References View", o, "compactRefs"), - toggle("Tag Names", o, "tagNames"), - toggle("Long Edges", o, "longEdges"), - toggle("Commit Timestamp", o, "commitTimestamp"), - toggle("References on the Left", o, "refsOnLeft"), - toggle("Details", o, "showDetails"), - toggle("Repository", o, "showRepository"), - { - label: "Columns", - submenu: [ - toggle("Author", o, "showAuthor"), - toggle("Date", o, "showDate"), - toggle("Hash", o, "showHash"), - toggle("Signature", o, "showSignature"), - toggle("GitHub Commit Checks", o, "showGitHubChecks"), - { kind: "separator" }, - toggle("Column Headers", o, "showColumnHeaders"), - ], - }, - { kind: "separator" }, - { kind: "header", label: "Highlight" }, - toggle("My Commits", o, "highlightMine"), - toggle("Merge Commits", o, "highlightMerges"), - toggle("Current Branch", o, "highlightCurrentBranch"), - ]; -} - -/** IDEA's Git Log commit context menu (Git.Log.ContextMenu); `selection` = all selected commits, newest first. */ -export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { - if ((c as RepoCommit).readOnly) - return [ - { kind: "action", action: "vcs.log.copyRevision", arg: c }, - { label: "Copy Commit Message", run: () => copyCommitMessage(c) }, - { - label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit", - run: () => toggleCommitBookmark(c), - }, - { - label: "Assign Mnemonic", - run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }), - }, - { kind: "action", action: "vcs.log.goToParent", arg: c }, - { kind: "action", action: "vcs.log.goToChild", arg: c }, - { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, - ]; - const many = selection.length > 1 && selection.some((x) => commitKey(x) === commitKey(c)); - const repo = commitRepo(c); - const vcs = useVcs.getState(); - const head = (repo ? vcs.heads[repo]?.head : vcs.branch?.head) ?? null; - const { outgoing } = useGitLog.getState(); - if (many) { - return [ - { kind: "action", action: "vcs.log.copyRevision", arg: selection, label: "Copy Revision Numbers" }, - { kind: "action", action: "vcs.log.createPatch", arg: selection }, - { kind: "action", action: "vcs.log.cherryPick", arg: selection }, - ...(selection.length === 2 - ? [{ kind: "action", action: "vcs.log.compareVersions", arg: selection } satisfies MenuItem] - : []), - { kind: "separator" }, - { kind: "action", action: "vcs.log.revert", arg: selection, label: "Revert Commits" }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.squashCommits", arg: selection }, - { kind: "action", action: "vcs.log.dropCommit", arg: selection, label: "Drop Commits" }, - ]; - } - // Without an upstream there is no outgoing set: allow pushing up to any commit of HEAD. - const canPushHere = - !!head && - ((commitRepo(c) === undefined ? !!outgoing : useGitLog.getState().tracked.has(commitRepo(c) ?? "")) - ? !!outgoing?.has(commitKey(c)) - : true); - const branches = ((c as RepoCommit).refBranches ?? []).filter((branch) => !branch.current); - const branchActions: MenuItem[] = branches.map((branch) => { - const menu = branchMenu(branch, head); - return { - label: tx`Branch '${branch.name}'`, - submenu: repo ? inRepo(repo, menu) : menu, - }; - }); - if (!branchActions.length) - branchActions.push({ - kind: "action", - action: "vcs.log.rebaseOntoCommit", - arg: c, - label: tx`Rebase '${head ?? "HEAD"}' onto Selected Commit`, - disabled: !head, - }); - return [ - { kind: "action", action: "vcs.log.copyRevision", arg: c }, - { - label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit", - run: () => toggleCommitBookmark(c), - }, - { label: "Copy Commit Message", run: () => copyCommitMessage(c) }, - { kind: "action", action: "vcs.log.createPatch", arg: c }, - { kind: "action", action: "vcs.log.cherryPick", arg: c }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.checkoutRevision", arg: c }, - { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, - { kind: "action", action: "vcs.log.compareWithLocal", arg: c }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.resetToHere", arg: c }, - { kind: "action", action: "vcs.log.revert", arg: c }, - { kind: "action", action: "vcs.log.undoCommit", arg: c }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.editMessage", arg: c }, - { kind: "action", action: "vcs.log.fixup", arg: c }, - { kind: "action", action: "vcs.log.squashInto", arg: c }, - { kind: "action", action: "vcs.log.dropCommit", arg: c }, - { kind: "action", action: "vcs.log.interactiveRebase", arg: c }, - { kind: "action", action: "vcs.log.pushUpToHere", arg: c, disabled: !canPushHere }, - { kind: "separator" }, - ...(branchActions.length > 2 ? [{ label: "Branches", submenu: branchActions }] : branchActions), - { kind: "action", action: "vcs.log.newBranch", arg: c }, - { kind: "action", action: "vcs.log.newTag", arg: c }, - { kind: "separator" }, - { - label: "Assign Mnemonic", - run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }), - }, - { kind: "action", action: "vcs.log.goToChild", arg: c }, - { kind: "action", action: "vcs.log.goToParent", arg: c, disabled: !c.parents.length }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.openInBrowser", arg: c }, - ]; -} - -async function copyCommitMessage(c: Commit) { - const message = c.messageTruncated ? (await loadLogDetails(c)).message : c.message; - await copyText(message); -} - -function CommitList() { - const scope = useContext(LogIdContext); - const shown = useGitLog((s) => s.shownLog); - const active = !scope || scope === shown; - const all = useGitLog((s) => s.commits); - const selection = useGitLog((s) => s.selection); - const earlier = useMemo(() => { - const seen = new Set(); - return all.some((c) => { - const repo = commitRepo(c); - if (seen.has(repo)) return false; - seen.add(repo); - return (c.logPosition ?? 0) > 0; - }); - }, [all]); - const opts = useLogOptions(); - const ChecksCell = useGitLogChecks((s) => s.cell); - const bookmarks = useGitLog((s) => s.bookmarks); - const fragments = useGitLog((s) => s.fragments); - const { expanded: expandedFragments, collapsed: collapsedFragments, merges: expandedMerges } = fragments; - const [hoverColor, setHoverColor] = useState(null); - const [boundaryTitles, setBoundaryTitles] = useState>(() => new Map()); - const boundaryRequests = useRef(new Set()); - const [speedSearch, setSpeedSearch] = useState(""); - const speedGeneration = useRef(0); - const speedTimer = useRef | undefined>(undefined); - useEffect(() => () => clearTimeout(speedTimer.current), []); - const columns = useMemo(() => { - const builtins: LogColumn[] = [ - ...(opts.showAuthor ? [{ id: "author", title: "Author", width: 130, render: (c: Commit) => c.author }] : []), - ...(opts.showDate - ? [ - { - id: "date", - title: "Date", - // Fits a 12-hour date and time ("11/05/2026 02:30 PM", "Yesterday 09:07 AM"). - width: 140, - render: (c: Commit) => formatTime(opts.commitTimestamp ? (c.commitTimeMs ?? c.timeMs) : c.timeMs), - }, - ] - : []), - ...(opts.showHash ? [{ id: "hash", title: "Hash", width: 72, render: (c: Commit) => c.shortId }] : []), - ...(opts.showSignature - ? [{ id: "signature", title: "Signature", width: 100, render: (c: Commit) => }] - : []), - ...(opts.showGitHubChecks && ChecksCell - ? [ - { - id: "github-checks", - title: "GitHub Commit Checks", - width: 44, - render: (c: Commit) => { - const root = commitRepo(c) ?? currentRepoRoot(); - return root && !(c as RepoCommit).readOnly ? : null; - }, - }, - ] - : []), - ]; - const order = [...new Set([...opts.columnOrder, ...builtins.map((c) => c.id)])]; - return builtins.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id)); - }, [ - opts.showAuthor, - opts.showDate, - opts.showHash, - opts.showSignature, - opts.showGitHubChecks, - opts.commitTimestamp, - opts.columnOrder, - ChecksCell, - ]); - const user = useGitLog((s) => s.user); - const headCommit = useVcs((s) => s.branch?.headCommit ?? null); - const branches = useVcs((s) => s.branches); - const remoteNames = useMemo(() => new Set(branches.filter((b) => b.remote).map((b) => b.name)), [branches]); - // Date, No Merges and First Parent are applied by the backend with parent rewriting, - // so the graph stays connected under them. - const heads = useVcs((s) => s.heads); - const headKeys = useMemo( - () => - new Set( - all - .filter( - (c) => c.refs.includes("HEAD") || c.id === (commitRepo(c) ? heads[commitRepo(c)!]?.headCommit : headCommit), - ) - .map(commitKey), - ), - [all, heads, headCommit], - ); - const keep = useMemo( - () => - opts.collapseLinear || fragments.collapsed.size - ? new Set([...headKeys, ...selection, ...Object.keys(bookmarks)]) - : null, - [opts.collapseLinear, fragments.collapsed, headKeys, selection, bookmarks], - ); - const { - commits, - rows, - linear, - collapsed, - graph: displayedGraph, - } = useMemo(() => presentLogGraph(all, opts, fragments, keep ?? new Set()), [all, opts, fragments, keep]); - const { edges: highlighted, nodes: highlightedNodes } = useMemo(() => { - const empty = { edges: new Set(), nodes: new Set() }; - if (!hoverColor) return empty; - const nodeId = hoverColor.startsWith("node:") ? hoverColor.slice(5) : null; - const merge = nodeId ?? linear?.fragments.get(hoverColor); - const fragment = merge ? linear?.nodes.get(merge) : null; - const nodes = new Set(fragment); - if (!fragment) { - const source = nodeId - ? displayedGraph.find((c) => c.id === nodeId) - : displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === hoverColor)); - const target = source?.parents.find((p) => nodeId || `${source.id}\0${p}` === hoverColor); - if (source) nodes.add(source.id); - const byId = new Map(displayedGraph.map((c) => [c.id, c])); - const children = new Map(); - for (const c of displayedGraph) for (const p of c.parents) children.set(p, (children.get(p) ?? 0) + 1); - for (let current = target; current && !nodes.has(current);) { - nodes.add(current); - const c = byId.get(current); - if (!c || c.parents.length !== 1 || children.get(current) !== 1 || c.refs?.length || headKeys.has(current)) - break; - current = c.parents[0]; - } - } - return { - nodes, - edges: new Set( - displayedGraph.flatMap((c) => - nodes.has(c.id) ? c.parents.filter((p) => nodes.has(p)).map((p) => `${c.id}\0${p}`) : [], - ), - ), - }; - }, [hoverColor, linear, displayedGraph, headKeys]); - const minWidth = useMemo( - () => - rows.reduce((width, row) => Math.max(width, row.width * LANE), 100) + - columns.reduce( - (width, column) => width + (opts.columnWidths[column.id] ?? column.width ?? 120), - opts.showRepository && useVcs.getState().roots.length > 1 ? 220 : 120, - ), - [rows, columns, opts.columnWidths, opts.showRepository], - ); - const filterBranches = useGitLog((s) => s.filters.branches); - const currentBranch = useVcs((s) => s.branch?.head ?? null); - // Nothing to tell apart when the log is filtered to the current branch. - const onlyCurrent = filterBranches.length > 0 && filterBranches.every((b) => b === "HEAD" || b === currentBranch); - const onBranch = useMemo(() => { - if (!opts.highlightCurrentBranch || onlyCurrent) return null; - const reach = all.some((c) => c.onCurrentBranch == null) - ? reachableFrom(all.map(graphCommit), headKeys) - : new Set(); - for (const c of all) { - if (c.onCurrentBranch === true) reach.add(commitKey(c)); - else if (c.onCurrentBranch === false) reach.delete(commitKey(c)); - } - return reach; - }, [all, headKeys, opts.highlightCurrentBranch, onlyCurrent]); - const loading = useGitLog((s) => s.loading); - const done = useGitLog((s) => s.done); - const error = useGitLog((s) => s.error); - const selected = useGitLog((s) => s.selected); - const selectedSet = useMemo(() => new Set(selection), [selection]); - const revealTick = useGitLog((s) => s.revealTick); - const scrollRef = useRef(null); - const selectedIndex = useMemo( - () => (selected ? commits.findIndex((c) => commitKey(c) === selected) : -1), - [commits, selected], - ); - const lastRevealed = useRef(0); - // Recycled rows can emit enter events without the pointer moving. - const hoverPointer = useRef<{ x: number; y: number } | null>(null); - const previousRows = useRef(commits); - useLayoutEffect(() => { - const element = scrollRef.current; - const previous = previousRows.current; - previousRows.current = commits; - if (!element || previous === commits || (revealTick !== lastRevealed.current && selectedIndex >= 0)) return; - const top = Math.max(0, Math.floor((element.scrollTop - ROW) / ROW)); - // Preserve the first surviving visible commit and its pixel offset. - for (let i = top; i < previous.length; i++) { - const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!)); - if (next < 0) continue; - element.scrollTop += (next - i) * ROW; - break; - } - }, [commits, revealTick, selectedIndex]); - const finished = done; - const virtualizer = useVirtualizer({ - count: commits.length + (finished ? 0 : 1), - getScrollElement: () => scrollRef.current, - estimateSize: () => ROW, - overscan: 8, - scrollMargin: ROW, - }); - const items = virtualizer.getVirtualItems(); - const last = items[items.length - 1]; - - // The next page is requested while a page of rows is still ahead, so scrolling - // quickly doesn't reach the end before `git log` answers. - useEffect(() => { - if (!finished && !loading && last && last.index >= commits.length - PAGE) void loadMore(scope ?? undefined); - }, [last, commits.length, finished, loading, active, scope]); - - useLayoutEffect(() => { - if (revealTick === lastRevealed.current || selectedIndex < 0) return; - lastRevealed.current = revealTick; - virtualizer.scrollToIndex(selectedIndex, { align: "center" }); - }, [revealTick, selectedIndex, virtualizer]); - - const visible = useRef(commits); - visible.current = commits; - const pick = useCallback((id: string, e: ReactMouseEvent) => { - if (e.button === 2) { - if (!useGitLog.getState().selection.includes(id)) selectCommit(id); - } else if (e.button !== 0) return; - else if (e.shiftKey) extendCommitSelection(id, visible.current); - else if (e.metaKey || e.ctrlKey) toggleCommitSelection(id); - else selectCommit(id); - }, []); - // CommitRow is memoized: rows get handlers that stay the same across renders and - // call this render's (assigned before rendering). - const rowEvents = useRef(null); - const rowHandlers = useMemo( - () => ({ - onHover: (edge) => rowEvents.current?.onHover(edge), - onFragment: (from, target, expand) => rowEvents.current?.onFragment(from, target, expand), - onNavigate: (index, key) => rowEvents.current?.onNavigate(index, key), - }), - [], - ); - // Called while a row renders its graph, so it changes with what it reads. - const targetTitle = useCallback( - (index: number, key?: string) => { - const target = commits[index]; - return target - ? `${target.shortId} ${target.summary} — ${target.author}` - : (key && boundaryTitles.get(key)) || - `${tx("Commit is outside the loaded history")} · ${key?.split("\0").at(-1)?.slice(0, 8) ?? ""}`; - }, - [commits, boundaryTitles], - ); - - const onKeyDown = (e: KeyboardEvent) => { - if (!e.ctrlKey && !e.metaKey && !e.altKey && (e.key.length === 1 || e.key === "Backspace" || e.key === "Escape")) { - const query = e.key === "Escape" ? "" : e.key === "Backspace" ? speedSearch.slice(0, -1) : speedSearch + e.key; - setSpeedSearch(query); - speedGeneration.current++; - clearTimeout(speedTimer.current); - speedTimer.current = setTimeout(() => setSpeedSearch(""), 1500); - if (query) { - const found = nextSpeedMatch(commits, query, opts, -1); - if (found >= 0) { - selectCommit(commitKey(commits[found]!), true); - virtualizer.scrollToIndex(found, { align: "auto" }); - } else if (query.length >= 2) { - const generation = ++speedGeneration.current; - const roots = [...new Set(all.map(commitRepo))]; - void Promise.all( - roots.map(async (repo) => { - const [hit] = await call( - commands.vcsLog(repo ?? currentRepo(), { - skip: 0, - limit: 1, - summaryOnly: true, - speedSearch: query, - searchFields: [...(opts.showAuthor ? ["author"] : []), ...(opts.showHash ? ["hash"] : [])], - branch: null, - path: null, - author: null, - text: null, - }), - ); - return hit ? { ...hit, repo } : null; - }), - ) - .then((hits) => { - const hit = hits.find(Boolean); - if (hit && speedGeneration.current === generation) void goToRef(hit.id, commitRepo(hit)); - }) - .catch(() => undefined); - } - } - e.preventDefault(); - return; - } - if (speedSearch && (e.key === "F3" || e.key === "Enter")) { - e.preventDefault(); - const found = nextSpeedMatch(commits, speedSearch, opts, selectedIndex, e.shiftKey ? -1 : 1); - if (found >= 0) selectCommit(commitKey(commits[found]!), true); - return; - } - const lead = selectedIndex >= 0 ? commits[selectedIndex] : undefined; - if (lead && (e.key === "ArrowLeft" || e.key === "ArrowRight") && !e.altKey && !e.metaKey && !e.ctrlKey) { - e.preventDefault(); - if (e.key === "ArrowLeft") goToChild(lead); - else void goToParent(lead); - return; - } - let next: number; - if (e.key === "ArrowDown") next = Math.min(commits.length - 1, selectedIndex + 1); - else if (e.key === "ArrowUp") next = Math.max(0, selectedIndex - 1); - else if (e.key === "Home") next = 0; - else if (e.key === "End") next = commits.length - 1; - else if (e.key === "PageDown") next = Math.min(commits.length - 1, selectedIndex + 20); - else if (e.key === "PageUp") next = Math.max(0, selectedIndex - 20); - else return; - e.preventDefault(); - const c = commits[next]; - if (c) { - if (e.shiftKey) extendCommitSelection(commitKey(c), commits); - else selectCommit(commitKey(c)); - virtualizer.scrollToIndex(next, { align: "auto" }); - } - }; - - if (error && !commits.length) return
{error}
; - - const fragment = (from: string, target: string, expand: boolean) => { - if (from === target && (expandedMerges.has("*") ? !expandedMerges.has(from) : expandedMerges.has(from))) { - useGitLog.setState({ - fragments: { - ...fragments, - merges: expandedMerges.has("*") - ? new Set([...expandedMerges, from]) - : new Set([...expandedMerges].filter((id) => id !== from)), - }, - }); - return; - } - if ( - from === target && - linear && - all.find((c) => commitKey(c) === from)?.parents.length === 2 && - linear.graph.find((c) => c.id === from)?.parents.length === 1 - ) { - useGitLog.setState({ - fragments: { - ...fragments, - merges: expandedMerges.has("*") - ? new Set([...expandedMerges].filter((id) => id !== from)) - : new Set([...expandedMerges, from]), - }, - }); - return; - } - if (from === target) { - const shown = (linear?.graph ?? collapsed?.graph ?? all.map(graphCommit)).find((c) => c.id === from); - target = shown?.parents[0] ?? target; - expand = !!shown?.dashed?.[0]; - } - const merge = linear?.fragments.get(`${from}\0${target}`); - if (merge) { - useGitLog.setState({ - fragments: { - ...fragments, - merges: expandedMerges.has("*") - ? new Set([...expandedMerges].filter((id) => id !== merge)) - : new Set([...expandedMerges, merge]), - }, - }); - return; - } - const graph = new Map( - all.map((c) => { - const g = graphCommit(c); - return [g.id, g] as const; - }), - ); - const childCounts = new Map(); - for (const c of graph.values()) - for (const parent of c.parents) childCounts.set(parent, (childCounts.get(parent) ?? 0) + 1); - const hidden: string[] = []; - for (const start of expand ? (graph.get(from)?.parents ?? []) : [target]) { - const chain: string[] = []; - let current: string | undefined = start; - const seen = new Set(); - while (current && !seen.has(current)) { - seen.add(current); - const node = graph.get(current); - if ( - !node || - (expand && current === target) || - node.parents.length !== 1 || - childCounts.get(current) !== 1 || - node.refs.length || - headKeys.has(current) - ) - break; - chain.push(current); - current = node.parents[0]; - } - if (!expand || current === target) hidden.push(...chain); - } - if (expand) { - useGitLog.setState({ - fragments: { - ...fragments, - expanded: new Set([...expandedFragments, ...hidden]), - collapsed: new Set([...collapsedFragments].filter((id) => !hidden.includes(id))), - }, - }); - } else { - useGitLog.setState({ - fragments: { - ...fragments, - expanded: new Set([...expandedFragments].filter((id) => !hidden.includes(id))), - collapsed: new Set([...collapsedFragments, ...hidden]), - }, - }); - } - }; - - rowEvents.current = { - onHover: (edge) => { - if ( - edge === hoverColor || - (edge && (virtualizer.isScrolling || scrollRef.current?.hasAttribute("data-hover-paused"))) - ) - return; - setHoverColor(edge); - if (!edge) return; - const source = displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === edge)); - const target = source?.parents.find((p) => `${source.id}\0${p}` === edge); - if (!source || !target || commits.some((c) => commitKey(c) === target) || boundaryRequests.current.has(target)) - return; - const original = all.find((c) => commitKey(c) === source.id); - if (!original) return; - boundaryRequests.current.add(target); - const split = target.lastIndexOf("\0"), - id = target.slice(split + 1); - void loadLogDetails({ ...original, id }) - .then((details) => - setBoundaryTitles((current) => - new Map(current).set(target, `${id.slice(0, 8)} ${details.message.split("\n")[0]}`), - ), - ) - .catch(() => undefined); - }, - onFragment: fragment, - onNavigate: (index, key) => { - const target = commits[index]; - if (target) selectCommit(commitKey(target), true); - else if (key) { - const split = key.lastIndexOf("\0"); - void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : currentRepo()); - } - }, - }; - - return ( -
- {earlier && ( - - )} - {speedSearch && ( -
- {speedSearch} -
- )} - {error && ( -
- {error} -
- )} - -
= 0 ? `commit-${scope ?? "log"}-${selectedIndex}` : undefined} - tabIndex={0} - onScroll={(e) => { - if (!e.currentTarget.hasAttribute("data-hover-paused")) e.currentTarget.dataset.hoverPaused = ""; - setHoverColor(null); - }} - onPointerMoveCapture={(e) => { - const previous = hoverPointer.current; - hoverPointer.current = { x: e.clientX, y: e.clientY }; - if (!virtualizer.isScrolling && (!previous || previous.x !== e.clientX || previous.y !== e.clientY)) - delete e.currentTarget.dataset.hoverPaused; - }} - onPointerLeave={(e) => { - hoverPointer.current = { x: e.clientX, y: e.clientY }; - }} - onKeyDown={onKeyDown} - onCopy={(e) => { - if (window.getSelection()?.toString()) return; - const selected = commits.filter((c) => selectedSet.has(commitKey(c))); - if (!selected.length) return; - e.preventDefault(); - e.clipboardData.setData( - "text/plain", - selected - .map((c) => - [ - c.summary, - c.refs.join(" "), - ...(opts.showRepository ? [commitRepo(c) ?? ""] : []), - ...columns.map((column) => (typeof column.render(c) === "string" ? column.render(c) : "")), - ].join("\t"), - ) - .join("\n"), - ); - e.clipboardData.setData( - "application/x-openidea-vcs-commits", - JSON.stringify({ version: 1, commits: selected.map((c) => ({ root: commitRepo(c), hash: c.id })) }), - ); - }} - > - {opts.showColumnHeaders && } - {!commits.length && !loading && finished && ( -
{headCommit ? tx("No commits match the filters") : tx("No commits yet")}
- )} -
- {items.map((v) => { - const c = commits[v.index]; - if (!c) - return ( -
- {" "} - - Loading… - -
- ); - return ( - - ); - })} -
-
-
- ); -} - -interface ColumnDrag { - id: string; - target: string | null; - after: boolean; -} -// The flexible "Commit" column shares the same order and can be dragged like the rest. -const SUBJECT_COLUMN: LogColumn = { id: "subject", title: "Commit", width: 0, render: () => "" }; -// Until the user drags the commit column somewhere, it leads the row. -const columnSequence = (columnOrder: string[], builtins: LogColumn[]): string[] => { - const ids = [...new Set([...columnOrder, ...builtins.map((c) => c.id)])]; - return columnOrder.includes(SUBJECT_COLUMN.id) ? ids : [SUBJECT_COLUMN.id, ...ids]; -}; -function ColumnHeaders({ - columns, - options, - minWidth, -}: { - columns: LogColumn[]; - options: LogOptions; - minWidth: number; -}) { - const [drag, setDrag] = useState(null); - const ids = columnSequence(options.columnOrder, columns); - const cancel = useCallback(() => setDrag(null), []); - const move = (source: string, target: string | null, after: boolean) => { - if (!target || source === target || !ids.includes(source) || !ids.includes(target)) return; - const reordered = ids.filter((id) => id !== source); - const to = reordered.indexOf(target); - reordered.splice(after ? to + 1 : to, 0, source); - updateLogOptions({ columnOrder: reordered }); - }; - const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id)); - return ( -
- {options.showRepository && useVcs.getState().roots.length > 1 && ( - {tx("Repository")} - )} - {ids.map((cid) => { - const column = cid === SUBJECT_COLUMN.id ? SUBJECT_COLUMN : columns.find((c) => c.id === cid); - if (!column) return null; - return ( - - setDrag((d) => (d?.id === id && d.target === target && d.after === after ? d : { id, target, after })) - } - onDragCancel={cancel} - /> - ); - })} -
- ); -} - -// Column headers reorder by pointer capture: WebView2 blocks HTML5 drag events -// while dragDropEnabled is on, so dragging must not rely on them. -function LogColumnHeader({ - column, - subject, - ids, - options, - drag, - onMove, - onDragOver, - onDragCancel, -}: { - column: LogColumn; - subject?: boolean; - ids: string[]; - options: LogOptions; - drag: ColumnDrag | null; - onMove(source: string, target: string | null, after: boolean): void; - onDragOver(id: string, target: string | null, after: boolean): void; - onDragCancel(): void; -}) { - const press = useRef<{ - x: number; - y: number; - active: boolean; - element: HTMLElement; - pointerId: number; - } | null>(null); - const resizeDrag = useRef<{ - x: number; - width: number; - element: HTMLElement; - pointerId: number; - releaseCursor: () => void; - } | null>(null); - const cancel = useCallback(() => { - const captures = [press.current, resizeDrag.current]; - press.current = null; - resizeDrag.current?.releaseCursor(); - resizeDrag.current = null; - for (const capture of captures) - if (capture?.element.hasPointerCapture?.(capture.pointerId)) - capture.element.releasePointerCapture(capture.pointerId); - onDragCancel(); - }, [onDragCancel]); - useEffect(() => { - const escape = (e: globalThis.KeyboardEvent) => { - if (e.key !== "Escape" || (!press.current && !resizeDrag.current)) return; - e.preventDefault(); - e.stopPropagation(); - cancel(); - }; - window.addEventListener("blur", cancel); - window.addEventListener("keydown", escape, true); - return () => { - window.removeEventListener("blur", cancel); - window.removeEventListener("keydown", escape, true); - cancel(); - }; - }, [cancel]); - const width = options.columnWidths[column.id] ?? column.width ?? 120; - const resize = (value: number) => - updateLogOptions({ - columnWidths: { ...logOptions().columnWidths, [column.id]: Math.max(40, Math.min(800, value)) }, - }); - const index = ids.indexOf(column.id); - const hitColumn = (x: number, y: number) => { - const el = document.elementFromPoint(x, y)?.closest?.("[data-log-column]"); - if (!el || el.parentElement !== press.current?.element.parentElement) return null; - const rect = el.getBoundingClientRect(); - return { id: el.getAttribute("data-log-column")!, after: x > rect.left + rect.width / 2 }; - }; - return ( - { - if (e.button !== 0) return; - press.current = { x: e.clientX, y: e.clientY, active: false, element: e.currentTarget, pointerId: e.pointerId }; - e.currentTarget.setPointerCapture?.(e.pointerId); - }} - onPointerMove={(e) => { - const start = press.current; - if (!start || start.pointerId !== e.pointerId) return; - if (!start.active && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 4) return; - start.active = true; - const target = hitColumn(e.clientX, e.clientY); - onDragOver(column.id, target?.id ?? null, target?.after ?? false); - }} - onPointerUp={(e) => { - const start = press.current; - if (!start || start.pointerId !== e.pointerId) return; - const target = hitColumn(e.clientX, e.clientY); - if (start.active) onMove(column.id, target?.id ?? null, target?.after ?? false); - cancel(); - }} - onPointerCancel={cancel} - onLostPointerCapture={cancel} - onContextMenu={(e) => { - e.preventDefault(); - showContextMenu(e, [ - { - label: "Move Left", - disabled: index === 0, - run: () => onMove(column.id, ids[index - 1] ?? null, false), - }, - { - label: "Move Right", - disabled: index === ids.length - 1, - run: () => onMove(column.id, ids[index + 1] ?? null, true), - }, - ...(subject ? [] : [{ label: "Reset Width", run: () => resize(column.width ?? 120) }]), - ]); - }} - > - {tx(column.title)} - {!subject && ( - { - if (e.button !== 0) return; - e.preventDefault(); - e.stopPropagation(); - resizeDrag.current = { - x: e.clientX, - width, - element: e.currentTarget, - pointerId: e.pointerId, - releaseCursor: lockDragCursor("ew-resize"), - }; - e.currentTarget.setPointerCapture(e.pointerId); - }} - onPointerMove={(e) => { - if (resizeDrag.current && e.currentTarget.hasPointerCapture(e.pointerId)) - resize(resizeDrag.current.width + e.clientX - resizeDrag.current.x); - }} - onPointerUp={(e) => { - resizeDrag.current?.releaseCursor(); - resizeDrag.current = null; - if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); - }} - onPointerCancel={() => { - resizeDrag.current?.releaseCursor(); - resizeDrag.current = null; - }} - onLostPointerCapture={() => { - resizeDrag.current?.releaseCursor(); - resizeDrag.current = null; - }} - onKeyDown={(e) => { - if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; - e.preventDefault(); - e.stopPropagation(); - if (e.altKey) - onMove(column.id, ids[index + (e.key === "ArrowLeft" ? -1 : 1)] ?? null, e.key === "ArrowRight"); - else resize(width + (e.key === "ArrowLeft" ? -10 : 10)); - }} - /> - )} - - ); -} - -type RowEvents = { - onHover: (edge: string | null) => void; - onFragment: (from: string, target: string, expand: boolean) => void; - onNavigate: (index: number, key?: string) => void; -}; - -const remoteNameSets = new WeakMap>(); - -/** A commit's own remote names (multi-root logs) as one set per array, else the shared one. */ -function rowRemoteNames(own: readonly string[] | undefined, shared: ReadonlySet): ReadonlySet { - if (!own) return shared; - let set = remoteNameSets.get(own); - if (!set) remoteNameSets.set(own, (set = new Set(own))); - return set; -} - -function CommitRowView({ - id, - commit: c, - graph, - top, - selected, - head, - mine, - onBranch, - opts, - remoteNames, - onPick, - hoverColor, - highlighted, - highlightedNodes, - onHover, - onFragment, - onNavigate, - targetTitle, - columns, - bookmarked, - interactive, -}: { - id: string; - commit: Commit; - graph: GraphRow | undefined; - top: number; - selected: boolean; - head: boolean; - mine: boolean; - onBranch: boolean; - opts: LogOptions; - remoteNames: ReadonlySet; - onPick: (id: string, e: ReactMouseEvent) => void; - hoverColor: string | null; - highlighted: ReadonlySet; - highlightedNodes: ReadonlySet; - onHover: (color: string | null) => void; - onFragment: (from: string, target: string, expand: boolean) => void; - onNavigate: (index: number, key?: string) => void; - targetTitle: (index: number, key?: string) => string; - columns: LogColumn[]; - bookmarked: boolean; - /** False for rows rendered mid-scroll: their graph is drawn without hit targets. */ - interactive: boolean; -}) { - const merge = opts.highlightMerges && c.parents.length > 1; - const subjectRef = useRef(null); - const [tooltip, setTooltip] = useState(false); - const tooltipBody = useRef(null); - const tooltipTimer = useRef | undefined>(undefined); - useEffect(() => () => clearTimeout(tooltipTimer.current), []); - useEffect(() => { - if (!tooltip) return; - // Scrolling the log moves the anchor away; scrolling a long message inside the card doesn't. - const hide = (e: Event) => { - const card = tooltipBody.current?.closest("[data-popup]"); - if (e.target instanceof Node && card?.contains(e.target)) return; - setTooltip(false); - }; - window.addEventListener("scroll", hide, true); - return () => window.removeEventListener("scroll", hide, true); - }, [tooltip]); - const enterTooltip = () => { - clearTimeout(tooltipTimer.current); - if (tooltip || subjectRef.current?.closest("[data-hover-paused]")) return; - tooltipTimer.current = setTimeout(() => { - if (!subjectRef.current?.closest("[data-hover-paused]")) setTooltip(true); - }, TOOLTIP_DELAY); - }; - const leaveTooltip = () => { - clearTimeout(tooltipTimer.current); - tooltipTimer.current = setTimeout(() => setTooltip(false), 120); - }; - const refs = c.refs.length > 0 && ( - - ); - const subjectCell = ( - - {graph && ( - onFragment(source ?? commitKey(c), target, expand)} - onNode={() => onFragment(commitKey(c), commitKey(c), false)} - interactive={interactive} - /> - )} - {bookmarked && } - {opts.refsOnLeft && refs} - { - clearTimeout(tooltipTimer.current); - setTooltip(false); - }} - > - - - {!opts.refsOnLeft && refs} - setTooltip(false)} - className={styles.commitTooltip} - > -
clearTimeout(tooltipTimer.current)} onPointerLeave={leaveTooltip}> - -
-
-
- ); - return ( -
{ - if (e.shiftKey) e.preventDefault(); // no text selection on range clicks - onPick(commitKey(c), e); - }} - onContextMenu={(e) => { - e.preventDefault(); - showContextMenu(e, commitMenu(c, selectedCommits())); - }} - > - {opts.showRepository && commitRepo(c) && useVcs.getState().roots.length > 1 && ( - - {repoName(commitRepo(c)!)} - - )} - {columnSequence(opts.columnOrder, columns).map((cid) => { - if (cid === SUBJECT_COLUMN.id) return subjectCell; - const column = columns.find((col) => col.id === cid); - if (!column) return null; - return ( - ` : undefined} - > - {column.render(c)} - - ); - })} -
- ); -} - -// A row that is already interactive stays so when scrolling starts; only rows -// whose content changes mid-scroll are drawn without hit targets. -const CommitRow = memo(CommitRowView, (prev, next) => { - for (const key in next) { - const k = key as keyof typeof next; - if (prev[k] !== next[k] && !(k === "interactive" && prev.interactive)) return false; - } - return true; -}); - -function x(lane: number) { - return LANE / 2 + lane * LANE; -} - -/** Straight, also across lanes (IDEA's diagonal edges). */ -function seg(fromX: number, fromY: number, toX: number, toY: number) { - return `M${fromX} ${fromY}L${toX} ${toY}`; -} - -export function GraphCell({ - row, - head, - activeColor, - highlighted, - highlightedNodes, - onHover, - onNavigate, - onFragment, - targetTitle, - onNode, - interactive = true, -}: { - row: GraphRow; - head?: boolean; - activeColor?: string | null; - highlighted?: ReadonlySet; - highlightedNodes?: ReadonlySet; - onHover?: (edge: string | null) => void; - onNavigate?: (index: number, key?: string) => void; - onFragment?: (target: string, expand: boolean, source?: string) => void; - targetTitle?: (index: number, key?: string) => string; - onNode?: () => void; - interactive?: boolean; -}) { - const cy = ROW / 2; - const draw = (s: GraphSegment, i: number, up: boolean) => { - const fromX = x(s.fromX ?? s.from); - const toX = x(s.toX ?? s.to); - const path = - seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) + - (s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : ""); - const line = ( - - ); - if (!interactive) return line; - const target = (up ? row.upTargets : row.downTargets)?.[i]; - const canFragment = - !!target && - !!onFragment && - s.kind !== "filtered" && - s.kind !== "shallow" && - (!!s.source || (!up && s.from === row.lane)); - const canNavigate = s.targetRow != null && s.kind !== "shallow" && !!onNavigate; - const actionable = canNavigate || canFragment; - const label = - s.kind === "shallow" - ? tx("Shallow history boundary") - : s.targetRow != null - ? (targetTitle?.(s.targetRow, target) ?? tx("Go to connected commit")) - : s.dashed - ? tx("Expand this fragment") - : tx("Collapse this fragment"); - const activate = () => { - if (canNavigate) onNavigate?.(s.targetRow!, target); - else if (canFragment) onFragment?.(target!, !!s.dashed, s.source); - }; - return ( - - onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)} - onMouseMove={() => onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)} - onMouseDown={(e) => e.stopPropagation()} - onClick={(e) => { - e.stopPropagation(); - activate(); - }} - onKeyDown={(e) => { - if (actionable && (e.key === "Enter" || e.key === " ")) { - e.preventDefault(); - e.stopPropagation(); - activate(); - } - }} - > - {label} - - {line} - - ); - }; - return ( - onHover?.(null)} - > - {row.up.map((s, i) => draw(s, i, true))} - {row.down.map((s, i) => draw(s, i, false))} - e.stopPropagation()} - onMouseEnter={() => row.id && onHover?.(`node:${row.id}`)} - onMouseMove={() => row.id && onHover?.(`node:${row.id}`)} - onClick={(e) => { - e.stopPropagation(); - onNode?.(); - }} - onKeyDown={(e) => { - if (onNode && (e.key === "Enter" || e.key === " ")) { - e.preventDefault(); - e.stopPropagation(); - onNode(); - } - }} - > - - - {head && } - - - ); -} - -/** Arrow head at (`px`, `py`) pointing up (`dir` -1) or down (1): a long edge continues. */ -function arrowHead(px: number, py: number, dir: 1 | -1) { - const back = py - dir * 4; - return `M${px - 3} ${back}L${px} ${py}L${px + 3} ${back}`; -} - -const REF_KIND_CLASS = { - head: styles.refHead, - local: styles.refLocal, - remote: styles.refRemote, - tag: styles.refTag, -}; - -const NO_REMOTES: ReadonlySet = new Set(); - -export function RefLabels({ - refs, - compact = false, - tagNames = true, - remoteNames = NO_REMOTES, - left = false, -}: { - refs: string[]; - compact?: boolean; - tagNames?: boolean; - remoteNames?: ReadonlySet; - left?: boolean; -}) { - const labels = refLabels(refs, { compact, tagNames }, remoteNames); - return ( - - {labels.map((l) => ( - - {l.text} - - ))} - - ); -} - -/** - * The selected commits' changes: one commit's files against its first parent, or, for several - * (IDEA), their combined changes with every selected commit listed below. - */ -export function CommitDetails({ commits }: { commits: Commit[] }) { - const scope = useContext(LogIdContext); - const [menuBelow, dropdown] = useDropdownMenu(); - const shown = useGitLog((s) => s.shownLog); - const active = !scope || scope === shown; - const readOnly = useReadOnlyLog(); - const selected = useGitLog((s) => s.selected); - const selection = useGitLog((s) => s.selection); - // Newest first (log order). - const chosen = useMemo(() => { - const ids = new Set(selection); - return commits.filter((c) => ids.has(commitKey(c))); - }, [commits, selection]); - const commit = selected ? commits.find((c) => commitKey(c) === selected) : undefined; - const many = chosen.length > 1; - const idsKey = chosen.map(commitKey).join(" "); - const commitRoot = commit ? commitRepo(commit) : null; - const [result, setResult] = useState<{ - key: string; - files: LogChange[] | null; - error: string | null; - } | null>(null); - const [expanded, setExpanded] = useState | null>(null); - const [parentIndex, setParentIndex] = useState(-1); - const fromParents = useLogOptions((s) => s.changesFromParents); - const onlyAffected = useLogOptions((s) => s.showOnlyAffected); - const preview = useLogOptions((s) => s.diffPreview); - const savedLocation = useLogOptions((s) => s.diffLocation); - // The modal commit interface keeps diffs out of editor tabs (#1863): the "Editor" - // preview shows beside the changes instead. - const modal = useWorkflowSettings((s) => !s.vcs.commit.nonModal); - const diffLocation = modal && savedLocation === "editor" ? "right" : savedLocation; - const showLineStats = useLogOptions((s) => s.showLineStats); - const filters = useGitLog((s) => s.filters); - const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, showLineStats]); - const files = result?.key === filesKey ? result.files : null; - const error = result?.key === filesKey ? result.error : null; - - useEffect(() => { - if (!idsKey) return; - let alive = true; - const load = (async () => { - if (many) { - const roots = [...new Set(chosen.map(commitRepo))]; - return ( - await Promise.all( - roots.map(async (repo) => { - const group = chosen.filter((c) => commitRepo(c) === repo); - const files = await call( - commands.vcsCommitsChanges(repo ?? currentRepo(), group.map((c) => c.id).reverse()), - ); - return toLogChanges(files, null, repo, readOnly); - }), - ) - ).flat(); - } - const c = chosen[0]!; - if (c.parents.length > 1) { - const groups = await Promise.all( - c.parents.map(async (id, index) => { - const files = await call(commands.vcsDiffRevisions(commitRoot ?? currentRepo(), id, c.id)); - return toLogChanges(files, { ...c, parents: [id] }, commitRoot, readOnly).map((f) => ({ - ...f, - group: `${tx("Parent")} ${index + 1}: ${id.slice(0, 8)}`, - })); - }), - ); - if (fromParents) return parentIndex < 0 ? groups.flat() : (groups[parentIndex] ?? []); - // A merge's combined changes are files changed against every parent. - return groups[0]! - .filter((f) => groups.every((group) => group.some((x) => x.path === f.path))) - .map((f) => ({ - ...f, - group: undefined, - mergeParents: c.parents - .slice(0, 2) - .map((rev, i) => ({ rev, path: groups[i]!.find((x) => x.path === f.path)?.oldPath ?? f.path })), - })); - } - const files = await call(commands.vcsCommitFiles(commitRoot ?? currentRepo(), c.id)); - return toLogChanges(files, c, commitRoot, readOnly); - })(); - load - .then((files) => (showLineStats ? withLineStats(files).catch(() => files) : files)) - .then((files) => alive && setResult({ key: filesKey, files, error: null })) - .catch( - (e) => alive && setResult({ key: filesKey, files: null, error: e instanceof Error ? e.message : String(e) }), - ); - return () => { - alive = false; - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [idsKey, fromParents, parentIndex, commitRoot, filesKey, many, readOnly, showLineStats]); - - const groupByDirectory = useLogOptions((s) => s.groupByDirectory); - const [selectedKeys, setSelectedKeys] = useState>(() => new Set()); - const treeRef = useRef(null); - const [diffToReveal, setDiffToReveal] = useState<{ key: string } | null>(null); - const syncingDiff = useRef(false); - const changes = useMemo(() => { - const changes = files ?? []; - const paths = filters.paths?.length ? filters.paths : filters.path ? [filters.path] : []; - return onlyAffected && paths.length - ? changes.filter((c) => - paths.some((p) => { - const matches = (rel: string) => { - const abs = absolutePath(rel, c.repo); - return abs === p || abs.startsWith(`${p}/`) || (!many && commit?.historyPath === rel); - }; - return matches(c.path) || (c.oldPath != null && matches(c.oldPath)); - }), - ) - : changes; - }, [files, commit, many, filters.path, filters.paths, onlyAffected]); - const lineTotals = useMemo(() => { - if (!showLineStats || !changes.length) return null; - if (changes.some((f) => f.added === undefined || f.removed === undefined)) return null; - return changes.reduce((sum, f) => ({ added: sum.added + f.added!, removed: sum.removed + f.removed! }), { - added: 0, - removed: 0, - }); - }, [changes, showLineStats]); - const multipleRoots = new Set(chosen.map(commitRepo)).size > 1; - const changeTreePath = useCallback( - (f: LogChange) => `${multipleRoots ? `${repoName(f.repo ?? "")}/` : ""}${f.group ? `${f.group}/` : ""}${f.path}`, - [multipleRoots], - ); - const tree = useMemo( - () => (groupByDirectory ? buildFileTree(changes, changeTreePath) : flatFileNodes(changes, changeTreePath)), - [changes, groupByDirectory, changeTreePath], - ); - const allDirs = useMemo(() => dirKeys(tree), [tree]); - const ordered = useMemo(() => filesUnder(tree), [tree]); - const chosenChanges = useMemo(() => filesUnder(tree, selectedKeys), [tree, selectedKeys]); - - // Show Diff Preview: a single selected file follows into the editor's preview tab. - const previewTimer = useRef | undefined>(undefined); - useEffect(() => { - if (!active) clearTimeout(previewTimer.current); - return () => clearTimeout(previewTimer.current); - }, [active]); - const previewSelection = (sel: ReadonlySet) => { - clearTimeout(previewTimer.current); - if (syncingDiff.current || sel.size !== 1) return; - // While the editor shows one of this pane's diffs, the selection walks it along (a click or - // arrow key), as in the Commit window. - const shown = maybeEditorService()?.activeInput?.(); - const following = shown?.kind === DIFF_KIND && ordered.some((c) => diffInput(c.diff).key === shown.key); - if (!following && (!logOptions().diffPreview || logOptions().diffLocation !== "editor" || vcsDiffInFront())) return; - const file = fileNodeAt(tree, [...sel][0]!)?.file; - // A preview that cannot open (no editor yet, the file went away) is just skipped. - if (file) - previewTimer.current = setTimeout(() => void showChangesDiff([file], true).catch(() => undefined), PREVIEW_DELAY); - }; - - // Follow only this pane's exact diff (path AND revisions); another commit or - // Compare with Local must not move its selection. Never take focus from F7. - useEffect(() => { - const editor = maybeEditorService(); - const followDiff = (input: EditorInput | null) => { - if (input?.kind !== DIFF_KIND) return; - const change = ordered.find((c) => diffInput(c.diff).key === input.key); - if (!change) return; - clearTimeout(previewTimer.current); - const rel = changeTreePath(change); - setExpanded((current) => { - const next = new Set(current ?? allDirs); - for (const key of allDirs) if (rel.startsWith(key.slice(2) + "/")) next.add(key); - return next; - }); - setDiffToReveal({ key: `f:${rel}` }); - }; - followDiff(editor?.activeInput?.() ?? null); - return editor?.onActiveInputChange?.(followDiff); - }, [ordered, allDirs, changeTreePath]); - - // Tree.reveal needs the expanded rows to have rendered. Suppress the reverse - // preview update so it cannot reopen the diff and lose its requested chunk. - useLayoutEffect(() => { - if (!diffToReveal) return; - syncingDiff.current = true; - treeRef.current?.reveal(diffToReveal.key); - syncingDiff.current = false; - }, [diffToReveal]); - - useEffect(() => { - if (!active) return; - useLogChanges.setState({ commits: chosen, all: ordered, selected: chosenChanges }); - }, [chosen, ordered, chosenChanges, active]); - useEffect( - () => () => { - if (!scope || useGitLog.getState().shownLog === scope) - useLogChanges.setState({ commits: [], all: [], selected: [] }); - }, - [scope], - ); - useEffect(() => () => setContext("vcsLogChangesFocus", false), []); - - if (!commit) - return ( -
- - Select a commit to view changes - -
- ); - - const openViewOptions = (e: ReactMouseEvent) => - menuBelow(e, [ - { kind: "header", label: "Group By" }, - { kind: "action", action: "vcs.log.changes.groupByDirectory" }, - { kind: "separator" }, - { kind: "action", action: "vcs.log.changes.diffPreview" }, - toggle("Show Only Affected Changes", logOptions(), "showOnlyAffected"), - toggle("Show lines added and deleted", logOptions(), "showLineStats"), - toggle("Show Changes from Parents", logOptions(), "changesFromParents"), - { - label: "Diff Preview Location", - submenu: (["editor", "right", "bottom"] as const).map((location) => ({ - label: location === "editor" ? "Editor" : location === "right" ? "Right" : "Bottom", - checked: savedLocation === location, - run: () => updateLogOptions({ diffLocation: location }), - })), - }, - ]); - - const onFileMenu = (node: FileTreeNode | null, sel: ReadonlySet, e: ReactMouseEvent) => { - if (!node) return; - const target = sel.has(node.key) ? filesUnder(tree, sel) : filesUnder([node]); - if (!target.length) return; - e.preventDefault(); - showContextMenu(e, changesMenu(target)); - }; - - const details = ( - - -
setContext("vcsLogChangesFocus", true)} - onBlurCapture={(e) => { - if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("vcsLogChangesFocus", false); - }} - > -
- - c.repo)).size > 1} - /> - - {!many && fromParents && commit.parents.length > 1 && ( - - )} - - {files ? fileCount(changes.length) : ""} - {many ? " " + tx`in ${chosen.length} commits` : ""} - - {lineTotals && } - - setExpanded(new Set(allDirs))} - /> - setExpanded(new Set())} - /> -
- {error &&
{error}
} - {!files && !error && ( -
- -
- )} - {files && ( - > - handleRef={treeRef} - roots={tree} - getKey={(n) => n.key} - getLabel={(n) => n.name} - getChildren={(n) => (n.file ? undefined : n.children)} - isExpandable={(n) => !n.file} - expanded={expanded ?? new Set(allDirs)} - onExpandedChange={(next) => setExpanded(next)} - selected={selectedKeys} - onSelectionChange={(sel) => { - setSelectedKeys(sel); - previewSelection(sel); - }} - renderNode={(n) => } - onActivate={(n) => n.file && void showChangesDiff([n.file])} - onJumpToSource={(n, sel) => { - const files = sel.has(n.key) ? filesUnder(tree, sel) : filesUnder([n]); - void executeAction("vcs.log.changes.jumpToSource", files); - }} - onContextMenu={onFileMenu} - aria-label="Changed files" - className={styles.fileTree} - /> - )} -
-
- - -
- {many ? ( - chosen.map((c) => ) - ) : ( - - )} -
-
-
- ); - const embedded = preview && diffLocation !== "editor"; - const selectedChange = chosenChanges.length === 1 ? chosenChanges[0] : undefined; - return ( -
- {dropdown} - {embedded ? ( - - - {details} - - - - {selectedChange ? ( - selectedChange.mergeParents?.length === 2 && selectedChange.after ? ( - - ) : ( - - ) - ) : ( - - Select a file to preview its changes - - )} - - - ) : ( - details - )} -
- ); -} - -/** A commit's message and metadata; `compact` (one of several selected): without the body. */ -function CommitMessage({ commit, compact = false }: { commit: Commit; compact?: boolean }) { - const { details, error } = useCommitDetails(commit, !compact); - const repo = commitRepo(commit) ?? currentRepo(); - const message = details?.message || commit.message; - const [subject, ...bodyLines] = message.replace(/\s+$/, "").split("\n"); - const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, ""); - return ( -
-
- -
- {body && ( -
- -
- )} -
- {" "} - {commit.author} <{commit.email}> - {commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""} -
- {!compact && - commit.committer && - (commit.committer !== commit.author || - commit.committerEmail !== commit.email || - commit.commitTimeMs !== commit.timeMs) && ( -
- {tx("Committed by")} {commit.committer} <{commit.committerEmail}>{" "} - {commit.commitTimeMs ? new Date(commit.commitTimeMs).toLocaleString() : ""} -
- )} - {commit.parents.length > 0 && ( -
- {tx(commit.parents.length > 1 ? "Merge of" : "Parent")}{" "} - {commit.parents.map((id, i) => ( - - {i > 0 ? ", " : ""} - - - ))} -
- )} - {details && ( - <> -
- {tx("Containing branches")}:{" "} - {details.containingBranches.length - ? details.containingBranches.map((branch, i) => ( - - {i > 0 ? ", " : ""} - - - )) - : tx("None")} -
-
- {tx("Signature")}: {signatureLabel(details.signature)} - {details.signer ? ` · ${details.signer}` : ""} -
- - )} - {error && ( -
- {tx("Could not load containing branches or signature details")} -
- )} - {commit.refs.length > 0 && ( -
- -
- )} -
- ); -} - -function signatureLabel(code: string) { - return tx( - ( - { - G: "Verified", - U: "Good signature with unknown trust", - B: "Bad signature", - E: "Could not verify", - N: "Unsigned", - X: "Expired signature", - Y: "Expired signing key", - R: "Revoked signing key", - } as Record - )[code] ?? "Could not verify", - ); -} - -function CommitSignature({ commit }: { commit: Commit }) { - const { details, error } = useCommitDetails(commit); - return ( - - {details ? signatureLabel(details.signature) : error ? tx("Could not verify") : tx("Loading…")} - - ); -} - -function CommitMessageText({ text, repo }: { text: string; repo: string | null | undefined }) { - return text.split(/\b([a-fA-F0-9]{7,64})\b/g).map((part, i) => - i % 2 ? ( - - ) : ( - - ), - ); -} - -/** IDEA's changes browser context menu in the Git Log; `changes` = the files it acts on. */ -export function changesMenu(changes: LogChange[]): MenuItem[] { - const one = changes.length === 1 ? changes[0]! : null; - return [ - { kind: "action", action: "vcs.log.changes.showDiff", arg: changes }, - { kind: "action", action: "vcs.log.changes.compareWithLocal", arg: changes, disabled: !one?.after || one.readOnly }, - { - kind: "action", - action: "vcs.log.changes.compareBeforeWithLocal", - arg: changes, - disabled: !one?.before || one.readOnly, - }, - { kind: "separator" }, - { - kind: "action", - action: "vcs.log.changes.jumpToSource", - arg: changes, - disabled: !changes.some((c) => c.after && !c.readOnly), - }, - { kind: "separator" }, - { - kind: "action", - action: "vcs.log.changes.revert", - arg: changes, - disabled: changes.some((c) => c.readOnly) || new Set(changes.map((c) => c.repo)).size > 1, - }, - { - kind: "action", - action: "vcs.log.changes.getFromRevision", - arg: changes, - disabled: changes.some((c) => c.readOnly), - }, - { kind: "separator" }, - ...(one?.readOnly - ? [{ label: "Show History for File", run: () => openLogTab("history", absolutePath(one.path, one.repo)) }] - : [ - { - kind: "action", - action: "vcs.showHistory", - arg: one ? absolutePath(one.path, one.repo) : undefined, - disabled: !one?.after, - } satisfies MenuItem, - ]), - ]; -} - -function lineCount(file: ChangedFile | LogChange): { added: number; removed: number } | null { - if (!("added" in file) || typeof file.added !== "number" || typeof file.removed !== "number") return null; - return { added: file.added, removed: file.removed }; -} - -/** Sum of a directory once every file under it has counts; otherwise the row stays without them. */ -function nodeLineCount(node: FileTreeNode): { added: number; removed: number } | null { - if (node.file) return lineCount(node.file); - let added = 0; - let removed = 0; - for (const child of node.children) { - const count = nodeLineCount(child); - if (!count) return null; - added += count.added; - removed += count.removed; - } - return node.children.length ? { added, removed } : null; -} - -function LineStats({ added, removed }: { added: number; removed: number }) { - return ( - - - +{added} - - - −{removed} - - - ); -} - -function ChangedFileRow({ node, flat = false }: { node: FileTreeNode; flat?: boolean }) { - const stats = nodeLineCount(node); - if (!node.file) - return ( - - - {node.name} - {fileCount(node.count)} - {stats && } - - ); - const f = node.file; - const kind: EffectiveKind = f.kind === "untracked" ? "added" : f.kind; - return ( - - - - {node.name} - - {flat && dirName(f.path) && {dirName(f.path)}} - {f.oldPath && {renameFrom(f.path, f.oldPath)}} - {stats && } - - ); -} - // --------------------------------------------------------------------------- // Console diff --git a/src/features/vcs/__tests__/gitLogRefLabels.test.tsx b/src/features/vcs/__tests__/gitLogRefLabels.test.tsx index c06eef609..6d910b1ff 100644 --- a/src/features/vcs/__tests__/gitLogRefLabels.test.tsx +++ b/src/features/vcs/__tests__/gitLogRefLabels.test.tsx @@ -1,7 +1,7 @@ -import { readFileSync } from "node:fs"; import { render, screen } from "@testing-library/react"; +import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { RefLabels } from "../GitLog"; +import { RefLabels } from "../log/CommitMessage"; const css = readFileSync("src/features/vcs/GitLog.module.css", "utf8"); diff --git a/src/features/vcs/__tests__/historyOps.test.ts b/src/features/vcs/__tests__/historyOps.test.ts index 09512b549..ba02724d0 100644 --- a/src/features/vcs/__tests__/historyOps.test.ts +++ b/src/features/vcs/__tests__/historyOps.test.ts @@ -1,10 +1,10 @@ -import { describe, expect, it } from "vitest"; import type { Commit } from "@/bindings"; +import { describe, expect, it } from "vitest"; import { operationActions } from "../BranchWidget"; +import { commitMenu } from "../log/commitMenu"; +import { extendCommitSelection, selectCommit, selectedCommits, toggleCommitSelection, useGitLog } from "../logStore"; import { controlLabel, inProgress, operationControls, operationTitle, validateTagName } from "../operations"; import { suggestedPatchName } from "../patches"; -import { commitMenu } from "../GitLog"; -import { extendCommitSelection, selectCommit, selectedCommits, toggleCommitSelection, useGitLog } from "../logStore"; const commit = (summary: string, id = "0123456789abcdef0123456789abcdef01234567"): Commit => ({ id, diff --git a/src/features/vcs/__tests__/logBranches.test.tsx b/src/features/vcs/__tests__/logBranches.test.tsx index 29f3d2195..8a6602a54 100644 --- a/src/features/vcs/__tests__/logBranches.test.tsx +++ b/src/features/vcs/__tests__/logBranches.test.tsx @@ -1,7 +1,7 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; -import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import type { Branch, BranchInfo } from "@/bindings"; import { isMacHost } from "@/platform/keymap"; +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); @@ -22,8 +22,8 @@ vi.mock("@/platform/actions", async (importOriginal) => ({ })); import { ContextMenuHost } from "@/ui"; -import { BranchesPanel } from "../GitLog"; import syncStyles from "../BranchSync.module.css"; +import { BranchesPanel } from "../log/BranchesPanel"; import { emptyFilters, useGitLog } from "../logStore"; import { useVcs } from "../store"; diff --git a/src/features/vcs/__tests__/logGraphCorrectness.test.tsx b/src/features/vcs/__tests__/logGraphCorrectness.test.tsx index 24fef18ab..90a533cee 100644 --- a/src/features/vcs/__tests__/logGraphCorrectness.test.tsx +++ b/src/features/vcs/__tests__/logGraphCorrectness.test.tsx @@ -1,12 +1,12 @@ -import { describe, expect, it, vi } from "vitest"; -import { fireEvent, render, screen } from "@testing-library/react"; import type { Commit } from "@/bindings"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; import { collapseLinear, computeGraph, hideLongEdges, linearizeMerges } from "../graph"; -import { commitKey, graphCommit } from "../multiRoot"; -import { presentLogGraph } from "../logPresentation"; -import { DEFAULT_LOG_OPTIONS } from "../logOptions"; -import { GraphCell } from "../GitLog"; +import { GraphCell } from "../log/GraphCell"; import { toLogChanges } from "../logChanges"; +import { DEFAULT_LOG_OPTIONS } from "../logOptions"; +import { presentLogGraph } from "../logPresentation"; +import { commitKey, graphCommit } from "../multiRoot"; const commit = (id: string, parents: string[] = [], refs: string[] = []): Commit => ({ id, diff --git a/src/features/vcs/__tests__/logPanes.test.tsx b/src/features/vcs/__tests__/logPanes.test.tsx index a0ab87d93..8c218b838 100644 --- a/src/features/vcs/__tests__/logPanes.test.tsx +++ b/src/features/vcs/__tests__/logPanes.test.tsx @@ -1,6 +1,6 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import type { Branch, Commit } from "@/bindings"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const vcsCommitFiles = vi.fn(); const vcsDiffNumstat = vi.fn(); @@ -27,9 +27,13 @@ vi.mock("@/platform/ipc", async (importOriginal) => { }; }); +import { LogSettingsPage } from "../LogSettingsPage"; import { canDeleteBranch } from "../branchOps"; import { buildBranchTree, filterBranchTree } from "../branches"; import { buildFileTree } from "../fileTree"; +import { BranchesPanel } from "../log/BranchesPanel"; +import { CommitDetails, changesMenu } from "../log/CommitDetails"; +import { graphOptionsMenu } from "../log/FilterBar"; import { EMPTY_TREE, assignLineStats, @@ -40,12 +44,10 @@ import { toLogChanges, useLogChanges, } from "../logChanges"; -import { canUpdateBranch, useBranchesPane } from "../logPaneActions"; -import { BranchesPanel, CommitDetails, changesMenu, graphOptionsMenu } from "../GitLog"; -import { LogSettingsPage } from "../LogSettingsPage"; import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions"; -import { renameFrom } from "../model"; +import { canUpdateBranch, useBranchesPane } from "../logPaneActions"; import { emptyFilters, useGitLog } from "../logStore"; +import { renameFrom } from "../model"; import { useVcs } from "../store"; const b = (name: string, opts: Partial = {}): Branch => ({ diff --git a/src/features/vcs/__tests__/logUiFeatures.test.tsx b/src/features/vcs/__tests__/logUiFeatures.test.tsx index e707d0182..609245f38 100644 --- a/src/features/vcs/__tests__/logUiFeatures.test.tsx +++ b/src/features/vcs/__tests__/logUiFeatures.test.tsx @@ -1,7 +1,7 @@ -import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Commit } from "@/bindings"; import { ContextMenuHost, hideContextMenu } from "@/ui"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const api = vi.hoisted(() => ({ commits: [] as Commit[], details: vi.fn(), diff: vi.fn() })); vi.mock("@/platform/ipc", async (original) => { @@ -28,12 +28,13 @@ vi.mock("@/platform/ipc", async (original) => { }; }); -import { CommitDetails, LogView } from "../GitLog"; -import { useVcs } from "../store"; -import { commitKey } from "../multiRoot"; -import { emptyFilters, openLogTab, reloadLog, selectGitTab, useGitLog } from "../logStore"; +import { LogView } from "../GitLog"; import { LogScope } from "../LogScope"; +import { CommitDetails } from "../log/CommitDetails"; import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions"; +import { emptyFilters, openLogTab, reloadLog, selectGitTab, useGitLog } from "../logStore"; +import { commitKey } from "../multiRoot"; +import { useVcs } from "../store"; const c = (id: string, parents: string[] = [], refs: string[] = []): Commit => ({ id, diff --git a/src/features/vcs/log/BranchesPanel.tsx b/src/features/vcs/log/BranchesPanel.tsx new file mode 100644 index 000000000..973d402a7 --- /dev/null +++ b/src/features/vcs/log/BranchesPanel.tsx @@ -0,0 +1,312 @@ +import type { Branch } from "@/bindings"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { hasPrimaryModifier } from "@/platform/keymap"; +import { IconButton, SearchField, T, Tree, copyText, showContextMenu, type MenuItem } from "@/ui"; +import { useContext, useEffect, useMemo, useState, type KeyboardEvent, type ReactNode } from "react"; +import { + branchFolderKeys, + branchGroupKeys, + buildBranchTree, + buildRepositoryBranchTree, + filterBranchTree, + isFavoriteBranch, + type BranchTreeNode, +} from "../branches"; +import { branchMenu, inRepo, tagMenu } from "../branchMenu"; +import { canDeleteBranch, loadFavoriteBranches, useFavoriteBranches } from "../branchOps"; +import { BranchSync } from "../BranchSync"; +import styles from "../GitLog.module.css"; +import { LogIdContext } from "../logContext"; +import { canUpdateBranch, useBranchesPane, type BranchTarget } from "../logPaneActions"; +import { reloadLog, setLogBranches, setLogFilters, useGitLog } from "../logStore"; +import { branchesByRepo } from "../multiRoot"; +import { currentRepo, loadBranches, repoName, useVcs } from "../store"; +import { useLogRepositories, useReadOnlyLog } from "./logHooks"; + +// --- branches --------------------------------------------------------------- + +function branchDetail(n: BranchTreeNode): ReactNode { + const b = n.branch; + if (!b) return undefined; + if (!b.current && b.behind <= 0 && b.ahead <= 0) return undefined; + return ( + + {b.current && {tx("current")}} + + + ); +} + +export function BranchesPanel() { + const scope = useContext(LogIdContext); + const shown = useGitLog((s) => s.shownLog); + const active = !scope || scope === shown; + const logGeneration = useGitLog((s) => s.generation); + const selectedBranches = useVcs((s) => s.branches); + const repositories = useLogRepositories(); + const readOnly = useReadOnlyLog(); + const version = useVcs((s) => s.version); + const [allBranches, setAllBranches] = useState>({}); + const [allTags, setAllTags] = useState>({}); + const currentRepository = currentRepo(); + const branches = useMemo( + () => + repositories.length === 1 && repositories[0] !== currentRepository + ? (allBranches[repositories[0]!] ?? []) + : selectedBranches, + [repositories, currentRepository, allBranches, selectedBranches], + ); + const root = useVcs((s) => s.root); + const branchesLoaded = useVcs((s) => s.branchesLoaded); + const current = useVcs((s) => s.branch?.head ?? null); + const favorites = useFavoriteBranches((s) => s.names); + const filterBranches = useGitLog((s) => s.filters.branches); + const filterRepositories = useGitLog((s) => s.filters.repositories); + const [query, setQuery] = useState(""); + const [tags, setTags] = useState([]); + useEffect(() => loadFavoriteBranches(), [root]); + // Branches reload when refs move (fetch, new tag…): the tags are re-read with them. + useEffect(() => { + let live = true; + call(commands.vcsTags(repositories[0] ?? currentRepo())).then( + (t) => live && setTags(t), + () => live && setTags([]), + ); + return () => { + live = false; + }; + }, [root, branches, repositories]); + useEffect(() => { + let live = true; + void branchesByRepo(repositories) + .then((value) => live && setAllBranches(value)) + .catch(() => undefined); + void Promise.all(repositories.map(async (r) => [r, await call(commands.vcsTags(r))] as const)) + .then((value) => live && setAllTags(Object.fromEntries(value))) + .catch(() => undefined); + return () => { + live = false; + }; + }, [repositories, version, logGeneration]); + const allRoots = useMemo(() => { + if (repositories.length < 2) return buildBranchTree(branches, favorites, tags); + return buildRepositoryBranchTree( + repositories.map((repo) => ({ + root: repo, + name: repoName(repo), + branches: allBranches[repo] ?? [], + tags: allTags[repo] ?? [], + })), + favorites, + ); + }, [repositories, allBranches, allTags, branches, favorites, tags]); + const roots = useMemo(() => filterBranchTree(allRoots, query), [allRoots, query]); + // While searching every match is shown expanded. + const searchExpanded = useMemo(() => (query.trim() ? new Set(branchGroupKeys(roots)) : undefined), [roots, query]); + // Highlighted rows: a click only selects (IDEA), and only a double click or + // Enter switches the log, so the selection is the pane's own state. It still + // follows the filter when something else changes it (Show Log, the filter bar). + const filterKeys = useMemo( + () => + filterBranches.flatMap((b) => { + if (b === "HEAD") return ["head"]; + if (repositories.length < 2) return [`b:${b}`]; + return (filterRepositories?.length ? filterRepositories : repositories).map((r) => `${r}:b:${b}`); + }), + [filterBranches, filterRepositories, repositories], + ); + const filterKey = filterKeys.join("\n"); + const [shownKey, setShownKey] = useState(filterKey); + const [selected, setSelected] = useState>(() => new Set(filterKeys)); + if (shownKey !== filterKey) { + // The filter changed elsewhere (Show Log, the filter bar): highlight it. + setShownKey(filterKey); + setSelected(new Set(filterKeys)); + } + // Refs in tree order, for Copy: full refs, so the folder path comes along + // (`feat/x`, `origin/main`). + const refs = useMemo(() => { + const out: { key: string; ref: string; branch?: Branch; repo?: string }[] = []; + const walk = (nodes: readonly BranchTreeNode[]) => { + for (const n of nodes) { + if (n.ref) out.push({ key: n.key, ref: n.ref, branch: n.branch, repo: n.repo }); + walk(n.children ?? []); + } + }; + walk(allRoots); + return out; + }, [allRoots]); + const targets = useMemo( + (): BranchTarget[] => + refs.filter((r) => selected.has(r.key)).map(({ ref, branch, repo }) => ({ ref, branch, repo })), + [refs, selected], + ); + useEffect(() => { + if (!active) return; + useBranchesPane.setState({ selected: targets }); + return () => useBranchesPane.setState({ selected: [] }); + }, [targets, active]); + const target = targets[0] ?? undefined; + const favorite = !!target?.branch && isFavoriteBranch(target.branch, favorites); + const onKeyDownCapture = (e: KeyboardEvent) => { + if ((e.key !== "c" && e.key !== "C") || !hasPrimaryModifier(e) || e.altKey || e.shiftKey) return; + // The branch search keeps the browser's own copy. + if ((e.target as HTMLElement).closest("input, textarea")) return; + const names = targets.map((r) => r.ref); + if (!names.length) return; + e.preventDefault(); + e.stopPropagation(); + void copyText(names.join("\n")); + }; + return ( +
+
+ + {!readOnly && ( + <> + + + canDeleteBranch(t))} + /> + + + + + )} + (readOnly ? void reloadLog({ preserve: true }) : void loadBranches())} + /> +
+
+
+ +
+ + key={`${root ?? ""}:${branchesLoaded}`} + roots={roots} + getKey={(n) => n.key} + getLabel={(n) => (n.kind === "head" || n.kind === "group" ? tx(n.label) : n.label)} + getChildren={(n) => n.children} + isExpandable={(n) => !!n.children} + defaultExpanded={[ + ...branchGroupKeys(allRoots), + "g:local", + "g:remote", + ...roots.flatMap((r) => r.children?.filter((c) => c.kind === "remote").map((c) => c.key) ?? []), + ...(current ? branchFolderKeys(roots, current) : []), + ]} + expanded={searchExpanded} + getIcon={(n) => + n.kind === "head" + ? "commit" + : n.kind === "tag" + ? "tag" + : n.branch?.current + ? "current-branch" + : n.kind === "branch" + ? n.favorite + ? "star" + : "branch" + : "folder" + } + getDetail={branchDetail} + selected={selected} + onSelectionChange={(sel) => setSelected(sel)} + onActivate={(n) => { + // IDEA: double click (or Enter) switches the log to that ref, or to every + // selected one when it is part of a multi-selection; checking out stays in the context menu. + if (!n.ref) return; + const sel = selected.has(n.key) ? targets.filter((r) => r.repo === n.repo).map((r) => r.ref) : [n.ref]; + setLogFilters({ branches: sel, repositories: n.repo ? [n.repo] : [] }); + }} + onContextMenu={(n, _sel, e) => { + if (readOnly) { + if (!n?.ref) return; + e.preventDefault(); + showContextMenu(e, [ + { label: "Show in Git Log", run: () => setLogBranches([n.ref!]) }, + { label: "Copy", run: () => void copyText(n.ref!) }, + ]); + return; + } + // The menu acts on the whole selection when the right-clicked branch is part of it. + const picked: BranchTarget[] = + n && selected.has(n.key) ? targets : n?.ref ? [{ ref: n.ref, branch: n.branch, repo: n.repo }] : []; + const menu = n?.branch + ? branchMenu( + n.branch, + n.repo ? (useVcs.getState().heads[n.repo]?.head ?? null) : current, + () => {}, + picked, + ) + : n?.kind === "tag" + ? tagMenu(n.ref!) + : n?.kind === "remote" || (n?.kind === "group" && n.key.endsWith("g:remote")) + ? REMOTES_MENU + : []; + // Delete scopes each selected target itself and must preserve the original focus. + const items = n?.repo + ? menu.flatMap((item) => + n.branch && "label" in item && item.label === "Delete" ? [item] : inRepo(n.repo!, [item]), + ) + : menu; + if (!items.length) return; + e.preventDefault(); + showContextMenu(e, items); + }} + empty={ + query.trim() ? ( + + No matching branches + + ) : undefined + } + aria-label="Branches" + className={styles.branchTree} + /> +
+
+ ); +} + +/** IDEA: the Remote node and each remote of the Branches pane offer Manage Remotes…. */ +const REMOTES_MENU: MenuItem[] = [{ label: "Manage Remotes…", run: () => void executeAction("vcs.manageRemotes") }]; diff --git a/src/features/vcs/log/ColumnHeaders.tsx b/src/features/vcs/log/ColumnHeaders.tsx new file mode 100644 index 000000000..32a8b8b9b --- /dev/null +++ b/src/features/vcs/log/ColumnHeaders.tsx @@ -0,0 +1,243 @@ +import { tx } from "@/platform/i18n"; +import { lockDragCursor, showContextMenu } from "@/ui"; +import clsx from "clsx"; +import { useCallback, useEffect, useRef, useState } from "react"; +import styles from "../GitLog.module.css"; +import { logOptions, type LogOptions } from "../logOptions"; +import { updateLogOptions } from "../logStore"; +import { useVcs } from "../store"; +import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared"; + +interface ColumnDrag { + id: string; + target: string | null; + after: boolean; +} + +export function ColumnHeaders({ + columns, + options, + minWidth, +}: { + columns: LogColumn[]; + options: LogOptions; + minWidth: number; +}) { + const [drag, setDrag] = useState(null); + const ids = columnSequence(options.columnOrder, columns); + const cancel = useCallback(() => setDrag(null), []); + const move = (source: string, target: string | null, after: boolean) => { + if (!target || source === target || !ids.includes(source) || !ids.includes(target)) return; + const reordered = ids.filter((id) => id !== source); + const to = reordered.indexOf(target); + reordered.splice(after ? to + 1 : to, 0, source); + updateLogOptions({ columnOrder: reordered }); + }; + const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id)); + return ( +
+ {options.showRepository && useVcs.getState().roots.length > 1 && ( + {tx("Repository")} + )} + {ids.map((cid) => { + const column = cid === SUBJECT_COLUMN.id ? SUBJECT_COLUMN : columns.find((c) => c.id === cid); + if (!column) return null; + return ( + + setDrag((d) => (d?.id === id && d.target === target && d.after === after ? d : { id, target, after })) + } + onDragCancel={cancel} + /> + ); + })} +
+ ); +} + +// Column headers reorder by pointer capture: WebView2 blocks HTML5 drag events +// while dragDropEnabled is on, so dragging must not rely on them. +function LogColumnHeader({ + column, + subject, + ids, + options, + drag, + onMove, + onDragOver, + onDragCancel, +}: { + column: LogColumn; + subject?: boolean; + ids: string[]; + options: LogOptions; + drag: ColumnDrag | null; + onMove(source: string, target: string | null, after: boolean): void; + onDragOver(id: string, target: string | null, after: boolean): void; + onDragCancel(): void; +}) { + const press = useRef<{ + x: number; + y: number; + active: boolean; + element: HTMLElement; + pointerId: number; + } | null>(null); + const resizeDrag = useRef<{ + x: number; + width: number; + element: HTMLElement; + pointerId: number; + releaseCursor: () => void; + } | null>(null); + const cancel = useCallback(() => { + const captures = [press.current, resizeDrag.current]; + press.current = null; + resizeDrag.current?.releaseCursor(); + resizeDrag.current = null; + for (const capture of captures) + if (capture?.element.hasPointerCapture?.(capture.pointerId)) + capture.element.releasePointerCapture(capture.pointerId); + onDragCancel(); + }, [onDragCancel]); + useEffect(() => { + const escape = (e: globalThis.KeyboardEvent) => { + if (e.key !== "Escape" || (!press.current && !resizeDrag.current)) return; + e.preventDefault(); + e.stopPropagation(); + cancel(); + }; + window.addEventListener("blur", cancel); + window.addEventListener("keydown", escape, true); + return () => { + window.removeEventListener("blur", cancel); + window.removeEventListener("keydown", escape, true); + cancel(); + }; + }, [cancel]); + const width = options.columnWidths[column.id] ?? column.width ?? 120; + const resize = (value: number) => + updateLogOptions({ + columnWidths: { ...logOptions().columnWidths, [column.id]: Math.max(40, Math.min(800, value)) }, + }); + const index = ids.indexOf(column.id); + const hitColumn = (x: number, y: number) => { + const el = document.elementFromPoint(x, y)?.closest?.("[data-log-column]"); + if (!el || el.parentElement !== press.current?.element.parentElement) return null; + const rect = el.getBoundingClientRect(); + return { id: el.getAttribute("data-log-column")!, after: x > rect.left + rect.width / 2 }; + }; + return ( + { + if (e.button !== 0) return; + press.current = { x: e.clientX, y: e.clientY, active: false, element: e.currentTarget, pointerId: e.pointerId }; + e.currentTarget.setPointerCapture?.(e.pointerId); + }} + onPointerMove={(e) => { + const start = press.current; + if (!start || start.pointerId !== e.pointerId) return; + if (!start.active && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 4) return; + start.active = true; + const target = hitColumn(e.clientX, e.clientY); + onDragOver(column.id, target?.id ?? null, target?.after ?? false); + }} + onPointerUp={(e) => { + const start = press.current; + if (!start || start.pointerId !== e.pointerId) return; + const target = hitColumn(e.clientX, e.clientY); + if (start.active) onMove(column.id, target?.id ?? null, target?.after ?? false); + cancel(); + }} + onPointerCancel={cancel} + onLostPointerCapture={cancel} + onContextMenu={(e) => { + e.preventDefault(); + showContextMenu(e, [ + { + label: "Move Left", + disabled: index === 0, + run: () => onMove(column.id, ids[index - 1] ?? null, false), + }, + { + label: "Move Right", + disabled: index === ids.length - 1, + run: () => onMove(column.id, ids[index + 1] ?? null, true), + }, + ...(subject ? [] : [{ label: "Reset Width", run: () => resize(column.width ?? 120) }]), + ]); + }} + > + {tx(column.title)} + {!subject && ( + { + if (e.button !== 0) return; + e.preventDefault(); + e.stopPropagation(); + resizeDrag.current = { + x: e.clientX, + width, + element: e.currentTarget, + pointerId: e.pointerId, + releaseCursor: lockDragCursor("ew-resize"), + }; + e.currentTarget.setPointerCapture(e.pointerId); + }} + onPointerMove={(e) => { + if (resizeDrag.current && e.currentTarget.hasPointerCapture(e.pointerId)) + resize(resizeDrag.current.width + e.clientX - resizeDrag.current.x); + }} + onPointerUp={(e) => { + resizeDrag.current?.releaseCursor(); + resizeDrag.current = null; + if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId); + }} + onPointerCancel={() => { + resizeDrag.current?.releaseCursor(); + resizeDrag.current = null; + }} + onLostPointerCapture={() => { + resizeDrag.current?.releaseCursor(); + resizeDrag.current = null; + }} + onKeyDown={(e) => { + if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; + e.preventDefault(); + e.stopPropagation(); + if (e.altKey) + onMove(column.id, ids[index + (e.key === "ArrowLeft" ? -1 : 1)] ?? null, e.key === "ArrowRight"); + else resize(width + (e.key === "ArrowLeft" ? -10 : 10)); + }} + /> + )} + + ); +} diff --git a/src/features/vcs/log/CommitDetails.tsx b/src/features/vcs/log/CommitDetails.tsx new file mode 100644 index 000000000..2da8ce5e3 --- /dev/null +++ b/src/features/vcs/log/CommitDetails.tsx @@ -0,0 +1,578 @@ +import type { ChangedFile, Commit } from "@/bindings"; +import { executeAction } from "@/platform/actions"; +import { setContext } from "@/platform/context"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { useWorkflowSettings } from "@/platform/workflowSettings"; +import { + EmptyState, + Icon, + IconButton, + Spinner, + SplitGroup, + SplitHandle, + SplitPanel, + T, + Tree, + fileIconName, + lazyComponent, + showContextMenu, + type MenuItem, + type TreeHandle, +} from "@/ui"; +import { maybeEditorService, type EditorInput } from "@/workbench/contributions"; +import { + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type MouseEvent as ReactMouseEvent, +} from "react"; +import { DIFF_KIND, diffInput, vcsDiffInFront } from "../diffInput"; +import { buildFileTree, dirKeys, type FileTreeNode } from "../fileTree"; +import styles from "../GitLog.module.css"; +import { + absolutePath, + filesUnder, + flatFileNodes, + showChangesDiff, + toLogChanges, + useLogChanges, + withLineStats, + type LogChange, +} from "../logChanges"; +import { LogIdContext } from "../logContext"; +import { logOptions, useLogOptions } from "../logOptions"; +import { openLogTab, updateLogOptions, useGitLog } from "../logStore"; +import { KIND_COLOR, dirName, fileCount, renameFrom, type EffectiveKind } from "../model"; +import { commitKey, commitRepo } from "../multiRoot"; +import { currentRepo, repoName } from "../store"; +import { CommitMessage } from "./CommitMessage"; +import { useDropdownMenu, useReadOnlyLog } from "./logHooks"; +import { toggle } from "./shared"; + +const LogMergePreview = lazyComponent(() => import("../GitMergeDiff").then((m) => m.GitMergeDiff)); + +const LogDiffPreview = lazyComponent(() => import("../DiffEditor").then((m) => m.DiffEditor)); + +/** Keyboard moves through several files quickly: preview the one the selection settles on. */ +const PREVIEW_DELAY = 120; + +function fileNodeAt(nodes: readonly FileTreeNode[], key: string): FileTreeNode | null { + for (const n of nodes) { + if (n.key === key) return n.file ? n : null; + if (!n.file) { + const hit = fileNodeAt(n.children, key); + if (hit) return hit; + } + } + return null; +} + +/** + * The selected commits' changes: one commit's files against its first parent, or, for several + * (IDEA), their combined changes with every selected commit listed below. + */ +export function CommitDetails({ commits }: { commits: Commit[] }) { + const scope = useContext(LogIdContext); + const [menuBelow, dropdown] = useDropdownMenu(); + const shown = useGitLog((s) => s.shownLog); + const active = !scope || scope === shown; + const readOnly = useReadOnlyLog(); + const selected = useGitLog((s) => s.selected); + const selection = useGitLog((s) => s.selection); + // Newest first (log order). + const chosen = useMemo(() => { + const ids = new Set(selection); + return commits.filter((c) => ids.has(commitKey(c))); + }, [commits, selection]); + const commit = selected ? commits.find((c) => commitKey(c) === selected) : undefined; + const many = chosen.length > 1; + const idsKey = chosen.map(commitKey).join(" "); + const commitRoot = commit ? commitRepo(commit) : null; + const [result, setResult] = useState<{ + key: string; + files: LogChange[] | null; + error: string | null; + } | null>(null); + const [expanded, setExpanded] = useState | null>(null); + const [parentIndex, setParentIndex] = useState(-1); + const fromParents = useLogOptions((s) => s.changesFromParents); + const onlyAffected = useLogOptions((s) => s.showOnlyAffected); + const preview = useLogOptions((s) => s.diffPreview); + const savedLocation = useLogOptions((s) => s.diffLocation); + // The modal commit interface keeps diffs out of editor tabs (#1863): the "Editor" + // preview shows beside the changes instead. + const modal = useWorkflowSettings((s) => !s.vcs.commit.nonModal); + const diffLocation = modal && savedLocation === "editor" ? "right" : savedLocation; + const showLineStats = useLogOptions((s) => s.showLineStats); + const filters = useGitLog((s) => s.filters); + const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, showLineStats]); + const files = result?.key === filesKey ? result.files : null; + const error = result?.key === filesKey ? result.error : null; + + useEffect(() => { + if (!idsKey) return; + let alive = true; + const load = (async () => { + if (many) { + const roots = [...new Set(chosen.map(commitRepo))]; + return ( + await Promise.all( + roots.map(async (repo) => { + const group = chosen.filter((c) => commitRepo(c) === repo); + const files = await call( + commands.vcsCommitsChanges(repo ?? currentRepo(), group.map((c) => c.id).reverse()), + ); + return toLogChanges(files, null, repo, readOnly); + }), + ) + ).flat(); + } + const c = chosen[0]!; + if (c.parents.length > 1) { + const groups = await Promise.all( + c.parents.map(async (id, index) => { + const files = await call(commands.vcsDiffRevisions(commitRoot ?? currentRepo(), id, c.id)); + return toLogChanges(files, { ...c, parents: [id] }, commitRoot, readOnly).map((f) => ({ + ...f, + group: `${tx("Parent")} ${index + 1}: ${id.slice(0, 8)}`, + })); + }), + ); + if (fromParents) return parentIndex < 0 ? groups.flat() : (groups[parentIndex] ?? []); + // A merge's combined changes are files changed against every parent. + return groups[0]! + .filter((f) => groups.every((group) => group.some((x) => x.path === f.path))) + .map((f) => ({ + ...f, + group: undefined, + mergeParents: c.parents + .slice(0, 2) + .map((rev, i) => ({ rev, path: groups[i]!.find((x) => x.path === f.path)?.oldPath ?? f.path })), + })); + } + const files = await call(commands.vcsCommitFiles(commitRoot ?? currentRepo(), c.id)); + return toLogChanges(files, c, commitRoot, readOnly); + })(); + load + .then((files) => (showLineStats ? withLineStats(files).catch(() => files) : files)) + .then((files) => alive && setResult({ key: filesKey, files, error: null })) + .catch( + (e) => alive && setResult({ key: filesKey, files: null, error: e instanceof Error ? e.message : String(e) }), + ); + return () => { + alive = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [idsKey, fromParents, parentIndex, commitRoot, filesKey, many, readOnly, showLineStats]); + + const groupByDirectory = useLogOptions((s) => s.groupByDirectory); + const [selectedKeys, setSelectedKeys] = useState>(() => new Set()); + const treeRef = useRef(null); + const [diffToReveal, setDiffToReveal] = useState<{ key: string } | null>(null); + const syncingDiff = useRef(false); + const changes = useMemo(() => { + const changes = files ?? []; + const paths = filters.paths?.length ? filters.paths : filters.path ? [filters.path] : []; + return onlyAffected && paths.length + ? changes.filter((c) => + paths.some((p) => { + const matches = (rel: string) => { + const abs = absolutePath(rel, c.repo); + return abs === p || abs.startsWith(`${p}/`) || (!many && commit?.historyPath === rel); + }; + return matches(c.path) || (c.oldPath != null && matches(c.oldPath)); + }), + ) + : changes; + }, [files, commit, many, filters.path, filters.paths, onlyAffected]); + const lineTotals = useMemo(() => { + if (!showLineStats || !changes.length) return null; + if (changes.some((f) => f.added === undefined || f.removed === undefined)) return null; + return changes.reduce((sum, f) => ({ added: sum.added + f.added!, removed: sum.removed + f.removed! }), { + added: 0, + removed: 0, + }); + }, [changes, showLineStats]); + const multipleRoots = new Set(chosen.map(commitRepo)).size > 1; + const changeTreePath = useCallback( + (f: LogChange) => `${multipleRoots ? `${repoName(f.repo ?? "")}/` : ""}${f.group ? `${f.group}/` : ""}${f.path}`, + [multipleRoots], + ); + const tree = useMemo( + () => (groupByDirectory ? buildFileTree(changes, changeTreePath) : flatFileNodes(changes, changeTreePath)), + [changes, groupByDirectory, changeTreePath], + ); + const allDirs = useMemo(() => dirKeys(tree), [tree]); + const ordered = useMemo(() => filesUnder(tree), [tree]); + const chosenChanges = useMemo(() => filesUnder(tree, selectedKeys), [tree, selectedKeys]); + + // Show Diff Preview: a single selected file follows into the editor's preview tab. + const previewTimer = useRef | undefined>(undefined); + useEffect(() => { + if (!active) clearTimeout(previewTimer.current); + return () => clearTimeout(previewTimer.current); + }, [active]); + const previewSelection = (sel: ReadonlySet) => { + clearTimeout(previewTimer.current); + if (syncingDiff.current || sel.size !== 1) return; + // While the editor shows one of this pane's diffs, the selection walks it along (a click or + // arrow key), as in the Commit window. + const shown = maybeEditorService()?.activeInput?.(); + const following = shown?.kind === DIFF_KIND && ordered.some((c) => diffInput(c.diff).key === shown.key); + if (!following && (!logOptions().diffPreview || logOptions().diffLocation !== "editor" || vcsDiffInFront())) return; + const file = fileNodeAt(tree, [...sel][0]!)?.file; + // A preview that cannot open (no editor yet, the file went away) is just skipped. + if (file) + previewTimer.current = setTimeout(() => void showChangesDiff([file], true).catch(() => undefined), PREVIEW_DELAY); + }; + + // Follow only this pane's exact diff (path AND revisions); another commit or + // Compare with Local must not move its selection. Never take focus from F7. + useEffect(() => { + const editor = maybeEditorService(); + const followDiff = (input: EditorInput | null) => { + if (input?.kind !== DIFF_KIND) return; + const change = ordered.find((c) => diffInput(c.diff).key === input.key); + if (!change) return; + clearTimeout(previewTimer.current); + const rel = changeTreePath(change); + setExpanded((current) => { + const next = new Set(current ?? allDirs); + for (const key of allDirs) if (rel.startsWith(key.slice(2) + "/")) next.add(key); + return next; + }); + setDiffToReveal({ key: `f:${rel}` }); + }; + followDiff(editor?.activeInput?.() ?? null); + return editor?.onActiveInputChange?.(followDiff); + }, [ordered, allDirs, changeTreePath]); + + // Tree.reveal needs the expanded rows to have rendered. Suppress the reverse + // preview update so it cannot reopen the diff and lose its requested chunk. + useLayoutEffect(() => { + if (!diffToReveal) return; + syncingDiff.current = true; + treeRef.current?.reveal(diffToReveal.key); + syncingDiff.current = false; + }, [diffToReveal]); + + useEffect(() => { + if (!active) return; + useLogChanges.setState({ commits: chosen, all: ordered, selected: chosenChanges }); + }, [chosen, ordered, chosenChanges, active]); + useEffect( + () => () => { + if (!scope || useGitLog.getState().shownLog === scope) + useLogChanges.setState({ commits: [], all: [], selected: [] }); + }, + [scope], + ); + useEffect(() => () => setContext("vcsLogChangesFocus", false), []); + + if (!commit) + return ( +
+ + Select a commit to view changes + +
+ ); + + const openViewOptions = (e: ReactMouseEvent) => + menuBelow(e, [ + { kind: "header", label: "Group By" }, + { kind: "action", action: "vcs.log.changes.groupByDirectory" }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.changes.diffPreview" }, + toggle("Show Only Affected Changes", logOptions(), "showOnlyAffected"), + toggle("Show lines added and deleted", logOptions(), "showLineStats"), + toggle("Show Changes from Parents", logOptions(), "changesFromParents"), + { + label: "Diff Preview Location", + submenu: (["editor", "right", "bottom"] as const).map((location) => ({ + label: location === "editor" ? "Editor" : location === "right" ? "Right" : "Bottom", + checked: savedLocation === location, + run: () => updateLogOptions({ diffLocation: location }), + })), + }, + ]); + + const onFileMenu = (node: FileTreeNode | null, sel: ReadonlySet, e: ReactMouseEvent) => { + if (!node) return; + const target = sel.has(node.key) ? filesUnder(tree, sel) : filesUnder([node]); + if (!target.length) return; + e.preventDefault(); + showContextMenu(e, changesMenu(target)); + }; + + const details = ( + + +
setContext("vcsLogChangesFocus", true)} + onBlurCapture={(e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setContext("vcsLogChangesFocus", false); + }} + > +
+ + c.repo)).size > 1} + /> + + {!many && fromParents && commit.parents.length > 1 && ( + + )} + + {files ? fileCount(changes.length) : ""} + {many ? " " + tx`in ${chosen.length} commits` : ""} + + {lineTotals && } + + setExpanded(new Set(allDirs))} + /> + setExpanded(new Set())} + /> +
+ {error &&
{error}
} + {!files && !error && ( +
+ +
+ )} + {files && ( + > + handleRef={treeRef} + roots={tree} + getKey={(n) => n.key} + getLabel={(n) => n.name} + getChildren={(n) => (n.file ? undefined : n.children)} + isExpandable={(n) => !n.file} + expanded={expanded ?? new Set(allDirs)} + onExpandedChange={(next) => setExpanded(next)} + selected={selectedKeys} + onSelectionChange={(sel) => { + setSelectedKeys(sel); + previewSelection(sel); + }} + renderNode={(n) => } + onActivate={(n) => n.file && void showChangesDiff([n.file])} + onJumpToSource={(n, sel) => { + const files = sel.has(n.key) ? filesUnder(tree, sel) : filesUnder([n]); + void executeAction("vcs.log.changes.jumpToSource", files); + }} + onContextMenu={onFileMenu} + aria-label="Changed files" + className={styles.fileTree} + /> + )} +
+
+ + +
+ {many ? ( + chosen.map((c) => ) + ) : ( + + )} +
+
+
+ ); + const embedded = preview && diffLocation !== "editor"; + const selectedChange = chosenChanges.length === 1 ? chosenChanges[0] : undefined; + return ( +
+ {dropdown} + {embedded ? ( + + + {details} + + + + {selectedChange ? ( + selectedChange.mergeParents?.length === 2 && selectedChange.after ? ( + + ) : ( + + ) + ) : ( + + Select a file to preview its changes + + )} + + + ) : ( + details + )} +
+ ); +} + +/** IDEA's changes browser context menu in the Git Log; `changes` = the files it acts on. */ +export function changesMenu(changes: LogChange[]): MenuItem[] { + const one = changes.length === 1 ? changes[0]! : null; + return [ + { kind: "action", action: "vcs.log.changes.showDiff", arg: changes }, + { kind: "action", action: "vcs.log.changes.compareWithLocal", arg: changes, disabled: !one?.after || one.readOnly }, + { + kind: "action", + action: "vcs.log.changes.compareBeforeWithLocal", + arg: changes, + disabled: !one?.before || one.readOnly, + }, + { kind: "separator" }, + { + kind: "action", + action: "vcs.log.changes.jumpToSource", + arg: changes, + disabled: !changes.some((c) => c.after && !c.readOnly), + }, + { kind: "separator" }, + { + kind: "action", + action: "vcs.log.changes.revert", + arg: changes, + disabled: changes.some((c) => c.readOnly) || new Set(changes.map((c) => c.repo)).size > 1, + }, + { + kind: "action", + action: "vcs.log.changes.getFromRevision", + arg: changes, + disabled: changes.some((c) => c.readOnly), + }, + { kind: "separator" }, + ...(one?.readOnly + ? [{ label: "Show History for File", run: () => openLogTab("history", absolutePath(one.path, one.repo)) }] + : [ + { + kind: "action", + action: "vcs.showHistory", + arg: one ? absolutePath(one.path, one.repo) : undefined, + disabled: !one?.after, + } satisfies MenuItem, + ]), + ]; +} + +function lineCount(file: ChangedFile | LogChange): { added: number; removed: number } | null { + if (!("added" in file) || typeof file.added !== "number" || typeof file.removed !== "number") return null; + return { added: file.added, removed: file.removed }; +} + +/** Sum of a directory once every file under it has counts; otherwise the row stays without them. */ +function nodeLineCount(node: FileTreeNode): { added: number; removed: number } | null { + if (node.file) return lineCount(node.file); + let added = 0; + let removed = 0; + for (const child of node.children) { + const count = nodeLineCount(child); + if (!count) return null; + added += count.added; + removed += count.removed; + } + return node.children.length ? { added, removed } : null; +} + +function LineStats({ added, removed }: { added: number; removed: number }) { + return ( + + + +{added} + + + −{removed} + + + ); +} + +function ChangedFileRow({ node, flat = false }: { node: FileTreeNode; flat?: boolean }) { + const stats = nodeLineCount(node); + if (!node.file) + return ( + + + {node.name} + {fileCount(node.count)} + {stats && } + + ); + const f = node.file; + const kind: EffectiveKind = f.kind === "untracked" ? "added" : f.kind; + return ( + + + + {node.name} + + {flat && dirName(f.path) && {dirName(f.path)}} + {f.oldPath && {renameFrom(f.path, f.oldPath)}} + {stats && } + + ); +} diff --git a/src/features/vcs/log/CommitList.tsx b/src/features/vcs/log/CommitList.tsx new file mode 100644 index 000000000..aae07e850 --- /dev/null +++ b/src/features/vcs/log/CommitList.tsx @@ -0,0 +1,622 @@ +import type { Commit } from "@/bindings"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Scrollbar, Spinner, T, hideNativeScrollbar } from "@/ui"; +import { useGitLogChecks } from "@/workbench/contributions"; +import { useVirtualizer } from "@tanstack/react-virtual"; +import clsx from "clsx"; +import { + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + type KeyboardEvent, + type MouseEvent as ReactMouseEvent, +} from "react"; +import styles from "../GitLog.module.css"; +import { reachableFrom } from "../graph"; +import { LogIdContext } from "../logContext"; +import { loadLogDetails } from "../logDetails"; +import { useLogOptions } from "../logOptions"; +import { presentLogGraph } from "../logPresentation"; +import { nextSpeedMatch } from "../logSearch"; +import { + PAGE, + extendCommitSelection, + goToChild, + goToParent, + goToRef, + isMine, + loadMore, + loadNewer, + selectCommit, + toggleCommitSelection, + useGitLog, +} from "../logStore"; +import { formatTime } from "../model"; +import { commitKey, commitRepo, graphCommit, type RepoCommit } from "../multiRoot"; +import { currentRepo, currentRepoRoot, useVcs } from "../store"; +import { ColumnHeaders } from "./ColumnHeaders"; +import { CommitSignature } from "./CommitMessage"; +import { CommitRow } from "./CommitRow"; +import { LANE, ROW, type LogColumn, type RowEvents } from "./shared"; + +const remoteNameSets = new WeakMap>(); + +/** A commit's own remote names (multi-root logs) as one set per array, else the shared one. */ +function rowRemoteNames(own: readonly string[] | undefined, shared: ReadonlySet): ReadonlySet { + if (!own) return shared; + let set = remoteNameSets.get(own); + if (!set) remoteNameSets.set(own, (set = new Set(own))); + return set; +} + +export function CommitList() { + const scope = useContext(LogIdContext); + const shown = useGitLog((s) => s.shownLog); + const active = !scope || scope === shown; + const all = useGitLog((s) => s.commits); + const selection = useGitLog((s) => s.selection); + const earlier = useMemo(() => { + const seen = new Set(); + return all.some((c) => { + const repo = commitRepo(c); + if (seen.has(repo)) return false; + seen.add(repo); + return (c.logPosition ?? 0) > 0; + }); + }, [all]); + const opts = useLogOptions(); + const ChecksCell = useGitLogChecks((s) => s.cell); + const bookmarks = useGitLog((s) => s.bookmarks); + const fragments = useGitLog((s) => s.fragments); + const { expanded: expandedFragments, collapsed: collapsedFragments, merges: expandedMerges } = fragments; + const [hoverColor, setHoverColor] = useState(null); + const [boundaryTitles, setBoundaryTitles] = useState>(() => new Map()); + const boundaryRequests = useRef(new Set()); + const [speedSearch, setSpeedSearch] = useState(""); + const speedGeneration = useRef(0); + const speedTimer = useRef | undefined>(undefined); + useEffect(() => () => clearTimeout(speedTimer.current), []); + const columns = useMemo(() => { + const builtins: LogColumn[] = [ + ...(opts.showAuthor ? [{ id: "author", title: "Author", width: 130, render: (c: Commit) => c.author }] : []), + ...(opts.showDate + ? [ + { + id: "date", + title: "Date", + // Fits a 12-hour date and time ("11/05/2026 02:30 PM", "Yesterday 09:07 AM"). + width: 140, + render: (c: Commit) => formatTime(opts.commitTimestamp ? (c.commitTimeMs ?? c.timeMs) : c.timeMs), + }, + ] + : []), + ...(opts.showHash ? [{ id: "hash", title: "Hash", width: 72, render: (c: Commit) => c.shortId }] : []), + ...(opts.showSignature + ? [{ id: "signature", title: "Signature", width: 100, render: (c: Commit) => }] + : []), + ...(opts.showGitHubChecks && ChecksCell + ? [ + { + id: "github-checks", + title: "GitHub Commit Checks", + width: 44, + render: (c: Commit) => { + const root = commitRepo(c) ?? currentRepoRoot(); + return root && !(c as RepoCommit).readOnly ? : null; + }, + }, + ] + : []), + ]; + const order = [...new Set([...opts.columnOrder, ...builtins.map((c) => c.id)])]; + return builtins.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id)); + }, [ + opts.showAuthor, + opts.showDate, + opts.showHash, + opts.showSignature, + opts.showGitHubChecks, + opts.commitTimestamp, + opts.columnOrder, + ChecksCell, + ]); + const user = useGitLog((s) => s.user); + const headCommit = useVcs((s) => s.branch?.headCommit ?? null); + const branches = useVcs((s) => s.branches); + const remoteNames = useMemo(() => new Set(branches.filter((b) => b.remote).map((b) => b.name)), [branches]); + // Date, No Merges and First Parent are applied by the backend with parent rewriting, + // so the graph stays connected under them. + const heads = useVcs((s) => s.heads); + const headKeys = useMemo( + () => + new Set( + all + .filter( + (c) => c.refs.includes("HEAD") || c.id === (commitRepo(c) ? heads[commitRepo(c)!]?.headCommit : headCommit), + ) + .map(commitKey), + ), + [all, heads, headCommit], + ); + const keep = useMemo( + () => + opts.collapseLinear || fragments.collapsed.size + ? new Set([...headKeys, ...selection, ...Object.keys(bookmarks)]) + : null, + [opts.collapseLinear, fragments.collapsed, headKeys, selection, bookmarks], + ); + const { + commits, + rows, + linear, + collapsed, + graph: displayedGraph, + } = useMemo(() => presentLogGraph(all, opts, fragments, keep ?? new Set()), [all, opts, fragments, keep]); + const { edges: highlighted, nodes: highlightedNodes } = useMemo(() => { + const empty = { edges: new Set(), nodes: new Set() }; + if (!hoverColor) return empty; + const nodeId = hoverColor.startsWith("node:") ? hoverColor.slice(5) : null; + const merge = nodeId ?? linear?.fragments.get(hoverColor); + const fragment = merge ? linear?.nodes.get(merge) : null; + const nodes = new Set(fragment); + if (!fragment) { + const source = nodeId + ? displayedGraph.find((c) => c.id === nodeId) + : displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === hoverColor)); + const target = source?.parents.find((p) => nodeId || `${source.id}\0${p}` === hoverColor); + if (source) nodes.add(source.id); + const byId = new Map(displayedGraph.map((c) => [c.id, c])); + const children = new Map(); + for (const c of displayedGraph) for (const p of c.parents) children.set(p, (children.get(p) ?? 0) + 1); + for (let current = target; current && !nodes.has(current);) { + nodes.add(current); + const c = byId.get(current); + if (!c || c.parents.length !== 1 || children.get(current) !== 1 || c.refs?.length || headKeys.has(current)) + break; + current = c.parents[0]; + } + } + return { + nodes, + edges: new Set( + displayedGraph.flatMap((c) => + nodes.has(c.id) ? c.parents.filter((p) => nodes.has(p)).map((p) => `${c.id}\0${p}`) : [], + ), + ), + }; + }, [hoverColor, linear, displayedGraph, headKeys]); + const minWidth = useMemo( + () => + rows.reduce((width, row) => Math.max(width, row.width * LANE), 100) + + columns.reduce( + (width, column) => width + (opts.columnWidths[column.id] ?? column.width ?? 120), + opts.showRepository && useVcs.getState().roots.length > 1 ? 220 : 120, + ), + [rows, columns, opts.columnWidths, opts.showRepository], + ); + const filterBranches = useGitLog((s) => s.filters.branches); + const currentBranch = useVcs((s) => s.branch?.head ?? null); + // Nothing to tell apart when the log is filtered to the current branch. + const onlyCurrent = filterBranches.length > 0 && filterBranches.every((b) => b === "HEAD" || b === currentBranch); + const onBranch = useMemo(() => { + if (!opts.highlightCurrentBranch || onlyCurrent) return null; + const reach = all.some((c) => c.onCurrentBranch == null) + ? reachableFrom(all.map(graphCommit), headKeys) + : new Set(); + for (const c of all) { + if (c.onCurrentBranch === true) reach.add(commitKey(c)); + else if (c.onCurrentBranch === false) reach.delete(commitKey(c)); + } + return reach; + }, [all, headKeys, opts.highlightCurrentBranch, onlyCurrent]); + const loading = useGitLog((s) => s.loading); + const done = useGitLog((s) => s.done); + const error = useGitLog((s) => s.error); + const selected = useGitLog((s) => s.selected); + const selectedSet = useMemo(() => new Set(selection), [selection]); + const revealTick = useGitLog((s) => s.revealTick); + const scrollRef = useRef(null); + const selectedIndex = useMemo( + () => (selected ? commits.findIndex((c) => commitKey(c) === selected) : -1), + [commits, selected], + ); + const lastRevealed = useRef(0); + // Recycled rows can emit enter events without the pointer moving. + const hoverPointer = useRef<{ x: number; y: number } | null>(null); + const previousRows = useRef(commits); + useLayoutEffect(() => { + const element = scrollRef.current; + const previous = previousRows.current; + previousRows.current = commits; + if (!element || previous === commits || (revealTick !== lastRevealed.current && selectedIndex >= 0)) return; + const top = Math.max(0, Math.floor((element.scrollTop - ROW) / ROW)); + // Preserve the first surviving visible commit and its pixel offset. + for (let i = top; i < previous.length; i++) { + const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!)); + if (next < 0) continue; + element.scrollTop += (next - i) * ROW; + break; + } + }, [commits, revealTick, selectedIndex]); + const finished = done; + const virtualizer = useVirtualizer({ + count: commits.length + (finished ? 0 : 1), + getScrollElement: () => scrollRef.current, + estimateSize: () => ROW, + overscan: 8, + scrollMargin: ROW, + }); + const items = virtualizer.getVirtualItems(); + const last = items[items.length - 1]; + + // The next page is requested while a page of rows is still ahead, so scrolling + // quickly doesn't reach the end before `git log` answers. + useEffect(() => { + if (!finished && !loading && last && last.index >= commits.length - PAGE) void loadMore(scope ?? undefined); + }, [last, commits.length, finished, loading, active, scope]); + + useLayoutEffect(() => { + if (revealTick === lastRevealed.current || selectedIndex < 0) return; + lastRevealed.current = revealTick; + virtualizer.scrollToIndex(selectedIndex, { align: "center" }); + }, [revealTick, selectedIndex, virtualizer]); + + const visible = useRef(commits); + visible.current = commits; + const pick = useCallback((id: string, e: ReactMouseEvent) => { + if (e.button === 2) { + if (!useGitLog.getState().selection.includes(id)) selectCommit(id); + } else if (e.button !== 0) return; + else if (e.shiftKey) extendCommitSelection(id, visible.current); + else if (e.metaKey || e.ctrlKey) toggleCommitSelection(id); + else selectCommit(id); + }, []); + // CommitRow is memoized: rows get handlers that stay the same across renders and + // call this render's (assigned before rendering). + const rowEvents = useRef(null); + const rowHandlers = useMemo( + () => ({ + onHover: (edge) => rowEvents.current?.onHover(edge), + onFragment: (from, target, expand) => rowEvents.current?.onFragment(from, target, expand), + onNavigate: (index, key) => rowEvents.current?.onNavigate(index, key), + }), + [], + ); + // Called while a row renders its graph, so it changes with what it reads. + const targetTitle = useCallback( + (index: number, key?: string) => { + const target = commits[index]; + return target + ? `${target.shortId} ${target.summary} — ${target.author}` + : (key && boundaryTitles.get(key)) || + `${tx("Commit is outside the loaded history")} · ${key?.split("\0").at(-1)?.slice(0, 8) ?? ""}`; + }, + [commits, boundaryTitles], + ); + + const onKeyDown = (e: KeyboardEvent) => { + if (!e.ctrlKey && !e.metaKey && !e.altKey && (e.key.length === 1 || e.key === "Backspace" || e.key === "Escape")) { + const query = e.key === "Escape" ? "" : e.key === "Backspace" ? speedSearch.slice(0, -1) : speedSearch + e.key; + setSpeedSearch(query); + speedGeneration.current++; + clearTimeout(speedTimer.current); + speedTimer.current = setTimeout(() => setSpeedSearch(""), 1500); + if (query) { + const found = nextSpeedMatch(commits, query, opts, -1); + if (found >= 0) { + selectCommit(commitKey(commits[found]!), true); + virtualizer.scrollToIndex(found, { align: "auto" }); + } else if (query.length >= 2) { + const generation = ++speedGeneration.current; + const roots = [...new Set(all.map(commitRepo))]; + void Promise.all( + roots.map(async (repo) => { + const [hit] = await call( + commands.vcsLog(repo ?? currentRepo(), { + skip: 0, + limit: 1, + summaryOnly: true, + speedSearch: query, + searchFields: [...(opts.showAuthor ? ["author"] : []), ...(opts.showHash ? ["hash"] : [])], + branch: null, + path: null, + author: null, + text: null, + }), + ); + return hit ? { ...hit, repo } : null; + }), + ) + .then((hits) => { + const hit = hits.find(Boolean); + if (hit && speedGeneration.current === generation) void goToRef(hit.id, commitRepo(hit)); + }) + .catch(() => undefined); + } + } + e.preventDefault(); + return; + } + if (speedSearch && (e.key === "F3" || e.key === "Enter")) { + e.preventDefault(); + const found = nextSpeedMatch(commits, speedSearch, opts, selectedIndex, e.shiftKey ? -1 : 1); + if (found >= 0) selectCommit(commitKey(commits[found]!), true); + return; + } + const lead = selectedIndex >= 0 ? commits[selectedIndex] : undefined; + if (lead && (e.key === "ArrowLeft" || e.key === "ArrowRight") && !e.altKey && !e.metaKey && !e.ctrlKey) { + e.preventDefault(); + if (e.key === "ArrowLeft") goToChild(lead); + else void goToParent(lead); + return; + } + let next: number; + if (e.key === "ArrowDown") next = Math.min(commits.length - 1, selectedIndex + 1); + else if (e.key === "ArrowUp") next = Math.max(0, selectedIndex - 1); + else if (e.key === "Home") next = 0; + else if (e.key === "End") next = commits.length - 1; + else if (e.key === "PageDown") next = Math.min(commits.length - 1, selectedIndex + 20); + else if (e.key === "PageUp") next = Math.max(0, selectedIndex - 20); + else return; + e.preventDefault(); + const c = commits[next]; + if (c) { + if (e.shiftKey) extendCommitSelection(commitKey(c), commits); + else selectCommit(commitKey(c)); + virtualizer.scrollToIndex(next, { align: "auto" }); + } + }; + + if (error && !commits.length) return
{error}
; + + const fragment = (from: string, target: string, expand: boolean) => { + if (from === target && (expandedMerges.has("*") ? !expandedMerges.has(from) : expandedMerges.has(from))) { + useGitLog.setState({ + fragments: { + ...fragments, + merges: expandedMerges.has("*") + ? new Set([...expandedMerges, from]) + : new Set([...expandedMerges].filter((id) => id !== from)), + }, + }); + return; + } + if ( + from === target && + linear && + all.find((c) => commitKey(c) === from)?.parents.length === 2 && + linear.graph.find((c) => c.id === from)?.parents.length === 1 + ) { + useGitLog.setState({ + fragments: { + ...fragments, + merges: expandedMerges.has("*") + ? new Set([...expandedMerges].filter((id) => id !== from)) + : new Set([...expandedMerges, from]), + }, + }); + return; + } + if (from === target) { + const shown = (linear?.graph ?? collapsed?.graph ?? all.map(graphCommit)).find((c) => c.id === from); + target = shown?.parents[0] ?? target; + expand = !!shown?.dashed?.[0]; + } + const merge = linear?.fragments.get(`${from}\0${target}`); + if (merge) { + useGitLog.setState({ + fragments: { + ...fragments, + merges: expandedMerges.has("*") + ? new Set([...expandedMerges].filter((id) => id !== merge)) + : new Set([...expandedMerges, merge]), + }, + }); + return; + } + const graph = new Map( + all.map((c) => { + const g = graphCommit(c); + return [g.id, g] as const; + }), + ); + const childCounts = new Map(); + for (const c of graph.values()) + for (const parent of c.parents) childCounts.set(parent, (childCounts.get(parent) ?? 0) + 1); + const hidden: string[] = []; + for (const start of expand ? (graph.get(from)?.parents ?? []) : [target]) { + const chain: string[] = []; + let current: string | undefined = start; + const seen = new Set(); + while (current && !seen.has(current)) { + seen.add(current); + const node = graph.get(current); + if ( + !node || + (expand && current === target) || + node.parents.length !== 1 || + childCounts.get(current) !== 1 || + node.refs.length || + headKeys.has(current) + ) + break; + chain.push(current); + current = node.parents[0]; + } + if (!expand || current === target) hidden.push(...chain); + } + if (expand) { + useGitLog.setState({ + fragments: { + ...fragments, + expanded: new Set([...expandedFragments, ...hidden]), + collapsed: new Set([...collapsedFragments].filter((id) => !hidden.includes(id))), + }, + }); + } else { + useGitLog.setState({ + fragments: { + ...fragments, + expanded: new Set([...expandedFragments].filter((id) => !hidden.includes(id))), + collapsed: new Set([...collapsedFragments, ...hidden]), + }, + }); + } + }; + + rowEvents.current = { + onHover: (edge) => { + if ( + edge === hoverColor || + (edge && (virtualizer.isScrolling || scrollRef.current?.hasAttribute("data-hover-paused"))) + ) + return; + setHoverColor(edge); + if (!edge) return; + const source = displayedGraph.find((c) => c.parents.some((p) => `${c.id}\0${p}` === edge)); + const target = source?.parents.find((p) => `${source.id}\0${p}` === edge); + if (!source || !target || commits.some((c) => commitKey(c) === target) || boundaryRequests.current.has(target)) + return; + const original = all.find((c) => commitKey(c) === source.id); + if (!original) return; + boundaryRequests.current.add(target); + const split = target.lastIndexOf("\0"), + id = target.slice(split + 1); + void loadLogDetails({ ...original, id }) + .then((details) => + setBoundaryTitles((current) => + new Map(current).set(target, `${id.slice(0, 8)} ${details.message.split("\n")[0]}`), + ), + ) + .catch(() => undefined); + }, + onFragment: fragment, + onNavigate: (index, key) => { + const target = commits[index]; + if (target) selectCommit(commitKey(target), true); + else if (key) { + const split = key.lastIndexOf("\0"); + void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : currentRepo()); + } + }, + }; + + return ( +
+ {earlier && ( + + )} + {speedSearch && ( +
+ {speedSearch} +
+ )} + {error && ( +
+ {error} +
+ )} + +
= 0 ? `commit-${scope ?? "log"}-${selectedIndex}` : undefined} + tabIndex={0} + onScroll={(e) => { + if (!e.currentTarget.hasAttribute("data-hover-paused")) e.currentTarget.dataset.hoverPaused = ""; + setHoverColor(null); + }} + onPointerMoveCapture={(e) => { + const previous = hoverPointer.current; + hoverPointer.current = { x: e.clientX, y: e.clientY }; + if (!virtualizer.isScrolling && (!previous || previous.x !== e.clientX || previous.y !== e.clientY)) + delete e.currentTarget.dataset.hoverPaused; + }} + onPointerLeave={(e) => { + hoverPointer.current = { x: e.clientX, y: e.clientY }; + }} + onKeyDown={onKeyDown} + onCopy={(e) => { + if (window.getSelection()?.toString()) return; + const selected = commits.filter((c) => selectedSet.has(commitKey(c))); + if (!selected.length) return; + e.preventDefault(); + e.clipboardData.setData( + "text/plain", + selected + .map((c) => + [ + c.summary, + c.refs.join(" "), + ...(opts.showRepository ? [commitRepo(c) ?? ""] : []), + ...columns.map((column) => (typeof column.render(c) === "string" ? column.render(c) : "")), + ].join("\t"), + ) + .join("\n"), + ); + e.clipboardData.setData( + "application/x-openidea-vcs-commits", + JSON.stringify({ version: 1, commits: selected.map((c) => ({ root: commitRepo(c), hash: c.id })) }), + ); + }} + > + {opts.showColumnHeaders && } + {!commits.length && !loading && finished && ( +
{headCommit ? tx("No commits match the filters") : tx("No commits yet")}
+ )} +
+ {items.map((v) => { + const c = commits[v.index]; + if (!c) + return ( +
+ {" "} + + Loading… + +
+ ); + return ( + + ); + })} +
+
+
+ ); +} diff --git a/src/features/vcs/log/CommitMessage.tsx b/src/features/vcs/log/CommitMessage.tsx new file mode 100644 index 000000000..6d589372a --- /dev/null +++ b/src/features/vcs/log/CommitMessage.tsx @@ -0,0 +1,173 @@ +import type { Commit } from "@/bindings"; +import { writeClipboardText } from "@/platform/clipboard"; +import { tx } from "@/platform/i18n"; +import clsx from "clsx"; +import styles from "../GitLog.module.css"; +import { IssueText } from "../issueLinks"; +import { useCommitDetails } from "../logDetails"; +import { refLabels } from "../logOptions"; +import { goToRef } from "../logStore"; +import { commitRepo } from "../multiRoot"; +import { currentRepo } from "../store"; + +const REF_KIND_CLASS = { + head: styles.refHead, + local: styles.refLocal, + remote: styles.refRemote, + tag: styles.refTag, +}; + +const NO_REMOTES: ReadonlySet = new Set(); + +export function RefLabels({ + refs, + compact = false, + tagNames = true, + remoteNames = NO_REMOTES, + left = false, +}: { + refs: string[]; + compact?: boolean; + tagNames?: boolean; + remoteNames?: ReadonlySet; + left?: boolean; +}) { + const labels = refLabels(refs, { compact, tagNames }, remoteNames); + return ( + + {labels.map((l) => ( + + {l.text} + + ))} + + ); +} + +/** A commit's message and metadata; `compact` (one of several selected): without the body. */ +export function CommitMessage({ commit, compact = false }: { commit: Commit; compact?: boolean }) { + const { details, error } = useCommitDetails(commit, !compact); + const repo = commitRepo(commit) ?? currentRepo(); + const message = details?.message || commit.message; + const [subject, ...bodyLines] = message.replace(/\s+$/, "").split("\n"); + const body = compact ? "" : bodyLines.join("\n").replace(/^\n+/, ""); + return ( +
+
+ +
+ {body && ( +
+ +
+ )} +
+ {" "} + {commit.author} <{commit.email}> + {commit.timeMs ? " " + tx`on ${new Date(commit.timeMs).toLocaleString()}` : ""} +
+ {!compact && + commit.committer && + (commit.committer !== commit.author || + commit.committerEmail !== commit.email || + commit.commitTimeMs !== commit.timeMs) && ( +
+ {tx("Committed by")} {commit.committer} <{commit.committerEmail}>{" "} + {commit.commitTimeMs ? new Date(commit.commitTimeMs).toLocaleString() : ""} +
+ )} + {commit.parents.length > 0 && ( +
+ {tx(commit.parents.length > 1 ? "Merge of" : "Parent")}{" "} + {commit.parents.map((id, i) => ( + + {i > 0 ? ", " : ""} + + + ))} +
+ )} + {details && ( + <> +
+ {tx("Containing branches")}:{" "} + {details.containingBranches.length + ? details.containingBranches.map((branch, i) => ( + + {i > 0 ? ", " : ""} + + + )) + : tx("None")} +
+
+ {tx("Signature")}: {signatureLabel(details.signature)} + {details.signer ? ` · ${details.signer}` : ""} +
+ + )} + {error && ( +
+ {tx("Could not load containing branches or signature details")} +
+ )} + {commit.refs.length > 0 && ( +
+ +
+ )} +
+ ); +} + +function signatureLabel(code: string) { + return tx( + ( + { + G: "Verified", + U: "Good signature with unknown trust", + B: "Bad signature", + E: "Could not verify", + N: "Unsigned", + X: "Expired signature", + Y: "Expired signing key", + R: "Revoked signing key", + } as Record + )[code] ?? "Could not verify", + ); +} + +export function CommitSignature({ commit }: { commit: Commit }) { + const { details, error } = useCommitDetails(commit); + return ( + + {details ? signatureLabel(details.signature) : error ? tx("Could not verify") : tx("Loading…")} + + ); +} + +function CommitMessageText({ text, repo }: { text: string; repo: string | null | undefined }) { + return text.split(/\b([a-fA-F0-9]{7,64})\b/g).map((part, i) => + i % 2 ? ( + + ) : ( + + ), + ); +} diff --git a/src/features/vcs/log/CommitRow.tsx b/src/features/vcs/log/CommitRow.tsx new file mode 100644 index 000000000..668a14d92 --- /dev/null +++ b/src/features/vcs/log/CommitRow.tsx @@ -0,0 +1,201 @@ +import type { Commit } from "@/bindings"; +import { Icon, Popup, TOOLTIP_DELAY, showContextMenu } from "@/ui"; +import clsx from "clsx"; +import { memo, useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from "react"; +import styles from "../GitLog.module.css"; +import { type GraphRow } from "../graph"; +import { IssueText } from "../issueLinks"; +import { type LogOptions } from "../logOptions"; +import { selectedCommits } from "../logStore"; +import { commitKey, commitRepo } from "../multiRoot"; +import { repoName, useVcs } from "../store"; +import { CommitMessage, RefLabels } from "./CommitMessage"; +import { GraphCell } from "./GraphCell"; +import { commitMenu } from "./commitMenu"; +import { SUBJECT_COLUMN, columnSequence, type LogColumn } from "./shared"; + +function CommitRowView({ + id, + commit: c, + graph, + top, + selected, + head, + mine, + onBranch, + opts, + remoteNames, + onPick, + hoverColor, + highlighted, + highlightedNodes, + onHover, + onFragment, + onNavigate, + targetTitle, + columns, + bookmarked, + interactive, +}: { + id: string; + commit: Commit; + graph: GraphRow | undefined; + top: number; + selected: boolean; + head: boolean; + mine: boolean; + onBranch: boolean; + opts: LogOptions; + remoteNames: ReadonlySet; + onPick: (id: string, e: ReactMouseEvent) => void; + hoverColor: string | null; + highlighted: ReadonlySet; + highlightedNodes: ReadonlySet; + onHover: (color: string | null) => void; + onFragment: (from: string, target: string, expand: boolean) => void; + onNavigate: (index: number, key?: string) => void; + targetTitle: (index: number, key?: string) => string; + columns: LogColumn[]; + bookmarked: boolean; + /** False for rows rendered mid-scroll: their graph is drawn without hit targets. */ + interactive: boolean; +}) { + const merge = opts.highlightMerges && c.parents.length > 1; + const subjectRef = useRef(null); + const [tooltip, setTooltip] = useState(false); + const tooltipBody = useRef(null); + const tooltipTimer = useRef | undefined>(undefined); + useEffect(() => () => clearTimeout(tooltipTimer.current), []); + useEffect(() => { + if (!tooltip) return; + // Scrolling the log moves the anchor away; scrolling a long message inside the card doesn't. + const hide = (e: Event) => { + const card = tooltipBody.current?.closest("[data-popup]"); + if (e.target instanceof Node && card?.contains(e.target)) return; + setTooltip(false); + }; + window.addEventListener("scroll", hide, true); + return () => window.removeEventListener("scroll", hide, true); + }, [tooltip]); + const enterTooltip = () => { + clearTimeout(tooltipTimer.current); + if (tooltip || subjectRef.current?.closest("[data-hover-paused]")) return; + tooltipTimer.current = setTimeout(() => { + if (!subjectRef.current?.closest("[data-hover-paused]")) setTooltip(true); + }, TOOLTIP_DELAY); + }; + const leaveTooltip = () => { + clearTimeout(tooltipTimer.current); + tooltipTimer.current = setTimeout(() => setTooltip(false), 120); + }; + const refs = c.refs.length > 0 && ( + + ); + const subjectCell = ( + + {graph && ( + onFragment(source ?? commitKey(c), target, expand)} + onNode={() => onFragment(commitKey(c), commitKey(c), false)} + interactive={interactive} + /> + )} + {bookmarked && } + {opts.refsOnLeft && refs} + { + clearTimeout(tooltipTimer.current); + setTooltip(false); + }} + > + + + {!opts.refsOnLeft && refs} + setTooltip(false)} + className={styles.commitTooltip} + > +
clearTimeout(tooltipTimer.current)} onPointerLeave={leaveTooltip}> + +
+
+
+ ); + return ( +
{ + if (e.shiftKey) e.preventDefault(); // no text selection on range clicks + onPick(commitKey(c), e); + }} + onContextMenu={(e) => { + e.preventDefault(); + showContextMenu(e, commitMenu(c, selectedCommits())); + }} + > + {opts.showRepository && commitRepo(c) && useVcs.getState().roots.length > 1 && ( + + {repoName(commitRepo(c)!)} + + )} + {columnSequence(opts.columnOrder, columns).map((cid) => { + if (cid === SUBJECT_COLUMN.id) return subjectCell; + const column = columns.find((col) => col.id === cid); + if (!column) return null; + return ( + ` : undefined} + > + {column.render(c)} + + ); + })} +
+ ); +} + +// A row that is already interactive stays so when scrolling starts; only rows +// whose content changes mid-scroll are drawn without hit targets. +export const CommitRow = memo(CommitRowView, (prev, next) => { + for (const key in next) { + const k = key as keyof typeof next; + if (prev[k] !== next[k] && !(k === "interactive" && prev.interactive)) return false; + } + return true; +}); diff --git a/src/features/vcs/log/FilterBar.tsx b/src/features/vcs/log/FilterBar.tsx new file mode 100644 index 000000000..e9af6b6fd --- /dev/null +++ b/src/features/vcs/log/FilterBar.tsx @@ -0,0 +1,502 @@ +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { Icon, IconButton, SearchField, type MenuItem } from "@/ui"; +import clsx from "clsx"; +import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { BranchFilterPopup } from "../BranchFilterPopup"; +import { chooseDateRange, chooseMany } from "../dialogs"; +import styles from "../GitLog.module.css"; +import { LogIdContext } from "../logContext"; +import { useLogOptions, type LogOptions } from "../logOptions"; +import { + ME, + dateRangeLabel, + goToRef, + openLogTab, + recentFilterValues, + recentLogFilters, + reloadLog, + setLogBranches, + setLogFilters, + toggleRepository, + updateLogOptions, + useGitLog, +} from "../logStore"; +import { relTo } from "../model"; +import { branchesByRepo } from "../multiRoot"; +import { chooseLogPaths } from "../PathFilterDialog"; +import { openExternalLog } from "../RevisionBrowser"; +import { currentRepo, repoName, useVcs } from "../store"; +import { useDropdownMenu, useLogRepositories, useReadOnlyLog } from "./logHooks"; +import { toggle } from "./shared"; + +// --- filters ---------------------------------------------------------------- + +const DAY = 86_400_000; + +const DATE_OPTIONS: { label: string; days: number }[] = [ + { label: "Last 24 Hours", days: 1 }, + { label: "Last 7 Days", days: 7 }, + { label: "Last 30 Days", days: 30 }, + { label: "Last Year", days: 365 }, +]; + +interface LogFilter { + label: string; + value: string | null; + onOpen: (anchor: HTMLElement) => void; + onClear: () => void; +} + +function FilterButton({ label, value, onOpen, onClear, hidden }: LogFilter & { hidden?: boolean }) { + return ( + + ); +} + +export function FilterBar() { + const scope = useContext(LogIdContext); + const shown = useGitLog((s) => s.shownLog); + const active = !scope || scope === shown; + const logGeneration = useGitLog((s) => s.generation); + const filters = useGitLog((s) => s.filters); + const commits = useGitLog((s) => s.commits); + const selectedBranches = useVcs((s) => s.branches); + const [branches, setBranches] = useState(selectedBranches); + const version = useVcs((s) => s.version); + const root = useVcs((s) => s.root); + const repositories = useLogRepositories(); + const readOnly = useReadOnlyLog(); + const bookmarks = useGitLog((s) => s.bookmarks); + const showBranches = useLogOptions((s) => s.showBranches); + useEffect(() => { + let live = true; + const roots = filters.repositories?.length ? filters.repositories : repositories; + void branchesByRepo(roots) + .then((all) => { + if (live) + setBranches([ + ...new Map( + Object.values(all) + .flat() + .map((b) => [b.name, b]), + ).values(), + ]); + }) + .catch(() => undefined); + return () => { + live = false; + }; + }, [repositories, filters.repositories, version, logGeneration]); + const [text, setText] = useState(filters.text); + const [branchAnchor, setBranchAnchor] = useState(null); + const [menuBelow, dropdown] = useDropdownMenu(); + // Filters that do not fit move behind a chevron, like a toolbar's overflow. + const groupRef = useRef(null); + const [hiddenFrom, setHiddenFrom] = useState(Infinity); + useLayoutEffect(() => { + const group = groupRef.current; + if (!group) return; + const measure = () => { + const items = [...group.children] as HTMLElement[]; + const i = items.findIndex((el) => el.offsetLeft + el.offsetWidth > group.clientWidth + 1); + setHiddenFrom(i < 0 ? Infinity : i); + }; + measure(); + const ro = new ResizeObserver(measure); + ro.observe(group); + for (const el of group.children) ro.observe(el); + return () => ro.disconnect(); + }, [filters, repositories.length]); + + // Keep the field in sync when filters change elsewhere (Show History, reveal). + const [seen, setSeen] = useState(filters); + if (seen !== filters) { + setSeen(filters); + setText(filters.text); + } + + useEffect(() => { + if (!active || text === filters.text) return; + const t = setTimeout(() => setLogFilters({ text }), 300); + return () => clearTimeout(t); + }, [text, filters.text, active]); + + const branchNames = () => branches.filter((b) => !b.name.endsWith("/HEAD")).map((b) => b.name); + + const selectBranches = async () => { + setBranchAnchor(null); + const r = await chooseMany({ + title: "Filter by Branch", + options: [ + ...new Set([ + "HEAD", + ...branchNames(), + ...recentFilterValues("branches").flat(), + ...recentFilterValues("range").filter((s): s is string => !!s), + ]), + ], + initial: filters.branches, + customLabel: "Branches, patterns, exclusions or ranges (comma-separated):", + }); + if (r) setLogBranches(r); + }; + + const openUser = async (anchor: HTMLElement) => { + const roots = filters.repositories?.length + ? filters.repositories + : repositories.length + ? repositories + : [currentRepo()]; + const users = await Promise.all(roots.map((repo) => call(commands.vcsLogUsers(repo)).catch(() => [] as string[]))); + const authors = [...new Set(users.flat().concat(commits.map((c) => `${c.author} <${c.email}>`)))].sort((a, b) => + a.localeCompare(b), + ); + menuBelow(anchor, [ + ...recentFilterValues("authors").map((authors) => ({ + label: authors.join(", "), + run: () => setLogFilters({ authors }), + })), + { label: ME, checked: filters.authors.includes(ME), run: () => setLogFilters({ authors: [ME] }) }, + ...(authors.length ? [{ kind: "separator" as const }] : []), + ...authors.slice(0, 30).map((a) => ({ + label: a, + checked: filters.authors.includes(a), + run: () => setLogFilters({ authors: [a] }), + })), + { kind: "separator" }, + { + label: "Select…", + run: async () => { + const r = await chooseMany({ + title: "Filter by User", + options: [ME, ...authors], + initial: filters.authors, + customLabel: "Other names or emails (comma-separated):", + }); + if (r) setLogFilters({ authors: r }); + }, + }, + ]); + }; + + const openDate = (anchor: HTMLElement) => + menuBelow(anchor, [ + ...recentFilterValues("date") + .filter((date) => date != null) + .map((date) => ({ label: date.label, run: () => setLogFilters({ date }) })), + ...DATE_OPTIONS.map((o) => ({ + label: o.label, + checked: filters.date?.label === o.label, + run: () => setLogFilters({ date: { after: Date.now() - o.days * DAY, before: null, label: o.label } }), + })), + { kind: "separator" }, + { + label: "Select…", + run: async () => { + const r = await chooseDateRange(); + if (r) setLogFilters({ date: { ...r, label: dateRangeLabel(r.after, r.before) } }); + }, + }, + ]); + + const openPaths = (anchor: HTMLElement) => + menuBelow(anchor, [ + ...recentFilterValues("paths") + .filter((paths) => paths?.length) + .map((paths) => ({ label: paths!.join(", "), run: () => setLogFilters({ paths, path: null }) })), + { + label: "Select Folders…", + run: async () => { + const paths = await chooseLogPaths( + repositories.length ? repositories : root ? [root] : [], + filters.paths ?? (filters.path ? [filters.path] : []), + readOnly, + ); + if (paths) setLogFilters({ path: null, paths }); + }, + }, + ]); + + const logFilters: LogFilter[] = [ + ...(repositories.length > 1 + ? [ + { + label: "Repository", + value: filters.repositories?.map(repoName).join(", ") || null, + onOpen: (anchor: HTMLElement) => + menuBelow( + anchor, + repositories.map((repo) => ({ + label: repoName(repo), + checked: filters.repositories?.includes(repo) ?? false, + run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }), + })), + ), + onClear: () => setLogFilters({ repositories: [] }), + }, + ] + : []), + { + label: "Branch", + value: filters.range || filters.branches.join(", ") || null, + onOpen: (anchor: HTMLElement) => setBranchAnchor((open) => (open === anchor ? null : anchor)), + onClear: () => setLogBranches([]), + }, + { + label: "User", + value: filters.authors.join(", ") || null, + onOpen: openUser, + onClear: () => setLogFilters({ authors: [] }), + }, + { + label: "Date", + value: filters.date?.label ?? null, + onOpen: openDate, + onClear: () => setLogFilters({ date: null }), + }, + { + label: "Paths", + value: filters.paths?.length + ? filters.paths.map((p) => (root ? relTo(root, p) : p)).join(", ") + : filters.path + ? (root ? relTo(root, filters.path) : filters.path) || "." + : null, + onOpen: openPaths, + onClear: () => setLogFilters({ path: null, paths: [] }), + }, + ]; + + return ( +
+ {!showBranches && ( + + )} + setLogFilters({ regex }), + }, + { + id: "case", + icon: "case", + title: "Match Case", + pressed: filters.matchCase, + onToggle: (matchCase) => setLogFilters({ matchCase }), + }, + ]} + /> + + {logFilters.map((f, i) => ( + + {hiddenFrom < logFilters.length && ( + { + const anchor = e.currentTarget; + menuBelow( + anchor, + logFilters.slice(hiddenFrom).map((f) => ({ + label: f.value ? `${tx(f.label)}: ${f.value}` : f.label, + run: () => f.onOpen(anchor), + })), + ); + }} + /> + )} + {dropdown} + {branchAnchor && ( + setBranchAnchor(null)} + onSelect={(branch) => { + setLogBranches([branch]); + setBranchAnchor(null); + }} + onSelectMany={() => void selectBranches()} + /> + )} + + + menuBelow( + e, + Object.entries(bookmarks).map(([key, summary]) => ({ + label: summary, + run: () => { + const split = key.lastIndexOf("\0"); + void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined); + }, + })), + ) + } + /> + + menuBelow(e, [ + { + label: "In Tool Window", + run: () => { + openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`); + }, + }, + { + label: "In Editor", + run: () => { + openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor"); + }, + }, + { label: "External Repository…", run: openExternalLog }, + ]) + } + /> + + menuBelow( + e, + recentLogFilters().map((filters) => ({ + label: + [ + filters.range, + filters.branches.join(", "), + filters.authors.join(", "), + filters.text, + filters.path, + filters.paths?.join(", "), + filters.date?.label, + ] + .filter(Boolean) + .join(" · ") || tx("All commits"), + run: () => setLogFilters(filters), + })), + ) + } + /> + void reloadLog({ preserve: true })} /> + menuBelow(e, graphOptionsMenu(useLogOptions.getState()))} + /> + menuBelow(e, viewOptionsMenu(useLogOptions.getState()))} + /> + +
+ ); +} + +/** IDEA's Git Log › Graph Options (sort, first parent / no merges, linear branches). */ +export function graphOptionsMenu(o: LogOptions): MenuItem[] { + return [ + { kind: "header", label: "Sort" }, + { label: "By Commit Date", checked: o.sort === "date", run: () => updateLogOptions({ sort: "date" }) }, + { label: "Topologically", checked: o.sort === "topo", run: () => updateLogOptions({ sort: "topo" }) }, + { + label: "Incoming Commits First", + checked: o.sort === "standard", + run: () => updateLogOptions({ sort: "standard" }), + }, + { kind: "separator" }, + { kind: "header", label: "Options" }, + toggle("First Parent", o, "firstParent"), + toggle("No Merges", o, "noMerges"), + { + label: "Linearize Merges", + checked: o.linearizeMerges, + run: () => + updateLogOptions({ linearizeMerges: !o.linearizeMerges, ...(!o.linearizeMerges ? { sort: "standard" } : {}) }), + }, + { kind: "separator" }, + { kind: "header", label: "Branch Actions" }, + { kind: "action", action: "vcs.log.collapseLinear" }, + { kind: "action", action: "vcs.log.expandLinear" }, + ]; +} + +/** IDEA's Git Log › View Options (what rows show and highlight). */ +export function viewOptionsMenu(o: LogOptions): MenuItem[] { + return [ + { kind: "header", label: "Show" }, + toggle("Compact References View", o, "compactRefs"), + toggle("Tag Names", o, "tagNames"), + toggle("Long Edges", o, "longEdges"), + toggle("Commit Timestamp", o, "commitTimestamp"), + toggle("References on the Left", o, "refsOnLeft"), + toggle("Details", o, "showDetails"), + toggle("Repository", o, "showRepository"), + { + label: "Columns", + submenu: [ + toggle("Author", o, "showAuthor"), + toggle("Date", o, "showDate"), + toggle("Hash", o, "showHash"), + toggle("Signature", o, "showSignature"), + toggle("GitHub Commit Checks", o, "showGitHubChecks"), + { kind: "separator" }, + toggle("Column Headers", o, "showColumnHeaders"), + ], + }, + { kind: "separator" }, + { kind: "header", label: "Highlight" }, + toggle("My Commits", o, "highlightMine"), + toggle("Merge Commits", o, "highlightMerges"), + toggle("Current Branch", o, "highlightCurrentBranch"), + ]; +} diff --git a/src/features/vcs/log/GraphCell.tsx b/src/features/vcs/log/GraphCell.tsx new file mode 100644 index 000000000..fe2f19ac0 --- /dev/null +++ b/src/features/vcs/log/GraphCell.tsx @@ -0,0 +1,161 @@ +import { tx } from "@/platform/i18n"; +import { Fragment } from "react"; +import styles from "../GitLog.module.css"; +import { laneColor, type GraphRow, type GraphSegment } from "../graph"; +import { LANE, ROW } from "./shared"; + +export function x(lane: number) { + return LANE / 2 + lane * LANE; +} + +/** Straight, also across lanes (IDEA's diagonal edges). */ +function seg(fromX: number, fromY: number, toX: number, toY: number) { + return `M${fromX} ${fromY}L${toX} ${toY}`; +} + +export function GraphCell({ + row, + head, + activeColor, + highlighted, + highlightedNodes, + onHover, + onNavigate, + onFragment, + targetTitle, + onNode, + interactive = true, +}: { + row: GraphRow; + head?: boolean; + activeColor?: string | null; + highlighted?: ReadonlySet; + highlightedNodes?: ReadonlySet; + onHover?: (edge: string | null) => void; + onNavigate?: (index: number, key?: string) => void; + onFragment?: (target: string, expand: boolean, source?: string) => void; + targetTitle?: (index: number, key?: string) => string; + onNode?: () => void; + interactive?: boolean; +}) { + const cy = ROW / 2; + const draw = (s: GraphSegment, i: number, up: boolean) => { + const fromX = x(s.fromX ?? s.from); + const toX = x(s.toX ?? s.to); + const path = + seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) + + (s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : ""); + const line = ( + + ); + if (!interactive) return line; + const target = (up ? row.upTargets : row.downTargets)?.[i]; + const canFragment = + !!target && + !!onFragment && + s.kind !== "filtered" && + s.kind !== "shallow" && + (!!s.source || (!up && s.from === row.lane)); + const canNavigate = s.targetRow != null && s.kind !== "shallow" && !!onNavigate; + const actionable = canNavigate || canFragment; + const label = + s.kind === "shallow" + ? tx("Shallow history boundary") + : s.targetRow != null + ? (targetTitle?.(s.targetRow, target) ?? tx("Go to connected commit")) + : s.dashed + ? tx("Expand this fragment") + : tx("Collapse this fragment"); + const activate = () => { + if (canNavigate) onNavigate?.(s.targetRow!, target); + else if (canFragment) onFragment?.(target!, !!s.dashed, s.source); + }; + return ( + + onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)} + onMouseMove={() => onHover?.(s.edge ?? `${s.source ?? ""}\0${target ?? ""}`)} + onMouseDown={(e) => e.stopPropagation()} + onClick={(e) => { + e.stopPropagation(); + activate(); + }} + onKeyDown={(e) => { + if (actionable && (e.key === "Enter" || e.key === " ")) { + e.preventDefault(); + e.stopPropagation(); + activate(); + } + }} + > + {label} + + {line} + + ); + }; + return ( + onHover?.(null)} + > + {row.up.map((s, i) => draw(s, i, true))} + {row.down.map((s, i) => draw(s, i, false))} + e.stopPropagation()} + onMouseEnter={() => row.id && onHover?.(`node:${row.id}`)} + onMouseMove={() => row.id && onHover?.(`node:${row.id}`)} + onClick={(e) => { + e.stopPropagation(); + onNode?.(); + }} + onKeyDown={(e) => { + if (onNode && (e.key === "Enter" || e.key === " ")) { + e.preventDefault(); + e.stopPropagation(); + onNode(); + } + }} + > + + + {head && } + + + ); +} + +/** Arrow head at (`px`, `py`) pointing up (`dir` -1) or down (1): a long edge continues. */ +function arrowHead(px: number, py: number, dir: 1 | -1) { + const back = py - dir * 4; + return `M${px - 3} ${back}L${px} ${py}L${px + 3} ${back}`; +} diff --git a/src/features/vcs/log/commitMenu.ts b/src/features/vcs/log/commitMenu.ts new file mode 100644 index 000000000..182633eb1 --- /dev/null +++ b/src/features/vcs/log/commitMenu.ts @@ -0,0 +1,116 @@ +import type { Commit } from "@/bindings"; +import { useBookmarkPopups } from "@/features/search/bookmarks/store"; +import { tx } from "@/platform/i18n"; +import { copyText, type MenuItem } from "@/ui"; +import { branchMenu, inRepo } from "../branchMenu"; +import { commitBookmarkPath } from "../logBookmarks"; +import { loadLogDetails } from "../logDetails"; +import { toggleCommitBookmark, useGitLog } from "../logStore"; +import { commitKey, commitRepo, type RepoCommit } from "../multiRoot"; +import { browseRepositoryAt } from "../RevisionBrowser"; +import { useVcs } from "../store"; + +/** IDEA's Git Log commit context menu (Git.Log.ContextMenu); `selection` = all selected commits, newest first. */ +export function commitMenu(c: Commit, selection: Commit[] = [c]): MenuItem[] { + if ((c as RepoCommit).readOnly) + return [ + { kind: "action", action: "vcs.log.copyRevision", arg: c }, + { label: "Copy Commit Message", run: () => copyCommitMessage(c) }, + { + label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit", + run: () => toggleCommitBookmark(c), + }, + { + label: "Assign Mnemonic", + run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }), + }, + { kind: "action", action: "vcs.log.goToParent", arg: c }, + { kind: "action", action: "vcs.log.goToChild", arg: c }, + { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, + ]; + const many = selection.length > 1 && selection.some((x) => commitKey(x) === commitKey(c)); + const repo = commitRepo(c); + const vcs = useVcs.getState(); + const head = (repo ? vcs.heads[repo]?.head : vcs.branch?.head) ?? null; + const { outgoing } = useGitLog.getState(); + if (many) { + return [ + { kind: "action", action: "vcs.log.copyRevision", arg: selection, label: "Copy Revision Numbers" }, + { kind: "action", action: "vcs.log.createPatch", arg: selection }, + { kind: "action", action: "vcs.log.cherryPick", arg: selection }, + ...(selection.length === 2 + ? [{ kind: "action", action: "vcs.log.compareVersions", arg: selection } satisfies MenuItem] + : []), + { kind: "separator" }, + { kind: "action", action: "vcs.log.revert", arg: selection, label: "Revert Commits" }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.squashCommits", arg: selection }, + { kind: "action", action: "vcs.log.dropCommit", arg: selection, label: "Drop Commits" }, + ]; + } + // Without an upstream there is no outgoing set: allow pushing up to any commit of HEAD. + const canPushHere = + !!head && + ((commitRepo(c) === undefined ? !!outgoing : useGitLog.getState().tracked.has(commitRepo(c) ?? "")) + ? !!outgoing?.has(commitKey(c)) + : true); + const branches = ((c as RepoCommit).refBranches ?? []).filter((branch) => !branch.current); + const branchActions: MenuItem[] = branches.map((branch) => { + const menu = branchMenu(branch, head); + return { + label: tx`Branch '${branch.name}'`, + submenu: repo ? inRepo(repo, menu) : menu, + }; + }); + if (!branchActions.length) + branchActions.push({ + kind: "action", + action: "vcs.log.rebaseOntoCommit", + arg: c, + label: tx`Rebase '${head ?? "HEAD"}' onto Selected Commit`, + disabled: !head, + }); + return [ + { kind: "action", action: "vcs.log.copyRevision", arg: c }, + { + label: useGitLog.getState().bookmarks[commitKey(c)] ? "Remove Commit Bookmark" : "Bookmark Commit", + run: () => toggleCommitBookmark(c), + }, + { label: "Copy Commit Message", run: () => copyCommitMessage(c) }, + { kind: "action", action: "vcs.log.createPatch", arg: c }, + { kind: "action", action: "vcs.log.cherryPick", arg: c }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.checkoutRevision", arg: c }, + { label: "Browse Repository at Revision", run: () => browseRepositoryAt(c) }, + { kind: "action", action: "vcs.log.compareWithLocal", arg: c }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.resetToHere", arg: c }, + { kind: "action", action: "vcs.log.revert", arg: c }, + { kind: "action", action: "vcs.log.undoCommit", arg: c }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.editMessage", arg: c }, + { kind: "action", action: "vcs.log.fixup", arg: c }, + { kind: "action", action: "vcs.log.squashInto", arg: c }, + { kind: "action", action: "vcs.log.dropCommit", arg: c }, + { kind: "action", action: "vcs.log.interactiveRebase", arg: c }, + { kind: "action", action: "vcs.log.pushUpToHere", arg: c, disabled: !canPushHere }, + { kind: "separator" }, + ...(branchActions.length > 2 ? [{ label: "Branches", submenu: branchActions }] : branchActions), + { kind: "action", action: "vcs.log.newBranch", arg: c }, + { kind: "action", action: "vcs.log.newTag", arg: c }, + { kind: "separator" }, + { + label: "Assign Mnemonic", + run: () => useBookmarkPopups.setState({ chooser: { path: commitBookmarkPath(c), line: 0, text: c.summary } }), + }, + { kind: "action", action: "vcs.log.goToChild", arg: c }, + { kind: "action", action: "vcs.log.goToParent", arg: c, disabled: !c.parents.length }, + { kind: "separator" }, + { kind: "action", action: "vcs.log.openInBrowser", arg: c }, + ]; +} + +async function copyCommitMessage(c: Commit) { + const message = c.messageTruncated ? (await loadLogDetails(c)).message : c.message; + await copyText(message); +} diff --git a/src/features/vcs/log/logHooks.tsx b/src/features/vcs/log/logHooks.tsx new file mode 100644 index 000000000..c2f198c89 --- /dev/null +++ b/src/features/vcs/log/logHooks.tsx @@ -0,0 +1,35 @@ +import { Menu, type MenuItem } from "@/ui"; +import { useContext, useMemo, useState, type MouseEvent as ReactMouseEvent } from "react"; +import { LogIdContext } from "../logContext"; +import { useGitLog } from "../logStore"; +import { useVcs } from "../store"; + +export function useLogRepositories() { + const scope = useContext(LogIdContext); + const tab = useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog))); + const roots = useVcs((s) => s.roots); + const repo = tab?.repo; + const repositories = tab?.repositories; + const key = (repositories?.length ? repositories : repo ? [repo] : roots).join("\0"); + // eslint-disable-next-line react-hooks/exhaustive-deps + return useMemo(() => (repositories?.length ? repositories : repo ? [repo] : roots), [key]); +} + +export function useReadOnlyLog() { + const scope = useContext(LogIdContext); + return useGitLog((s) => s.logTabs.find((t) => t.id === (scope ?? s.shownLog))?.readOnly === true); +} + +/** + * A toolbar button's dropdown, anchored to the button: a second click on it closes the menu + * instead of reopening it, as in IDEA. Returns the opener and the element to render. + */ +export function useDropdownMenu() { + const [menu, setMenu] = useState<{ anchor: HTMLElement; items: MenuItem[] } | null>(null); + const open = (anchor: HTMLElement | ReactMouseEvent, items: MenuItem[]) => { + const el = "currentTarget" in anchor ? anchor.currentTarget : anchor; + setMenu((m) => (m?.anchor === el ? null : { anchor: el, items })); + }; + const dropdown = menu && setMenu(null)} />; + return [open, dropdown] as const; +} diff --git a/src/features/vcs/log/shared.ts b/src/features/vcs/log/shared.ts new file mode 100644 index 000000000..bd0a9b9d3 --- /dev/null +++ b/src/features/vcs/log/shared.ts @@ -0,0 +1,37 @@ +import type { Commit } from "@/bindings"; +import { type MenuItem } from "@/ui"; +import { type ReactNode } from "react"; +import { type LogOptions } from "../logOptions"; +import { updateLogOptions } from "../logStore"; + +export const ROW = 26; + +export const LANE = 14; + +export interface LogColumn { + id: string; + title: string; + width: number; + render(commit: Commit): ReactNode; +} + +// The flexible "Commit" column shares the same order and can be dragged like the rest. +export const SUBJECT_COLUMN: LogColumn = { id: "subject", title: "Commit", width: 0, render: () => "" }; + +// Until the user drags the commit column somewhere, it leads the row. +export const columnSequence = (columnOrder: string[], builtins: LogColumn[]): string[] => { + const ids = [...new Set([...columnOrder, ...builtins.map((c) => c.id)])]; + return columnOrder.includes(SUBJECT_COLUMN.id) ? ids : [SUBJECT_COLUMN.id, ...ids]; +}; + +export type RowEvents = { + onHover: (edge: string | null) => void; + onFragment: (from: string, target: string, expand: boolean) => void; + onNavigate: (index: number, key?: string) => void; +}; + +export const toggle = (label: string, o: LogOptions, key: keyof LogOptions): MenuItem => ({ + label, + checked: !!o[key], + run: () => updateLogOptions({ [key]: !o[key] }), +});