/** * Git Log presentation options (IDEA's Graph Options and View Options menus), * persisted across sessions. */ import { create } from "zustand"; import { useContext } from "react"; import { LogOptionsContext } from "./logContext"; export type LogSort = "date" | "topo" | "standard"; export type DiffLocation = "editor" | "right" | "bottom"; export interface LogOptions { sort: LogSort; firstParent: boolean; noMerges: boolean; collapseLinear: boolean; compactRefs: boolean; tagNames: boolean; longEdges: boolean; commitTimestamp: boolean; refsOnLeft: boolean; showAuthor: boolean; showDate: boolean; showHash: boolean; showSignature: boolean; showGitHubChecks: boolean; /** The row naming the columns, where they are resized and reordered. */ showColumnHeaders: boolean; /** Draw a 1px divider on each column's left edge (off by default, like IDEA). */ showColumnDividers: boolean; highlightMine: boolean; highlightMerges: boolean; highlightCurrentBranch: boolean; /** The Branches pane on the left of the log. */ showBranches: boolean; /** Single-clicking a branch in the Branches pane updates the log's branch filter. */ branchClickFilters: boolean; /** Changed files grouped by directory (else a flat list). */ groupByDirectory: boolean; /** Selecting a changed file updates the embedded preview or an open editor preview. */ diffPreview: boolean; /** Changed files show how many lines the commit added and deleted. */ showLineStats: boolean; showDetails: boolean; showRepository: boolean; showOnlyAffected: boolean; changesFromParents: boolean; diffLocation: DiffLocation; /** File history keeps its own location (IDEA's FileHistoryUiProperties): its file's diff beside the revisions. */ historyDiffLocation: DiffLocation; columnOrder: string[]; columnWidths: Record; linearizeMerges: boolean; } /** IDEA's defaults. */ export const DEFAULT_LOG_OPTIONS: LogOptions = { sort: "date", firstParent: false, noMerges: false, collapseLinear: false, compactRefs: true, tagNames: false, longEdges: false, commitTimestamp: false, refsOnLeft: false, showAuthor: true, showDate: true, showHash: false, showSignature: false, showGitHubChecks: false, showColumnHeaders: false, showColumnDividers: false, highlightMine: true, highlightMerges: true, highlightCurrentBranch: true, showBranches: true, branchClickFilters: false, groupByDirectory: true, diffPreview: true, showLineStats: false, showDetails: true, showRepository: true, showOnlyAffected: false, changesFromParents: false, diffLocation: "editor", historyDiffLocation: "right", columnOrder: ["author", "date", "hash"], columnWidths: {}, linearizeMerges: false, }; /** Options that change which commits the backend returns (a reload is needed). */ export const QUERY_OPTIONS: ReadonlyArray = ["sort", "firstParent", "noMerges"]; const APPLICATION_LOG_OPTION_KEYS = [ "compactRefs", "tagNames", "commitTimestamp", "refsOnLeft", "showAuthor", "showDate", "showHash", "showSignature", "showGitHubChecks", "branchClickFilters", "diffPreview", "changesFromParents", "diffLocation", "historyDiffLocation", "columnOrder", ] as const satisfies readonly (keyof LogOptions)[]; export type ApplicationLogOptions = Pick; const KEY = "openidea.vcs.logOptions"; export function parseLogOptions(raw: unknown): LogOptions { const o = raw && typeof raw === "object" ? (raw as Record) : {}; const out = { ...DEFAULT_LOG_OPTIONS }; for (const k of Object.keys(out) as Array) { if (k === "sort") out.sort = o.sort === "standard" || o.sort === "topo" || o.sort === "date" ? o.sort : DEFAULT_LOG_OPTIONS.sort; else if (k === "diffLocation" || k === "historyDiffLocation") { const v = o[k]; out[k] = v === "editor" || v === "right" || v === "bottom" ? v : DEFAULT_LOG_OPTIONS[k]; } else if (k === "columnOrder") out.columnOrder = Array.isArray(o.columnOrder) ? [...new Set(o.columnOrder.filter((v): v is string => typeof v === "string"))] : [...DEFAULT_LOG_OPTIONS.columnOrder]; else if (k === "columnWidths" && o.columnWidths && typeof o.columnWidths === "object") out.columnWidths = Object.fromEntries( Object.entries(o.columnWidths).filter( (entry): entry is [string, number] => typeof entry[1] === "number" && Number.isFinite(entry[1]) && entry[1] >= 40 && entry[1] <= 800, ), ); else if (typeof o[k] === "boolean") (out as Record)[k] = o[k]; } return out; } function pickApplicationOptions(options: LogOptions): ApplicationLogOptions { return Object.fromEntries(APPLICATION_LOG_OPTION_KEYS.map((key) => [key, options[key]])) as ApplicationLogOptions; } function loadApplicationOptions(): ApplicationLogOptions { try { const raw = localStorage.getItem(KEY); return pickApplicationOptions(parseLogOptions(raw ? JSON.parse(raw) : null)); } catch { return pickApplicationOptions(DEFAULT_LOG_OPTIONS); } } export const rootLogOptions = create(() => ({ ...DEFAULT_LOG_OPTIONS, ...loadApplicationOptions() })); export const useLogOptions = Object.assign(function useScopedLogOptions( selector?: (state: LogOptions) => T, ): T { const scoped = useContext(LogOptionsContext); return rootLogOptions((state) => (selector ? selector(scoped ?? state) : ((scoped ?? state) as T))); }, rootLogOptions); export function applicationLogOptions(options: LogOptions = rootLogOptions.getState()): ApplicationLogOptions { return pickApplicationOptions(options); } export function withApplicationLogOptions(options: Partial): LogOptions { return { ...DEFAULT_LOG_OPTIONS, ...options, ...applicationLogOptions() }; } export function setActiveLogOptions(options: Partial): void { rootLogOptions.setState(withApplicationLogOptions(options)); } // Settings › Version Control › Log edits them from the Settings window too. if (typeof window !== "undefined") window.addEventListener("storage", (e) => { if (e.key === KEY) rootLogOptions.setState((state) => ({ ...state, ...loadApplicationOptions() })); }); export const logOptions = () => rootLogOptions.getState(); export type RefKind = "head" | "local" | "remote" | "tag"; export interface RefLabel { kind: RefKind; /** Empty for a tag shown without its name. */ text: string; title: string; } /** * Reference labels of a commit row. `refs` are decorations (`HEAD`, `main`, * `origin/main`, `tag: v1`); `remoteNames` the remote-tracking branch names. * Compact: a local branch absorbs its remote-tracking branches (`origin & main`) and * HEAD is left out next to other references. Without tag names, tags are one icon. */ export function refLabels( refs: readonly string[], opts: { compact: boolean; tagNames: boolean }, remoteNames: ReadonlySet, ): RefLabel[] { const isRemote = (r: string) => (remoteNames.size ? remoteNames.has(r) : r.includes("/")); const tags = refs.filter((r) => r.startsWith("tag: ")).map((r) => r.slice(5)); const branches = refs.filter((r) => r !== "HEAD" && !r.startsWith("tag: ")); const out: RefLabel[] = []; if (refs.includes("HEAD") && (!opts.compact || !branches.length)) out.push({ kind: "head", text: "HEAD", title: "HEAD" }); const locals = branches.filter((b) => !isRemote(b)); const remotes = branches.filter(isRemote); const absorbed = new Set(); for (const l of locals) { const tracking = opts.compact ? remotes.filter((r) => r.endsWith(`/${l}`)) : []; tracking.forEach((r) => absorbed.add(r)); const prefixes = tracking.map((r) => r.slice(0, -l.length - 1)); out.push({ kind: "local", text: prefixes.length ? `${prefixes.join(", ")} & ${l}` : l, title: [l, ...tracking].join(", "), }); } for (const r of remotes) if (!absorbed.has(r)) out.push({ kind: "remote", text: r, title: r }); if (tags.length) { if (opts.tagNames) out.push(...tags.map((t) => ({ kind: "tag" as const, text: t, title: t }))); else out.push({ kind: "tag", text: "", title: tags.join(", ") }); } return out; } /** Updates options and persists application-level properties; returns whether the log has to be reloaded. */ export function setLogOptions(patch: Partial): boolean { const before = rootLogOptions.getState(); const after = { ...before, ...patch }; rootLogOptions.setState(after); try { // Per-tab properties are saved in the log session, not in the application store. localStorage.setItem(KEY, JSON.stringify(applicationLogOptions(after))); } catch { // Storage unavailable: the options last for this session. } return QUERY_OPTIONS.some((k) => before[k] !== after[k]); }