Skip to content
Open
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
1 change: 1 addition & 0 deletions src/app/__tests__/layout.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import RootLayout from '../layout';
// Mock next/navigation for RouteAnnouncer's usePathname call.
jest.mock('next/navigation', () => ({
usePathname: jest.fn().mockReturnValue('/'),
useRouter: () => ({ push: jest.fn(), replace: jest.fn(), prefetch: jest.fn() }),
}));

function renderLayout() {
Expand Down
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { PreferencesProvider } from '@/lib/preferences';
import { SettingsTrigger } from '@/components/settings/SettingsTrigger';
import { WalletProvider } from '@/contexts/WalletContext';
import RouteAnnouncer from '@/components/RouteAnnouncer';
import { CommandPalette } from '@/components/CommandPalette';
import Navbar from '@/components/Navbar';
import HeaderActions from '@/components/HeaderActions';

Expand Down Expand Up @@ -87,6 +88,7 @@ export default function RootLayout({
{children}
</main>
</div>
<CommandPalette />
<SettingsTrigger />
</WalletProvider>
</ToastProvider>
Expand Down
155 changes: 155 additions & 0 deletions src/components/CommandPalette.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
'use client';

import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useDialogFocusTrap } from '@/hooks/useDialogFocusTrap';
import { useMediaQuery } from '@/hooks/useMediaQuery';

type PaletteEntry = {
id: string;
label: string;
href: string;
keywords: string[];
};

const NAV_ENTRIES: PaletteEntry[] = [
{ id: 'home', label: 'Home', href: '/', keywords: ['home', 'dashboard', 'start'] },
{ id: 'contracts', label: 'Contracts', href: '/contracts', keywords: ['contracts', 'agreements'] },
{ id: 'milestones', label: 'Milestones', href: '/milestones', keywords: ['milestones', 'checkpoints', 'goals'] },
{ id: 'reputation', label: 'Reputation', href: '/reputation', keywords: ['reputation', 'trust', 'score', 'history'] },
];

function matchEntry(query: string, label: string, keywords: string[]): boolean {
const q = query.toLowerCase();
if (label.toLowerCase().includes(q)) return true;
return keywords.some((k) => k.toLowerCase().includes(q));
}

export function CommandPalette() {
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
const dialogRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const router = useRouter();
const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');

const close = useCallback(() => {
setIsOpen(false);
setQuery('');
setSelectedIndex(0);
}, []);

useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
const target = e.target as HTMLElement;
if (typeof target.closest === 'function' && target.closest('input, textarea, select, [contenteditable="true"]')) return;
e.preventDefault();
if (!isOpen) setIsOpen(true);
}
};
document.addEventListener('keydown', handler);
return () => document.removeEventListener('keydown', handler);
}, [isOpen]);

useDialogFocusTrap({
isOpen,
dialogRef,
initialFocusRef: inputRef,
onEscape: close,
restoreFocus: true,
});

const filtered = query === ''
? NAV_ENTRIES
: NAV_ENTRIES.filter((e) => matchEntry(query, e.label, e.keywords));

const selectedEntry = filtered.length > 0 ? filtered[selectedIndex] : null;

const navigate = useCallback(
(entry: PaletteEntry) => {
router.push(entry.href);
close();
},
[router, close],
);

const handleListKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (filtered.length === 0) return;

if (e.key === 'ArrowDown') {
e.preventDefault();
setSelectedIndex((prev) => (prev + 1) % filtered.length);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setSelectedIndex((prev) => (prev - 1 + filtered.length) % filtered.length);
} else if (e.key === 'Enter' && selectedEntry) {
e.preventDefault();
navigate(selectedEntry);
}
},
[filtered.length, selectedEntry, navigate],
);

if (!isOpen) return null;

return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]">
<div
className={`absolute inset-0 bg-black/50 ${prefersReducedMotion ? '' : 'backdrop-blur-sm transition-opacity'}`}
onClick={close}
/>
<div
ref={dialogRef}
role="dialog"
aria-label="Command palette"
className="relative z-10 w-full max-w-lg rounded-xl border border-[var(--border)] bg-[var(--background)] shadow-2xl"
onKeyDown={handleListKeyDown}
>
<div className="border-b border-[var(--border)] px-4">
<input
ref={inputRef}
role="combobox"
aria-expanded="true"
aria-controls="cp-list"
aria-activedescendant={
filtered.length > 0 && selectedEntry ? `cp-opt-${selectedEntry.id}` : undefined
}
placeholder="Search pages..."
value={query}
onChange={(e) => {
setQuery(e.target.value);
setSelectedIndex(0);
}}
className="w-full bg-transparent py-4 text-sm text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"
/>
</div>
<ul id="cp-list" role="listbox" aria-label="Pages" className="p-2">
{filtered.length === 0 ? (
<li className="p-4 text-center text-sm text-[var(--muted-foreground)]">No results</li>
) : (
filtered.map((entry, i) => (
<li
key={entry.id}
role="option"
id={`cp-opt-${entry.id}`}
aria-selected={i === selectedIndex}
onClick={() => navigate(entry)}
className={`flex cursor-pointer items-center justify-between rounded-lg px-3 py-2.5 text-sm transition-colors ${
i === selectedIndex
? 'bg-[var(--accent)] text-[var(--foreground)]'
: 'text-[var(--muted-foreground)] hover:bg-[var(--accent)] hover:text-[var(--foreground)]'
}`}
>
<span className="font-medium">{entry.label}</span>
<span className="text-xs text-[var(--muted-foreground)]">{entry.href}</span>
</li>
))
)}
</ul>
</div>
</div>
);
}
199 changes: 199 additions & 0 deletions src/components/__tests__/CommandPalette.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { CommandPalette } from '../CommandPalette';

