Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions app/packages/web/src/components/confirm-dialog.component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ConfirmDialog } from './confirm-dialog.component.js';
import { isSuppressed } from '../lib/confirm-skip.utils.js';

const mockStore = new Set<string>();

vi.mock('../lib/confirm-skip.utils.js', () => ({
isSuppressed: (key: string) => mockStore.has(key),
suppress: (key: string) => mockStore.add(key),
}));

function open(overrides: Partial<Parameters<typeof ConfirmDialog>[0]> = {}) {
const onConfirm = vi.fn();
const onOpenChange = vi.fn();
render(
<ConfirmDialog
open
onOpenChange={onOpenChange}
title="Delete this?"
description="This cannot be undone."
onConfirm={onConfirm}
{...overrides}
/>,
);
return { onConfirm, onOpenChange };
}

describe('ConfirmDialog', () => {
beforeEach(() => {
mockStore.clear();
});

it('should render the title and description', () => {
open();
expect(screen.getByRole('alertdialog')).toBeInTheDocument();
expect(screen.getByText('Delete this?')).toBeInTheDocument();
expect(screen.getByText('This cannot be undone.')).toBeInTheDocument();
});

it('should call onConfirm when the confirm button is clicked', async () => {
const { onConfirm } = open();
await userEvent.click(screen.getByRole('button', { name: /confirm/i }));
expect(onConfirm).toHaveBeenCalledOnce();
});

it('should not call onConfirm when cancel is clicked', async () => {
const { onConfirm, onOpenChange } = open();
await userEvent.click(screen.getByRole('button', { name: /cancel/i }));
expect(onConfirm).not.toHaveBeenCalled();
expect(onOpenChange).toHaveBeenCalledWith(false);
});

it('should disable Confirm until the typed value matches typeToConfirm', async () => {
open({ typeToConfirm: 'abc123' });
const confirmBtn = screen.getByRole('button', { name: /confirm/i });
expect(confirmBtn).toBeDisabled();

await userEvent.type(screen.getByRole('textbox'), 'abc123');
expect(confirmBtn).not.toBeDisabled();
});

it('should suppress the key and call onConfirm when "don\'t ask again" is checked', async () => {
const { onConfirm } = open({ confirmKey: 'test-key' });
await userEvent.click(screen.getByRole('checkbox'));
await userEvent.click(screen.getByRole('button', { name: /confirm/i }));
expect(onConfirm).toHaveBeenCalledOnce();
expect(isSuppressed('test-key')).toBe(true);
});

it('should not suppress the key when "don\'t ask again" is NOT checked', async () => {
open({ confirmKey: 'other-key' });
await userEvent.click(screen.getByRole('button', { name: /confirm/i }));
expect(isSuppressed('other-key')).toBe(false);
});

it('should use a custom confirmLabel when provided', () => {
open({ confirmLabel: 'Yes, stop it' });
expect(screen.getByRole('button', { name: 'Yes, stop it' })).toBeInTheDocument();
});
});
107 changes: 107 additions & 0 deletions app/packages/web/src/components/confirm-dialog.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { useState, useEffect } from 'react';
import {
AlertDialog,
AlertDialogContent,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogCancel,
AlertDialogAction,
} from '@/components/ui/alert-dialog.component';
import { Input } from '@/components/ui/input.component';
import { suppress } from '../lib/confirm-skip.utils.js';

interface ConfirmDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
description: string;
onConfirm: () => void;
/** Label for the confirm button. Defaults to "Confirm". */
confirmLabel?: string;
/**
* When provided, shows a "Don't ask again for this session" checkbox.
* The key is stored in the module-level session store so the caller can
* bypass opening the dialog on future clicks via `isSuppressed(confirmKey)`.
*/
confirmKey?: string;
/**
* When provided, shows a text input; the confirm button stays disabled
* until the typed value exactly matches this string (e.g. a guild ID).
*/
typeToConfirm?: string;
}

