Skip to content

Commit 7e7df96

Browse files
committed
fix(components): refuse clipped whole edits, keep keyboard focus and name value toggles by their text
A whole-value edit now refuses clipped text, truncation markers and Map, Set or class values. Focus stays in the list after Show more and moves to the owner row after Show owner, value toggles are named by their visible text, the filter count says rows when directive hosts are listed, and the resources page documents the new tree fields. Refs #341
1 parent 224e86e commit 7e7df96

7 files changed

Lines changed: 178 additions & 24 deletions

File tree

‎app/src/__tests__/component-tree-hydration.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ComponentTree } from '../pages/component-tree';
55
import {
66
countText,
77
directiveHostLabel,
8+
filterAnnouncement,
89
filterTree,
910
withoutDirectiveHosts,
1011
type TreeNode,
@@ -136,6 +137,9 @@ describe('tree search and directive hosts (state)', () => {
136137
).toBe('[Highlight]');
137138
expect(countText(4, 0, false, false, 2)).toBe('4 instances · 2 directive hosts');
138139
expect(countText(4, 1, true, false, 2)).toBe('1 of 6');
140+
// With directive hosts shown, the filter result counts rows, not instances.
141+
expect(filterAnnouncement(4, 1, 'tip', false, 2)).toBe('1 of 6 rows match.');
142+
expect(filterAnnouncement(4, 1, 'tip')).toBe('1 of 4 instances match.');
139143
});
140144
});
141145

@@ -195,6 +199,7 @@ describe('component tree hydration and directive hosts', () => {
195199
await settle();
196200
expect(rowIds(el)).toEqual(['c1', 'c4', 'c5']);
197201
expect(el.querySelector('.count')!.textContent!.trim()).toBe('1 of 6');
202+
expect(fixture.componentInstance.announcement()).toBe('1 of 6 rows match.');
198203
});
199204

