Skip to content

Commit a0e8859

Browse files
authored
feat(components): copy actions, keyboard pick, defer details and force-load, CD reload (#476)
Copy as JSON and host path, value change flash, Show in Signals deep link, CD recording across reload, defer block history and details, load-defer-block action tool, keyboard picking, likely directive source, most-checked CD table. Refs #366
1 parent 2baa859 commit a0e8859

56 files changed

Lines changed: 3108 additions & 201 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎app/src/__tests__/cd-cycle-chart.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,8 @@ describe('CdRecording with the chart', () => {
342342
await fixture.whenStable();
343343
const host = fixture.nativeElement as HTMLElement;
344344
const table = () =>
345-
[...host.querySelectorAll('.cd-grid table tbody tr')].map(
346-
(tr) => tr.querySelector('td')!.textContent,
345+
[...host.querySelectorAll('.cd-grid table:first-of-type tbody tr')].map((tr) =>
346+
tr.querySelector('td')!.textContent!.trim(),
347347
);
348348
expect(host.querySelector('app-cd-cycle-chart')).not.toBeNull();
349349
expect(table()).toEqual(['List', 'Cart']);
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
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+
import { componentJson, hostPathText } from '../pages/component-copy';
6+
import { ValueFlash, changedKeys } from '../pages/component-value-flash';
7+
import type { SignalFocus } from '../types/signal-focus.types';
8+
9+
function detail(count: number) {
10+
return {
11+
id: 'c1',
12+
name: 'Cart',
13+
tag: 'app-cart',
14+
path: 'app-root > app-cart',
15+
selector: 'body:nth-child(2) > app-root:nth-child(1) > app-cart:nth-child(1)',
16+
inputs: [{ name: 'title', prop: 'title', value: 'Basket' }],
17+
outputs: [{ name: 'checkout', prop: 'checkout', listened: true }],
18+
properties: [
19+
{ name: 'count', prop: 'count', value: count, kind: 'signal' },
20+
{ name: 'token', prop: 'token', value: '[redacted]' },
21+
],
22+
listeners: [],
23+
directives: [],
24+
dependencies: [
25+
{ from: 'c1', token: 'CartStore', flags: [], providedBy: 'r', providedByName: 'Root' },
26+
],
27+
};
28+
}
29+
30+
function page(count: number) {
31+
return {
32+
pageId: 'p1',
33+
roots: [{ id: 'c1', name: 'Cart', tag: 'app-cart', children: [] }],
34+
count: 1,
35+
detail: detail(count),
36+
reportedAt: 1000,
37+
deferBlocks: [
38+
{
39+
id: 'd1',
40+
owner: { id: 'c1', name: 'Cart', tag: 'app-cart' },
41+
state: 'placeholder',
42+
hydration: 'not-configured',
43+
triggers: ['on viewport'],
44+
rootIds: [],
45+
},
46+
],
47+
};
48+
}
49+
50+
function client() {
51+
const listeners: ((value: unknown) => void)[] = [];
52+
let value: unknown = { pages: { p1: page(1) } };
53+
const rpc = {
54+
call: () => Promise.resolve([]),
55+
callEvent: () => Promise.resolve(),
56+
sharedState: (name: string) =>
57+
Promise.resolve({
58+
value: () => (name === 'component-tree' ? value : null),
59+
on: (_event: string, listener: (value: unknown) => void) => {
60+
if (name === 'component-tree') listeners.push(listener);
61+
return () => {};
62+
},
63+
}),
64+
};
65+
const push = (next: unknown) => {
66+
value = next;
67+
for (const listener of listeners) listener(next);
68+
};
69+
const rpcClient = { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
70+
return { rpcClient, push };
71+
}
72+
73+
async function settle(fixture: ComponentFixture<unknown>) {
74+
for (let i = 0; i < 3; i++) {
75+
await new Promise((resolve) => setTimeout(resolve));
76+
await fixture.whenStable();
77+
}
78+
}
79+
80+
async function selected() {
81+
const fixture = TestBed.createComponent(ComponentTree);
82+
const { rpcClient, push } = client();
83+
fixture.componentRef.setInput('rpc', rpcClient);
84+
fixture.componentRef.setInput('canShowSignals', true);
85+
await settle(fixture);
86+
fixture.componentInstance.selectedId.set('c1');
87+
await settle(fixture);
88+
return { fixture, push, el: fixture.nativeElement as HTMLElement };
89+
}
90+
91+
function button(el: HTMLElement, text: string): HTMLButtonElement {
92+
const found = Array.from(el.querySelectorAll<HTMLButtonElement>('button')).find((b) =>
93+
b.textContent?.replace(/\s+/g, ' ').trim().startsWith(text),
94+
);
95+
if (!found) throw new Error(`no button ${text}`);
96+
return found;
97+
}
98+
99+
describe('component detail actions', () => {
100+
afterEach(() => {
101+
document.body.innerHTML = '';
102+
vi.restoreAllMocks();
103+
vi.useRealTimers();
104+
});
105+
106+
it('copies the detail as JSON and the host selector', async () => {
107+
const writeText = vi.fn((_text: string) => Promise.resolve());
108+
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
109+
const { fixture, el } = await selected();
110+
button(el, 'Copy as JSON').click();
111+
await settle(fixture);
112+
const json = JSON.parse(writeText.mock.calls[0]![0]);
113+
expect(json).toMatchObject({
114+
component: 'Cart',
115+
hostPath: 'app-root > app-cart',
116+
inputs: { title: 'Basket' },
117+
outputs: [{ name: 'checkout', listened: true }],
118+
properties: { count: 1, token: '[redacted]' },
119+
injected: [{ token: 'CartStore', providedBy: 'Root' }],
120+
});
121+
expect(el.textContent).toContain('Copied Cart as JSON.');
122+
button(el, 'Copy host path').click();
123+
await settle(fixture);
124+
expect(writeText).toHaveBeenLastCalledWith(detail(1).selector);
125+
expect(el.textContent).toContain('Copied the host selector.');
126+
});
127+
128+
it('says so when the clipboard refuses', async () => {
129+
Object.defineProperty(navigator, 'clipboard', {
130+
value: { writeText: () => Promise.reject(new Error('denied')) },
131+
configurable: true,
132+
});
133+
const { fixture, el } = await selected();
134+
button(el, 'Copy host path').click();
135+
await settle(fixture);
136+
expect(el.textContent).toContain('The clipboard is not available here.');
137+
});
138+
139+
it('outlines a value that changed in the last push', async () => {
140+
const { fixture, push, el } = await selected();
141+
const rows = () => Array.from(el.querySelectorAll('.prop.changed')).map((r) => r.textContent);
142+
expect(rows()).toEqual([]);
143+
push({ pages: { p1: page(2) } });
144+
await settle(fixture);
145+
expect(rows()).toHaveLength(1);
146+
expect(rows()[0]).toContain('count');
147+
});
148+
149+
it('opens a signal property in the Signals tab', async () => {
150+
const { fixture, el } = await selected();
151+
const opened: SignalFocus[] = [];
152+
fixture.componentInstance.showSignals.subscribe((focus) => opened.push(focus));
153+
const link = el.querySelector<HTMLButtonElement>('.signal-link')!;
154+
expect(link.textContent).toContain('Show in Signals');
155+
link.click();
156+
button(el, 'Show in Signals').click();
157+
expect(opened).toEqual([
158+
{ componentId: 'c1', pageId: 'p1', key: 'count' },
159+
{ componentId: 'c1', pageId: 'p1' },
160+
]);
161+
});
162+
163+
it("lists the component's own defer blocks", async () => {
164+
const { el } = await selected();
165+
const heading = Array.from(el.querySelectorAll('.detail h3')).find((h) =>
166+
h.textContent?.includes('Defer blocks'),
167+
);
168+
expect(heading?.parentElement?.textContent).toContain('on viewport');
169+
});
170+
});
171+
172+
describe('component copy text', () => {
173+
it('falls back to the component path without a selector', () => {
174+
expect(hostPathText({ path: 'Page > Label' })).toBe('Page > Label');
175+
expect(hostPathText({ path: 'a > b', selector: 'a > b:nth-child(2)' })).toBe(
176+
'a > b:nth-child(2)',
177+
);
178+
});
179+
180+
it('keeps the masked values the page sent', () => {
181+
const text = componentJson({ ...detail(1), selector: undefined });
182+
expect(JSON.parse(text).properties.token).toBe('[redacted]');
183+
expect(JSON.parse(text).selector).toBeUndefined();
184+
});
185+
});
186+
187+
describe('ValueFlash', () => {
188+
it('flashes changed keys for a second, and starts over for another component', () => {
189+
vi.useFakeTimers();
190+
const flash = new ValueFlash();
191+
flash.update('p1|c1', new Map([['input:a', 1]]));
192+
flash.update('p1|c1', new Map([['input:a', 2]]));
193+
expect([...flash.changed()]).toEqual(['input:a']);
194+
vi.advanceTimersByTime(999);
195+
expect(flash.changed().size).toBe(1);
196+
vi.advanceTimersByTime(1);
197+
expect(flash.changed().size).toBe(0);
198+
flash.update('p1|c2', new Map([['input:a', 3]]));
199+
expect(flash.changed().size).toBe(0);
200+
});
201+
202+
it('does not count a new or a removed key as a change', () => {
203+
expect(
204+
changedKeys(
205+
new Map([
206+
['a', '1'],
207+
['b', '2'],
208+
]),
209+
new Map([
210+
['a', '1'],
211+
['c', '3'],
212+
]),
213+
),
214+
).toEqual([]);
215+
});
216+
});
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { TestBed, type ComponentFixture } from '@angular/core/testing';
2+
import type { DevframeRpcClient } from 'devframe/client';
3+
import { afterEach, describe, expect, it } from 'vitest';
4+
import { ComponentTree } from '../pages/component-tree';
5+
6+
const page = {
7+
pageId: 'p1',
8+
roots: [{ id: 'c1', name: 'App', tag: 'app-root', children: [] }],
9+
count: 1,
10+
detail: null,
11+
reportedAt: 1000,
12+
};
13+
14+
function client(calls: { name: string; args: unknown }[]) {
15+
const rpc = {
16+
call: (name: string, args: unknown) => {
17+
calls.push({ name, args });
18+
if (name === 'request-component-pick') return new Promise(() => {});
19+
if (name === 'request-component-pick-move') {
20+
return Promise.resolve({ moved: true, id: 'c1', name: 'App', tag: 'app-root' });
21+
}
22+
return Promise.resolve([]);
23+
},
24+
callEvent: () => Promise.resolve(),
25+
sharedState: (name: string) =>
26+
Promise.resolve({
27+
value: () => (name === 'component-tree' ? { pages: { p1: page } } : null),
28+
on: () => () => {},
29+
}),
30+
};
31+
return { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient;
32+
}
33+
34+
async function settle(fixture: ComponentFixture<unknown>) {
35+
for (let i = 0; i < 3; i++) {
36+
await new Promise((resolve) => setTimeout(resolve));
37+
await fixture.whenStable();
38+
}
39+
}
40+
41+
describe('keyboard pick', () => {
42+
afterEach(() => {
43+
document.body.innerHTML = '';
44+
});
45+
46+
it('sends the arrow keys and Enter to the page while picking, and announces the component', async () => {
47+
const calls: { name: string; args: unknown }[] = [];
48+
const fixture = TestBed.createComponent(ComponentTree);
49+
fixture.componentRef.setInput('rpc', client(calls));
50+
await settle(fixture);
51+
const el = fixture.nativeElement as HTMLElement;
52+
const press = (key: string) => {
53+
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
54+
el.querySelector('.pick')!.dispatchEvent(event);
55+
return event;
56+
};
57+
expect(press('ArrowDown').defaultPrevented).toBe(false);
58+
void fixture.componentInstance.pick();
59+
await settle(fixture);
60+
expect(press('ArrowDown').defaultPrevented).toBe(true);
61+
await settle(fixture);
62+
expect(calls.filter((c) => c.name === 'request-component-pick-move')).toEqual([
63+
{ name: 'request-component-pick-move', args: { pageId: 'p1', key: 'next' } },
64+
]);
65+
expect(fixture.componentInstance.announcement()).toBe(
66+
'App <app-root>. Press Enter to pick it.',
67+
);
68+
expect(press('Enter').defaultPrevented).toBe(true);
69+
expect(calls.at(-1)).toEqual({
70+
name: 'request-component-pick-move',
71+
args: { pageId: 'p1', key: 'pick' },
72+
});
73+
});
74+
});

0 commit comments

Comments
 (0)