feat(git): a labeled repository picker for multi-repo workspaces

A container workspace that discovers several repositories rendered one
chip per root above the Changes section; with location labels the row
does not scale, and same-named checkouts were indistinguishable. The
row is now a compact labeled select: the current root stays on screen,
the full list is one click away, and options carry disambiguation
labels (deeper roots show their relative parent) shared with the
More -> Repository submenu. The picker shows the resolved status root —
a server fallback renders as a disabled stand-in with its own short
label instead of silently selecting the first option. Single-repo
workspaces render no row; switching still goes through chooseRepo.
This commit is contained in:
Sidebar Test authored and Menghuan1918 committed 2026-11-16 00:33:58 +08:00
1 parent 7c374293c7
commit ea770cc2e1
7 files changed
+577 -85

No files matched your search

+49 -16
View File
@@ -24,6 +24,7 @@ import { resolveSidebarPath } from '../paths.ts'
import { isZh, t } from '../locales.ts'
import { GitGraphSection, type GraphDetailsSelection } from './GitGraphSection.tsx'
import type { SidebarDiffRef } from '../state.ts'
import { buildRepositoryLabels } from './repo-labels.ts'
import {
ConfirmDialog, IconButton, Notice, StatusBadge, invalidateGitStatus, statusOfXY,
useGitStatus, type GitFileStatus, type GitTone, type StatusTone,
@@ -67,6 +68,19 @@ function errorMessage(reason: unknown): string {
return reason instanceof Error ? reason.message : String(reason)
}
/** Existing Host fact used only to disambiguate ambiguous path spellings (a
* leading `//` is either POSIX or Windows UNC). Read through the guarded
* face; never rendered and never requested. */
function hostHomeOf(ctx: Context | undefined): string | undefined {
try {
const remote = ctx?.get('remote') as { $host?: { home?: unknown } } | undefined
return typeof remote?.$host?.home === 'string' ? remote.$host.home : undefined
} catch {
// A composition without the Remote service must not take the lens down.
return undefined
}
}
/** One checkout root in the form comparisons use: `git rev-parse` reports
* forward slashes, React state may carry the shell's backslashes, Windows
* folds case, and a trailing separator means the same directory.
@@ -556,6 +570,25 @@ export function GitLens(props: GitLensProps) {
if (lastStatus.current.key !== statusKey) lastStatus.current = { key: statusKey, value: null }
if (status.snapshot !== null) lastStatus.current.value = status.snapshot
const snapshot: GitStatusResult | null = status.snapshot ?? lastStatus.current.value
// Display-only labels for the picker and the ⋯ → Repository menu. The
// reference is the session's existing cwd (best effort — it can shift with
// the active worktree); `hostHome` only disambiguates `//` dialects and is
// never rendered.
const hostHome = hostHomeOf(ctx)
// A requested repoRoot can disappear from server discovery; the server then
// falls back. Show the RESOLVED status root, never the stale request or an
// arbitrary first option — matched by identity but keeping the option's
// original root, or a disabled stand-in with its own short label.
const actualRoot = snapshot?.root
const selectedCandidate = actualRoot === undefined ? undefined : repoChoices.find(root => sameRepoRoot(root, actualRoot))
const unlistedRoot = actualRoot !== undefined && selectedCandidate === undefined ? actualRoot : undefined
const allRepositoryLabels = useMemo(
() => buildRepositoryLabels(unlistedRoot === undefined ? repoChoices : [...repoChoices, unlistedRoot], scope.cwd, hostHome),
[repoChoices, unlistedRoot, scope.cwd, hostHome],
)
const repositoryLabels = unlistedRoot === undefined ? allRepositoryLabels : allRepositoryLabels.slice(0, -1)
const resolvedRepository = selectedCandidate ?? actualRoot
const resolvedRepositoryLabel = unlistedRoot === undefined ? undefined : allRepositoryLabels.at(-1)?.label
useEffect(() => {
const repositories = snapshot?.repositories
if (repositories !== undefined && repositories.length > 1) setRepoChoices(repositories)
@@ -1101,24 +1134,24 @@ export function GitLens(props: GitLensProps) {
{snapshot?.truncated === true && <Notice kind="warn">{t('statusTruncated')}</Notice>}
{/* A container workspace can hold several independent repositories, and
every view below is pinned to ONE of them — without this row the
every view below is pinned to ONE of them — without this picker the
panel silently shows the first root, so nothing on screen says the
others exist. The switcher is not a second source of truth:
others exist. The picker is not a second source of truth:
`repoChoices` comes from the status snapshot, `chooseRepo` re-pins
the scope (reads, writes, graph) to the clicked root. */}
the scope (reads, writes, graph) to the picked root. A labeled
select keeps the current root on screen and the rest one click away
however many repositories discovery finds. */}
{isRepo && repoChoices.length > 1 && (
<div className={css.repoSwitcher} data-scm-repos role="group" aria-label={t('gitRepository')}>
{repoChoices.map(root => {
const isActive = sameRepoRoot(root, repoRoot ?? snapshot?.root)
return (
<button key={root} type="button" className={css.repoChip} data-scm-repo={root}
data-active={isActive ? 'true' : undefined} aria-pressed={isActive} title={root}
disabled={busy || suggesting} onClick={() => { chooseRepo(root) }}>
{baseName(root)}
</button>
)
})}
</div>
<label className={css.repoPick} data-scm-repos>
<span className={css.repoPickLabel}>{t('gitRepository')}</span>
<select className={css.repoPickSelect} aria-label={t('gitRepository')}
value={resolvedRepository ?? ''} disabled={busy || suggesting}
onChange={event => { chooseRepo(event.target.value) }}>
{resolvedRepository !== undefined && !repositoryLabels.some(item => item.root === resolvedRepository) &&
<option value={resolvedRepository} disabled>{resolvedRepositoryLabel ?? t('gitRepository')}</option>}
{repositoryLabels.map(item => <option key={item.root} value={item.root}>{item.label}</option>)}
</select>
</label>
)}
{isRepo && (
@@ -1149,7 +1182,7 @@ export function GitLens(props: GitLensProps) {
{ id: 'pull', label: t('pull'), disabled: busy || suggesting || snapshot?.detached === true },
{ id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true },
...(repoChoices.length > 1 ? [{ id: 'repos', label: t('gitRepository'),
submenu: repoChoices.map(root => ({ id: `repo:${root}`, label: baseName(root), disabled: busy || suggesting })),
submenu: repositoryLabels.map(({ root, label }) => ({ id: `repo:${root}`, label, disabled: busy || suggesting })),
}] : []),
...(worktrees.length > 1 ? [{ id: 'worktrees', label: t('worktree'),
submenu: worktrees.map(entry => ({ id: `worktree:${entry.path}`,
+20 -27
View File
@@ -59,46 +59,39 @@
@media (hover: none) { .scmActions { opacity: 1; } }
/* Child repositories of a workspace container: every view in this panel is
pinned to ONE root, so the switcher is the only surface that says the others
exist. One band above the sections, one chip per discovered root; it scrolls
sideways rather than wrapping so a deep root list cannot push the changes
away from the top of the pane. */
.repoSwitcher {
pinned to ONE root, so the picker is the only surface that names the current
one and lists the others one click away. A labeled select scales to any
number of discovered roots in a single compact band — a chip per root does
not, once location labels distinguish same-named checkouts. */
.repoPick {
flex: none;
display: flex;
align-items: center;
gap: 4px;
gap: 6px;
min-width: 0;
padding: 0 6px 2px;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
color: var(--dsw-alias-label-secondary);
font: var(--dsw-font-xxxs-11);
cursor: pointer;
}
.repoSwitcher::-webkit-scrollbar { display: none; }
.repoChip {
flex: none;
max-width: 160px;
min-height: 22px;
padding: 2px 8px;
.repoPickLabel { flex: none; white-space: nowrap; }
.repoPickSelect {
flex: 1;
min-width: 0;
max-width: 100%;
height: 22px;
padding: 0 4px;
border: 1px solid var(--dsw-alias-border-l1);
border-radius: 3px;
background: transparent;
color: var(--dsw-alias-label-secondary);
color: var(--dsw-alias-label-primary);
font: var(--dsw-font-xxxs-11);
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
}
.repoChip:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); }
.repoChip[data-active='true'] {
border-color: var(--dsw-alias-border-l2);
background: var(--dsw-alias-interactive-bg-hover-accent);
color: var(--dsw-alias-label-primary);
}
.repoChip:disabled { opacity: 0.45; cursor: default; }
.repoChip:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; }
.repoPickSelect:hover:not(:disabled) { border-color: var(--dsw-alias-border-l2); background: var(--dsw-alias-interactive-bg-hover); }
.repoPickSelect:disabled { opacity: 0.45; cursor: default; }
.repoPickSelect:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; }
/* Docked by the flex column above (a sibling of `.gitScroll`), plus sticky so
it also survives the case where the host tab body itself scrolls the whole
+168
View File
@@ -0,0 +1,168 @@
/** Display-only labels for discovered checkout roots. No filesystem or browser-platform access. */
export interface RepositoryLabel {
readonly root: string
readonly label: string
}
type PathKind = 'posix' | 'drive' | 'unc' | 'relative'
interface ParsedPath {
kind: PathKind
anchor: string
parts: string[]
separator: '/' | '\\'
name: string
absolute: string
hasParentSegment: boolean
}
/** Interpret each path in its own host dialect, never in the browser's dialect. */
function parsePath(raw: string, preferPosixDoubleSlash = false): ParsedPath {
// Windows may hand out namespaced drive or UNC paths. Remove only the
// namespace for comparison/display; the original root remains untouched.
const spelling = preferPosixDoubleSlash && raw.startsWith('/') ? raw
: /^[\\/]{2}\?[\\/]UNC[\\/]/i.test(raw)
? raw.replace(/^[\\/]{2}\?[\\/]UNC[\\/]/i, '\\\\')
: raw.replace(/^[\\/]{2}\?[\\/](?=[a-zA-Z]:[\\/])/, '')
let kind: PathKind = 'relative'
let anchor = ''
let rest = spelling
let separator: '/' | '\\' = '/'
const drive = /^([a-zA-Z]:)[\\/]+/.exec(spelling)
const unc = /^[\\/]{2}([^\\/]+)[\\/]+([^\\/]+)(?:[\\/]+|$)/.exec(spelling)
if (drive) {
kind = 'drive'
anchor = drive[1]!
rest = spelling.slice(drive[0].length)
separator = '\\'
} else if (unc && !(preferPosixDoubleSlash && spelling.startsWith('/'))) {
kind = 'unc'
anchor = `\\\\${unc[1]!}\\${unc[2]!}`
rest = spelling.slice(unc[0].length)
separator = '\\'
} else if (spelling.startsWith('/')) {
kind = 'posix'
anchor = '/'
rest = spelling.replace(/^\/+/, '')
}
const split = kind === 'posix' || kind === 'relative' ? /\/+/ : /[\\/]+/
const parts: string[] = []
for (const part of rest.split(split)) {
if (part && part !== '.') parts.push(part)
}
// Resolving '..' lexically can be wrong across a symlink. With no filesystem
// access, preserve it for display and decline to infer containment.
const hasParentSegment = parts.includes('..')
const name = parts[parts.length - 1]
?? (kind === 'posix' ? '/' : kind === 'drive' ? `${anchor}\\` : kind === 'unc' ? anchor.split('\\').at(-1)! : raw)
const suffix = parts.join(separator)
const absolute = kind === 'posix' ? `/${suffix}`
: kind === 'drive' ? `${anchor}\\${suffix}`
: kind === 'unc' ? `${anchor}${suffix ? `\\${suffix}` : ''}`
: suffix || raw
return { kind, anchor, parts, separator, name, absolute, hasParentSegment }
}
/** Check full path components and drive/share identity; POSIX paths stay case-sensitive. */
function relativeParts(path: ParsedPath, base: ParsedPath | undefined): string[] | undefined {
if (!base || base.kind === 'relative' || path.kind !== base.kind || base.hasParentSegment || path.hasParentSegment) return undefined
const windows = path.kind === 'drive' || path.kind === 'unc'
const same = (left: string, right: string) => windows ? left.toLowerCase() === right.toLowerCase() : left === right
if (!same(path.anchor, base.anchor) || path.parts.length < base.parts.length) return undefined
if (!base.parts.every((part, i) => same(part, path.parts[i]!))) return undefined
return path.parts.slice(base.parts.length)
}
interface LabelCandidate {
root: string
parsed: ParsedPath
parents: string[]
context: string | undefined
nextDepth: number
phase: 0 | 1 | 2
label: string
}
/** Build a longer label only when a collision actually needs it. */
function advanceLabel(candidate: LabelCandidate): boolean {
const { parsed, parents } = candidate
if (candidate.nextDepth <= parents.length) {
const part = parents[parents.length - candidate.nextDepth]!
candidate.context = candidate.context === undefined ? part : `${part}${parsed.separator}${candidate.context}`
candidate.nextDepth += 1
candidate.label = `${parsed.name} (${candidate.context})`
return true
}
if (candidate.phase === 0) {
candidate.phase = 1
candidate.label = `${parsed.name} (${parsed.absolute})`
return true
}
if (candidate.phase === 1) {
candidate.phase = 2
candidate.label = candidate.root
return true
}
return false
}
/**
* Build labels once for the complete list. Short names cover the base, its
* direct children and an unknown base; deeper paths expose their full relative
* parent. Roots outside a known base show short parent context. Collisions
* expand context up to absolute/raw paths, never numbers. Exact duplicate roots
* share a label and keep their original rows.
*/
export function buildRepositoryLabels(
roots: readonly string[],
displayCwd: string | undefined,
hostHome?: string,
): readonly RepositoryLabel[] {
// The host's existing home is only a dialect hint; it is never appended to a label.
// A forward-slash UNC home is itself ambiguous, so do not claim a dialect.
const homePosix = hostHome !== undefined && hostHome.startsWith('/') && !hostHome.startsWith('//') && !hostHome.startsWith('/\\')
const homeWindows = hostHome !== undefined && (/^[a-zA-Z]:[\\/]/.test(hostHome) || /^\\[\\/]/.test(hostHome))
// Without a host hint, a // base is ambiguous. Preserve its spelling and
// use case-sensitive comparison rather than silently asserting UNC semantics.
const ambiguousBase = !homePosix && !homeWindows
&& (displayCwd?.startsWith('//') === true || displayCwd?.startsWith('/\\') === true)
const base = displayCwd === undefined ? undefined : parsePath(displayCwd, homePosix || ambiguousBase)
const preferPosix = homePosix || (!homeWindows && (base === undefined || base.kind === 'relative' || base.kind === 'posix'))
const distinct = new Map<string, LabelCandidate>()
for (const root of roots) {
if (distinct.has(root)) continue
const parsed = parsePath(root, preferPosix)
const relative = relativeParts(parsed, base)
const relativeParent = relative && relative.length > 1 ? relative.slice(0, -1) : []
const parents = parsed.parts.slice(0, -1)
const outsideKnownBase = base !== undefined && base.kind !== 'relative' && !base.hasParentSegment
&& parsed.kind !== 'relative' && !parsed.hasParentSegment && relative === undefined
const shortParent = !outsideKnownBase ? undefined : parents.at(-1)
?? (parsed.kind === 'unc' && parsed.parts.length === 0
? `\\\\${parsed.anchor.split('\\')[2]}`
: parsed.parts.length === 0 ? undefined : parsed.kind === 'posix' ? '/' : `${parsed.anchor}\\`)
const context = relativeParent.length > 0 ? relativeParent.join(parsed.separator) : shortParent
const label = context === undefined ? parsed.name : `${parsed.name} (${context})`
const usedDepth = relativeParent.length || (shortParent !== undefined && parents.length > 0 ? 1 : 0)
distinct.set(root, { root, parsed, parents, context, nextDepth: Math.max(1, usedDepth + 1), phase: 0, label })
}
// Resolve collisions globally, including a literal directory named like a
// generated label. Every candidate ends in its distinct raw root, so the
// process terminates without a synthetic numeric identifier.
for (;;) {
const byLabel = new Map<string, LabelCandidate[]>()
for (const candidate of distinct.values()) {
const group = byLabel.get(candidate.label)
if (group) group.push(candidate)
else byLabel.set(candidate.label, [candidate])
}
const collisions = [...byLabel.values()].filter(group => group.length > 1)
if (collisions.length === 0) break
for (const group of collisions) {
let advanced = false
for (const candidate of group) advanced = advanceLabel(candidate) || advanced
if (!advanced) throw new Error('repository labels could not be disambiguated')
}
}
return roots.map(root => ({ root, label: distinct.get(root)!.label }))
}