200205
it('selects a directive host locally and offers its owning component', async () => {
@@ -208,9 +213,14 @@ describe('component tree hydration and directive hosts', () => {
208213
expect(detail.textContent).toContain('MatTooltip');
209214
const owner = detail.querySelector<HTMLButtonElement>('.owner-action button')!;
210215
expect(owner.textContent!.trim()).toBe('Show TripMap');
216+
owner.focus();
211217
owner.click();
212218
await settle();
213219
expect(el.querySelector('.row.selected')!.getAttribute('data-id')).toBe('c4');
220+
// The button goes away with the host's detail, so focus moves to the owner's row.
221+
expect(document.activeElement).not.toBe(document.body);
222+
expect(document.activeElement?.getAttribute('data-id')).toBe('c4');
223+
expect(document.activeElement?.getAttribute('tabindex')).toBe('0');
214224
});
215225

216226
it('reaches directive host rows with the arrow keys', async () => {

‎app/src/__tests__/component-value-tree.test.ts‎

Lines changed: 81 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -186,12 +186,13 @@ describe('ComponentTree value expansion', () => {
186186
: [],
187187
);
188188
const fixture = await open(call);
189-
const toggle = button(fixture, 'Expand user');
189+
// The name holds the visible summary; aria-expanded carries the state.
190+
const toggle = button(fixture, 'user: Object (2 keys)');
190191
expect(toggle.getAttribute('aria-expanded')).toBe('false');
191192
expect(toggle.textContent).toContain('Object (2 keys)');
192193
toggle.click();
193194
await settle(fixture);
194-
expect(button(fixture, 'Collapse user').getAttribute('aria-expanded')).toBe('true');
195+
expect(button(fixture, 'user: Object (2 keys)').getAttribute('aria-expanded')).toBe('true');
195196
expect(valueCalls(call)).toHaveLength(0);
196197
expect(el(fixture).textContent).toContain('"Ada"');
197198

@@ -220,7 +221,7 @@ describe('ComponentTree value expansion', () => {
220221
: [],
221222
);
222223
const fixture = await open(call);
223-
button(fixture, 'Expand items').click();
224+
button(fixture, 'items: Array (45 items)').click();
224225
await settle(fixture);
225226
const more = button(fixture, /^Show 15 more \(15 not listed\)$/);
226227
more.click();
@@ -233,19 +234,60 @@ describe('ComponentTree value expansion', () => {
233234
expect(el(fixture).querySelectorAll('app-value-tree li').length).toBeGreaterThanOrEqual(45);
234235
});
235236

237+
it('keeps keyboard focus in the list when the last Show more goes away', async () => {
238+
const call = vi.fn<Call>(async (name) =>
239+
name === 'request-component-value'
240+
? { ok: true, value: Array.from({ length: 45 }, (_, i) => i) }
241+
: [],
242+
);
243+
const fixture = await open(call);
244+
button(fixture, 'items: Array (45 items)').click();
245+
await settle(fixture);
246+
const more = button(fixture, /^Show 15 more/);
247+
more.focus();
248+
more.click();
249+
await settle(fixture);
250+
expect(hasButton(fixture, /^Show \d+ more/)).toBe(false);
251+
// Focus moves to a control among the entries instead of falling to the page.
252+
expect(document.activeElement).not.toBe(document.body);
253+
expect(document.activeElement?.closest('ul')?.getAttribute('aria-label')).toBe('items entries');
254+
});
255+
256+
it('moves focus to the first new entry that has a control', async () => {
257+
const call = vi.fn<Call>(async (name) =>
258+
name === 'request-component-value'
259+
? {
260+
ok: true,
261+
value: [
262+
...Array.from({ length: 30 }, (_, i) => i),
263+
...Array.from({ length: 15 }, () => ({ $collapsed: 'Object', size: 1 })),
264+
],
265+
}
266+
: [],
267+
);
268+
const fixture = await open(call);
269+
button(fixture, 'items: Array (45 items)').click();
270+
await settle(fixture);
271+
const more = button(fixture, /^Show 15 more/);
272+
more.focus();
273+
more.click();
274+
await settle(fixture);
275+
expect(document.activeElement?.getAttribute('aria-label')).toBe('30: Object (1 key)');
276+
});
277+
236278
it('shows the levels the page pushed, and says why a level could not be read', async () => {
237279
const call = vi.fn<Call>(async (name) =>
238280
name === 'request-component-value'
239281
? { error: 'No component instance `c1` is on this page. It may have been destroyed.' }
240282
: [],
241283
);
242284
const fixture = await open(call, { [pathKey(['user'])]: { name: 'Grace', extra: true } });
243-
button(fixture, 'Expand user').click();
285+
button(fixture, /^user: Object/).click();
244286
await settle(fixture);
245287
expect(el(fixture).textContent).toContain('"Grace"');
246288
expect(el(fixture).textContent).not.toContain('"Ada"');
247289
// The pushed level has no profile any more, so open a fresh tree on another value.
248-
button(fixture, 'Expand items').click();
290+
button(fixture, 'items: Array (45 items)').click();
249291
await settle(fixture);
250292
expect(hasButton(fixture, /^Show 15 more/)).toBe(true);
251293
button(fixture, /^Show 15 more/).click();
@@ -259,7 +301,7 @@ describe('ComponentTree value expansion', () => {
259301
name === 'request-component-edit' ? { ok: true } : [],
260302
);
261303
const fixture = await open(call);
262-
button(fixture, 'Expand user').click();
304+
button(fixture, /^user: Object/).click();
263305
await settle(fixture);
264306
button(fixture, 'Edit user.name').click();
265307
await settle(fixture);
@@ -283,7 +325,7 @@ describe('ComponentTree value expansion', () => {
283325
);
284326
const fixture = await open(call);
285327
// `count` is a number, so it shows as before, with no toggle.
286-
expect(hasButton(fixture, 'Expand count')).toBe(false);
328+
expect(hasButton(fixture, /^count: /)).toBe(false);
287329
expect(hasButton(fixture, 'Edit count')).toBe(true);
288330
const page = fixture.componentInstance.page()!;
289331
const small = {
@@ -307,6 +349,37 @@ describe('ComponentTree value expansion', () => {
307349
expect(field.value).toBe('{"name":"Ada","tags":["a"]}');
308350
});
309351

352+
it.each([
353+
['text the page clipped', { name: 'Ada', bio: `${'x'.repeat(300)}…` }],
354+
['a budget marker', { name: 'Ada', tags: ['a', '[Truncated]'] }],
355+
['a redacted value', { name: 'Ada', token: '[redacted]' }],
356+
['a level left collapsed', { name: 'Ada', tags: { $collapsed: 'Array', size: 1 } }],
357+
['a Map', { name: 'Ada', seen: { $type: 'Map', size: 1, entries: [['a', 1]] } }],
358+
])('refuses a whole edit when the value read has %s', async (_, value) => {
359+
const call = vi.fn<Call>(async (name) =>
360+
name === 'request-component-value' ? { ok: true, value } : [],
361+
);
362+
const fixture = await open(call);
363+
const page = fixture.componentInstance.page()!;
364+
const small = {
365+
name: 'small',
366+
prop: 'small',
367+
value: { name: 'Ada', tags: { $collapsed: 'Array', size: 1 } },
368+
edit: 'property' as const,
369+
editInside: 'property' as const,
370+
};
371+
fixture.componentInstance.pages.set({
372+
p1: { ...page, detail: { ...page.detail!, properties: [small] } },
373+
});
374+
await settle(fixture);
375+
button(fixture, 'Edit small').click();
376+
await settle(fixture);
377+
expect(el(fixture).querySelector('app-value-tree input')).toBeNull();
378+
expect(el(fixture).textContent).toContain(
379+
'Too large to edit as a whole. Open it to edit the values inside.',
380+
);
381+
});
382+
310383
it('filters values by name and by loaded nested keys, with a count and a no-match state', async () => {
311384
const call = vi.fn<Call>(async () => []);
312385
const fixture = await open(call);
@@ -329,7 +402,7 @@ describe('ComponentTree value expansion', () => {
329402
type(filter, 'NAME');
330403
await settle(fixture);
331404
expect(names()).toEqual(['user']);
332-
expect(button(fixture, 'Collapse user').getAttribute('aria-expanded')).toBe('true');
405+
expect(button(fixture, 'user: Object (2 keys)').getAttribute('aria-expanded')).toBe('true');
333406
expect(el(fixture).textContent).toContain('"Ada"');
334407
expect(hasButton(fixture, /^profile: /)).toBe(false);
335408

‎app/src/pages/component-tree-state.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,16 +83,24 @@ export function countText(
8383
return `${shown} ${total === 1 && !truncated ? 'instance' : 'instances'}${hosts}`;
8484
}
8585

86+
/**
87+
* The live message for a filter result. `total` counts component instances;
88+
* with directive host rows shown, the result counts rows, since it holds both.
89+
*/
8690
export function filterAnnouncement(
8791
total: number,
8892
matches: number,
8993
query: string,
9094
truncated = false,
95+
directiveHosts = 0,
9196
): string {
9297
if (!query.trim()) return '';
9398
if (!matches) return 'No components match.';
94-
const shown = truncated ? `${total}+` : `${total}`;
95-
return `${matches} of ${shown} ${total === 1 && !truncated ? 'instance' : 'instances'} match.`;
99+
const rows = total + directiveHosts;
100+
const shown = truncated ? `${rows}+` : `${rows}`;
101+
const one = !truncated && rows === 1;
102+
const noun = directiveHosts ? (one ? 'row' : 'rows') : one ? 'instance' : 'instances';
103+
return `${matches} of ${shown} ${noun} match.`;
96104
}
97105

98106
export function truncationNotice(truncatedBy?: { components?: number; depth?: number }): string {

‎app/src/pages/component-tree.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,9 @@ function storedDirectiveHosts(): boolean {
409409
</p>
410410
@if (ownerOf(host.id); as owner) {
411411
<div class="actions owner-action">
412-
<button type="button" (click)="reveal(owner.id)">Show {{ owner.name }}</button>
412+
<button type="button" (click)="reveal(owner.id, true)">
413+
Show {{ owner.name }}
414+
</button>
413415
</div>
414416
}
415417
</div>
@@ -2142,10 +2144,11 @@ export class ComponentTree {
21422144
const { matches } = this.filtered();
21432145
this.announcement.set(
21442146
filterAnnouncement(
2145-
(this.page()?.count ?? 0) + this.shownDirectiveHosts(),
2147+
this.page()?.count ?? 0,
21462148
matches,
21472149
value,
21482150
!!this.page()?.truncated,
2151+
this.shownDirectiveHosts(),
21492152
),
21502153
);
21512154
}
@@ -2272,7 +2275,8 @@ export class ComponentTree {
22722275
if (this.index().map.has(id)) this.reveal(id);
22732276
}
22742277

2275-
reveal(id: string) {
2278+
/** Opens the tree to a node and selects it; `focus` also moves keyboard focus to its row. */
2279+
reveal(id: string, focus = false) {
22762280
const { parents } = this.index();
22772281
this.collapsed.update((set) => {
22782282
const next = new Set(set);
@@ -2281,11 +2285,13 @@ export class ComponentTree {
22812285
});
22822286
if (!this.rows().some((row) => row.node.id === id)) this.setFilter('');
22832287
if (this.selectedId() !== id) this.select(id);
2288+
if (focus) this.focusId.set(id);
22842289
afterNextRender(
2285-
() =>
2286-
document
2287-
.querySelector(`.row[data-id="${CSS.escape(id)}"]`)
2288-
?.scrollIntoView({ block: 'nearest' }),
2290+
() => {
2291+
const row = document.querySelector<HTMLElement>(`.row[data-id="${CSS.escape(id)}"]`);
2292+
row?.scrollIntoView({ block: 'nearest' });
2293+
if (focus) row?.focus();
2294+
},
22892295
{ injector: this.injector },
22902296
);
22912297
}

‎app/src/pages/component-value-tree.ts‎

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Component, computed, input } from '@angular/core';
1+
import { Component, ElementRef, afterRenderEffect, computed, inject, input } from '@angular/core';
22
import type { DevframeRpcClient } from 'devframe/client';
33
import { PropValue, type EditableProp } from './component-prop-value';
44
import {
@@ -52,6 +52,22 @@ function leafText(value: unknown): string {
5252
}
5353
}
5454

55+
/**
56+
* Whether a value the page read for a whole edit holds all of it: no level
57+
* left collapsed or cut (`$collapsed`, `$more`), no Map, Set or class marker
58+
* (`$type`), and only leaves a nested edit could write too, so clipped text,
59+
* redacted values and markers such as `[Truncated]` are not written back.
60+
*/
61+
function wholeValue(value: unknown): boolean {
62+
if (Array.isArray(value)) return value.every(wholeValue);
63+
if (value && typeof value === 'object') {
64+
const obj = value as Record<string, unknown>;
65+
if (['$collapsed', '$more', '$type'].some((key) => Object.hasOwn(obj, key))) return false;
66+
return Object.values(obj).every(wholeValue);
67+
}
68+
return editableLeaf(value);
69+
}
70+
5571
/**
5672
* One input or property value of the selected component. Text, numbers and
5773
* other leaves show as before; an object, array, Map or Set shows its first
@@ -70,7 +86,7 @@ function leafText(value: unknown): string {
7086
class="toggle"
7187
[attr.aria-expanded]="rootOpen()"
7288
[attr.aria-controls]="rootOpen() ? listId : null"
73-
[attr.aria-label]="(rootOpen() ? 'Collapse ' : 'Expand ') + prop().name"
89+
[attr.aria-label]="prop().name + ': ' + summaryOf(c)"
7490
(click)="toggleRoot()"
7591
>
7692
<svg class="chevron" viewBox="0 0 24 24" aria-hidden="true">
@@ -275,6 +291,28 @@ export class ValueTree {
275291

276292
protected readonly listId = `value-tree-${++nextId}`;
277293

294+
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
295+
296+
/** Rows listed when "Show more" was pressed, until the next entries render. */
297+
private pendingMore: Set<string> | null = null;
298+
299+
constructor() {
300+
// "Show more" goes away once the last entries are listed; keep focus in the list.
301+
afterRenderEffect(() => {
302+
const rows = this.rows();
303+
const before = this.pendingMore;
304+
if (!before) return;
305+
const added = rows.findIndex(
306+
(row) => (row.kind === 'leaf' || row.kind === 'node') && !before.has(row.id),
307+
);
308+
if (added < 0) return;
309+
this.pendingMore = null;
310+
const active = document.activeElement;
311+
if (active && active !== document.body && active.isConnected) return;
312+
this.focusNear(added);
313+
});
314+
}
315+
278316
private readonly rootPath = computed(() => [this.prop().prop]);
279317

280318
/** The first level: the one the detail carries, or a longer one the panel loaded. */
@@ -405,8 +443,7 @@ export class ValueTree {
405443
protected readonly readWhole = async () => {
406444
const answer = await this.store().read(this.rootPath(), EDIT_READ.depth, EDIT_READ.limit);
407445
if (!answer.ok) return { error: answer.error ?? 'The page did not read it.' };
408-
const text = JSON.stringify(answer.value);
409-
if (/"\$collapsed"|"\$more"|"\[redacted\]"/.test(text)) {
446+
if (!wholeValue(answer.value)) {
410447
return { error: 'Too large to edit as a whole. Open it to edit the values inside.' };
411448
}
412449
return { value: answer.value };
@@ -417,17 +454,37 @@ export class ValueTree {
417454
}
418455

419456
protected toggleRoot() {
457+
this.pendingMore = null;
420458
this.store().toggle(this.rootPath(), this.directive(), false);
421459
}
422460

423461
protected toggle(row: Row) {
462+
this.pendingMore = null;
424463
this.store().toggle(row.path, this.directive(), !!row.container?.collapsed);
425464
}
426465

427466
protected more(row: Row) {
467+
this.pendingMore = new Set(this.rows().map((r) => r.id));
428468
this.store().more(row.path, this.directive(), row.listed ?? 0);
429469
}
430470

471+
/**
472+
* Focuses the first control in the entry at `index` or after it (a toggle,
473+
* an Edit button, the next "Show more"), else the closest one before it,
474+
* else the root toggle.
475+
*/
476+
private focusNear(index: number) {
477+
const root = this.host.nativeElement;
478+
const entries = Array.from(root.querySelectorAll<HTMLElement>(`#${this.listId} > li`));
479+
const control = (entry: HTMLElement | undefined) =>
480+
entry?.querySelector<HTMLElement>('button:not([disabled]), input, textarea, [tabindex="0"]');
481+
const target =
482+
entries.slice(index).map(control).find(Boolean) ??
483+
entries.slice(0, index).reverse().map(control).find(Boolean) ??
484+
root.querySelector<HTMLElement>('.root > .toggle');
485+
target?.focus();
486+
}
487+
431488
protected step(row: Row): number {
432489
return Math.min(LOAD_STEP, row.more ?? 0);
433490
}

‎apps/docs/src/content/agents/resources.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ When one of the first four runs past 100,000 characters, it returns a summary in
5050

5151
### component-tree
5252

53-
The component instances of each page, under `pages[pageId].roots`. Each node has an instance id, class name, host tag and the directives on its host. `detail` holds the live inputs, outputs, other properties, listeners, change detection, encapsulation and injected dependencies of the selected instance. Each value shows its first level, with nested objects, arrays, `Map`s and `Set`s as `{"$collapsed": type, "size": n}`; read them with `inspect-component` and `path`. `detail.expanded` holds the nested levels opened in the panel. The selection is the one made in the panel, by clicking in the page with **Pick component on page**, or with the `highlight` or `inspect-component` tool. `truncated` is `true` when the page has more instances than it lists, and `truncatedBy` names the limit it hit: `components` (2000 instances) or `depth` (256 levels of DOM nesting). `deferBlocks` lists the page's `@defer` blocks, and is missing when the page has no util to read them. `nodes` repeats the roots of the most recent page.
53+
The component instances of each page, under `pages[pageId].roots`. Each node has an instance id, class name, host tag, the directives on its host, and `attributes`, the selector attribute names of those directives. In a page rendered on the server, each node also has its `hydration` status: `hydrated`, `skipped`, `mismatched` or `client`. An element that hosts directives but no component is a node too, with `kind: "directive"`, all of its directives in `directives`, and the first one as `name`. `platform` is `angular-native` for an Angular Native app, and missing for a browser page. `count` counts the component instances and `directiveHostCount` the directive hosts. `hydration` reports the page's hydration: counts by status, dehydrated `@defer` blocks, mismatches between what Angular expected and found, and whether the hydration overlay is on. It is missing when the page was not rendered on the server. `detail` holds the live inputs, outputs, other properties, listeners, change detection, encapsulation and injected dependencies of the selected instance, and `source`, the project-relative `file` and 1-based `line` of its class when a dev build has the debug info of Angular. `detail.properties` lists the other own fields, with signals and resources unwrapped. Each value shows its first level, with nested objects, arrays, `Map`s and `Set`s as `{"$collapsed": type, "size": n}`; read them with `inspect-component` and `path`. `detail.expanded` holds the nested levels opened in the panel. The selection is the one made in the panel, by clicking in the page with **Pick component on page**, or with the `highlight` or `inspect-component` tool. `truncated` is `true` when the page has more instances than it lists, and `truncatedBy` names the limit it hit: `components` (2000 instances), `depth` (256 levels of DOM nesting) or `directiveHosts` (1000 elements that host directives but no component). `deferBlocks` lists the page's `@defer` blocks, and is missing when the page has no util to read them. `nodes` repeats the roots of the most recent page.
5454

5555
The instance ids here are what `highlight` and `inspect-component` accept.
5656

0 commit comments

Comments
 (0)