Skip to content

Commit 228af61

Browse files
authored
feat(ui): add a command palette, settings, item links and an Errors inspector (#389)
Refs #342.
1 parent 2a2d8d6 commit 228af61

53 files changed

Lines changed: 7923 additions & 156 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
import { Component, signal } from '@angular/core';
2+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
3+
import { afterEach, describe, expect, it } from 'vitest';
4+
import { CommandPalette } from '../ui/command-palette';
5+
import { filterCommands, fuzzyScore, type PaletteCommand } from '../palette-filter';
6+
7+
const COMMANDS: PaletteCommand[] = [
8+
{ id: 'tab:dashboard', title: 'Go to Dashboard', group: 'Go to' },
9+
{ id: 'tab:signals', title: 'Go to Signals', group: 'Go to' },
10+
{ id: 'tab:network', title: 'Go to SSR & HTTP', group: 'Go to' },
11+
{ id: 'pick-component', title: 'Pick component on page', group: 'Actions', keywords: 'select' },
12+
{ id: 'theme:dark', title: 'Theme: dark', group: 'Theme' },
13+
];
14+
15+
describe('palette filter', () => {
16+
it('matches letters in order and ranks word starts and runs higher', () => {
17+
expect(fuzzyScore('Go to Signals', 'gtsig')).toBeGreaterThan(0);
18+
expect(fuzzyScore('Go to Signals', 'xyz')).toBe(-1);
19+
expect(fuzzyScore('Go to Signals', 'sig')).toBeGreaterThan(fuzzyScore('Design', 'sig'));
20+
});
21+
22+
it('keeps the order for an empty query and puts the best match first', () => {
23+
expect(filterCommands(COMMANDS, ' ')).toEqual(COMMANDS);
24+
expect(filterCommands(COMMANDS, 'sig').map((c) => c.id)[0]).toBe('tab:signals');
25+
expect(filterCommands(COMMANDS, 'http').map((c) => c.id)).toEqual(['tab:network']);
26+
expect(filterCommands(COMMANDS, 'dark').map((c) => c.id)).toEqual(['theme:dark']);
27+
});
28+
29+
it('also matches the group and keywords, below a title match', () => {
30+
expect(filterCommands(COMMANDS, 'select').map((c) => c.id)).toEqual(['pick-component']);
31+
expect(filterCommands(COMMANDS, 'theme').map((c) => c.id)[0]).toBe('theme:dark');
32+
});
33+
});
34+
35+
@Component({
36+
imports: [CommandPalette],
37+
template: `
38+
<button type="button" id="opener" (click)="open.set(true)">Open</button>
39+
<app-command-palette [commands]="commands" [(open)]="open" (picked)="picked.push($event)" />
40+
`,
41+
})
42+
class Host {
43+
readonly commands = COMMANDS;
44+
readonly open = signal(false);
45+
readonly picked: string[] = [];
46+
}
47+
48+
async function settle(fixture: ComponentFixture<unknown>) {
49+
for (let i = 0; i < 3; i++) {
50+
await new Promise((resolve) => setTimeout(resolve));
51+
await fixture.whenStable();
52+
}
53+
}
54+
55+
function key(target: Element, name: string) {
56+
target.dispatchEvent(
57+
new KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true }),
58+
);
59+
}
60+
61+
async function openPalette() {
62+
const fixture = TestBed.createComponent(Host);
63+
document.body.appendChild(fixture.nativeElement);
64+
await settle(fixture);
65+
const opener = fixture.nativeElement.querySelector('#opener') as HTMLButtonElement;
66+
opener.focus();
67+
opener.click();
68+
await settle(fixture);
69+
const root = fixture.nativeElement as HTMLElement;
70+
const input = root.querySelector('input[role="combobox"]') as HTMLInputElement;
71+
return { fixture, root, input, opener };
72+
}
73+
74+
afterEach(() => {
75+
document.body.innerHTML = '';
76+
TestBed.resetTestingModule();
77+
});
78+
79+
describe('CommandPalette', () => {
80+
it('is a modal dialog with a combobox that controls a listbox', async () => {
81+
const { root, input } = await openPalette();
82+
const dialog = root.querySelector('[role="dialog"]')!;
83+
expect(dialog.getAttribute('aria-modal')).toBe('true');
84+
const title = root.querySelector(`#${dialog.getAttribute('aria-labelledby')}`);
85+
expect(title?.textContent?.trim()).toBe('Command palette');
86+
expect(document.activeElement).toBe(input);
87+
expect(input.getAttribute('aria-expanded')).toBe('true');
88+
const list = root.querySelector(`#${input.getAttribute('aria-controls')}`)!;
89+
expect(list.getAttribute('role')).toBe('listbox');
90+
const options = list.querySelectorAll('[role="option"]');
91+
expect(options).toHaveLength(COMMANDS.length);
92+
expect(input.getAttribute('aria-activedescendant')).toBe(options[0].id);
93+
expect(options[0].getAttribute('aria-selected')).toBe('true');
94+
expect(options[1].getAttribute('aria-selected')).toBe('false');
95+
});
96+
97+
it('filters as you type and says when nothing matches', async () => {
98+
const { fixture, root, input } = await openPalette();
99+
input.value = 'sig';
100+
input.dispatchEvent(new Event('input'));
101+
await settle(fixture);
102+
const options = [...root.querySelectorAll('[role="option"]')];
103+
expect(options[0].textContent).toContain('Go to Signals');
104+
expect(root.querySelector('[role="status"]')?.textContent).toMatch(/command/);
105+
106+
input.value = 'zzzz';
107+
input.dispatchEvent(new Event('input'));
108+
await settle(fixture);
109+
expect(root.querySelectorAll('[role="option"]')).toHaveLength(0);
110+
expect(root.querySelector('.empty')?.textContent).toContain('No commands match “zzzz”');
111+
expect(input.getAttribute('aria-activedescendant')).toBeNull();
112+
});
113+
114+
it('moves with the arrow keys, wraps, and runs the active command on Enter', async () => {
115+
const { fixture, root, input, opener } = await openPalette();
116+
key(input, 'ArrowDown');
117+
key(input, 'ArrowDown');
118+
await settle(fixture);
119+
const options = root.querySelectorAll('[role="option"]');
120+
expect(input.getAttribute('aria-activedescendant')).toBe(options[2].id);
121+
key(input, 'ArrowUp');
122+
key(input, 'ArrowUp');
123+
key(input, 'ArrowUp');
124+
await settle(fixture);
125+
expect(input.getAttribute('aria-activedescendant')).toBe(options[COMMANDS.length - 1].id);
126+
127+
key(input, 'Enter');
128+
await settle(fixture);
129+
expect(root.querySelector('[role="dialog"]')).toBeNull();
130+
expect(fixture.componentInstance.picked).toEqual(['theme:dark']);
131+
// Focus went back to what opened it before the command ran.
132+
expect(document.activeElement).toBe(opener);
133+
});
134+
135+
it('closes on Escape without running anything, and keeps Tab inside', async () => {
136+
const { fixture, root, input, opener } = await openPalette();
137+
const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
138+
input.dispatchEvent(tab);
139+
expect(tab.defaultPrevented).toBe(true);
140+
const escape = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true });
141+
input.dispatchEvent(escape);
142+
expect(escape.defaultPrevented).toBe(true);
143+
await settle(fixture);
144+
expect(root.querySelector('[role="dialog"]')).toBeNull();
145+
expect(fixture.componentInstance.picked).toEqual([]);
146+
expect(fixture.componentInstance.open()).toBe(false);
147+
expect(document.activeElement).toBe(opener);
148+
});
149+
150+
it('runs a command on click and starts empty the next time', async () => {
151+
const { fixture, root, input } = await openPalette();
152+
input.value = 'pick';
153+
input.dispatchEvent(new Event('input'));
154+
await settle(fixture);
155+
(root.querySelector('[role="option"]') as HTMLElement).click();
156+
await settle(fixture);
157+
expect(fixture.componentInstance.picked).toEqual(['pick-component']);
158+
fixture.componentInstance.open.set(true);
159+
await settle(fixture);
160+
expect((root.querySelector('input[role="combobox"]') as HTMLInputElement).value).toBe('');
161+
expect(root.querySelectorAll('[role="option"]')).toHaveLength(COMMANDS.length);
162+
});
163+
});
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { DevframeRpcClient } from 'devframe/client';
3+
import { afterEach, describe, expect, it, vi } from 'vitest';
4+
import { ComponentTree } from '../pages/component-tree';
5+
6+
const roots = [{ id: 'app', name: 'App', tag: 'app-root', children: [] }];
7+
8+
function client(options: { live?: boolean; recording?: boolean } = {}) {
9+
const calls: { name: string; args: unknown[] }[] = [];
10+
const page = {
11+
pageId: 'a',
12+
title: 'a',
13+
url: '/',
14+
roots: options.live === false ? [] : roots,
15+
count: 1,
16+
detail: null,
17+
reportedAt: 1,
18+
};
19+
const state: Record<string, unknown> = {
20+
'component-tree': { pages: { a: page } },
21+
'change-detection': {
22+
pages: {
23+
a: {
24+
pageId: 'a',
25+
supported: true,
26+
recording: options.recording === true,
27+
startedAt: null,
28+
cycles: [],
29+
dropped: 0,
30+
components: [],
31+
hosts: {},
32+
},
33+
},
34+
},
35+
};
36+
const rpc = {
37+
call: (name: string, ...args: unknown[]) => {
38+
calls.push({ name, args });
39+
// A pick waits for a click in the app; the test only checks it started.
40+
return name === 'request-component-pick' ? new Promise(() => {}) : Promise.resolve([]);
41+
},
42+
callEvent: () => Promise.resolve(),
43+
sharedState: (name: string) =>
44+
Promise.resolve({ value: () => state[name] ?? null, on: () => () => {} }),
45+
};
46+
const fake = { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
47+
return { fake, calls };
48+
}
49+
50+
async function settle(fixture: ComponentFixture<unknown>) {
51+
for (let i = 0; i < 3; i++) {
52+
await new Promise((resolve) => setTimeout(resolve));
53+
await fixture.whenStable();
54+
}
55+
}
56+
57+
async function setup(options: { live?: boolean; recording?: boolean } = {}) {
58+
const { fake, calls } = client(options);
59+
const fixture = TestBed.createComponent(ComponentTree);
60+
fixture.componentRef.setInput('rpc', fake);
61+
const handled = vi.fn();
62+
fixture.componentInstance.commandHandled.subscribe(handled);
63+
document.body.appendChild(fixture.nativeElement);
64+
await settle(fixture);
65+
return { fixture, calls, handled };
66+
}
67+
68+
afterEach(() => {
69+
document.body.innerHTML = '';
70+
TestBed.resetTestingModule();
71+
});
72+
73+
describe('Components tab palette commands', () => {
74+
it('starts picking a component on the page', async () => {
75+
const { fixture, calls, handled } = await setup();
76+
fixture.componentRef.setInput('command', { kind: 'pick' });
77+
await settle(fixture);
78+
expect(calls.some((call) => call.name === 'request-component-pick')).toBe(true);
79+
expect(fixture.componentInstance.picking()).toBe(true);
80+
expect(handled).toHaveBeenCalledTimes(1);
81+
});
82+
83+
it('starts, stops and clears the change detection recording', async () => {
84+
const records = async (kind: 'cd-start' | 'cd-stop' | 'cd-clear', recording: boolean) => {
85+
const { fixture, calls } = await setup({ recording });
86+
fixture.componentRef.setInput('command', { kind });
87+
await settle(fixture);
88+
const sent = calls
89+
.filter((call) => call.name === 'request-change-detection-record')
90+
.map((call) => call.args[0]);
91+
fixture.destroy();
92+
TestBed.resetTestingModule();
93+
return sent;
94+
};
95+
expect(await records('cd-start', false)).toEqual([{ pageId: 'a', on: true }]);
96+
expect(await records('cd-start', true)).toEqual([]);
97+
expect(await records('cd-stop', true)).toEqual([{ pageId: 'a', on: false }]);
98+
expect(await records('cd-clear', false)).toEqual([{ pageId: 'a', clear: true }]);
99+
});
100+
101+
it('drops a command when no live page is connected', async () => {
102+
const { fixture, calls, handled } = await setup({ live: false });
103+
fixture.componentRef.setInput('command', { kind: 'pick' });
104+
await settle(fixture);
105+
expect(calls.some((call) => call.name === 'request-component-pick')).toBe(false);
106+
expect(handled).toHaveBeenCalledTimes(1);
107+
expect(fixture.nativeElement.textContent).toContain('The page reported no component instances');
108+
});
109+
});

0 commit comments

Comments
 (0)