/**
* Generic confirmation dialog for destructive actions. Wraps shadcn AlertDialog
* with optional type-to-confirm input and "don't ask again" session suppression.
* ESC, focus-trap, and reduce-motion are handled by Radix automatically.
*/
export function ConfirmDialog({
open,
onOpenChange,
title,
description,
onConfirm,
confirmLabel = 'Confirm',
confirmKey,
typeToConfirm,
}: ConfirmDialogProps) {
const [typed, setTyped] = useState('');
const [skipSession, setSkipSession] = useState(false);

useEffect(() => {
if (!open) {
setTyped('');
setSkipSession(false);
}
}, [open]);

const confirmDisabled = typeToConfirm !== undefined && typed !== typeToConfirm;

function handleConfirm() {
if (confirmKey && skipSession) suppress(confirmKey);
onConfirm();
}

return (
<AlertDialog open={open} onOpenChange={onOpenChange}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>

{typeToConfirm !== undefined && (
<Input
value={typed}
onChange={(e) => setTyped(e.target.value)}
placeholder={typeToConfirm}
className="font-[var(--font-mono)]"
aria-label="Type to confirm"
/>
)}

{confirmKey && (
<label className="flex items-center gap-2 text-sm text-[var(--color-muted-foreground)] cursor-pointer">
<input
type="checkbox"
checked={skipSession}
onChange={(e) => setSkipSession(e.target.checked)}
className="size-3.5 rounded"
/>
Don&apos;t ask again for this session
</label>
)}

<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={handleConfirm} disabled={confirmDisabled}>
Comment on lines +98 to +100
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5dc1e08 — removed the handleCancel function and the onClick from AlertDialogCancel. The Radix controlled root already fires onOpenChange(false) on cancel, so the explicit handler was a duplicate call.


Generated by Claude Code

{confirmLabel}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
77 changes: 77 additions & 0 deletions app/packages/web/src/components/game-card.component.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { GameCard } from './game-card.component.js';

const apiMock = vi.hoisted(() => ({
stop: vi.fn().mockResolvedValue(undefined),
start: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('../api.service.js', () => ({ api: apiMock }));

const mockIsSuppressed = vi.hoisted(() => vi.fn().mockReturnValue(false));
vi.mock('../lib/confirm-skip.utils.js', () => ({
isSuppressed: mockIsSuppressed,
suppress: vi.fn(),
}));

/** A minimal running-server status fixture. */
const runningStatus = {
game: 'minecraft',
state: 'running' as const,
};

function renderCard() {
return render(
<MemoryRouter>
<GameCard
status={runningStatus}
onRefresh={vi.fn()}
onOpenFiles={vi.fn()}
/>
</MemoryRouter>,
);
}

describe('GameCard — Stop confirmation', () => {
it('should show the confirmation dialog when Stop is clicked and the action is not suppressed', async () => {
mockIsSuppressed.mockReturnValue(false);
renderCard();

await userEvent.click(screen.getByRole('button', { name: /stop/i }));

expect(screen.getByRole('alertdialog')).toBeInTheDocument();
expect(screen.getByText('Stop minecraft?')).toBeInTheDocument();
});

it('should call api.stop directly without showing the dialog when the action is suppressed', async () => {
mockIsSuppressed.mockReturnValue(true);
renderCard();

await userEvent.click(screen.getByRole('button', { name: /stop/i }));

expect(apiMock.stop).toHaveBeenCalledWith('minecraft');
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
});

it('should call api.stop after the user confirms the dialog', async () => {
mockIsSuppressed.mockReturnValue(false);
renderCard();

await userEvent.click(screen.getByRole('button', { name: /stop/i }));
await userEvent.click(screen.getByRole('button', { name: /stop server/i }));

expect(apiMock.stop).toHaveBeenCalledWith('minecraft');
});

it('should not call api.stop when the user cancels the dialog', async () => {
mockIsSuppressed.mockReturnValue(false);
renderCard();

await userEvent.click(screen.getByRole('button', { name: /stop/i }));
await userEvent.click(screen.getByRole('button', { name: /cancel/i }));

expect(apiMock.stop).not.toHaveBeenCalled();
});
});
Loading
Loading