const mockPush = jest.fn();

jest.mock('next/navigation', () => ({
useRouter: () => ({ push: jest.fn((...args) => mockPush(...args)), replace: jest.fn(), prefetch: jest.fn() }),
}));

beforeEach(() => {
mockPush.mockClear();
});

function openPalette() {
fireEvent.keyDown(document, { key: 'k', metaKey: true });
}

describe('CommandPalette', () => {
describe('shortcut', () => {
it('opens on Cmd+K', () => {
render(<CommandPalette />);
fireEvent.keyDown(document, { key: 'k', metaKey: true });
expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
});

it('opens on Ctrl+K', () => {
render(<CommandPalette />);
fireEvent.keyDown(document, { key: 'k', ctrlKey: true });
expect(screen.getByRole('dialog', { name: 'Command palette' })).toBeInTheDocument();
});

it('does not open on plain K', () => {
render(<CommandPalette />);
fireEvent.keyDown(document, { key: 'k' });
expect(screen.queryByRole('dialog', { name: 'Command palette' })).not.toBeInTheDocument();
});

it('does not open while typing in an input', () => {
render(
<div>
<input placeholder="Type here" />
<CommandPalette />
</div>,
);
const input = screen.getByPlaceholderText('Type here');
fireEvent.keyDown(input, { key: 'k', metaKey: true });
expect(screen.queryByRole('dialog', { name: 'Command palette' })).not.toBeInTheDocument();
});

it('does not open while typing in a contenteditable', () => {
render(
<div>
<div contentEditable role="textbox" />
<CommandPalette />
</div>,
);
const editable = screen.getByRole('textbox');
fireEvent.keyDown(editable, { key: 'k', metaKey: true });
expect(screen.queryByRole('dialog', { name: 'Command palette' })).not.toBeInTheDocument();
});
});

describe('filtering', () => {
it('shows all entries when query is empty', () => {
render(<CommandPalette />);
openPalette();
expect(screen.getByRole('option', { name: /Home/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Contracts/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Milestones/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Reputation/ })).toBeInTheDocument();
});

it('filters by label prefix', () => {
render(<CommandPalette />);
openPalette();
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'con' } });
expect(screen.getByRole('option', { name: /Contracts/ })).toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Home/ })).not.toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Milestones/ })).not.toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Reputation/ })).not.toBeInTheDocument();
});

it('filters by label substring', () => {
render(<CommandPalette />);
openPalette();
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'put' } });
expect(screen.getByRole('option', { name: /Reputation/ })).toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Contracts/ })).not.toBeInTheDocument();
});

it('filters by keyword match', () => {
render(<CommandPalette />);
openPalette();
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'trust' } });
expect(screen.getByRole('option', { name: /Reputation/ })).toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Contracts/ })).not.toBeInTheDocument();
});

it('shows no results for an unmatched query', () => {
render(<CommandPalette />);
openPalette();
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'xyzzy' } });
expect(screen.getByText('No results')).toBeInTheDocument();
});

it('returns a single result for an overlapping query (no duplicates)', () => {
render(<CommandPalette />);
openPalette();
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'home' } });
const options = screen.getAllByRole('option');
expect(options).toHaveLength(1);
expect(options[0]).toHaveTextContent('Home');
});
});

describe('activation', () => {
it('navigates on Enter and closes', async () => {
const user = userEvent.setup();
render(<CommandPalette />);
openPalette();
await user.type(screen.getByRole('combobox'), 'mil');
await user.keyboard('{Enter}');
expect(mockPush).toHaveBeenCalledWith('/milestones');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

it('navigates on click and closes', async () => {
const user = userEvent.setup();
render(<CommandPalette />);
openPalette();
await user.click(screen.getByRole('option', { name: /Reputation/ }));
expect(mockPush).toHaveBeenCalledWith('/reputation');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});

describe('keyboard navigation', () => {
it('closes on Escape', () => {
render(<CommandPalette />);
openPalette();
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

it('cycles with ArrowDown and ArrowUp', () => {
render(<CommandPalette />);
openPalette();
const combobox = screen.getByRole('combobox');

fireEvent.keyDown(combobox, { key: 'ArrowDown' });
expect(screen.getByRole('option', { name: /Contracts/ })).toHaveAttribute('aria-selected', 'true');

fireEvent.keyDown(combobox, { key: 'ArrowDown' });
expect(screen.getByRole('option', { name: /Milestones/ })).toHaveAttribute('aria-selected', 'true');

fireEvent.keyDown(combobox, { key: 'ArrowUp' });
expect(screen.getByRole('option', { name: /Contracts/ })).toHaveAttribute('aria-selected', 'true');
});

it('combined flow: open → type → ArrowDown → Enter navigates highlighted item', async () => {
const user = userEvent.setup();
render(<CommandPalette />);
openPalette();

const combobox = screen.getByRole('combobox');
await user.type(combobox, 'rep');

fireEvent.keyDown(combobox, { key: 'ArrowDown' });
await user.keyboard('{Enter}');

expect(mockPush).toHaveBeenCalledWith('/reputation');
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});

describe('focus', () => {
it('focuses the search input when opened', () => {
render(<CommandPalette />);
openPalette();
expect(screen.getByRole('combobox')).toHaveFocus();
});

it('restores focus to the trigger element after closing', () => {
render(
<div>
<button type="button">Trigger</button>
<CommandPalette />
</div>,
);
const trigger = screen.getByRole('button', { name: 'Trigger' });
trigger.focus();
openPalette();
fireEvent.keyDown(document, { key: 'Escape' });
expect(trigger).toHaveFocus();
});
});
});
Loading