diff --git a/src/client/changes/GitLens.tsx b/src/client/changes/GitLens.tsx index 01574f1e..48c0bf60 100644 --- a/src/client/changes/GitLens.tsx +++ b/src/client/changes/GitLens.tsx @@ -19,6 +19,7 @@ import type { GitLineCounts, GitLogEntry, GitStatusEntry, GitStatusResult, GitWo import { api, SidebarApiError } from '../api.ts' import { builtinFileIcon, builtinFolderIcon } from '../file-icons.tsx' import { usePolling } from '../use-polling.ts' +import { useSubmenuFlip } from '../menu-flip.ts' import { baseName, relativeTo } from '../paths.ts' import { resolveSidebarPath } from '../paths.ts' import { isZh, t } from '../locales.ts' @@ -403,7 +404,17 @@ export function GitLens(props: GitLensProps) { const [graphRefresh, setGraphRefresh] = useState(0) const [changesOpen, setChangesOpen] = useState(true) const [graphOpen, setGraphOpen] = useState(true) - const [moreOpen, setMoreOpen] = useState(false) + /** + * The open More Actions menu: the trigger's viewport corner (null = closed). + * Its repo/worktree rows carry nested submenus, which the primitives anchor + * with static CSS growing RIGHT of the card — past the right edge of this + * docked panel. This menu is button-anchored (no cursor point to publish), + * so open/close keeps the measured corner and hands it to the same flip + * mechanism as the file-tree row menu. + */ + const [moreMenu, setMoreMenu] = useState<{ x: number; y: number } | null>(null) + const moreOpen = moreMenu !== null + useSubmenuFlip(moreMenu) const [branchOpen, setBranchOpen] = useState(false) /** Commit drafts, one per scope: the Commit button asks only for a message * and a staged row, so a draft typed against another project would submit @@ -557,7 +568,7 @@ export function GitLens(props: GitLensProps) { setFileMenu(null) setHistoryMenu(null) setConfirm(null) - setMoreOpen(false) + setMoreMenu(null) setBranchOpen(false) } @@ -1092,9 +1103,15 @@ export function GitLens(props: GitLensProps) { disabled={!canCommit} onClick={commit} /> } label={t('refresh')} disabled={busy || suggesting} onClick={() => { invalidateGitStatus(scope.sessionId); void refresh(false) }} /> - { setMoreOpen(false) }} portal compact align="end" autoFocus + { setMoreMenu(null) }} portal compact align="end" autoFocus anchor={} label={t('gitMoreActions')} - active={moreOpen} onClick={() => { setMoreOpen(open => !open) }} />} + active={moreOpen} onClick={(event) => { + if (moreOpen) { setMoreMenu(null); return } + // The menu hangs off this button, so its corner IS the anchor the + // flip heuristic needs (a keyboard activation has no cursor point). + const rect = event.currentTarget.getBoundingClientRect() + setMoreMenu({ x: rect.right, y: rect.top }) + }} />} items={[ { id: 'pull', label: t('pull'), disabled: busy || suggesting || snapshot?.detached === true }, { id: 'push', label: t('push'), disabled: busy || suggesting || snapshot?.detached === true }, @@ -1108,7 +1125,7 @@ export function GitLens(props: GitLensProps) { }] : []), ]} onSelect={id => { - setMoreOpen(false) + setMoreMenu(null) if (id === 'push') push() else if (id === 'pull') pull() else if (id.startsWith('repo:')) chooseRepo(id.slice(5)) diff --git a/src/client/layout.css b/src/client/layout.css index de01d88e..b28fb0ab 100644 --- a/src/client/layout.css +++ b/src/client/layout.css @@ -78,6 +78,7 @@ body[data-dsh-sidebar-dragging] #root [data-dsh-center-col] { #root [data-dsh-center-col] { transition: none; } +} /* Context-menu submenu flip (viewport clamping for the portaled menus). * @@ -91,8 +92,8 @@ body[data-dsh-sidebar-dragging] #root [data-dsh-center-col] { * * menu-flip.ts publishes `data-dsh-sidebar-submenu` on — with the * words "down" and/or "left" — for exactly the lifetime of one of OUR - * submenu-bearing menus (FileTree row menu, TabBar tab menu). The tokens - * flip the growth direction; the attribute's absence restores the + * submenu-bearing menus (FileTree row menu, Git panel's More Actions menu). + * The tokens flip the growth direction; the attribute's absence restores the * primitive's own geometry untouched, and host-owned menus are never * affected because they never open while the attribute exists (each side * closes on the other's outside pointerdown). diff --git a/tests/css-block-scope.spec.ts b/tests/css-block-scope.spec.ts new file mode 100644 index 00000000..62c1d3e9 --- /dev/null +++ b/tests/css-block-scope.spec.ts @@ -0,0 +1,196 @@ +/** + * Block-scope guard for the client stylesheets. + * + * layout.css shipped from 36fbc5a up to 0.27.0 with an unclosed + * @media (prefers-reduced-motion: reduce) block (issue #955): every rule after + * it — the context-menu submenu flip and the visual tether — became a + * descendant of that media query. The flip then applied only to users who had + * reduce-motion turned on; everyone else lost the flip and the tether, and the + * "open with" submenu grew past the right edge of a right-docked workbench. + * + * tests/menu-flip.spec.tsx could not see it: expect(css).toContain(...) matches + * selector text wherever it sits, and nesting does not change text. These + * assertions read the block structure instead — every client stylesheet has to + * close what it opens, and the rules the flip depends on have to stay at top + * level — so the same mistake fails here. + */ +import { readdirSync, readFileSync } from 'node:fs' +import { join, relative, resolve } from 'node:path' +import { describe, expect, it } from 'vitest' +import { SUBMENU_FLIP_ATTR } from '../src/client/menu-flip.ts' + +const ROOT = resolve(import.meta.dirname, '..') + +interface Block { + /** The selector (or at-rule prelude) that opened this block, normalised. */ + prelude: string + /** The nesting depth the block opens at: 0 = top level. */ + depth: number + /** Index of the enclosing block in the same list, or -1 at top level. */ + parent: number +} + +interface Scan { + blocks: Block[] + /** Blocks still open at end of file. */ + unclosed: number + /** Closing braces with nothing to close. */ + extraClosers: number +} + +/** + * Whitespace collapsed and attribute-value quotes dropped, so a reformatted or + * re-quoted selector (div[role="menu"] vs div[role=menu]) still compares equal + * to the selector a test names — this guard is about block structure, not text. + */ +function normalize(selector: string): string { + return selector + .trim() + .replace(/\s+/g, ' ') + .replace(/\[([-\w]+)\s*([~|^$*]?=)\s*"([^"]*)"\]/g, '[$1$2$3]') + .replace(/\[([-\w]+)\s*([~|^$*]?=)\s*'([^']*)'\]/g, '[$1$2$3]') +} + +/** + * Walk a stylesheet and report every block it opens, with the depth it opens at. + * Comment bodies are dropped as they are read and quoted strings are consumed + * whole — including the quotes inside a url() token — so a brace inside + * content: "}" or inside a data URI can neither open nor close a block. + */ +function scanBlocks(css: string): Scan { + const blocks: Block[] = [] + const stack: number[] = [] + let extraClosers = 0 + let prelude = '' + let i = 0 + + /** The quoted string that starts at `from`. */ + function quoted(from: number): string { + const quote = css.charAt(from) + let text = quote + let j = from + 1 + while (j < css.length) { + const inner = css.charAt(j) + text += inner + j += 1 + if (inner === '\\') { text += css.charAt(j); j += 1; continue } + if (inner === quote) break + } + i = j + return text + } + + /** The url(...) token that starts at `from`, unquoted payload included. */ + function urlToken(from: number): string { + let text = '' + let j = from + let parens = 0 + while (j < css.length) { + const inner = css.charAt(j) + if (inner === '"' || inner === "'") { text += quoted(j); j = i; continue } + text += inner + j += 1 + if (inner === '(') parens += 1 + else if (inner === ')') { parens -= 1; if (parens === 0) break } + } + i = j + return text + } + + while (i < css.length) { + const ch = css.charAt(i) + if (ch === '/' && css.charAt(i + 1) === '*') { + const close = css.indexOf('*/', i + 2) + i = close === -1 ? css.length : close + 2 + prelude += ' ' + continue + } + if (ch === '"' || ch === "'") { prelude += quoted(i); continue } + if (css.slice(i, i + 4).toLowerCase() === 'url(') { prelude += urlToken(i); continue } + if (ch === '{') { + const parent = stack.length > 0 ? (stack[stack.length - 1] ?? -1) : -1 + blocks.push({ prelude: normalize(prelude), depth: stack.length, parent }) + stack.push(blocks.length - 1) + prelude = '' + i += 1 + continue + } + if (ch === '}') { + if (stack.length === 0) extraClosers += 1 + else stack.pop() + prelude = '' + i += 1 + continue + } + prelude += ch + i += 1 + } + return { blocks, unclosed: stack.length, extraClosers } +} + +function cssFilesUnder(dir: string): string[] { + const found: string[] = [] + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name) + if (entry.isDirectory()) found.push(...cssFilesUnder(path)) + else if (entry.name.toLowerCase().endsWith('.css')) found.push(path) + } + return found +} + +describe('client stylesheet block scope', () => { + it('closes every block it opens, in every stylesheet under src/', () => { + const files = cssFilesUnder(join(ROOT, 'src')) + // A walk that silently found nothing would make the assertion below vacuous. + expect(files.length).toBeGreaterThan(0) + const unbalanced = files + .map(path => ({ path, ...scanBlocks(readFileSync(path, 'utf8')) })) + .filter(({ unclosed, extraClosers }) => unclosed !== 0 || extraClosers !== 0) + .map(({ path, unclosed, extraClosers }) => { + const faults = [ + unclosed > 0 ? unclosed + ' unclosed block(s)' : '', + extraClosers > 0 ? extraClosers + ' extra closing brace(s)' : '', + ].filter(Boolean) + return relative(ROOT, path) + ': ' + faults.join(', ') + }) + expect(unbalanced).toEqual([]) + }) + + it('keeps the submenu flip and tether rules out of the reduced-motion media query', () => { + const { blocks } = scanBlocks(readFileSync(join(ROOT, 'src/client/layout.css'), 'utf8')) + + // menu-flip.ts publishes the attribute on ; these six rules are its + // only consumers, and they are the whole mechanism that keeps OUR nested + // menus inside the viewport. Every one of them has to match in the default + // theme, not only for users who asked for reduced motion. + const ATTR = SUBMENU_FLIP_ATTR + const indexOfRule = (selector: string): number => { + const wanted = normalize(selector) + const matched = blocks.findIndex(block => block.prelude === wanted) + expect(matched, 'no rule opened by ' + wanted).toBeGreaterThanOrEqual(0) + expect(blocks.filter(block => block.prelude === wanted), 'more than one rule for ' + wanted).toHaveLength(1) + expect(blocks[matched]?.depth, wanted + ' is nested instead of top level').toBe(0) + return matched + } + + const tetherGap = indexOfRule('body[' + ATTR + '] div[role="menu"] div[role="menu"]') + indexOfRule('body[' + ATTR + '] div[role="menu"] button[aria-expanded="true"]') + indexOfRule('body[' + ATTR + '] div[role="menu"] div[role="menu"]::before') + indexOfRule('body[' + ATTR + '~="down"] div[role="menu"] div[role="menu"]') + const flipLeft = indexOfRule('body[' + ATTR + '~="left"] div[role="menu"] div[role="menu"]') + indexOfRule('body[' + ATTR + '~="left"] div[role="menu"] div[role="menu"]::before') + + // Same specificity, so the declared order decides: layout.css puts the + // tether BEFORE the flip overrides "so their left/right flips still win". + // Moving the tether below them silently kills the left flip. + expect(tetherGap, 'the tether has to stay declared before the flip overrides').toBeLessThan(flipLeft) + + // Only the center-column override belongs inside the reduced-motion block. + // A rule that follows a block missing its closing brace lands here as an + // extra child — which is exactly how #955 shipped, silently and unseen. + const media = blocks.findIndex(block => block.prelude === '@media (prefers-reduced-motion: reduce)') + expect(media, 'the reduced-motion media query is gone').toBeGreaterThanOrEqual(0) + const insideMedia = blocks.filter(block => block.parent === media).map(block => block.prelude) + expect(insideMedia).toEqual(['#root [data-dsh-center-col]']) + }) +}) diff --git a/tests/git-view-worktree.spec.tsx b/tests/git-view-worktree.spec.tsx index 37e835e2..93a1eec0 100644 --- a/tests/git-view-worktree.spec.tsx +++ b/tests/git-view-worktree.spec.tsx @@ -19,6 +19,7 @@ import { createSidebarStore } from '../src/client/state.ts' import { api, type GitStatusEntry, type GitStatusResult, type GitWorktree } from '../src/client/api.ts' import type { BetterSidebarService } from '../src/client/service.ts' import { t } from '../src/client/locales.ts' +import { SUBMENU_FLIP_ATTR } from '../src/client/menu-flip.ts' import type { Context } from '../src/context-types.ts' import { setupReactAct } from './test-utils.ts' @@ -493,6 +494,51 @@ describe('GitLens (changes tab, git lens) linked-worktree consistency', () => { }) }) +/** + * Issue #988: the More Actions menu's repo/worktree rows open nested + * submenus. The button-anchored menu used to skip the body attribute the + * file-tree row menu publishes (menu-flip.ts), so layout.css never had the + * tokens it needs to flip those submenus back inside the viewport — in a + * right-docked sidebar they opened past the right edge and were unreachable. + */ +describe('GitLens (changes tab, git lens) More Actions submenu flip (#988)', () => { + it('publishes the flip geometry while the menu is open and clears it on close', async () => { + vi.spyOn(api, 'gitWorktrees').mockResolvedValue(inventories) + vi.spyOn(api, 'gitStatus').mockImplementation(async (_scope, target) => statusFor(target)) + vi.spyOn(api, 'gitBranch').mockImplementation(async (_scope, target) => ({ + current: target === AGENT ? 'agent' : 'main', + names: target === AGENT ? ['agent'] : ['main'], + })) + vi.spyOn(api, 'gitGraph').mockResolvedValue(graphFor(AGENT)) + + const { container, root } = makeRoot() + try { + mountGit(root) + await flushEffects() + // The attribute's lifetime IS the mechanism's scope: closed menu, no + // attribute (layout.css must not touch host-owned menus). + expect(document.body.hasAttribute(SUBMENU_FLIP_ATTR)).toBe(false) + + // The trigger of a right-docked sidebar, above the viewport's midpoint. + // Those coordinates have to produce BOTH flips: left (no right-hand room + // for card + submenu) and down (more room below the top-edge row menu). + const trigger = container.querySelector(`button[aria-label="${t('gitMoreActions')}"]`) + if (trigger === null) throw new Error('More Actions button not found') + vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(976, 100, 24, 24)) + + expect(openMoreSubmenu(container, t('worktree')).length).toBeGreaterThan(0) + expect(document.body.getAttribute(SUBMENU_FLIP_ATTR)).toBe('down left') + + // Closing the menu drops the tokens: the next menu gets its own geometry. + act(() => { trigger.click() }) + expect(document.body.hasAttribute(SUBMENU_FLIP_ATTR)).toBe(false) + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) +}) + describe('GitLens (changes tab, git lens) change tree', () => { /** Mount with one changed-file inventory; every test picks its own entries. */ async function mountTree(