feat(git): make the repository switcher responsive (#1130)
Keep the contributor label work but place the control above Changes per the product decision: chips at natural width while every root fits, one native select once it does not. A hidden measurement row makes the decision content-driven; the More -> Repository submenu stays as the folded fallback.
This commit is contained in:
1 parent
da860d9aef
commit
83a25c27bc
9 files changed
+350
-113
No files matched your search
+5
-3
@@ -2,6 +2,11 @@
|
||||
|
||||
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
|
||||
|
||||
### 未发布
|
||||
|
||||
- 🌿 **多仓库工作区的仓库切换器改成响应式**(贡献者 PR [#1130](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1130) @iasiv5):容器工作区发现多个仓库时,「更改」上方一行在宽度足够时横排仓库胶囊,放不下时自动改为「仓库 ▾」下拉;两种形态共用位置消歧标签(深层仓库显示 `名 (相对父路径)`,如 `knowhow (ob-harness/contexts)`),当前根始终可见,服务端回退根以禁用项如实显示实际根而不是冒充候选。单仓库工作区不显示;「更多操作 → 仓库」保留为兜底;切换仍走既有 `chooseRepo`,读数、写操作与提交图继续钉在选中的根上。
|
||||
- 🧪 测试:`tests/git-repo-labels.spec.ts`(32 例:POSIX / Windows / UNC / 扩展路径、同名消歧、顺序与输入不变)与 `tests/git-repo-switcher.spec.tsx`(宽时胶囊、窄时下拉、标签与回退禁用项、单仓不显示)。
|
||||
|
||||
### v0.32.1
|
||||
|
||||
- 🧩 **适配 DSH 0.2.2-rc.2**:插件基线抬到 0.2.2 线的最新 RC,同时跟上这一版宿主的客户端契约与团队服务。
|
||||
@@ -156,9 +161,6 @@
|
||||
|
||||
### v0.30.1
|
||||
|
||||
- 🌿 **Git 面板新增「仓库 ▾」下拉,同名仓库一眼可辨**:容器工作区发现多个仓库时,提交图工具栏开头与「所有分支」筛选并排一行显示「仓库 ▾」下拉(仓库在前、分支在后)——当前选中的仓库始终可见,完整列表一键展开,仓库再多也只占一行,且比独立成行更省纵向空间。选项使用位置消歧标签:深层仓库显示 `名 (相对父路径)`(如 `knowhow (ob-harness/contexts)`),同名可辨,极端冲突用完整路径兜底。若服务端把所选仓库回退到其他根,下拉会以禁用项如实显示实际根,不冒充候选;「更多操作 → 仓库」二级菜单保留,作为提交图折叠时的切换兜底。单仓库工作区不显示此下拉;切换仍走既有 `chooseRepo`,读数、写操作与提交图继续钉在选中的根上。
|
||||
- 🧪 测试:`tests/git-repo-labels.spec.ts`(32 例:路径方言、同名消歧、顺序与输入不变)与 `tests/git-repo-switcher.spec.tsx`(下拉选项与标签、拼写折叠、服务端回退的禁用临时项、单仓不显示)。
|
||||
|
||||
- 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。
|
||||
- 🧪 测试:`tests/settings-nav-icon.spec.tsx` 钉住图标按宿主给的 `size` 缩放、只用 `currentColor`;真实宿主上用无头浏览器确认导航行只剩一个 `svg`、无残留标记。
|
||||
|
||||
|
||||
+5
-3
@@ -4,6 +4,11 @@
|
||||
>
|
||||
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
|
||||
|
||||
### Unreleased
|
||||
|
||||
- 🌿 **The multi-repository switcher is now responsive** (contributor PR [#1130](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1130) @iasiv5): when a container workspace discovers several repositories, the row above Changes renders natural-width chips while every root fits on one line and switches to a `Repository ▾` select once it does not. Both forms share the same location labels (deeper roots show `name (relative/parent)`, e.g. `knowhow (ob-harness/contexts)`), the current root stays visible, and a server-fallback root appears as a disabled stand-in instead of masquerading as a candidate. Single-repository workspaces render nothing; the ⋯ → Repository submenu stays as the fallback; switching still goes through `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root.
|
||||
- 🧪 `tests/git-repo-labels.spec.ts` (32 cases: POSIX / Windows / UNC / extended paths, duplicate disambiguation, order and input immutability) and `tests/git-repo-switcher.spec.tsx` (chips when wide, select when narrow, labels and the disabled fallback, single-repo absence).
|
||||
|
||||
### v0.32.1
|
||||
|
||||
- 🧩 **DSH 0.2.2-rc.2 support**: the plugin baseline moves to the newest 0.2.2 RC and follows that host's client contract and team service.
|
||||
@@ -152,9 +157,6 @@
|
||||
|
||||
### v0.30.1
|
||||
|
||||
- 🌿 **A labeled "Repository" dropdown for multi-repo workspaces, with same-named checkouts tellable apart**: when a container workspace discovers several repositories, the graph toolbar opens with a `Repository ▾` select sharing one row with the branch filter (repository first, filter second) — the current root stays on screen and the full list is one click away, one line however many roots discovery finds, and no extra row above the sections. Options carry location labels: deeper repositories show `name (relative/parent)` (e.g. `knowhow (ob-harness/contexts)`), so same-named checkouts are distinguishable, and extreme collisions fall back to full paths. If the server fell back from the requested root, the picker displays the actual root as a disabled stand-in instead of masquerading as a candidate; the ⋯ → Repository submenu stays reachable as the fallback surface while the graph is folded. Single-repository workspaces render no picker; switching still goes through the existing `chooseRepo`, so reads, mutations and the commit graph stay pinned to the chosen root.
|
||||
- 🧪 `tests/git-repo-labels.spec.ts` (32 cases: path dialects, duplicate disambiguation, order and input immutability) and `tests/git-repo-switcher.spec.tsx` (picker options and labels, spelling folding, the server-fallback disabled stand-in, single-repo absence).
|
||||
|
||||
- 🎯 **The "Side card" settings row no longer shows two icons**: the plugin still assumed the settings navigation had no icon channel, so it hid the fallback gear with CSS and painted its own glyph. The shell has long since exposed a `settings.section.icon` slot addressed by section id, and it now wraps the nav icon in a span — the stale `> svg:first-child` rule stopped hiding the fallback, so both glyphs rendered side by side. The row now contributes its icon **through the slot**, and the marker + CSS-mask apparatus is gone (along with a document-wide MutationObserver).
|
||||
- 🧪 `tests/settings-nav-icon.spec.tsx` pins the glyph to the slot-provided `size` and `currentColor`; a headless pass against a real host confirms one `svg` in the row and no leftover marker.
|
||||
|
||||
|
||||
@@ -35,18 +35,6 @@ export interface GraphDetailsSelection {
|
||||
readonly slot: number
|
||||
}
|
||||
|
||||
/** The lens-owned multi-repository picker state. `labels` pairs each
|
||||
* discovered root with its display-only disambiguation label; `value` is the
|
||||
* RESOLVED status root; `standInLabel` is set when the server fell back from
|
||||
* the requested root — rendered as a disabled option, never a candidate. */
|
||||
export interface RepoPickerState {
|
||||
readonly labels: ReadonlyArray<{ readonly root: string; readonly label: string }>
|
||||
readonly value: string
|
||||
readonly standInLabel?: string
|
||||
readonly disabled: boolean
|
||||
readonly onChooseRepo: (root: string) => void
|
||||
}
|
||||
|
||||
export interface GitGraphSectionProps {
|
||||
scope: SessionScope
|
||||
worktree?: string
|
||||
@@ -64,12 +52,6 @@ export interface GitGraphSectionProps {
|
||||
/** Row context menu: the Git lens's advanced commit actions (view / copy /
|
||||
* revert / cherry-pick). Absent, the rows simply carry no menu. */
|
||||
onContextMenu?: (event: MouseEvent<HTMLButtonElement>, entry: GraphEntry) => void
|
||||
/** The lens-owned multi-repository picker, rendered at the head of the
|
||||
* toolbar so the row reads as one scope line: pick the root, then filter
|
||||
* its history. Present only when the workspace holds several roots; the
|
||||
* lens keeps the ⋯ → Repository submenu reachable so a FOLDED graph never
|
||||
* orphans the switcher (the toolbar unmounts with the section). */
|
||||
repoPicker?: RepoPickerState
|
||||
}
|
||||
|
||||
/** One-line rows: the GitLens-style picture is rail + ref pills + subject on
|
||||
@@ -154,7 +136,7 @@ export function RefPill({ pill, slot }: { pill: RefPillModel; slot?: number }) {
|
||||
</span>
|
||||
}
|
||||
|
||||
export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onPreview, selectedRef, onClearPreview, onDetailsChange, onContextMenu, repoPicker }: GitGraphSectionProps) {
|
||||
export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onPreview, selectedRef, onClearPreview, onDetailsChange, onContextMenu }: GitGraphSectionProps) {
|
||||
const [branch, setBranch] = useState('')
|
||||
const [page, setPage] = useState<GraphPage | null>(null)
|
||||
const [branches, setBranches] = useState<GraphPage['branches']>([])
|
||||
@@ -368,18 +350,6 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
|
||||
return <section className={css.root} aria-label={t('gitGraph')} data-git-graph
|
||||
data-graph-count={page?.entries.length ?? 0}>
|
||||
<div className={css.toolbar}>
|
||||
{repoPicker && (
|
||||
<label className={css.repoPick} data-scm-repos>
|
||||
<span className={css.repoPickLabel}>{t('gitRepository')}</span>
|
||||
<select className={css.select} aria-label={t('gitRepository')}
|
||||
value={repoPicker.value} disabled={repoPicker.disabled}
|
||||
onChange={event => { repoPicker.onChooseRepo(event.target.value) }}>
|
||||
{repoPicker.standInLabel !== undefined &&
|
||||
<option value={repoPicker.value} disabled>{repoPicker.standInLabel}</option>}
|
||||
{repoPicker.labels.map(item => <option key={item.root} value={item.root}>{item.label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{linearFallback && <div role="status">{t('graphLinearFallback')}</div>}
|
||||
{!linearFallback && <select className={css.select} aria-label={t('graphBranchFilter')}
|
||||
value={branch} onChange={event => { chooseBranch(event.target.value) }}>
|
||||
|
||||
@@ -25,6 +25,7 @@ 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 { RepoSwitcher } from './RepoSwitcher.tsx'
|
||||
import {
|
||||
ConfirmDialog, IconButton, Notice, StatusBadge, invalidateGitStatus, statusOfXY,
|
||||
useGitStatus, type GitFileStatus, type GitTone, type StatusTone,
|
||||
@@ -1133,6 +1134,25 @@ export function GitLens(props: GitLensProps) {
|
||||
{snapshot !== null && !isRepo && <Notice kind="empty" tone="page">{t('notRepo')}</Notice>}
|
||||
{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
|
||||
panel silently shows the first root, so nothing on screen says the
|
||||
others exist. The switcher is not a second source of truth:
|
||||
repoChoices comes from the status snapshot, chooseRepo re-pins the
|
||||
scope (reads, writes, graph) to the picked root. It renders chips
|
||||
while they fit and one select otherwise; the list is shared with
|
||||
the More -> Repository submenu. */}
|
||||
{isRepo && repoChoices.length > 1 && (
|
||||
<RepoSwitcher
|
||||
labels={repositoryLabels}
|
||||
value={resolvedRepository}
|
||||
standInLabel={resolvedRepositoryLabel}
|
||||
disabled={busy || suggesting}
|
||||
visible={visible && active}
|
||||
onChoose={chooseRepo}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isRepo && (
|
||||
<section className={css.changesSection} data-scm-section="changes">
|
||||
<div className={css.scmHeader}>
|
||||
@@ -1214,10 +1234,6 @@ export function GitLens(props: GitLensProps) {
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* The graph toolbar hosts the multi-repo picker at its head (repository
|
||||
first, then the branch filter — one scope row). The picker rides the
|
||||
section, so a folded graph hides it; the ⋯ → Repository submenu in
|
||||
the Changes header stays reachable as the fallback surface. */}
|
||||
{isRepo && <section className={graphOpen ? css.graphSection : undefined} data-scm-section="graph">
|
||||
<div className={css.scmHeader}>
|
||||
<button type="button" className={css.scmDisclosure} aria-expanded={graphOpen}
|
||||
@@ -1239,13 +1255,6 @@ export function GitLens(props: GitLensProps) {
|
||||
onClearPreview={() => { props.onClearPreview?.() }}
|
||||
onDetailsChange={props.onDetailsChange}
|
||||
onContextMenu={openHistoryMenu}
|
||||
repoPicker={repoChoices.length > 1 ? {
|
||||
labels: repositoryLabels,
|
||||
value: resolvedRepository ?? '',
|
||||
standInLabel: resolvedRepositoryLabel,
|
||||
disabled: busy || suggesting,
|
||||
onChooseRepo: chooseRepo,
|
||||
} : undefined}
|
||||
/>
|
||||
</div>}
|
||||
</section>}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Multi-repository switcher for a workspace CONTAINER (a project directory
|
||||
* that is not itself a repository but holds several).
|
||||
*
|
||||
* The row is responsive by content, not by a fixed viewport breakpoint: the
|
||||
* chips render at their natural width whenever every discovered root fits on
|
||||
* one line; once they do not (many roots, long location labels, or a narrow
|
||||
* side card) the same list becomes one native select. A hidden measurement row
|
||||
* keeps the decision stable even while the select is mounted — there is no
|
||||
* flip-flop between the two forms.
|
||||
*
|
||||
* Both forms are display-only over the same label list; selecting a root calls
|
||||
* the lens's existing chooseRepo, so reads, writes and the commit graph stay
|
||||
* pinned to one root.
|
||||
*/
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { t } from '../locales.ts'
|
||||
import type { RepositoryLabel } from './repo-labels.ts'
|
||||
import css from './changes.module.css'
|
||||
|
||||
/** The switcher's current presentation. */
|
||||
type RepoSwitcherMode = 'chips' | 'select'
|
||||
|
||||
export interface RepoSwitcherProps {
|
||||
/** Discovered roots in discovery order, with display-only labels. */
|
||||
readonly labels: readonly RepositoryLabel[]
|
||||
/** The RESOLVED root (never the stale request), when known. */
|
||||
readonly value: string | undefined
|
||||
/** Label for a resolved root that is no longer in the discovered list. */
|
||||
readonly standInLabel: string | undefined
|
||||
readonly disabled: boolean
|
||||
/** Whether the hosting tab is on screen (gates the resize observer). */
|
||||
readonly visible: boolean
|
||||
readonly onChoose: (root: string) => void
|
||||
}
|
||||
|
||||
/** One root's display row, including the server-fallback stand-in. */
|
||||
interface SwitcherOption extends RepositoryLabel {
|
||||
readonly standIn?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the responsive repository switcher.
|
||||
* @param props - labels, resolved root, and the existing chooseRepo callback.
|
||||
* @returns the switcher, or nothing when only one root exists.
|
||||
*/
|
||||
export function RepoSwitcher({ labels, value, standInLabel, disabled, visible, onChoose }: RepoSwitcherProps) {
|
||||
const [mode, setMode] = useState<RepoSwitcherMode>('chips')
|
||||
const hostRef = useRef<HTMLDivElement>(null)
|
||||
const measureRef = useRef<HTMLDivElement>(null)
|
||||
const options: readonly SwitcherOption[] = value !== undefined && standInLabel !== undefined
|
||||
? [...labels, { root: value, label: standInLabel, standIn: true }]
|
||||
: labels
|
||||
|
||||
/** Compare the chips' natural width with the row's content box. */
|
||||
const measure = useCallback((): void => {
|
||||
const host = hostRef.current
|
||||
const row = measureRef.current
|
||||
if (host === null || row === null) return
|
||||
// A hidden tab (and jsdom) reports width 0: keep the current form rather
|
||||
// than deciding on a meaningless measurement. The observer re-runs once
|
||||
// the tab is on screen.
|
||||
if (host.clientWidth <= 0) {
|
||||
setMode('chips')
|
||||
return
|
||||
}
|
||||
// The row's horizontal padding (6px each side) is not available content.
|
||||
const available = host.clientWidth - 12
|
||||
setMode(row.scrollWidth > available ? 'select' : 'chips')
|
||||
}, [])
|
||||
|
||||
useLayoutEffect(() => { measure() }, [measure, labels, value, standInLabel, visible])
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return
|
||||
const host = hostRef.current
|
||||
const row = measureRef.current
|
||||
if (host === null || row === null || typeof ResizeObserver === 'undefined') return
|
||||
const observer = new ResizeObserver(() => { measure() })
|
||||
observer.observe(host)
|
||||
observer.observe(row)
|
||||
measure()
|
||||
return () => { observer.disconnect() }
|
||||
}, [visible, measure, labels, value, standInLabel])
|
||||
|
||||
if (options.length <= 1) return null
|
||||
|
||||
return (
|
||||
<div ref={hostRef} className={css.repoSwitcher} data-scm-repos role="group"
|
||||
aria-label={t('gitRepository')} data-repo-mode={mode}>
|
||||
{mode === 'chips'
|
||||
? (
|
||||
<div className={css.repoChips} role="presentation">
|
||||
{options.map(item => (
|
||||
<button key={item.root} type="button" className={css.repoChip} data-scm-repo={item.root}
|
||||
data-active={item.standIn === true || item.root === value ? 'true' : undefined}
|
||||
data-standin={item.standIn === true ? 'true' : undefined}
|
||||
aria-pressed={item.root === value} title={item.root}
|
||||
disabled={disabled || item.standIn === true}
|
||||
onClick={() => { onChoose(item.root) }}>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<label className={css.repoPick}>
|
||||
<span className={css.repoPickLabel}>{t('gitRepository')}</span>
|
||||
<select className={css.repoPickSelect} aria-label={t('gitRepository')}
|
||||
value={value ?? ''} disabled={disabled}
|
||||
onChange={event => { onChoose(event.target.value) }}>
|
||||
{value === undefined && <option value="" disabled>{t('gitRepository')}</option>}
|
||||
{value !== undefined && standInLabel !== undefined &&
|
||||
<option value={value} disabled>{standInLabel}</option>}
|
||||
{labels.map(item => <option key={item.root} value={item.root}>{item.label}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{/* Natural-width measurement copy. Hidden from layout, AT and tests. */}
|
||||
<div ref={measureRef} className={css.repoMeasure} data-repo-measure aria-hidden="true">
|
||||
{options.map(item => <span key={item.root} className={css.repoChip}>{item.label}</span>)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -58,6 +58,92 @@
|
||||
.scmHeader:hover .scmActions, .scmHeader:focus-within .scmActions { opacity: 1; }
|
||||
@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. The SAME list renders as natural-width chips while it fits on one
|
||||
line and as one native select once it does not; a hidden measurement row
|
||||
makes that decision from content width, not a viewport breakpoint. */
|
||||
.repoSwitcher {
|
||||
position: relative;
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
padding: 0 6px 2px;
|
||||
}
|
||||
.repoChips {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.repoChips::-webkit-scrollbar { display: none; }
|
||||
.repoChip {
|
||||
flex: none;
|
||||
min-height: 22px;
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
border-radius: 3px;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font: var(--dsw-font-xxxs-11);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
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; }
|
||||
|
||||
/* The narrow form: the same caption/box rhythm as the graph's branch select. */
|
||||
.repoPick {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
font: var(--dsw-font-xxs-strong-12);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
.repoPickLabel { flex: none; white-space: nowrap; }
|
||||
.repoPickSelect {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
height: 28px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 3px;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
color: var(--dsw-alias-label-primary);
|
||||
font: inherit;
|
||||
}
|
||||
.repoPickSelect:disabled { opacity: 0.45; cursor: default; }
|
||||
.repoPickSelect:focus-visible { outline: 2px solid var(--dsw-alias-interactive-bg-hover-accent); outline-offset: -2px; }
|
||||
|
||||
/* Natural-width copy used only for the fit decision. Keep it in the layout
|
||||
tree (visibility, not display) so scrollWidth is measurable. */
|
||||
.repoMeasure {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 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
|
||||
tab — the branch control must never leave the bottom of the pane.
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
.root { display: flex; flex: 1; flex-direction: column; min-height: 0; min-width: 0; font: var(--dsw-font-xxs-12); color: var(--dsw-alias-label-primary); }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px 12px; }
|
||||
.select { flex: 1; min-width: 0; max-width: 100%; height: 28px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 3px; background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary); font: inherit; }
|
||||
/* The multi-repo picker slots in ahead of the branch filter so the toolbar
|
||||
reads as one scope row — root first, then its history filter. The slot
|
||||
flexes like .select, so both boxes share the row instead of stacking. */
|
||||
.repoPick { flex: 1; min-width: 0; display: flex; align-items: center; gap: 6px; }
|
||||
.repoPickLabel { flex: none; white-space: nowrap; font: var(--dsw-font-xxs-strong-12); color: var(--dsw-alias-label-primary); }
|
||||
.hint { color: var(--dsw-alias-label-secondary); font: var(--dsw-font-xxxs-11); }
|
||||
.scroll { flex: 1; min-height: 0; overflow: auto; }
|
||||
/* A commit row is ONE 28px line — rail, ref pills, subject (the GitLens-style
|
||||
|
||||
@@ -1,29 +1,23 @@
|
||||
/**
|
||||
* Multi-repository picker in the Git lens (a workspace CONTAINER, i.e. a
|
||||
* project directory that is not itself a repository but holds several).
|
||||
* Responsive multi-repository switcher in the Git lens (a workspace CONTAINER:
|
||||
* a project directory that is not itself a repository but holds several).
|
||||
*
|
||||
* Contract:
|
||||
* - `git.status` reports `repositories` (every discovered root). When it holds
|
||||
* more than one, the lens renders a labeled <select> ("Repository") at the
|
||||
* head of the commit-graph toolbar, ahead of the branch filter: each option
|
||||
* pairs the display-only disambiguation
|
||||
* label (`buildRepositoryLabels(roots, scope.cwd, hostHome)` — deeper roots
|
||||
* carry their relative parent, so same-named checkouts stay tellable apart)
|
||||
* with its absolute root as the value.
|
||||
* - The picker's value is the RESOLVED status root, and both spellings of one
|
||||
* checkout fold (forward/back slashes, trailing separator, Windows case).
|
||||
* When that root is no longer among the retained choices (the server fell
|
||||
* back), it renders as a DISABLED stand-in option with its own short label —
|
||||
* the stale request or the first option is never silently presented as the
|
||||
* selection.
|
||||
* - Changing the picker re-pins the scope through the existing `chooseRepo`,
|
||||
* so the next status read carries that root and the picker
|
||||
* survives the following read (a selected child still reports the full
|
||||
* `repositories` list).
|
||||
* - A single-repository workspace renders NO picker: nothing steals vertical
|
||||
* space from the ordinary case.
|
||||
* - The picker lives in the graph toolbar, so a folded graph hides it; the
|
||||
* ⋯ → Repository submenu stays reachable as the fallback surface.
|
||||
* - The same discovered-root list renders as horizontal chips while every
|
||||
* label fits on one line, and as one native <select> once it does not. The
|
||||
* decision is content-driven (hidden natural-width measurement row), never a
|
||||
* fixed viewport breakpoint; a hidden tab keeps the chips form.
|
||||
* - Chips and options share the display-only labels from
|
||||
* buildRepositoryLabels(roots, scope.cwd, hostHome): deeper roots carry their
|
||||
* relative parent, so same-named checkouts stay tellable apart.
|
||||
* - The selected value is the RESOLVED status root; both spellings of one
|
||||
* checkout fold. When that root is no longer among the retained choices (the
|
||||
* server fell back), it renders as a DISABLED stand-in with its own short
|
||||
* label — never as a silent first option.
|
||||
* - Selecting a root re-pins the scope through the existing chooseRepo, so the
|
||||
* next status read carries that root and the switcher survives the read.
|
||||
* - The ⋯ → Repository submenu keeps the same label list as the folded fallback.
|
||||
* - A single-repository workspace renders no switcher.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { act } from 'react-dom/test-utils'
|
||||
@@ -34,7 +28,31 @@ import { t } from '../src/client/locales.ts'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
|
||||
setupReactAct()
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
const originalClientWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientWidth')
|
||||
const originalScrollWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollWidth')
|
||||
|
||||
/** Restore the real layout readers after a test that stubbed them. */
|
||||
function restoreWidths(): void {
|
||||
delete (HTMLElement.prototype as unknown as Record<string, unknown>).clientWidth
|
||||
delete (HTMLElement.prototype as unknown as Record<string, unknown>).scrollWidth
|
||||
if (originalClientWidth !== undefined) Object.defineProperty(HTMLElement.prototype, 'clientWidth', originalClientWidth)
|
||||
if (originalScrollWidth !== undefined) Object.defineProperty(HTMLElement.prototype, 'scrollWidth', originalScrollWidth)
|
||||
}
|
||||
|
||||
/** jsdom reports 0 for both; tests inject the row/content widths explicitly. */
|
||||
function stubWidths(host: number, content: number): void {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
|
||||
configurable: true,
|
||||
get() { return this.hasAttribute('data-scm-repos') ? host : 0 },
|
||||
})
|
||||
Object.defineProperty(HTMLElement.prototype, 'scrollWidth', {
|
||||
configurable: true,
|
||||
get() { return this.hasAttribute('data-repo-measure') ? content : 0 },
|
||||
})
|
||||
}
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks(); restoreWidths() })
|
||||
|
||||
const CWD = 'C:/work'
|
||||
const ADMIN = 'C:/work-admin'
|
||||
@@ -42,19 +60,30 @@ const DOCS = 'C:/work-docs'
|
||||
const DEEP_A = 'C:/work/pack/alpha'
|
||||
const DEEP_B = 'C:/work/pack/beta'
|
||||
const flush = async (): Promise<void> => { await act(async () => { await Promise.resolve() }) }
|
||||
|
||||
const chips = (container: HTMLElement): HTMLButtonElement[] =>
|
||||
[...container.querySelectorAll<HTMLButtonElement>('[data-scm-repos] [data-scm-repo]')]
|
||||
|
||||
const picker = (container: HTMLElement): HTMLSelectElement => {
|
||||
const node = container.querySelector<HTMLSelectElement>(`[data-scm-repos] select[aria-label="${t('gitRepository')}"]`)
|
||||
if (node === null) throw new Error('repository picker missing')
|
||||
const node = container.querySelector<HTMLSelectElement>('[data-scm-repos] select[aria-label="' + t('gitRepository') + '"]')
|
||||
if (node === null) throw new Error('repository select missing')
|
||||
return node
|
||||
}
|
||||
|
||||
const options = (node: HTMLSelectElement): HTMLOptionElement[] => [...node.options].filter(option => !option.disabled)
|
||||
|
||||
/** One container-workspace snapshot: the resolved root plus every discovered root. */
|
||||
const snapshot = (root: string, repositories: string[]): GitStatusResult =>
|
||||
({ isRepo: true, branch: 'main', root, entries: [], repositories })
|
||||
|
||||
/** Mount the lens over a mocked host; `scopes` records every status request. */
|
||||
async function mount(options: { sessionId: string; repositories?: string[]; resolvedRoot?: (scope: SessionScope) => string }) {
|
||||
/** Mount the lens over a mocked host; scopes records every status request. */
|
||||
async function mount(options: {
|
||||
sessionId: string
|
||||
repositories?: string[]
|
||||
resolvedRoot?: (scope: SessionScope) => string
|
||||
widths?: { host: number; content: number }
|
||||
}) {
|
||||
if (options.widths !== undefined) stubWidths(options.widths.host, options.widths.content)
|
||||
const scopes: SessionScope[] = []
|
||||
const repositories = options.repositories ?? [CWD, ADMIN, DOCS]
|
||||
const resolvedRoot = options.resolvedRoot ?? (scope => scope.repoRoot ?? CWD)
|
||||
@@ -77,59 +106,81 @@ async function mount(options: { sessionId: string; repositories?: string[]; reso
|
||||
return { ...view, scopes }
|
||||
}
|
||||
|
||||
it('lists every discovered repository and re-pins the scope through the picker', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-multi' })
|
||||
function openMoreSubmenu(container: HTMLElement, label: string): HTMLButtonElement[] {
|
||||
const trigger = container.querySelector<HTMLButtonElement>('button[aria-label="' + t('gitMoreActions') + '"]')
|
||||
if (trigger === null) throw new Error('More Actions button not found')
|
||||
act(() => { trigger.click() })
|
||||
const parent = [...document.querySelectorAll<HTMLButtonElement>('[role="menuitem"]')]
|
||||
.find(button => button.textContent?.trim() === label)
|
||||
if (parent === undefined) throw new Error('submenu parent not found: ' + label)
|
||||
act(() => { parent.click() })
|
||||
return [...document.querySelectorAll<HTMLButtonElement>('[role="menu"][data-submenu-layout] button[role="menuitem"]')]
|
||||
}
|
||||
|
||||
it('renders chips while the natural row fits and re-pins the scope', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-wide', widths: { host: 600, content: 300 } })
|
||||
const buttons = chips(view.container)
|
||||
expect(buttons.map(button => button.dataset.scmRepo)).toEqual([CWD, ADMIN, DOCS])
|
||||
expect(buttons.map(button => button.textContent)).toEqual(['work', 'work-admin (C:\\)', 'work-docs (C:\\)'])
|
||||
expect(buttons.map(button => button.dataset.active)).toEqual(['true', undefined, undefined])
|
||||
expect(buttons[0]!.getAttribute('aria-pressed')).toBe('true')
|
||||
expect(view.container.querySelector('[data-scm-repos] select')).toBeNull()
|
||||
|
||||
await act(async () => { buttons[1]!.click() })
|
||||
await flush()
|
||||
await flush()
|
||||
|
||||
// The click went through chooseRepo: the next status read targets that root.
|
||||
expect(view.scopes.at(-1)?.repoRoot).toBe(ADMIN)
|
||||
const after = chips(view.container)
|
||||
expect(after.map(button => button.dataset.active)).toEqual([undefined, 'true', undefined])
|
||||
})
|
||||
|
||||
it('switches the same list to a native select when the row does not fit', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-narrow', widths: { host: 120, content: 300 } })
|
||||
expect(chips(view.container)).toEqual([])
|
||||
const node = picker(view.container)
|
||||
expect(options(node).map(option => option.value)).toEqual([CWD, ADMIN, DOCS])
|
||||
// Siblings outside the session cwd's directory carry their parent context;
|
||||
// the base itself stays short.
|
||||
expect(options(node).map(option => option.textContent)).toEqual(['work', 'work-admin (C:\\)', 'work-docs (C:\\)'])
|
||||
expect(node.value).toBe(CWD)
|
||||
// The scope caption reads in front of the picker, ahead of the branch filter.
|
||||
const caption = node.closest('[data-scm-repos]')!.firstElementChild
|
||||
expect(caption?.tagName).toBe('SPAN')
|
||||
const caption = node.closest('[data-scm-repos]')!.querySelector('span')
|
||||
expect(caption?.textContent).toBe(t('gitRepository'))
|
||||
expect(options(node).map(option => option.textContent)).toEqual(['work', 'work-admin (C:\\)', 'work-docs (C:\\)'])
|
||||
|
||||
await act(async () => { node.value = ADMIN; node.dispatchEvent(new Event('change', { bubbles: true })) })
|
||||
await flush()
|
||||
await flush()
|
||||
|
||||
// The change went through `chooseRepo`: the next status read targets that root...
|
||||
expect(view.scopes.at(-1)?.repoRoot).toBe(ADMIN)
|
||||
// ...and the picker survives the following snapshot, still listing all roots.
|
||||
expect(picker(view.container).value).toBe(ADMIN)
|
||||
expect(options(picker(view.container)).map(option => option.value)).toEqual([CWD, ADMIN, DOCS])
|
||||
})
|
||||
|
||||
it('folds separator, trailing slash and case when naming the current checkout', async () => {
|
||||
// The status snapshot reports the git spelling (`C:/work`); the retained
|
||||
// option may be `C:\WORK\`. Both name the same checkout, so the picker
|
||||
// selects the original spelling instead of falling to the first option.
|
||||
const view = await mount({ sessionId: 'scm-repos-spelling', repositories: ['C:\\WORK\\', ADMIN] })
|
||||
const view = await mount({ sessionId: 'scm-repos-spelling', repositories: ['C:\\WORK\\', ADMIN], widths: { host: 120, content: 300 } })
|
||||
expect(picker(view.container).value).toBe('C:\\WORK\\')
|
||||
})
|
||||
|
||||
it('renders no picker for a single-repository workspace', async () => {
|
||||
it('renders no switcher for a single-repository workspace', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-single', repositories: [CWD] })
|
||||
expect(view.container.querySelector('[data-scm-repos]')).toBeNull()
|
||||
// The ordinary panel is intact: the Changes section is still there.
|
||||
expect(view.container.querySelector('[data-scm-section="changes"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('labels deeper repositories with their relative parent', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-labels', repositories: [CWD, DEEP_A, DEEP_B] })
|
||||
const view = await mount({ sessionId: 'scm-repos-labels', repositories: [CWD, DEEP_A, DEEP_B], widths: { host: 120, content: 300 } })
|
||||
expect(options(picker(view.container)).map(option => option.textContent))
|
||||
.toEqual(['work', 'alpha (pack)', 'beta (pack)'])
|
||||
})
|
||||
|
||||
it('shares the same disambiguated labels with the More Repository submenu', async () => {
|
||||
const view = await mount({ sessionId: 'scm-repos-menu', repositories: [CWD, DEEP_A, DEEP_B] })
|
||||
expect(openMoreSubmenu(view.container, t('gitRepository')).map(item => item.textContent))
|
||||
.toEqual(['work', 'alpha (pack)', 'beta (pack)'])
|
||||
})
|
||||
|
||||
it('shows the server-fallback root as a disabled stand-in, never as a silent first option', async () => {
|
||||
// Picking ADMIN while the server resolves it to a checkout outside the
|
||||
// retained list: the picker must name THAT root (short label, disabled), not
|
||||
// quietly select the first option or keep the stale request.
|
||||
const FALLBACK = '/elsewhere/checkout'
|
||||
const view = await mount({
|
||||
sessionId: 'scm-repos-fallback',
|
||||
resolvedRoot: scope => scope.repoRoot === ADMIN ? FALLBACK : (scope.repoRoot ?? CWD),
|
||||
widths: { host: 120, content: 300 },
|
||||
})
|
||||
await act(async () => {
|
||||
const node = picker(view.container)
|
||||
@@ -138,7 +189,6 @@ it('shows the server-fallback root as a disabled stand-in, never as a silent fir
|
||||
})
|
||||
await flush()
|
||||
await flush()
|
||||
// A scope change resets the status slot, so the picker remounts; re-query.
|
||||
const node = picker(view.container)
|
||||
expect(node.value).toBe(FALLBACK)
|
||||
const standIn = node.selectedOptions[0]!
|
||||
|
||||
@@ -258,12 +258,11 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => {
|
||||
await flushEffects()
|
||||
|
||||
// The workspace container's child repositories retain their basename labels.
|
||||
const repoPicker = container.querySelector<HTMLSelectElement>(`[data-scm-repos] select[aria-label="${t('gitRepository')}"]`)!
|
||||
expect(repoPicker).not.toBeNull()
|
||||
expect([...repoPicker.options].map(option => option.textContent)).toEqual(['a', 'b'])
|
||||
const repoChips = [...container.querySelectorAll<HTMLButtonElement>('[data-scm-repos] [data-scm-repo]')]
|
||||
expect(repoChips.map(chip => chip.textContent)).toEqual(['a', 'b'])
|
||||
const listingsBefore = worktrees.mock.calls.length
|
||||
|
||||
await act(async () => { repoPicker.value = REPO_B; repoPicker.dispatchEvent(new Event('change', { bubbles: true })) })
|
||||
await act(async () => { repoChips.find(chip => chip.dataset.scmRepo === REPO_B)!.click() })
|
||||
await flushEffects()
|
||||
|
||||
// The listing carries the selected repoRoot — a container's own listing
|
||||
@@ -287,10 +286,8 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => {
|
||||
act(() => { document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) })
|
||||
act(() => { document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) })
|
||||
|
||||
// The toolbar picker stays alongside the ⋯ → Repository fallback submenu.
|
||||
const picker = container.querySelector<HTMLSelectElement>(`[data-scm-repos] select[aria-label="${t('gitRepository')}"]`)!
|
||||
await act(async () => { picker.value = REPO_A; picker.dispatchEvent(new Event('change', { bubbles: true })) })
|
||||
await flushEffects()
|
||||
// The ⋯ → Repository submenu remains the folded/menu fallback.
|
||||
await chooseMoreOption(container, t('gitRepository'), 'a')
|
||||
expect(branchButton(container).title).toBe(`${t('branch')}: a-main*`)
|
||||
expect(container.querySelector('[data-path="a-change.ts"]')).not.toBeNull()
|
||||
expect(container.querySelector('[data-path="b-change.ts"]')).toBeNull()
|
||||
|
||||
Reference in new issue
Block a user