Make Enter confirm source-control discard dialogs (#4410)

This commit is contained in:
Neil
2026-06-01 18:54:44 -07:00
committed by GitHub
parent 46a66dd64a
commit cb3ea04e22
3 changed files with 234 additions and 58 deletions
@@ -81,10 +81,9 @@ import {
type SourceControlTreeNode
} from './source-control-tree'
import {
getDiscardAreaConfirmationCopy,
getDiscardEntryConfirmationCopy,
type DiscardConfirmationCopy
} from './source-control-discard-confirmation'
SourceControlDiscardDialog,
type PendingDiscardConfirmation
} from './source-control-discard-dialog'
import { refreshGitStatusForWorktree } from './git-status-refresh'
import { toast } from 'sonner'
import {
@@ -423,10 +422,6 @@ export function requestSourceControlViewModePreferenceWrite({
return next
}
type PendingDiscardConfirmation =
| { kind: 'entry'; entry: GitStatusEntry }
| { kind: 'area'; area: DiscardAllArea; paths: readonly string[] }
type GitStatusSourceControlTreeNode = SourceControlTreeNode<
GitStatusEntry,
(typeof SECTION_ORDER)[number]
@@ -1776,16 +1771,6 @@ function SourceControlInner(): React.JSX.Element {
}, [collapsedSections, flatEntries, sourceControlViewMode, visibleTreeRowsByArea])
const [isExecutingBulk, setIsExecutingBulk] = useState(false)
const pendingDiscardCopy = useMemo<DiscardConfirmationCopy | null>(() => {
if (!pendingDiscard) {
return null
}
if (pendingDiscard.kind === 'entry') {
return getDiscardEntryConfirmationCopy(pendingDiscard.entry)
}
return getDiscardAreaConfirmationCopy(pendingDiscard.area, pendingDiscard.paths.length)
}, [pendingDiscard])
const unresolvedConflicts = useMemo(
() => entries.filter((entry) => entry.conflictStatus === 'unresolved' && entry.conflictKind),
[entries]
@@ -4153,7 +4138,6 @@ function SourceControlInner(): React.JSX.Element {
const showGenericEmptyState =
!hasUncommittedEntries && branchSummary?.status === 'ready' && branchEntries.length === 0
const currentWorktreeId = activeWorktree.id
const PendingDiscardIcon = pendingDiscardCopy?.confirmLabel.startsWith('Delete') ? Trash : Undo2
return (
<>
@@ -4854,45 +4838,11 @@ function SourceControlInner(): React.JSX.Element {
</DialogContent>
</Dialog>
<Dialog
open={pendingDiscard !== null}
onOpenChange={(open) => {
if (!open) {
setPendingDiscard(null)
}
}}
>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="text-sm">
{pendingDiscardCopy?.title ?? 'Discard changes?'}
</DialogTitle>
<DialogDescription className="text-xs">
{pendingDiscardCopy?.description ?? 'This cannot be undone.'}
</DialogDescription>
</DialogHeader>
{pendingDiscard?.kind === 'area' ? (
<div className="rounded-md border border-border/70 bg-muted/35 px-3 py-2 text-xs text-muted-foreground">
{pendingDiscard.paths.length} {pendingDiscard.paths.length === 1 ? 'file' : 'files'}
</div>
) : pendingDiscard?.kind === 'entry' ? (
<div className="rounded-md border border-border/70 bg-muted/35 px-3 py-2 text-xs">
<div className="break-all font-medium text-foreground">
{pendingDiscard.entry.path}
</div>
</div>
) : null}
<DialogFooter>
<Button type="button" variant="outline" onClick={() => setPendingDiscard(null)}>
Cancel
</Button>
<Button type="button" variant="destructive" onClick={confirmPendingDiscard}>
<PendingDiscardIcon className="size-4" />
{pendingDiscardCopy?.confirmLabel ?? 'Discard'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<SourceControlDiscardDialog
pendingDiscard={pendingDiscard}
onCancel={() => setPendingDiscard(null)}
onConfirm={confirmPendingDiscard}
/>
<Dialog open={baseRefDialogOpen} onOpenChange={setBaseRefDialogOpen}>
<DialogContent className="max-w-xl">
@@ -0,0 +1,119 @@
import { renderToStaticMarkup } from 'react-dom/server'
import type { ButtonHTMLAttributes, ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { GitStatusEntry } from '../../../../shared/types'
type CapturedButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
children?: ReactNode
variant?: string
}
const mocks = vi.hoisted(() => ({
buttons: [] as CapturedButtonProps[],
dialogContentProps: [] as Record<string, unknown>[]
}))
vi.mock('@/components/ui/dialog', () => ({
Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
open ? <div>{children}</div> : null,
DialogContent: ({
children,
...props
}: {
children: ReactNode
onOpenAutoFocus?: (event: Event) => void
}) => {
mocks.dialogContentProps.push(props)
return <div>{children}</div>
},
DialogDescription: ({ children }: { children: ReactNode }) => <p>{children}</p>,
DialogFooter: ({ children }: { children: ReactNode }) => <footer>{children}</footer>,
DialogHeader: ({ children }: { children: ReactNode }) => <header>{children}</header>,
DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>
}))
vi.mock('@/components/ui/button', async () => {
const ReactModule = await import('react')
return {
Button: ReactModule.forwardRef<HTMLButtonElement, CapturedButtonProps>(function Button(
{ children, variant: _variant, ...props },
ref
) {
mocks.buttons.push({ ...props, variant: _variant, children })
return (
<button {...props} ref={ref}>
{children}
</button>
)
})
}
})
function entry(partial: Partial<GitStatusEntry> & { path: string }): GitStatusEntry {
return {
area: 'unstaged',
status: 'modified',
...partial
}
}
function textContent(node: ReactNode): string {
if (node == null || typeof node === 'boolean') {
return ''
}
if (typeof node === 'string' || typeof node === 'number') {
return String(node)
}
if (Array.isArray(node)) {
return node.map(textContent).join('')
}
if (typeof node === 'object' && 'props' in node) {
return textContent((node as { props?: { children?: ReactNode } }).props?.children)
}
return ''
}
describe('SourceControlDiscardDialog', () => {
beforeEach(() => {
mocks.buttons = []
mocks.dialogContentProps = []
})
it('makes the discard button the dialog default action', async () => {
const { SourceControlDiscardDialog } = await import('./source-control-discard-dialog')
renderToStaticMarkup(
<SourceControlDiscardDialog
pendingDiscard={{
kind: 'entry',
entry: entry({ path: 'src/changed.ts', status: 'modified' })
}}
onCancel={vi.fn()}
onConfirm={vi.fn()}
/>
)
const cancelButton = mocks.buttons.find((button) => textContent(button.children) === 'Cancel')
const discardButton = mocks.buttons.find((button) =>
textContent(button.children).includes('Discard')
)
expect(cancelButton?.autoFocus).not.toBe(true)
expect(discardButton?.variant).toBe('destructive')
expect(discardButton?.autoFocus).toBe(true)
expect(mocks.dialogContentProps[0]?.onOpenAutoFocus).toEqual(expect.any(Function))
})
})
describe('focusDiscardDialogConfirmButton', () => {
it('prevents Radix from focusing the first tabbable button', async () => {
const { focusDiscardDialogConfirmButton } = await import('./source-control-discard-dialog')
const event = { preventDefault: vi.fn() } as unknown as Event
const confirmButton = { focus: vi.fn() } as unknown as HTMLButtonElement
focusDiscardDialogConfirmButton(event, confirmButton)
expect(event.preventDefault).toHaveBeenCalledTimes(1)
expect(confirmButton.focus).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,107 @@
import { useMemo, useRef } from 'react'
import { Trash, Undo2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import type { GitStatusEntry } from '../../../../shared/types'
import type { DiscardAllArea } from './discard-all-sequence'
import {
getDiscardAreaConfirmationCopy,
getDiscardEntryConfirmationCopy
} from './source-control-discard-confirmation'
export type PendingDiscardConfirmation =
| { kind: 'entry'; entry: GitStatusEntry }
| { kind: 'area'; area: DiscardAllArea; paths: readonly string[] }
export function focusDiscardDialogConfirmButton(
event: Event,
confirmButton: HTMLButtonElement | null
): void {
if (!confirmButton) {
return
}
// Why: Radix otherwise focuses Cancel first, making Enter dismiss this destructive confirm.
event.preventDefault()
confirmButton.focus()
}
export function SourceControlDiscardDialog({
pendingDiscard,
onCancel,
onConfirm
}: {
pendingDiscard: PendingDiscardConfirmation | null
onCancel: () => void
onConfirm: () => void
}): React.JSX.Element {
const confirmButtonRef = useRef<HTMLButtonElement>(null)
const pendingDiscardCopy = useMemo(() => {
if (!pendingDiscard) {
return null
}
if (pendingDiscard.kind === 'entry') {
return getDiscardEntryConfirmationCopy(pendingDiscard.entry)
}
return getDiscardAreaConfirmationCopy(pendingDiscard.area, pendingDiscard.paths.length)
}, [pendingDiscard])
const PendingDiscardIcon = pendingDiscardCopy?.confirmLabel.startsWith('Delete') ? Trash : Undo2
return (
<Dialog
open={pendingDiscard !== null}
onOpenChange={(open) => {
if (!open) {
onCancel()
}
}}
>
<DialogContent
className="max-w-md"
onOpenAutoFocus={(event) =>
focusDiscardDialogConfirmButton(event, confirmButtonRef.current)
}
>
<DialogHeader>
<DialogTitle className="text-sm">
{pendingDiscardCopy?.title ?? 'Discard changes?'}
</DialogTitle>
<DialogDescription className="text-xs">
{pendingDiscardCopy?.description ?? 'This cannot be undone.'}
</DialogDescription>
</DialogHeader>
{pendingDiscard?.kind === 'area' ? (
<div className="rounded-md border border-border/70 bg-muted/35 px-3 py-2 text-xs text-muted-foreground">
{pendingDiscard.paths.length} {pendingDiscard.paths.length === 1 ? 'file' : 'files'}
</div>
) : pendingDiscard?.kind === 'entry' ? (
<div className="rounded-md border border-border/70 bg-muted/35 px-3 py-2 text-xs">
<div className="break-all font-medium text-foreground">{pendingDiscard.entry.path}</div>
</div>
) : null}
<DialogFooter>
<Button type="button" variant="outline" onClick={onCancel}>
Cancel
</Button>
<Button
ref={confirmButtonRef}
type="button"
variant="destructive"
autoFocus
onClick={onConfirm}
>
<PendingDiscardIcon className="size-4" />
{pendingDiscardCopy?.confirmLabel ?? 'Discard'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}