diff --git a/shell/e2e/component-tree.e2e.ts b/shell/e2e/component-tree.e2e.ts
new file mode 100644
index 000000000..4784fb8a1
--- /dev/null
+++ b/shell/e2e/component-tree.e2e.ts
@@ -0,0 +1,126 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {expect, test} from './fixtures';
+import {previewFrame} from '../src/app/preview/testing/preview-frame-locators';
+import {RENDERER_URLS} from '../src/app/preview/testing/renderer-urls';
+import {getMonacoContent, resetStorageOnce} from './helpers';
+
+test.beforeEach(async ({page}) => {
+ await resetStorageOnce(page, {
+ a2ui_composer_force_1p: 'true',
+ });
+});
+
+test.describe('Component Tree Panel', () => {
+ test('opens Component Tree tab and renders collapsible surface hierarchy', async ({page}) => {
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(error.message));
+
+ await page.goto(`/?renderer=${RENDERER_URLS.angular}`);
+ await expect(previewFrame(page).getByRole('button', {name: 'Search Cars'})).toBeVisible();
+
+ await page.locator('.dv-tab', {hasText: /^Component Tree/}).click();
+
+ const treeContainer = page.locator('a2ui-composer-component-tree .component-tree-container');
+ await expect(treeContainer).toBeVisible();
+ await expect(treeContainer.locator('.surface-header')).toContainText('sample-surface');
+ await expect(treeContainer.locator('.surface-header')).toContainText('7 components');
+
+ const rowIds = treeContainer.locator('.tree-row .id');
+ await expect(rowIds).toHaveText([
+ '#root',
+ '#title',
+ '#location_input',
+ '#pickup_input',
+ '#dropoff_input',
+ '#book_button',
+ '#book_button_text',
+ ]);
+
+ const bookButtonToggle = treeContainer
+ .locator('.tree-row', {hasText: '#book_button'})
+ .first()
+ .locator('.toggle');
+ await bookButtonToggle.click();
+ await expect(rowIds).toHaveText([
+ '#root',
+ '#title',
+ '#location_input',
+ '#pickup_input',
+ '#dropoff_input',
+ '#book_button',
+ ]);
+
+ await bookButtonToggle.click();
+ await expect(rowIds).toHaveText([
+ '#root',
+ '#title',
+ '#location_input',
+ '#pickup_input',
+ '#dropoff_input',
+ '#book_button',
+ '#book_button_text',
+ ]);
+ expect(pageErrors).toEqual([]);
+ });
+
+ test('selects a component from the tree, edits its property, and updates the preview and draft', async ({
+ page,
+ }) => {
+ const pageErrors: string[] = [];
+ page.on('pageerror', error => pageErrors.push(error.message));
+ await page.goto(`/?renderer=${RENDERER_URLS.angular}`);
+ await expect(previewFrame(page).getByRole('button', {name: 'Search Cars'})).toBeVisible();
+
+ await page.getByRole('tab', {name: 'Component Tree'}).click();
+ await page.getByRole('treeitem', {name: /#book_button_text/}).click();
+
+ await expect(page.getByRole('tab', {name: 'Property Editor', selected: true})).toBeVisible();
+ const propertyEditor = page.locator('a2ui-composer-property-editor');
+ await expect(propertyEditor.locator('[data-property-header]')).toContainText(
+ 'Text #book_button_text',
+ );
+ const textInput = propertyEditor.getByRole('textbox', {name: 'text', exact: true});
+ await expect(textInput).toHaveValue('Search Cars');
+
+ await textInput.fill('Book Now');
+
+ await page.getByRole('tab', {name: 'Rendered A2UI Preview'}).click();
+ await expect(previewFrame(page).getByRole('button', {name: 'Book Now'})).toBeVisible();
+ await expect
+ .poll(async () => {
+ const draft: unknown = JSON.parse(await getMonacoContent(page));
+ return draft;
+ })
+ .toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ createSurface: expect.objectContaining({
+ components: expect.arrayContaining([
+ {
+ id: 'book_button_text',
+ component: 'Text',
+ text: 'Book Now',
+ },
+ ]),
+ }),
+ }),
+ ]),
+ );
+ expect(pageErrors).toEqual([]);
+ });
+});
diff --git a/shell/e2e/workspace-layout-recovery.e2e.ts b/shell/e2e/workspace-layout-recovery.e2e.ts
index 4d4d8d510..17607d29b 100644
--- a/shell/e2e/workspace-layout-recovery.e2e.ts
+++ b/shell/e2e/workspace-layout-recovery.e2e.ts
@@ -68,7 +68,7 @@ for (const invalidState of ['retired panel', 'mismatched panel ID']) {
await page.goto(`/?renderer=${rendererUrl}`);
await expect(page.locator('.workspace-container')).toBeVisible();
- await expect(page.locator('.dv-tab')).toHaveCount(7);
+ await expect(page.locator('.dv-tab')).toHaveCount(9);
await expect(page.locator('.dv-tab', {hasText: /^Rendered A2UI Preview/})).toBeVisible();
const preview = previewFrame(page);
@@ -139,8 +139,8 @@ test('resets modified dockview layout back to default when clicking Reset Layout
);
await expect(page.locator('.dv-tab', {hasText: /^Data Model/})).toHaveClass(/dv-active-tab/);
- // Verify all 7 tabs are present
- await expect(page.locator('.dv-tab')).toHaveCount(7);
+ // Verify all 9 tabs are present
+ await expect(page.locator('.dv-tab')).toHaveCount(9);
// Verify DOCKVIEW_LAYOUT was cleared from localStorage
const savedLayout = await page.evaluate(
diff --git a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts
new file mode 100644
index 000000000..5267e63a3
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts
@@ -0,0 +1,670 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {Catalog} from '../../storage/models/catalog-storage.model';
+import {
+ ComponentTreeNode,
+ buildComponentTrees,
+ getSurfaceComponent,
+ updateSurfaceComponent,
+} from './component-tree-builder';
+
+const COMMON = 'https://a2ui.org/specification/v0_9/common_types.json#/$defs';
+
+const CATALOG: Catalog = {
+ catalogId: 'test',
+ components: {
+ Column: {
+ allOf: [
+ {$ref: `${COMMON}/ComponentCommon`},
+ {properties: {children: {$ref: `${COMMON}/ChildList`}}},
+ ],
+ },
+ Card: {properties: {child: {$ref: `${COMMON}/ComponentId`}}},
+ Tabs: {
+ properties: {
+ tabs: {
+ type: 'array',
+ items: {properties: {title: {type: 'string'}, child: {$ref: `${COMMON}/ComponentId`}}},
+ },
+ },
+ },
+ Modal: {$ref: '#/$defs/ModalProps'},
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ $defs: {
+ ModalProps: {
+ properties: {
+ trigger: {$ref: `${COMMON}/ComponentId`},
+ content: {$ref: `${COMMON}/ComponentId`},
+ },
+ },
+ },
+};
+
+function surface(components: Array>) {
+ return [
+ {version: 'v0.9', createSurface: {surfaceId: 's', catalogId: 'test'}},
+ {version: 'v0.9', updateComponents: {surfaceId: 's', components}},
+ ];
+}
+
+/** Renders a tree as indented `via:type#id [flags]` lines. */
+function outline(node: ComponentTreeNode | null, depth = 0): string[] {
+ if (!node) return [];
+ const flags = [
+ node.status !== 'ok' ? node.status : '',
+ node.shared ? 'shared' : '',
+ node.template !== null ? `each ${node.template}` : '',
+ ].filter(Boolean);
+ const line =
+ ' '.repeat(depth) +
+ `${node.via ? node.via + ':' : ''}${node.type ?? '?'}#${node.id}` +
+ (flags.length ? ` [${flags.join(', ')}]` : '');
+ return [line, ...node.children.flatMap(c => outline(c, depth + 1))];
+}
+
+describe('buildComponentTrees', () => {
+ it('follows ComponentId and ChildList references found in the catalog schema', () => {
+ const [tree] = buildComponentTrees(
+ surface([
+ {id: 'root', component: 'Column', children: ['card', 'tabs', 'modal']},
+ {id: 'card', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Hi'},
+ {
+ id: 'tabs',
+ component: 'Tabs',
+ tabs: [
+ {title: 'A', child: 'a'},
+ {title: 'B', child: 'b'},
+ ],
+ },
+ {id: 'a', component: 'Text'},
+ {id: 'b', component: 'Text'},
+ {id: 'modal', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text'},
+ {id: 'body', component: 'Text'},
+ ]),
+ CATALOG,
+ );
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:Card#card',
+ ' child:Text#title',
+ ' children:Tabs#tabs',
+ ' tabs[0].child:Text#a',
+ ' tabs[1].child:Text#b',
+ ' children:Modal#modal',
+ ' trigger:Text#open',
+ ' content:Text#body',
+ ]);
+ expect(tree.unreachable).toEqual([]);
+ expect(tree.componentCount).toBe(9);
+ });
+
+ it('reports missing, cyclic, shared, template and unreachable components', () => {
+ const [tree] = buildComponentTrees(
+ surface([
+ {id: 'root', component: 'Column', children: ['loop', 'shared', 'shared', 'ghost']},
+ {id: 'loop', component: 'Card', child: 'root'},
+ {id: 'shared', component: 'Column', children: {componentId: 'item', path: '/items'}},
+ {id: 'item', component: 'Text'},
+ {id: 'orphan', component: 'Card', child: 'orphanChild'},
+ {id: 'orphanChild', component: 'Text'},
+ ]),
+ CATALOG,
+ );
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:Card#loop',
+ ' child:Column#root [cycle]',
+ ' children:Column#shared [shared]',
+ ' children:Text#item [each /items]',
+ ' children:Column#shared [shared]',
+ ' children:Text#item [each /items]',
+ ' children:?#ghost [missing]',
+ ]);
+ expect(tree.unreachable.map(n => outline(n))).toEqual([
+ ['Card#orphan', ' child:Text#orphanChild'],
+ ]);
+ });
+
+ it('falls back to child/children without a catalog and tracks surface lifecycle', () => {
+ const trees = buildComponentTrees(
+ [
+ ...surface([
+ {id: 'root', component: 'Box', children: ['x']},
+ {id: 'x', component: 'Thing', child: 'y'},
+ {id: 'y', component: 'Thing'},
+ ]),
+ {version: 'v0.9', createSurface: {surfaceId: 'gone', catalogId: 'test'}},
+ {version: 'v0.9', deleteSurface: {surfaceId: 'gone'}},
+ ],
+ null,
+ );
+ expect(trees.map(t => t.surfaceId)).toEqual(['s']);
+ expect(outline(trees[0].root)).toEqual(['Box#root', ' children:Thing#x', ' child:Thing#y']);
+ });
+
+ it('has no root until the root component is defined', () => {
+ const [tree] = buildComponentTrees(surface([{id: 'x', component: 'Text'}]), CATALOG);
+ expect(tree.root).toBeNull();
+ expect(tree.unreachable.map(n => n.id)).toEqual(['x']);
+ });
+
+ it('follows references in bundled catalogs with namespaced $defs', () => {
+ const bundled: Catalog = {
+ catalogId: 'bundled',
+ components: {
+ Row: {
+ allOf: [
+ {$ref: '#/$defs/common_types_ComponentCommon'},
+ {properties: {children: {$ref: '#/$defs/common_types_ChildList'}}},
+ ],
+ },
+ Button: {properties: {child: {$ref: '#/$defs/common_types_ComponentId'}}},
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ $defs: {
+ common_types_ComponentCommon: {
+ properties: {id: {$ref: '#/$defs/common_types_ComponentId'}},
+ },
+ common_types_ComponentId: {type: 'string'},
+ common_types_ChildList: {},
+ },
+ };
+ const [tree] = buildComponentTrees(
+ surface([
+ {id: 'root', component: 'Row', children: ['btn']},
+ {id: 'btn', component: 'Button', child: 'label'},
+ {id: 'label', component: 'Text', text: 'Go'},
+ ]),
+ bundled,
+ );
+ expect(outline(tree.root)).toEqual([
+ 'Row#root',
+ ' children:Button#btn',
+ ' child:Text#label',
+ ]);
+ expect(tree.unreachable).toEqual([]);
+ });
+
+ it('assigns distinct node keys across surfaces with identical component ids', () => {
+ const components = [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Hi'},
+ {id: 'orphan', component: 'Text', text: 'Unused'},
+ ];
+ const [first, second] = buildComponentTrees(
+ [
+ {version: 'v0.9', createSurface: {surfaceId: 's1', catalogId: 'test'}},
+ {version: 'v0.9', updateComponents: {surfaceId: 's1', components}},
+ {version: 'v0.9', createSurface: {surfaceId: 's2', catalogId: 'test'}},
+ {version: 'v0.9', updateComponents: {surfaceId: 's2', components}},
+ ],
+ CATALOG,
+ );
+ expect(first.root!.key).not.toBe(second.root!.key);
+ expect(first.root!.children[0].key).not.toBe(second.root!.children[0].key);
+ expect(first.unreachable[0].key).not.toBe(second.unreachable[0].key);
+ });
+
+ it('builds a tree from inline v1.0 createSurface components', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text'},
+ ],
+ },
+ },
+ ];
+
+ const [tree] = buildComponentTrees(messages, CATALOG);
+
+ expect(outline(tree.root)).toEqual(['Card#root', ' child:Text#title']);
+ expect(tree.componentCount).toBe(2);
+ });
+
+ it('merges subsequent updateComponents onto inline createSurface components', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text'},
+ ],
+ },
+ },
+ {
+ version: '1.0',
+ updateComponents: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Column', children: ['title', 'extra']},
+ {id: 'extra', component: 'Text'},
+ ],
+ },
+ },
+ ];
+
+ const [tree] = buildComponentTrees(messages, CATALOG);
+
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:Text#title',
+ ' children:Text#extra',
+ ]);
+ expect(tree.componentCount).toBe(3);
+ });
+
+ it('follows v1.0 Child references in unbundled catalogs', () => {
+ const v1Catalog: Catalog = {
+ catalogId: 'v1-basic',
+ components: {
+ Column: {properties: {children: {$ref: 'common_types.json#/$defs/ChildList'}}},
+ Card: {properties: {child: {$ref: 'common_types.json#/$defs/Child'}}},
+ Modal: {
+ properties: {
+ trigger: {$ref: 'common_types.json#/$defs/Child'},
+ content: {$ref: 'common_types.json#/$defs/Child'},
+ },
+ },
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ };
+ const messages = surface([
+ {id: 'root', component: 'Column', children: ['card', 'modal']},
+ {id: 'card', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text'},
+ {id: 'modal', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text'},
+ {id: 'body', component: 'Text'},
+ ]);
+
+ const [tree] = buildComponentTrees(messages, v1Catalog);
+
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:Card#card',
+ ' child:Text#title',
+ ' children:Modal#modal',
+ ' trigger:Text#open',
+ ' content:Text#body',
+ ]);
+ expect(tree.unreachable).toEqual([]);
+ });
+
+ it('resolves Draft-07 #/definitions/ references in custom catalogs', () => {
+ const draft07Catalog = {
+ catalogId: 'draft-07',
+ components: {
+ Modal: {$ref: '#/definitions/ModalProps'},
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ definitions: {
+ ModalProps: {
+ properties: {
+ trigger: {$ref: `${COMMON}/ComponentId`},
+ content: {$ref: `${COMMON}/ComponentId`},
+ },
+ },
+ },
+ };
+ const messages = surface([
+ {id: 'root', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text'},
+ {id: 'body', component: 'Text'},
+ ]);
+
+ const [tree] = buildComponentTrees(messages, draft07Catalog);
+
+ expect(outline(tree.root)).toEqual([
+ 'Modal#root',
+ ' trigger:Text#open',
+ ' content:Text#body',
+ ]);
+ expect(tree.unreachable).toEqual([]);
+ });
+
+ it('ignores inherited prototype properties on catalog components and definitions', () => {
+ const inheritedDefs = Object.create({
+ InheritedSlot: {properties: {secret: {$ref: `${COMMON}/ComponentId`}}},
+ }) as Record>;
+ const catalog = {
+ catalogId: 'proto-guard',
+ components: {
+ Column: {properties: {children: {$ref: `${COMMON}/ChildList`}}},
+ UsesDefsProto: {$ref: '#/$defs/InheritedSlot'},
+ UsesDefinitionsProto: {$ref: '#/definitions/InheritedSlot'},
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ $defs: inheritedDefs,
+ definitions: inheritedDefs,
+ };
+ const messages = surface([
+ {
+ id: 'root',
+ component: 'Column',
+ children: ['constructorComp', 'defsComp', 'definitionsComp'],
+ },
+ {id: 'constructorComp', component: 'constructor', child: 'fallbackLeaf'},
+ {id: 'fallbackLeaf', component: 'Text'},
+ {id: 'defsComp', component: 'UsesDefsProto', secret: 'hiddenA'},
+ {id: 'definitionsComp', component: 'UsesDefinitionsProto', secret: 'hiddenB'},
+ {id: 'hiddenA', component: 'Text'},
+ {id: 'hiddenB', component: 'Text'},
+ ]);
+
+ const [tree] = buildComponentTrees(messages, catalog);
+
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:constructor#constructorComp',
+ ' child:Text#fallbackLeaf',
+ ' children:UsesDefsProto#defsComp',
+ ' children:UsesDefinitionsProto#definitionsComp',
+ ]);
+ expect(tree.unreachable.map(node => node.id)).toEqual(['hiddenA', 'hiddenB']);
+ });
+
+ it('memoizes discovered reference slots across repeated calls with the same catalog', () => {
+ let schemaReads = 0;
+ const catalog: Catalog = {
+ catalogId: 'memoized',
+ components: {
+ Card: {
+ get properties() {
+ schemaReads++;
+ return {child: {$ref: `${COMMON}/ComponentId`}};
+ },
+ },
+ Text: {properties: {text: {type: 'string'}}},
+ },
+ };
+ const messages = surface([
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text'},
+ ]);
+
+ buildComponentTrees(messages, catalog);
+ const [secondTree] = buildComponentTrees(messages, catalog);
+
+ expect(schemaReads).toBe(1);
+ expect(outline(secondTree.root)).toEqual(['Card#root', ' child:Text#title']);
+ });
+
+ it('truncates expansion at MAX_NODES when shared references multiply nodes', () => {
+ const levels = Array.from({length: 12}, (_, index) => ({
+ id: `n${index}`,
+ component: 'Column',
+ children: [`n${index + 1}`, `n${index + 1}`],
+ }));
+ const messages = surface([
+ {id: 'root', component: 'Column', children: ['n0', 'n0']},
+ ...levels,
+ {id: 'n12', component: 'Text'},
+ {id: 'orphan', component: 'Text'},
+ ]);
+
+ const [tree] = buildComponentTrees(messages, CATALOG);
+
+ expect(tree.truncated).toBe(true);
+ expect(tree.unreachable).toEqual([]);
+ });
+
+ it('falls back to child/children for stub component entries without schema keywords', () => {
+ const stubCatalog: Catalog = {
+ catalogId: 'stub-catalog',
+ components: {
+ Column: {name: 'Column'},
+ Card: {name: 'Card'},
+ Text: {name: 'Text'},
+ },
+ };
+ const messages = surface([
+ {id: 'root', component: 'Column', children: ['card']},
+ {id: 'card', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text'},
+ ]);
+
+ const [tree] = buildComponentTrees(messages, stubCatalog);
+
+ expect(outline(tree.root)).toEqual([
+ 'Column#root',
+ ' children:Card#card',
+ ' child:Text#title',
+ ]);
+ expect(tree.unreachable).toEqual([]);
+ });
+});
+
+describe('getSurfaceComponent', () => {
+ it('returns the target component from the latest updateComponents message for the surface', () => {
+ const messages = [
+ {version: 'v0.9', createSurface: {surfaceId: 's', catalogId: 'test'}},
+ {
+ version: 'v0.9',
+ updateComponents: {
+ surfaceId: 's',
+ components: [{id: 'title', component: 'Text', text: 'Old'}],
+ },
+ },
+ {
+ version: 'v0.9',
+ updateComponents: {
+ surfaceId: 's',
+ components: [{id: 'title', component: 'Text', text: 'Latest'}],
+ },
+ },
+ ];
+
+ expect(getSurfaceComponent(messages, 's', 'title')).toEqual({
+ id: 'title',
+ component: 'Text',
+ text: 'Latest',
+ });
+ });
+
+ it('returns a component defined inline in v1.0 createSurface.components', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Inline'},
+ ],
+ },
+ },
+ ];
+
+ expect(getSurfaceComponent(messages, 's', 'title')).toEqual({
+ id: 'title',
+ component: 'Text',
+ text: 'Inline',
+ });
+ });
+
+ it('returns null when the surface or component does not exist', () => {
+ const messages = surface([{id: 'root', component: 'Column', children: []}]);
+
+ expect(getSurfaceComponent(messages, 'missing-surface', 'root')).toBeNull();
+ expect(getSurfaceComponent(messages, 's', 'missing-component')).toBeNull();
+ });
+});
+
+describe('updateSurfaceComponent', () => {
+ it('replaces the target component in the latest updateComponents message for the surface', () => {
+ const messages = surface([
+ {id: 'root', component: 'Column', children: ['title']},
+ {id: 'title', component: 'Text', text: 'Hi'},
+ ]);
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'title', {
+ id: 'title',
+ component: 'Text',
+ text: 'Hello',
+ });
+
+ expect(updatedMessages).toEqual(
+ surface([
+ {id: 'root', component: 'Column', children: ['title']},
+ {id: 'title', component: 'Text', text: 'Hello'},
+ ]),
+ );
+ });
+
+ it('replaces the target component in inline v1.0 createSurface components when not overridden', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Hi'},
+ ],
+ },
+ },
+ ];
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'title', {
+ id: 'title',
+ component: 'Text',
+ text: 'Hello',
+ });
+
+ expect(updatedMessages).toEqual([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Hello'},
+ ],
+ },
+ },
+ ]);
+ });
+
+ it('updates the latest updateComponents override rather than an earlier inline createSurface component', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [
+ {id: 'root', component: 'Card', child: 'title'},
+ {id: 'title', component: 'Text', text: 'Initial'},
+ ],
+ },
+ },
+ {
+ version: '1.0',
+ updateComponents: {
+ surfaceId: 's',
+ components: [{id: 'title', component: 'Text', text: 'Overridden'}],
+ },
+ },
+ ];
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'title', {
+ id: 'title',
+ component: 'Text',
+ text: 'Edited',
+ });
+
+ expect(updatedMessages).toEqual([
+ messages[0],
+ {
+ version: '1.0',
+ updateComponents: {
+ surfaceId: 's',
+ components: [{id: 'title', component: 'Text', text: 'Edited'}],
+ },
+ },
+ ]);
+ });
+
+ it('does not mutate components from before a surface was recreated', () => {
+ const messages = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [{id: 'title', component: 'Text', text: 'Stale'}],
+ },
+ },
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ components: [{id: 'root', component: 'Column', children: []}],
+ },
+ },
+ ];
+ const snapshot = structuredClone(messages);
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'title', {
+ id: 'title',
+ component: 'Text',
+ text: 'Edited',
+ });
+
+ expect(updatedMessages).toBe(messages);
+ expect(messages).toEqual(snapshot);
+ });
+
+ it('does not mutate components after a surface was deleted', () => {
+ const messages = [
+ ...surface([{id: 'title', component: 'Text', text: 'Hi'}]),
+ {version: 'v0.9', deleteSurface: {surfaceId: 's'}},
+ ];
+ const snapshot = structuredClone(messages);
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'title', {
+ id: 'title',
+ component: 'Text',
+ text: 'Edited',
+ });
+
+ expect(updatedMessages).toBe(messages);
+ expect(messages).toEqual(snapshot);
+ });
+
+ it('returns the original messages reference when the component is not found', () => {
+ const messages = surface([{id: 'root', component: 'Column', children: []}]);
+ const snapshot = structuredClone(messages);
+
+ const updatedMessages = updateSurfaceComponent(messages, 's', 'missing', {
+ id: 'missing',
+ component: 'Text',
+ text: 'No-op',
+ });
+
+ expect(updatedMessages).toBe(messages);
+ expect(messages).toEqual(snapshot);
+ });
+});
diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts
new file mode 100644
index 000000000..196c646b9
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree-builder.ts
@@ -0,0 +1,516 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {Catalog} from '../../storage/models/catalog-storage.model';
+import {asRecord} from '../../utils/json';
+
+/**
+ * Builds the component tree of A2UI surfaces from their messages.
+ *
+ * A2UI v0.9 describes a surface as a flat list of components (an adjacency
+ * list) in which components reference other components by id, via properties
+ * typed `ComponentId` (a single child) or `ChildList` (a list of ids or a
+ * data-bound template). The tree is the expansion of these references from
+ * the `root` component. The protocol does not guarantee that the references
+ * form a tree, so the builder also reports:
+ * - references to undefined components (`missing`),
+ * - references to an ancestor (`cycle`, not expanded further),
+ * - components referenced more than once (`shared`; expanded at each use),
+ * - components not reachable from `root` (`unreachable`).
+ *
+ * Reference properties are discovered from the catalog's JSON schema
+ * (`$ref`s to `ComponentId` / `Child` / `ChildList`, at any depth, e.g.
+ * `tabs[].child`), falling back to the conventional `child` / `children`
+ * properties for components whose schema is unknown.
+ */
+
+/** Reference status of a tree node. */
+export type ComponentTreeNodeStatus = 'ok' | 'missing' | 'cycle';
+
+/** A component occurrence in the expanded tree. */
+export interface ComponentTreeNode {
+ /** Unique key of this occurrence (surface-scoped reference path). */
+ readonly key: string;
+ /** The referenced component id. */
+ readonly id: string;
+ /** The component type, or null if the component is not defined. */
+ readonly type: string | null;
+ /** The referencing property, e.g. `children`, `tabs[1].child`. */
+ readonly via: string | null;
+ readonly status: ComponentTreeNodeStatus;
+ /** True if the component is referenced from more than one place. */
+ readonly shared: boolean;
+ /**
+ * For template children, the data model path whose items each render one
+ * instance of this component.
+ */
+ readonly template: string | null;
+ readonly children: readonly ComponentTreeNode[];
+}
+
+/** The component tree of one surface. */
+export interface SurfaceComponentTree {
+ readonly surfaceId: string;
+ /** The tree from the `root` component, or null if there is none yet. */
+ readonly root: ComponentTreeNode | null;
+ /** Subtrees of components that are not reachable from `root`. */
+ readonly unreachable: readonly ComponentTreeNode[];
+ /** Number of defined components. */
+ readonly componentCount: number;
+ /** True if expansion stopped early because the tree was too large. */
+ readonly truncated: boolean;
+}
+
+/** Root component id mandated by the A2UI protocol. */
+export const ROOT_COMPONENT_ID = 'root';
+
+/** Upper bound on expanded nodes (shared references can multiply nodes). */
+const MAX_NODES = 5000;
+
+const COMPONENT_ID_DEF = 'ComponentId';
+const CHILD_DEF = 'Child';
+const CHILD_LIST_DEF = 'ChildList';
+const LOCAL_DEFS_PREFIX = '#/$defs/';
+const LOCAL_DEFINITIONS_PREFIX = '#/definitions/';
+const ANY_INDEX = '*';
+
+type ReferenceKind = 'single' | 'list';
+
+/**
+ * Returns the kind of component reference a `$ref` points to, if any. Matches
+ * both separate common-types schemas (`common_types.json#/$defs/ChildList`)
+ * and bundled catalogs with namespaced definitions
+ * (`#/$defs/common_types_ChildList`).
+ */
+function referenceKindOf(ref: string): ReferenceKind | null {
+ const name = ref.slice(ref.lastIndexOf('/') + 1);
+ const is = (def: string) => name === def || name.endsWith(`_${def}`);
+ if (is(COMPONENT_ID_DEF) || is(CHILD_DEF)) return 'single';
+ if (is(CHILD_LIST_DEF)) return 'list';
+ return null;
+}
+
+/** A property path (within a component) holding component references. */
+interface ReferenceSlot {
+ /** Property names, with `*` for "every array item". */
+ readonly path: readonly string[];
+ readonly kind: ReferenceKind;
+}
+
+/** A concrete reference found in a component instance. */
+interface Reference {
+ readonly id: string;
+ readonly via: string;
+ readonly template: string | null;
+}
+
+type ComponentRecord = Record;
+
+interface SurfaceState {
+ readonly components: Map;
+}
+
+const FALLBACK_SLOTS: readonly ReferenceSlot[] = [
+ {path: ['child'], kind: 'single'},
+ {path: ['children'], kind: 'list'},
+];
+
+/** Collects the surfaces described by a list of A2UI messages, in order. */
+function collectSurfaces(messages: readonly unknown[]): Map {
+ const surfaces = new Map();
+ const surfaceFor = (id: string) => {
+ let state = surfaces.get(id);
+ if (!state) {
+ state = {components: new Map()};
+ surfaces.set(id, state);
+ }
+ return state;
+ };
+ const addComponents = (state: SurfaceState, components: unknown) => {
+ if (!Array.isArray(components)) return;
+ for (const component of components) {
+ const componentRecord = asRecord(component);
+ if (componentRecord && typeof componentRecord['id'] === 'string') {
+ state.components.set(componentRecord['id'], componentRecord);
+ }
+ }
+ };
+ for (const message of messages) {
+ const record = asRecord(message);
+ if (!record) continue;
+ const create = asRecord(record['createSurface']);
+ if (create && typeof create['surfaceId'] === 'string') {
+ const state = surfaceFor(create['surfaceId']);
+ state.components.clear();
+ addComponents(state, create['components']);
+ }
+ const update = asRecord(record['updateComponents']);
+ if (update && typeof update['surfaceId'] === 'string' && Array.isArray(update['components'])) {
+ addComponents(surfaceFor(update['surfaceId']), update['components']);
+ }
+ const del = asRecord(record['deleteSurface']);
+ if (del && typeof del['surfaceId'] === 'string') {
+ surfaces.delete(del['surfaceId']);
+ }
+ }
+ return surfaces;
+}
+
+const SCHEMA_STRUCTURE_KEYS = ['$ref', 'allOf', 'anyOf', 'oneOf', 'properties', 'items'] as const;
+
+function hasSchemaStructure(schema: unknown): boolean {
+ const record = asRecord(schema);
+ return record !== null && SCHEMA_STRUCTURE_KEYS.some(key => Object.hasOwn(record, key));
+}
+
+/** Discovers the reference slots of each component type from the catalog. */
+class ReferenceSchema {
+ private readonly cache = new Map();
+
+ constructor(private readonly catalog: Catalog | null) {}
+
+ slotsFor(type: string): readonly ReferenceSlot[] {
+ const components = this.catalog?.components;
+ const schema = components && Object.hasOwn(components, type) ? components[type] : undefined;
+ if (!hasSchemaStructure(schema)) return FALLBACK_SLOTS;
+ let slots = this.cache.get(type);
+ if (!slots) {
+ const discovered: ReferenceSlot[] = [];
+ this.walk(schema, [], discovered, new Set());
+ slots = discovered.filter(s => !(s.path.length === 1 && s.path[0] === 'id'));
+ this.cache.set(type, slots);
+ }
+ return slots;
+ }
+
+ private walk(
+ schema: unknown,
+ path: readonly string[],
+ out: ReferenceSlot[],
+ visitingDefs: Set,
+ ): void {
+ const s = asRecord(schema);
+ if (!s) return;
+ const ref = s['$ref'];
+ if (typeof ref === 'string') {
+ const kind = referenceKindOf(ref);
+ if (kind) {
+ out.push({path, kind});
+ return;
+ }
+ const target = this.resolveLocalDefinition(ref);
+ if (target !== undefined && !visitingDefs.has(ref)) {
+ visitingDefs.add(ref);
+ this.walk(target, path, out, visitingDefs);
+ visitingDefs.delete(ref);
+ }
+ }
+ for (const key of ['allOf', 'anyOf', 'oneOf']) {
+ const variants = s[key];
+ if (Array.isArray(variants)) {
+ for (const variant of variants) this.walk(variant, path, out, visitingDefs);
+ }
+ }
+ const properties = asRecord(s['properties']);
+ if (properties) {
+ for (const [name, propertySchema] of Object.entries(properties)) {
+ this.walk(propertySchema, [...path, name], out, visitingDefs);
+ }
+ }
+ if (s['items'] !== undefined) {
+ this.walk(s['items'], [...path, ANY_INDEX], out, visitingDefs);
+ }
+ }
+
+ private resolveLocalDefinition(ref: string): unknown {
+ if (ref.startsWith(LOCAL_DEFS_PREFIX)) {
+ const name = ref.slice(LOCAL_DEFS_PREFIX.length);
+ const defs = this.catalog?.$defs;
+ return defs && Object.hasOwn(defs, name) ? defs[name] : undefined;
+ }
+ if (ref.startsWith(LOCAL_DEFINITIONS_PREFIX)) {
+ const name = ref.slice(LOCAL_DEFINITIONS_PREFIX.length);
+ const definitions = asRecord(asRecord(this.catalog)?.['definitions']);
+ return definitions && Object.hasOwn(definitions, name) ? definitions[name] : undefined;
+ }
+ return undefined;
+ }
+}
+
+/** Returns the references held by [component], in property order. */
+function referencesOf(component: ComponentRecord, schema: ReferenceSchema): Reference[] {
+ const type = typeof component['component'] === 'string' ? component['component'] : '';
+ const refs: Reference[] = [];
+ const seenSlots = new Set();
+ for (const slot of schema.slotsFor(type)) {
+ const slotKey = `${slot.kind}:${slot.path.join('.')}`;
+ if (seenSlots.has(slotKey)) continue;
+ seenSlots.add(slotKey);
+ collect(component, slot.path, 0, '', slot.kind, refs);
+ }
+ return refs;
+}
+
+function collect(
+ value: unknown,
+ path: readonly string[],
+ index: number,
+ label: string,
+ kind: ReferenceKind,
+ out: Reference[],
+): void {
+ if (index === path.length) {
+ if (kind === 'single') {
+ if (typeof value === 'string') out.push({id: value, via: label, template: null});
+ return;
+ }
+ if (Array.isArray(value)) {
+ for (const id of value) {
+ if (typeof id === 'string') out.push({id, via: label, template: null});
+ }
+ return;
+ }
+ const template = asRecord(value);
+ if (template && typeof template['componentId'] === 'string') {
+ out.push({
+ id: template['componentId'],
+ via: label,
+ template: typeof template['path'] === 'string' ? template['path'] : '',
+ });
+ }
+ return;
+ }
+ const segment = path[index];
+ if (segment === ANY_INDEX) {
+ if (!Array.isArray(value)) return;
+ value.forEach((item, i) => {
+ collect(item, path, index + 1, `${label}[${i}]`, kind, out);
+ });
+ return;
+ }
+ const record = asRecord(value);
+ if (!record || !(segment in record)) return;
+ collect(record[segment], path, index + 1, label ? `${label}.${segment}` : segment, kind, out);
+}
+
+const NULL_REFERENCE_SCHEMA = new ReferenceSchema(null);
+const referenceSchemaCache = new WeakMap();
+
+function referenceSchemaFor(catalog: Catalog | null): ReferenceSchema {
+ if (!catalog) return NULL_REFERENCE_SCHEMA;
+ let schema = referenceSchemaCache.get(catalog);
+ if (!schema) {
+ schema = new ReferenceSchema(catalog);
+ referenceSchemaCache.set(catalog, schema);
+ }
+ return schema;
+}
+
+/**
+ * Builds the component trees of all surfaces described by [messages] (a list
+ * of A2UI v0.9 server-to-client messages), using [catalog] to find reference
+ * properties.
+ */
+export function buildComponentTrees(
+ messages: readonly unknown[],
+ catalog: Catalog | null,
+): SurfaceComponentTree[] {
+ const schema = referenceSchemaFor(catalog);
+ const trees: SurfaceComponentTree[] = [];
+ for (const [surfaceId, state] of collectSurfaces(messages)) {
+ trees.push(buildSurfaceTree(surfaceId, state, schema));
+ }
+ return trees;
+}
+
+function buildSurfaceTree(
+ surfaceId: string,
+ state: SurfaceState,
+ schema: ReferenceSchema,
+): SurfaceComponentTree {
+ const {components} = state;
+ const references = new Map();
+ const referenceCounts = new Map();
+ for (const [id, component] of components) {
+ const refs = referencesOf(component, schema);
+ references.set(id, refs);
+ for (const ref of refs) {
+ referenceCounts.set(ref.id, (referenceCounts.get(ref.id) ?? 0) + 1);
+ }
+ }
+
+ const visited = new Set();
+ let nodeCount = 0;
+ let truncated = false;
+
+ const expand = (
+ id: string,
+ via: string | null,
+ template: string | null,
+ key: string,
+ ancestors: ReadonlySet,
+ ): ComponentTreeNode => {
+ nodeCount++;
+ const component = components.get(id);
+ const type =
+ component && typeof component['component'] === 'string' ? component['component'] : null;
+ const shared = (referenceCounts.get(id) ?? 0) > 1;
+ const base = {key, id, type, via, shared, template};
+ if (!component) {
+ return {...base, status: 'missing', children: []};
+ }
+ if (ancestors.has(id)) {
+ return {...base, status: 'cycle', children: []};
+ }
+ visited.add(id);
+ const nextAncestors = new Set(ancestors).add(id);
+ const children: ComponentTreeNode[] = [];
+ for (const [i, ref] of (references.get(id) ?? []).entries()) {
+ if (nodeCount >= MAX_NODES) {
+ truncated = true;
+ break;
+ }
+ children.push(expand(ref.id, ref.via, ref.template, `${key}/${i}:${ref.id}`, nextAncestors));
+ }
+ return {...base, status: 'ok', children};
+ };
+
+ const root = components.has(ROOT_COMPONENT_ID)
+ ? expand(ROOT_COMPONENT_ID, null, null, `${surfaceId}/${ROOT_COMPONENT_ID}`, new Set())
+ : null;
+
+ // Unreachable components: start from those no other unreachable component
+ // references, then pick up any remaining (cyclic) ones.
+ const unreachable: ComponentTreeNode[] = [];
+ const pending = [...components.keys()].filter(id => !visited.has(id));
+ const referencedByPending = new Set();
+ for (const id of pending) {
+ for (const ref of references.get(id) ?? []) referencedByPending.add(ref.id);
+ }
+ const orderedStarts = [
+ ...pending.filter(id => !referencedByPending.has(id)),
+ ...pending.filter(id => referencedByPending.has(id)),
+ ];
+ for (const id of orderedStarts) {
+ if (visited.has(id)) continue;
+ if (nodeCount >= MAX_NODES) {
+ truncated = true;
+ break;
+ }
+ unreachable.push(expand(id, null, null, `${surfaceId}/~${id}`, new Set()));
+ }
+
+ return {
+ surfaceId,
+ root,
+ unreachable,
+ componentCount: components.size,
+ truncated,
+ };
+}
+
+/**
+ * Returns the definition of component [componentId] in [surfaceId] from [messages], or null.
+ */
+export function getSurfaceComponent(
+ messages: readonly unknown[],
+ surfaceId: string,
+ componentId: string,
+): Record | null {
+ return collectSurfaces(messages).get(surfaceId)?.components.get(componentId) ?? null;
+}
+
+function replaceLastMatchingComponent(
+ components: readonly unknown[],
+ componentId: string,
+ updatedComponent: Record,
+): unknown[] | null {
+ for (let componentIndex = components.length - 1; componentIndex >= 0; componentIndex--) {
+ const component = asRecord(components[componentIndex]);
+ if (component && component['id'] === componentId) {
+ const nextComponents = [...components];
+ nextComponents[componentIndex] = updatedComponent;
+ return nextComponents;
+ }
+ }
+ return null;
+}
+
+/**
+ * Returns a copy of [messages] with component [componentId] in [surfaceId]
+ * replaced by [updatedComponent] in its latest `updateComponents` or inline
+ * `createSurface` message, or [messages] unchanged if no matching component is
+ * found.
+ */
+export function updateSurfaceComponent(
+ messages: readonly unknown[],
+ surfaceId: string,
+ componentId: string,
+ updatedComponent: Record,
+): readonly unknown[] {
+ for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) {
+ const record = asRecord(messages[messageIndex]);
+ if (!record) continue;
+ const deleteSurface = asRecord(record['deleteSurface']);
+ if (deleteSurface && deleteSurface['surfaceId'] === surfaceId) break;
+ const updateComponents = asRecord(record['updateComponents']);
+ if (
+ updateComponents &&
+ updateComponents['surfaceId'] === surfaceId &&
+ Array.isArray(updateComponents['components'])
+ ) {
+ const nextComponents = replaceLastMatchingComponent(
+ updateComponents['components'],
+ componentId,
+ updatedComponent,
+ );
+ if (nextComponents) {
+ const nextMessages = [...messages];
+ nextMessages[messageIndex] = {
+ ...record,
+ updateComponents: {
+ ...updateComponents,
+ components: nextComponents,
+ },
+ };
+ return nextMessages;
+ }
+ }
+ const createSurface = asRecord(record['createSurface']);
+ if (createSurface && createSurface['surfaceId'] === surfaceId) {
+ if (Array.isArray(createSurface['components'])) {
+ const nextComponents = replaceLastMatchingComponent(
+ createSurface['components'],
+ componentId,
+ updatedComponent,
+ );
+ if (nextComponents) {
+ const nextMessages = [...messages];
+ nextMessages[messageIndex] = {
+ ...record,
+ createSurface: {
+ ...createSurface,
+ components: nextComponents,
+ },
+ };
+ return nextMessages;
+ }
+ }
+ break;
+ }
+ }
+ return messages;
+}
diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html
new file mode 100644
index 000000000..3543cf942
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree.ng.html
@@ -0,0 +1,135 @@
+
+
+
+ @if (parseError(); as error) {
+
The A2UI JSON is invalid: {{ error }}
+ } @else if (trees().length === 0) {
+
No surfaces.
+ }
+
+ @for (tree of trees(); track tree.surfaceId) {
+
+
+
+ @if (tree.root; as root) {
+
+
+
+ } @else {
+ No root component.
+ }
+
+ @if (tree.unreachable.length > 0) {
+
+
+ @for (node of tree.unreachable; track node.key) {
+
+ }
+
+ }
+
+ }
+
+
+
+ 0 ? isExpanded(node) : null"
+ [attr.aria-selected]="isSelected(surfaceId, node)"
+ [class.selected]="isSelected(surfaceId, node)"
+ [class.missing]="node.status === 'missing'"
+ [class.cycle]="node.status === 'cycle'"
+ [style.padding-left.px]="8 + depth * 16"
+ [matTooltip]="tooltipFor(node)"
+ matTooltipPosition="above"
+ matTooltipClass="component-tree-tooltip"
+ [matTooltipShowDelay]="250"
+ (focus)="onFocus(surfaceId, node)"
+ (click)="selectNode(surfaceId, node, $event)"
+ (keydown.enter)="selectNode(surfaceId, node, $event)"
+ (keydown.space)="selectNode(surfaceId, node, $event)"
+ (keydown.arrowDown)="focusNextNode($event)"
+ (keydown.arrowUp)="focusPreviousNode($event)"
+ (keydown.arrowLeft)="collapseNode(node, parentRow, $event)"
+ (keydown.arrowRight)="expandNode(node, $event)"
+ (keydown.home)="focusFirstNode($event)"
+ (keydown.end)="focusLastNode($event)"
+ >
+ @if (node.children.length > 0) {
+
+ {{ isExpanded(node) ? '▾' : '▸' }}
+
+ } @else {
+
+ }
+ @if (node.via) {
+ {{ node.via }}:
+ }
+ {{ node.type ?? '?' }}
+ #{{ node.id }}
+ @if (node.template !== null) {
+ each {{ node.template || 'item' }}
+ }
+ @if (node.shared) {
+ shared
+ }
+ @if (node.status === 'missing') {
+ missing
+ }
+ @if (node.status === 'cycle') {
+ cycle
+ }
+
+ @if (isExpanded(node)) {
+ @for (child of node.children; track child.key) {
+
+ }
+ }
+
diff --git a/shell/src/app/debug/component-tree/component-tree.scss b/shell/src/app/debug/component-tree/component-tree.scss
new file mode 100644
index 000000000..f6215c362
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree.scss
@@ -0,0 +1,145 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+:host {
+ display: block;
+ height: 100%;
+ width: 100%;
+ overflow: auto;
+}
+
+.component-tree-container {
+ padding: 4px 0;
+ font-family: Roboto, 'Helvetica Neue', sans-serif;
+ font-size: 13px;
+ color: var(--mat-sys-on-surface);
+}
+
+code {
+ font-family: 'Roboto Mono', monospace;
+}
+
+.muted {
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.tree-message {
+ padding: 8px 12px;
+ color: var(--mat-sys-on-surface-variant);
+
+ &.error {
+ color: var(--mat-sys-error);
+ }
+}
+
+.surface + .surface {
+ margin-top: 8px;
+}
+
+.surface-header,
+.unreachable-header {
+ padding: 4px 12px;
+ font-weight: 500;
+}
+
+.unreachable-header {
+ margin-top: 8px;
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.tree-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-height: 24px;
+ padding-right: 12px;
+ cursor: pointer;
+ white-space: nowrap;
+
+ &:hover {
+ background: var(--mat-sys-surface-container-high);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--mat-sys-primary);
+ outline-offset: -2px;
+ }
+
+ &.selected {
+ background: var(--mat-sys-secondary-container);
+ color: var(--mat-sys-on-secondary-container);
+
+ .via,
+ .id {
+ color: var(--mat-sys-on-secondary-container);
+ }
+
+ .badge:not(.error):not(.warn) {
+ background: var(--mat-sys-surface);
+ color: var(--mat-sys-on-surface);
+ }
+ }
+
+ &.missing .type,
+ &.cycle .type {
+ color: var(--mat-sys-error);
+ }
+}
+
+.toggle,
+.toggle-spacer {
+ flex: none;
+ width: 16px;
+}
+
+.toggle {
+ cursor: pointer;
+ line-height: 16px;
+ text-align: center;
+ user-select: none;
+}
+
+.via {
+ color: var(--mat-sys-on-surface-variant);
+}
+
+.type {
+ font-weight: 500;
+}
+
+.id {
+ color: var(--mat-sys-on-surface-variant);
+ font-family: 'Roboto Mono', monospace;
+}
+
+.badge {
+ padding: 0 6px;
+ border-radius: 8px;
+ background: var(--mat-sys-secondary-container);
+ color: var(--mat-sys-on-secondary-container);
+ font-size: 11px;
+ line-height: 16px;
+
+ &.error {
+ background: var(--mat-sys-error-container);
+ color: var(--mat-sys-on-error-container);
+ }
+
+ &.warn {
+ background: var(--mat-sys-tertiary-container);
+ color: var(--mat-sys-on-tertiary-container);
+ }
+}
diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts
new file mode 100644
index 000000000..ff90a6663
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree.spec.ts
@@ -0,0 +1,848 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {TestKey} from '@angular/cdk/testing';
+import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
+import {signal, WritableSignal} from '@angular/core';
+import {ComponentFixture, TestBed} from '@angular/core/testing';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {StateSync} from '../../chat/state-sync/state-sync';
+import {ComposerPanelId, OpenPanelEvent} from '../../shell/composer-workspace/composer-panel-id';
+import {CatalogManagement} from '../../storage/catalog-management/catalog-management';
+import {Catalog} from '../../storage/models/catalog-storage.model';
+import {formatJson} from '../../utils/json';
+import {ComponentTree} from './component-tree';
+import {ComponentTreeHarness} from './test/component-tree.harness';
+
+const COMMON = 'https://a2ui.org/specification/v1_0/common_types.json#/$defs';
+
+const PRIMARY_CATALOG: Catalog = {
+ catalogId: 'primary-catalog',
+ components: {
+ Column: {properties: {children: {$ref: `${COMMON}/ChildList`}}},
+ Card: {properties: {child: {$ref: `${COMMON}/Child`}}},
+ Text: {properties: {text: {type: 'string'}}},
+ },
+};
+
+const MERGED_CATALOG: Catalog = {
+ catalogId: 'primary-catalog',
+ components: {
+ ...PRIMARY_CATALOG.components,
+ Modal: {
+ properties: {
+ trigger: {$ref: `${COMMON}/Child`},
+ content: {$ref: `${COMMON}/Child`},
+ },
+ },
+ },
+};
+
+const SECONDARY_MODAL_MESSAGES = [
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['modal']},
+ {id: 'modal', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text', text: 'Open'},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ],
+ },
+ },
+];
+
+describe('ComponentTree', () => {
+ let fixture: ComponentFixture;
+ let harness: ComponentTreeHarness;
+ let component: ComponentTree;
+ let activeDraft: WritableSignal;
+ let sessionResetNonce: WritableSignal;
+ let activeCatalog: WritableSignal;
+ let mergedActiveCatalog: WritableSignal;
+ let updateDraftSpy: ReturnType;
+
+ beforeEach(async () => {
+ activeDraft = signal(formatJson(SECONDARY_MODAL_MESSAGES));
+ sessionResetNonce = signal(0);
+ activeCatalog = signal(null);
+ mergedActiveCatalog = signal(null);
+ updateDraftSpy = vi.fn((next: string) => activeDraft.set(next));
+
+ await TestBed.configureTestingModule({
+ imports: [ComponentTree],
+ providers: [
+ {
+ provide: StateSync,
+ useValue: {
+ activeDraft,
+ sessionResetNonce,
+ updateDraft: updateDraftSpy,
+ },
+ },
+ {
+ provide: CatalogManagement,
+ useValue: {
+ activeCatalog,
+ mergedActiveCatalog,
+ },
+ },
+ ],
+ }).compileComponents();
+
+ fixture = TestBed.createComponent(ComponentTree);
+ component = fixture.componentInstance;
+ fixture.detectChanges();
+ harness = await TestbedHarnessEnvironment.harnessForFixture(fixture, ComponentTreeHarness);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('prefers mergedActiveCatalog over activeCatalog so secondary catalog reference slots are expanded', async () => {
+ activeCatalog.set(PRIMARY_CATALOG);
+ mergedActiveCatalog.set(MERGED_CATALOG);
+ fixture.detectChanges();
+
+ const rows = await harness.getRows();
+
+ expect(rows.map(row => row.id)).toEqual(['#root', '#modal', '#open', '#body']);
+ expect(rows.map(row => row.via)).toEqual([null, 'children:', 'trigger:', 'content:']);
+ expect(await harness.hasUnreachableHeader()).toBe(false);
+ });
+
+ it('falls back to activeCatalog when mergedActiveCatalog is null', async () => {
+ activeCatalog.set(MERGED_CATALOG);
+ mergedActiveCatalog.set(null);
+ fixture.detectChanges();
+
+ const rows = await harness.getRows();
+
+ expect(rows.map(row => row.id)).toEqual(['#root', '#modal', '#open', '#body']);
+ expect(rows.map(row => row.via)).toEqual([null, 'children:', 'trigger:', 'content:']);
+ expect(await harness.hasUnreachableHeader()).toBe(false);
+ });
+
+ it('renders a parse error message and no tree rows when the active draft is invalid JSON', async () => {
+ activeDraft.set('{invalid');
+ fixture.detectChanges();
+
+ expect(await harness.getErrorMessage()).toContain('The A2UI JSON is invalid:');
+ expect(await harness.getTrees()).toEqual([]);
+ expect(await harness.getRowIds()).toEqual([]);
+ });
+
+ it('renders an empty-state message when the draft has no surfaces', async () => {
+ activeDraft.set('[]');
+ fixture.detectChanges();
+
+ expect(await harness.getMessages()).toEqual(['No surfaces.']);
+ expect(await harness.getTrees()).toEqual([]);
+ expect(await harness.getRowIds()).toEqual([]);
+ });
+
+ it.each([
+ {label: 'empty', draft: ''},
+ {label: 'whitespace-only', draft: ' \n\t '},
+ ])(
+ 'renders an empty-state message without a parse error when the draft is $label',
+ async ({draft}) => {
+ activeDraft.set(draft);
+ fixture.detectChanges();
+
+ expect(await harness.getErrorMessage()).toBeNull();
+ expect(await harness.getMessages()).toEqual(['No surfaces.']);
+ expect(await harness.getRowIds()).toEqual([]);
+ },
+ );
+
+ it('renders a missing-root message and unreachable section when root is absent', async () => {
+ activeCatalog.set(PRIMARY_CATALOG);
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ catalogId: 'primary-catalog',
+ components: [{id: 'orphan', component: 'Text', text: 'Standalone'}],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ expect(await harness.getMessages()).toEqual(['No root component.']);
+ expect(await harness.hasUnreachableHeader()).toBe(true);
+ expect(await harness.getTrees()).toEqual([
+ {
+ label: 'Surface s, not reachable from root',
+ rowIds: ['#orphan'],
+ tabStops: ['#orphan'],
+ },
+ ]);
+ });
+
+ it('collapses and re-expands child rows when toggling a branch node', async () => {
+ activeCatalog.set(MERGED_CATALOG);
+ fixture.detectChanges();
+
+ await harness.toggleRow('#modal');
+
+ const collapsedRows = await harness.getRows();
+ expect(collapsedRows.map(row => row.id)).toEqual(['#root', '#modal']);
+ expect(collapsedRows[1].expanded).toBe(false);
+
+ await harness.toggleRow('#modal');
+
+ const expandedRows = await harness.getRows();
+ expect(expandedRows.map(row => row.id)).toEqual(['#root', '#modal', '#open', '#body']);
+ expect(expandedRows[1].expanded).toBe(true);
+ });
+
+ it('isolates collapsed state per surface when surfaces share component ids', async () => {
+ activeCatalog.set(PRIMARY_CATALOG);
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'first',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['childA']},
+ {id: 'childA', component: 'Text', text: 'A'},
+ ],
+ },
+ },
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'second',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['childB']},
+ {id: 'childB', component: 'Text', text: 'B'},
+ ],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ await harness.toggleRow('#root', 0);
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => ({id: row.id, expanded: row.expanded}))).toEqual([
+ {id: '#root', expanded: false},
+ {id: '#root', expanded: true},
+ {id: '#childB', expanded: null},
+ ]);
+ });
+
+ it('renders badges and tooltips for missing, cyclic, template, and shared nodes', async () => {
+ activeCatalog.set(PRIMARY_CATALOG);
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ catalogId: 'primary-catalog',
+ components: [
+ {
+ id: 'root',
+ component: 'Column',
+ children: ['ghost', 'loop', 'templatedPath', 'templatedNoPath', 'sharedLeaf'],
+ },
+ {id: 'loop', component: 'Card', child: 'loop'},
+ {
+ id: 'templatedPath',
+ component: 'Column',
+ children: {componentId: 'sharedLeaf', path: '/items'},
+ },
+ {
+ id: 'templatedNoPath',
+ component: 'Column',
+ children: {componentId: 'itemRow'},
+ },
+ {id: 'sharedLeaf', component: 'Text', text: 'Shared'},
+ {id: 'itemRow', component: 'Text', text: 'Row'},
+ ],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ const rows = await harness.getRows();
+
+ expect(rows.map(row => ({id: row.id, badges: row.badges}))).toEqual([
+ {id: '#root', badges: []},
+ {id: '#ghost', badges: ['missing']},
+ {id: '#loop', badges: ['shared']},
+ {id: '#loop', badges: ['shared', 'cycle']},
+ {id: '#templatedPath', badges: []},
+ {id: '#sharedLeaf', badges: ['each /items', 'shared']},
+ {id: '#templatedNoPath', badges: []},
+ {id: '#itemRow', badges: ['each item']},
+ {id: '#sharedLeaf', badges: ['shared']},
+ ]);
+ expect(await harness.getTooltipText('#root')).toBe('');
+ expect(await harness.getTooltipText('#ghost')).toBe(
+ 'Component "ghost" is not defined in this surface.',
+ );
+ expect(await harness.getTooltipText('#loop', 1)).toBe(
+ 'Reference cycle: "loop" is one of its own ancestors, so it is not expanded again.',
+ );
+ expect(await harness.getTooltipText('#sharedLeaf')).toBe(
+ 'Rendered once per item of /items.\n"sharedLeaf" is referenced from more than one place.',
+ );
+ expect(await harness.getTooltipText('#itemRow')).toBe(
+ 'Rendered once per item of the data list.',
+ );
+ });
+
+ it('renders the truncated warning badge when a surface exceeds MAX_NODES', async () => {
+ activeCatalog.set(MERGED_CATALOG);
+ fixture.detectChanges();
+ // Collapse root first so jsdom does not instantiate 5,000 MatTooltip DOM rows.
+ await harness.toggleRow('#root');
+
+ const levels = Array.from({length: 12}, (_, index) => ({
+ id: `n${index}`,
+ component: 'Column',
+ children: [`n${index + 1}`, `n${index + 1}`],
+ }));
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['n0', 'n0']},
+ ...levels,
+ {id: 'n12', component: 'Text', text: 'Leaf'},
+ ],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ expect(await harness.hasTruncatedBadge()).toBe(true);
+ expect(await harness.getRowIds()).toEqual(['#root']);
+ });
+
+ describe('selection and keyboard navigation', () => {
+ const surfaceDraft = (components: Array>) =>
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {surfaceId: 's', catalogId: 'primary-catalog', components},
+ },
+ ]);
+
+ beforeEach(() => {
+ activeCatalog.set(MERGED_CATALOG);
+ fixture.detectChanges();
+ });
+
+ it('starts with no node selected', () => {
+ expect(component.selected()).toBeNull();
+ expect(component.selectedComponent()).toBeNull();
+ });
+
+ it('selects a node on click and dispatches OpenPanelEvent for PropertyEditor', async () => {
+ const dispatchSpy = vi.spyOn(window, 'dispatchEvent');
+
+ await harness.selectRow('#open');
+
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: OpenPanelEvent.TYPE,
+ detail: {panelId: ComposerPanelId.PropertyEditor},
+ }),
+ );
+ const rows = await harness.getRows();
+ expect(rows.map(row => row.selected)).toEqual([false, false, true, false]);
+ expect(component.selectedComponent()).toEqual({
+ id: 'open',
+ component: 'Text',
+ text: 'Open',
+ });
+ });
+
+ it('does not select the row or open PropertyEditor when toggling expansion', async () => {
+ const dispatchSpy = vi.spyOn(window, 'dispatchEvent');
+
+ await harness.toggleRow('#modal');
+
+ expect(dispatchSpy).not.toHaveBeenCalled();
+ expect(component.selected()).toBeNull();
+ const rows = await harness.getRows();
+ expect(
+ rows.map(row => ({id: row.id, expanded: row.expanded, selected: row.selected})),
+ ).toEqual([
+ {id: '#root', expanded: true, selected: false},
+ {id: '#modal', expanded: false, selected: false},
+ ]);
+ });
+
+ it('updates the selected component in the active draft via updateSelectedComponent', async () => {
+ await harness.selectRow('#open');
+
+ component.updateSelectedComponent({
+ id: 'open',
+ component: 'Text',
+ text: 'Updated Open',
+ });
+ fixture.detectChanges();
+
+ expect(updateDraftSpy).toHaveBeenCalledTimes(1);
+ const updatedPayload = JSON.parse(activeDraft());
+ expect(updatedPayload[0].createSurface.components).toEqual([
+ {id: 'root', component: 'Column', children: ['modal']},
+ {id: 'modal', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text', text: 'Updated Open'},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ]);
+ });
+
+ it('skips updateDraft when the selected component does not exist in the draft', async () => {
+ activeDraft.set(surfaceDraft([{id: 'root', component: 'Column', children: ['ghost']}]));
+ fixture.detectChanges();
+ await harness.selectRow('#ghost');
+
+ component.updateSelectedComponent({id: 'ghost', component: 'Text', text: 'Ignored'});
+
+ expect(component.selected()?.id).toBe('ghost');
+ expect(updateDraftSpy).not.toHaveBeenCalled();
+ });
+
+ it('switches selection when a different node is clicked', async () => {
+ await harness.selectRow('#open');
+
+ await harness.selectRow('#root');
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => row.selected)).toEqual([true, false, false, false]);
+ expect(component.selected()?.id).toBe('root');
+ });
+
+ it('keeps the highlight on the selected occurrence of a shared component when edited', async () => {
+ activeDraft.set(
+ surfaceDraft([
+ {id: 'root', component: 'Column', children: ['shared', 'shared']},
+ {id: 'shared', component: 'Text', text: 'Initial'},
+ ]),
+ );
+ fixture.detectChanges();
+ await harness.selectRow('#shared', 1);
+
+ component.updateSelectedComponent({id: 'shared', component: 'Text', text: 'Updated'});
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => row.selected)).toEqual([false, false, true]);
+ expect(component.selected()?.key).toBe('s/root/1:shared');
+ });
+
+ it('re-resolves selection by (surfaceId, id) when sibling indices shift', async () => {
+ await harness.selectRow('#body');
+
+ activeDraft.set(
+ surfaceDraft([
+ {id: 'root', component: 'Column', children: ['modal']},
+ {id: 'modal', component: 'Modal', content: 'body'},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ]),
+ );
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => ({id: row.id, selected: row.selected}))).toEqual([
+ {id: '#root', selected: false},
+ {id: '#modal', selected: false},
+ {id: '#body', selected: true},
+ ]);
+ expect(component.selected()?.key).toBe('s/root/0:modal/0:body');
+ });
+
+ it('re-resolves selection when a catalog update moves the selected component into the tree', async () => {
+ activeCatalog.set(null);
+ fixture.detectChanges();
+ await harness.selectRow('#open');
+
+ activeCatalog.set(MERGED_CATALOG);
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => ({id: row.id, selected: row.selected}))).toEqual([
+ {id: '#root', selected: false},
+ {id: '#modal', selected: false},
+ {id: '#open', selected: true},
+ {id: '#body', selected: false},
+ ]);
+ expect(component.selected()?.key).toBe('s/root/0:modal/0:open');
+ });
+
+ it('clears selection when the selected component is removed', async () => {
+ await harness.selectRow('#open');
+
+ activeDraft.set(
+ surfaceDraft([
+ {id: 'root', component: 'Column', children: ['body']},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ]),
+ );
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => ({id: row.id, selected: row.selected}))).toEqual([
+ {id: '#root', selected: false},
+ {id: '#body', selected: false},
+ ]);
+ expect(component.selected()).toBeNull();
+ expect(component.selectedComponent()).toBeNull();
+ });
+
+ it('clears selection when the session resets even if the draft keeps the same component', async () => {
+ await harness.selectRow('#root');
+
+ sessionResetNonce.update(count => count + 1);
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => row.selected)).toEqual([
+ false,
+ false,
+ false,
+ false,
+ ]);
+ expect(component.selected()).toBeNull();
+ expect(component.selectedComponent()).toBeNull();
+ });
+
+ it('preserves selection across transient invalid JSON and re-resolves once valid again', async () => {
+ await harness.selectRow('#body');
+
+ activeDraft.set('{invalid');
+ fixture.detectChanges();
+ activeDraft.set(
+ surfaceDraft([
+ {id: 'root', component: 'Column', children: ['body']},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ]),
+ );
+ fixture.detectChanges();
+
+ expect((await harness.getRows()).map(row => ({id: row.id, selected: row.selected}))).toEqual([
+ {id: '#root', selected: false},
+ {id: '#body', selected: true},
+ ]);
+ expect(component.selected()?.key).toBe('s/root/0:body');
+ });
+
+ describe('keyboard navigation', () => {
+ it('sets roving tabindex and aria-level on tree rows', async () => {
+ const rows = await harness.getRows();
+
+ expect(rows.map(row => row.tabIndex)).toEqual([0, -1, -1, -1]);
+ expect(rows.map(row => row.level)).toEqual([1, 2, 3, 3]);
+ });
+
+ it('hides branch toggles from the accessibility tree without nesting interactive elements inside treeitems', async () => {
+ const rows = await harness.getRows();
+
+ expect(
+ rows.map(row => ({
+ id: row.id,
+ hasNestedInteractive: row.hasNestedInteractive,
+ toggleAriaHidden: row.toggleAriaHidden,
+ })),
+ ).toEqual([
+ {id: '#root', hasNestedInteractive: false, toggleAriaHidden: 'true'},
+ {id: '#modal', hasNestedInteractive: false, toggleAriaHidden: 'true'},
+ {id: '#open', hasNestedInteractive: false, toggleAriaHidden: null},
+ {id: '#body', hasNestedInteractive: false, toggleAriaHidden: null},
+ ]);
+ });
+
+ it('resets tabindex to the first row when the focused node is collapsed', async () => {
+ await harness.focusRow('#open');
+
+ await harness.toggleRow('#modal');
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => ({id: row.id, tabIndex: row.tabIndex}))).toEqual([
+ {id: '#root', tabIndex: 0},
+ {id: '#modal', tabIndex: -1},
+ ]);
+ });
+
+ it('resets tabindex to the first row when the focused node is removed from the draft', async () => {
+ await harness.focusRow('#open');
+
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 's',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['body']},
+ {id: 'body', component: 'Text', text: 'Details'},
+ ],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => ({id: row.id, tabIndex: row.tabIndex}))).toEqual([
+ {id: '#root', tabIndex: 0},
+ {id: '#body', tabIndex: -1},
+ ]);
+ });
+
+ it('moves focus with ArrowDown and ArrowUp across visible rows without selecting', async () => {
+ await harness.pressKeyOnRow('#root', TestKey.DOWN_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#modal');
+ expect(component.selected()).toBeNull();
+
+ await harness.pressKeyOnRow('#modal', TestKey.DOWN_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#open');
+
+ await harness.pressKeyOnRow('#open', TestKey.DOWN_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#body');
+
+ await harness.pressKeyOnRow('#body', TestKey.UP_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#open');
+
+ await harness.pressKeyOnRow('#open', TestKey.UP_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#modal');
+ });
+
+ it('selects the focused node and opens PropertyEditor on Enter or Space', async () => {
+ const dispatchSpy = vi.spyOn(window, 'dispatchEvent');
+
+ await harness.pressKeyOnRow('#open', TestKey.ENTER);
+ expect(component.selected()?.id).toBe('open');
+ expect((await harness.getRows()).map(row => row.selected)).toEqual([
+ false,
+ false,
+ true,
+ false,
+ ]);
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: OpenPanelEvent.TYPE,
+ detail: {panelId: ComposerPanelId.PropertyEditor},
+ }),
+ );
+
+ dispatchSpy.mockClear();
+
+ await harness.pressKeyOnRow('#modal', ' ');
+ expect(component.selected()?.id).toBe('modal');
+ expect((await harness.getRows()).map(row => row.selected)).toEqual([
+ false,
+ true,
+ false,
+ false,
+ ]);
+ expect(dispatchSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: OpenPanelEvent.TYPE,
+ detail: {panelId: ComposerPanelId.PropertyEditor},
+ }),
+ );
+ });
+
+ it('collapses an expanded node on ArrowLeft', async () => {
+ await harness.pressKeyOnRow('#modal', TestKey.LEFT_ARROW);
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => ({id: row.id, expanded: row.expanded}))).toEqual([
+ {id: '#root', expanded: true},
+ {id: '#modal', expanded: false},
+ ]);
+ });
+
+ it('focuses the parent node on ArrowLeft from a leaf or collapsed node', async () => {
+ await harness.pressKeyOnRow('#open', TestKey.LEFT_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#modal');
+
+ await harness.toggleRow('#modal');
+ await harness.pressKeyOnRow('#modal', TestKey.LEFT_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#root');
+ });
+
+ it('expands a collapsed node on ArrowRight', async () => {
+ await harness.toggleRow('#modal');
+
+ await harness.pressKeyOnRow('#modal', TestKey.RIGHT_ARROW);
+
+ const rows = await harness.getRows();
+ expect(rows.map(row => row.id)).toEqual(['#root', '#modal', '#open', '#body']);
+ expect(rows[1].expanded).toBe(true);
+ });
+
+ it('focuses the first child on ArrowRight from an expanded node', async () => {
+ await harness.pressKeyOnRow('#root', TestKey.RIGHT_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#modal');
+
+ await harness.pressKeyOnRow('#modal', TestKey.RIGHT_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#open');
+ });
+
+ it('labels each surface and unreachable section as its own tree with independent tab stops', async () => {
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'first',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Column', children: ['childA']},
+ {id: 'childA', component: 'Text', text: 'A'},
+ {id: 'orphan', component: 'Text', text: 'Orphan'},
+ ],
+ },
+ },
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'second',
+ catalogId: 'primary-catalog',
+ components: [{id: 'root', component: 'Text', text: 'B'}],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ await harness.focusRow('#childA');
+
+ expect(await harness.getTrees()).toEqual([
+ {label: 'Surface first', rowIds: ['#root', '#childA'], tabStops: ['#childA']},
+ {
+ label: 'Surface first, not reachable from root',
+ rowIds: ['#orphan'],
+ tabStops: ['#orphan'],
+ },
+ {label: 'Surface second', rowIds: ['#root'], tabStops: ['#root']},
+ ]);
+ });
+
+ it('scopes ArrowDown and ArrowUp navigation to the active tree', async () => {
+ activeDraft.set(
+ formatJson([
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'first',
+ catalogId: 'primary-catalog',
+ components: [
+ {id: 'root', component: 'Text', text: 'A'},
+ {id: 'orphan', component: 'Text', text: 'Orphan'},
+ ],
+ },
+ },
+ {
+ version: '1.0',
+ createSurface: {
+ surfaceId: 'second',
+ catalogId: 'primary-catalog',
+ components: [{id: 'root', component: 'Text', text: 'B'}],
+ },
+ },
+ ]),
+ );
+ fixture.detectChanges();
+
+ await harness.pressKeyOnRow('#root', TestKey.DOWN_ARROW, 0);
+ expect((await harness.getRows()).map(row => row.focused)).toEqual([true, false, false]);
+
+ await harness.pressKeyOnRow('#orphan', TestKey.UP_ARROW);
+ expect(await harness.getFocusedRowId()).toBe('#orphan');
+
+ await harness.pressKeyOnRow('#root', TestKey.UP_ARROW, 1);
+ expect((await harness.getRows()).map(row => row.focused)).toEqual([false, false, true]);
+ });
+
+ it('moves focus to the first and last visible rows on Home and End without changing selection', async () => {
+ await harness.selectRow('#open');
+
+ await harness.pressKeyOnRow('#open', TestKey.END);
+ const focusedAfterEnd = await harness.getFocusedRowId();
+ await harness.pressKeyOnRow('#body', TestKey.HOME);
+ const focusedAfterHome = await harness.getFocusedRowId();
+
+ expect(focusedAfterEnd).toBe('#body');
+ expect(focusedAfterHome).toBe('#root');
+ expect(component.selected()?.id).toBe('open');
+ expect(
+ (await harness.getRows()).map(row => ({
+ id: row.id,
+ selected: row.selected,
+ tabIndex: row.tabIndex,
+ })),
+ ).toEqual([
+ {id: '#root', selected: false, tabIndex: 0},
+ {id: '#modal', selected: false, tabIndex: -1},
+ {id: '#open', selected: true, tabIndex: -1},
+ {id: '#body', selected: false, tabIndex: -1},
+ ]);
+ });
+
+ it('scopes Home and End to visible rows in the active tree without expanding collapsed branches', async () => {
+ activeDraft.set(
+ surfaceDraft([
+ {id: 'root', component: 'Column', children: ['modal']},
+ {id: 'modal', component: 'Modal', trigger: 'open', content: 'body'},
+ {id: 'open', component: 'Text', text: 'Open'},
+ {id: 'body', component: 'Text', text: 'Details'},
+ {id: 'orphanA', component: 'Text', text: 'Orphan A'},
+ {id: 'orphanB', component: 'Text', text: 'Orphan B'},
+ ]),
+ );
+ fixture.detectChanges();
+ await harness.toggleRow('#modal');
+
+ await harness.pressKeyOnRow('#root', TestKey.END);
+ const focusedAfterEnd = await harness.getFocusedRowId();
+ await harness.pressKeyOnRow('#orphanB', TestKey.HOME);
+ const focusedAfterOrphanHome = await harness.getFocusedRowId();
+
+ expect(focusedAfterEnd).toBe('#modal');
+ expect(focusedAfterOrphanHome).toBe('#orphanA');
+ expect(
+ (await harness.getRows()).map(row => ({id: row.id, expanded: row.expanded})),
+ ).toEqual([
+ {id: '#root', expanded: true},
+ {id: '#modal', expanded: false},
+ {id: '#orphanA', expanded: null},
+ {id: '#orphanB', expanded: null},
+ ]);
+ });
+ });
+ });
+});
diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts
new file mode 100644
index 000000000..18d5fafef
--- /dev/null
+++ b/shell/src/app/debug/component-tree/component-tree.ts
@@ -0,0 +1,264 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {Component, computed, inject, linkedSignal, signal} from '@angular/core';
+import {NgTemplateOutlet} from '@angular/common';
+import {MatTooltipModule} from '@angular/material/tooltip';
+import {StateSync} from '../../chat/state-sync/state-sync';
+import {ComposerPanelId, OpenPanelEvent} from '../../shell/composer-workspace/composer-panel-id';
+import {CatalogManagement} from '../../storage/catalog-management/catalog-management';
+import {JsonParseResult, formatJson, tryParseJsonArray} from '../../utils/json';
+import {
+ ComponentTreeNode,
+ SurfaceComponentTree,
+ buildComponentTrees,
+ getSurfaceComponent,
+ updateSurfaceComponent,
+} from './component-tree-builder';
+
+/**
+ * Identifies a selected or focused occurrence in a surface's component tree so both the specific
+ * tree row (`key`) and its underlying component definition (`surfaceId`, `id`) can be tracked.
+ */
+export interface TreeNodeRef {
+ readonly surfaceId: string;
+ readonly key: string;
+ readonly id: string;
+}
+
+/**
+ * A workspace panel showing the component tree of the current A2UI document.
+ *
+ * The tree is derived from the document itself (the active draft) and the
+ * catalog schema; see {@link buildComponentTrees}.
+ */
+@Component({
+ selector: 'a2ui-composer-component-tree',
+ standalone: true,
+ imports: [NgTemplateOutlet, MatTooltipModule],
+ templateUrl: './component-tree.ng.html',
+ styleUrl: './component-tree.scss',
+})
+export class ComponentTree {
+ private readonly stateSync = inject(StateSync);
+ private readonly catalogManagement = inject(CatalogManagement);
+ private readonly parsedDraft = computed>(() => {
+ const draft = this.stateSync.activeDraft();
+ return draft.trim() ? tryParseJsonArray(draft) : {success: true, data: []};
+ });
+
+ private readonly _selected = linkedSignal<
+ {trees: SurfaceComponentTree[] | null; resetNonce: number},
+ TreeNodeRef | null
+ >({
+ source: () => ({
+ trees: this.parsedDraft().success ? this.trees() : null,
+ resetNonce: this.stateSync.sessionResetNonce(),
+ }),
+ computation: ({trees, resetNonce}, previous) => {
+ if (!previous || resetNonce !== previous.source.resetNonce) return null;
+ const current = previous.value;
+ if (!current || !trees) return current;
+ const tree = trees.find(tree => tree.surfaceId === current.surfaceId);
+ if (!tree) return null;
+ const roots = tree.root ? [tree.root, ...tree.unreachable] : tree.unreachable;
+ const findNode = (
+ nodes: readonly ComponentTreeNode[],
+ match: (node: ComponentTreeNode) => boolean,
+ ): ComponentTreeNode | null => {
+ for (const node of nodes) {
+ const found = match(node) ? node : findNode(node.children, match);
+ if (found) return found;
+ }
+ return null;
+ };
+ if (findNode(roots, node => node.key === current.key)) return current;
+ const fallback = findNode(roots, node => node.id === current.id);
+ return fallback ? {surfaceId: tree.surfaceId, key: fallback.key, id: fallback.id} : null;
+ },
+ });
+
+ /** Reference to the currently selected tree node, re-resolved when the tree changes. */
+ readonly selected = this._selected.asReadonly();
+
+ /** The component definition for the currently selected tree node, if defined. */
+ readonly selectedComponent = computed | null>(() => {
+ const selected = this.selected();
+ if (!selected) return null;
+ const result = this.parsedDraft();
+ if (!result.success) return null;
+ return getSurfaceComponent(result.data, selected.surfaceId, selected.id);
+ });
+
+ /** Keys of collapsed nodes (nodes are expanded by default). */
+ protected readonly collapsed = signal>(new Set());
+
+ /** Reference to the currently focused tree node for roving tabindex. */
+ protected readonly focused = signal(null);
+
+ /** Parse error message when the active draft is not valid A2UI JSON, or null. */
+ readonly parseError = computed(() => {
+ const result = this.parsedDraft();
+ return result.success ? null : result.error.message;
+ });
+
+ protected readonly trees = computed(() => {
+ const result = this.parsedDraft();
+ if (!result.success) return [];
+ const catalog =
+ this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog();
+ return buildComponentTrees(result.data, catalog);
+ });
+
+ protected isExpanded(node: ComponentTreeNode): boolean {
+ return !this.collapsed().has(node.key);
+ }
+
+ protected isSelected(surfaceId: string, node: ComponentTreeNode): boolean {
+ const selected = this.selected();
+ return selected?.surfaceId === surfaceId && selected.key === node.key;
+ }
+
+ protected readonly tabStopKeys = computed>(() => {
+ const focused = this.focused();
+ const hasNode = (node: ComponentTreeNode): boolean =>
+ node.key === focused?.key || (this.isExpanded(node) && node.children.some(hasNode));
+ const keys = new Set();
+ const addStop = (surfaceId: string, roots: readonly ComponentTreeNode[]) => {
+ const key =
+ focused?.surfaceId === surfaceId && roots.some(hasNode) ? focused.key : roots[0]?.key;
+ if (key) keys.add(`${surfaceId}\0${key}`);
+ };
+ for (const tree of this.trees()) {
+ if (tree.root) addStop(tree.surfaceId, [tree.root]);
+ addStop(tree.surfaceId, tree.unreachable);
+ }
+ return keys;
+ });
+
+ protected tabIndexFor(surfaceId: string, node: ComponentTreeNode): number {
+ return this.tabStopKeys().has(`${surfaceId}\0${node.key}`) ? 0 : -1;
+ }
+
+ protected onFocus(surfaceId: string, node: ComponentTreeNode): void {
+ this.focused.set({surfaceId, key: node.key, id: node.id});
+ }
+
+ selectNode(surfaceId: string, node: ComponentTreeNode, event?: Event): void {
+ event?.preventDefault();
+ const ref: TreeNodeRef = {surfaceId, key: node.key, id: node.id};
+ this.focused.set(ref);
+ this._selected.set(ref);
+ window.dispatchEvent(new OpenPanelEvent(ComposerPanelId.PropertyEditor));
+ }
+
+ updateSelectedComponent(updatedComponent: Record): void {
+ const selected = this.selected();
+ if (!selected) return;
+ const result = this.parsedDraft();
+ if (!result.success) return;
+ const updatedMessages = updateSurfaceComponent(
+ result.data,
+ selected.surfaceId,
+ selected.id,
+ updatedComponent,
+ );
+ if (updatedMessages === result.data) return;
+ this.stateSync.updateDraft(formatJson(updatedMessages));
+ }
+
+ protected focusNextNode(event: Event): void {
+ this.moveTreeFocus(event, (rows, currentIndex) => rows[currentIndex + 1]);
+ }
+
+ protected focusPreviousNode(event: Event): void {
+ this.moveTreeFocus(event, (rows, currentIndex) => rows[currentIndex - 1]);
+ }
+
+ protected focusFirstNode(event: Event): void {
+ this.moveTreeFocus(event, rows => rows[0]);
+ }
+
+ protected focusLastNode(event: Event): void {
+ this.moveTreeFocus(event, rows => rows.at(-1));
+ }
+
+ private moveTreeFocus(
+ event: Event,
+ selectTarget: (rows: readonly HTMLElement[], currentIndex: number) => HTMLElement | undefined,
+ ) {
+ event.preventDefault();
+ const currentRow = event.currentTarget;
+ if (!(currentRow instanceof HTMLElement)) return;
+ const tree = currentRow.closest('[role="tree"]');
+ if (!tree) return;
+ const rows = Array.from(tree.querySelectorAll('.tree-row'));
+ const currentIndex = rows.indexOf(currentRow);
+ if (currentIndex === -1) return;
+ selectTarget(rows, currentIndex)?.focus();
+ }
+
+ protected toggle(node: ComponentTreeNode, event?: Event): void {
+ event?.stopPropagation();
+ const next = new Set(this.collapsed());
+ if (next.has(node.key)) {
+ next.delete(node.key);
+ } else {
+ next.add(node.key);
+ }
+ this.collapsed.set(next);
+ }
+
+ protected expandNode(node: ComponentTreeNode, event: Event): void {
+ event.preventDefault();
+ if (node.children.length === 0) return;
+ if (!this.isExpanded(node)) {
+ this.toggle(node);
+ } else {
+ this.focusNextNode(event);
+ }
+ }
+
+ protected collapseNode(
+ node: ComponentTreeNode,
+ parentRow: HTMLElement | undefined,
+ event: Event,
+ ): void {
+ event.preventDefault();
+ if (node.children.length > 0 && this.isExpanded(node)) {
+ this.toggle(node);
+ } else {
+ parentRow?.focus();
+ }
+ }
+
+ protected tooltipFor(node: ComponentTreeNode): string {
+ if (node.status === 'missing') {
+ return `Component "${node.id}" is not defined in this surface.`;
+ }
+ if (node.status === 'cycle') {
+ return `Reference cycle: "${node.id}" is one of its own ancestors, so it is not expanded again.`;
+ }
+ const lines: string[] = [];
+ if (node.template !== null) {
+ lines.push(`Rendered once per item of ${node.template || 'the data list'}.`);
+ }
+ if (node.shared) {
+ lines.push(`"${node.id}" is referenced from more than one place.`);
+ }
+ return lines.join('\n');
+ }
+}
diff --git a/shell/src/app/debug/component-tree/test/component-tree.harness.ts b/shell/src/app/debug/component-tree/test/component-tree.harness.ts
new file mode 100644
index 000000000..69223b0b1
--- /dev/null
+++ b/shell/src/app/debug/component-tree/test/component-tree.harness.ts
@@ -0,0 +1,275 @@
+/**
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {ComponentHarness, TestKey} from '@angular/cdk/testing';
+import {MatTooltipHarness} from '@angular/material/tooltip/testing';
+
+/**
+ * Snapshot of a rendered row in the ComponentTree panel.
+ */
+export interface ComponentTreeRowSummary {
+ readonly via: string | null;
+ readonly type: string;
+ readonly id: string;
+ readonly badges: readonly string[];
+ readonly missing: boolean;
+ readonly cycle: boolean;
+ readonly expanded: boolean | null;
+ readonly selected: boolean;
+ readonly level: number | null;
+ readonly tabIndex: number | null;
+ readonly focused: boolean;
+ readonly hasNestedInteractive: boolean;
+ readonly toggleAriaHidden: string | null;
+}
+
+/**
+ * Snapshot of a `role="tree"` section in the ComponentTree panel.
+ */
+export interface ComponentTreeSectionSummary {
+ readonly label: string | null;
+ readonly rowIds: readonly string[];
+ readonly tabStops: readonly string[];
+}
+
+/**
+ * Test harness for the standalone ComponentTree panel.
+ */
+export class ComponentTreeHarness extends ComponentHarness {
+ static hostSelector = 'a2ui-composer-component-tree';
+
+ private readonly getMessageElements = this.locatorForAll('.tree-message');
+ private readonly getErrorMessageElement = this.locatorForOptional('.tree-message.error');
+ private readonly getTruncatedBadgeElement = this.locatorForOptional(
+ '.surface-header .badge.warn',
+ );
+ private readonly getUnreachableHeaderElement = this.locatorForOptional('.unreachable-header');
+ private readonly getTreeHarnesses = this.locatorForAll(ComponentTreeSectionHarness);
+ private readonly getRowHarnesses = this.locatorForAll(ComponentTreeRowHarness);
+ private readonly getRowTooltips = this.locatorForAll(
+ MatTooltipHarness.with({selector: '.tree-row'}),
+ );
+
+ /**
+ * Returns the text of all informational or empty-state messages in display order.
+ */
+ async getMessages(): Promise {
+ const elements = await this.getMessageElements();
+ return Promise.all(elements.map(async element => (await element.text()).trim()));
+ }
+
+ /**
+ * Returns the invalid-JSON error banner text, or null when the draft parses cleanly.
+ */
+ async getErrorMessage(): Promise {
+ const element = await this.getErrorMessageElement();
+ return element ? (await element.text()).trim() : null;
+ }
+
+ /**
+ * Checks whether the surface header displays the truncation warning badge.
+ */
+ async hasTruncatedBadge(): Promise {
+ return (await this.getTruncatedBadgeElement()) !== null;
+ }
+
+ /**
+ * Checks whether the "Not reachable from root" section header is rendered.
+ */
+ async hasUnreachableHeader(): Promise {
+ return (await this.getUnreachableHeaderElement()) !== null;
+ }
+
+ /**
+ * Returns structured summaries of all rendered `role="tree"` sections in display order.
+ */
+ async getTrees(): Promise {
+ const trees = await this.getTreeHarnesses();
+ return Promise.all(trees.map(tree => tree.getSummary()));
+ }
+
+ /**
+ * Returns structured summaries of all rendered tree rows in pre-order display sequence.
+ */
+ async getRows(): Promise {
+ const rows = await this.getRowHarnesses();
+ return Promise.all(rows.map(row => row.getSummary()));
+ }
+
+ /**
+ * Returns the `#id` labels of all visible tree rows in display order.
+ */
+ async getRowIds(): Promise {
+ const rows = await this.getRowHarnesses();
+ return Promise.all(rows.map(row => row.getId()));
+ }
+
+ /**
+ * Returns the `#id` label of the currently focused tree row, or null if none is focused.
+ */
+ async getFocusedRowId(): Promise {
+ const rows = await this.getRows();
+ return rows.find(row => row.focused)?.id ?? null;
+ }
+
+ /**
+ * Clicks the matching `#id` row (at the given occurrence) to select it.
+ */
+ async selectRow(id: string, occurrence = 0): Promise {
+ const index = await this.findRowIndex(id, occurrence);
+ const rows = await this.getRowHarnesses();
+ await rows[index].select();
+ }
+
+ /**
+ * Focuses the matching `#id` row (at the given occurrence).
+ */
+ async focusRow(id: string, occurrence = 0): Promise {
+ const index = await this.findRowIndex(id, occurrence);
+ const rows = await this.getRowHarnesses();
+ await rows[index].focus();
+ }
+
+ /**
+ * Focuses the matching `#id` row (at the given occurrence) and dispatches the given key.
+ */
+ async pressKeyOnRow(id: string, key: string | TestKey, occurrence = 0): Promise {
+ const index = await this.findRowIndex(id, occurrence);
+ const rows = await this.getRowHarnesses();
+ await rows[index].pressKey(key);
+ }
+
+ /**
+ * Clicks the expand/collapse toggle on the matching `#id` row (at the given occurrence).
+ */
+ async toggleRow(id: string, occurrence = 0): Promise {
+ const index = await this.findRowIndex(id, occurrence);
+ const rows = await this.getRowHarnesses();
+ await rows[index].toggle();
+ }
+
+ /**
+ * Shows, reads, and hides the tooltip text for the matching `#id` row (at the given occurrence).
+ */
+ async getTooltipText(id: string, occurrence = 0): Promise {
+ const index = await this.findRowIndex(id, occurrence);
+ const tooltips = await this.getRowTooltips();
+ const tooltip = tooltips[index];
+ if (await tooltip.isDisabled()) {
+ return '';
+ }
+ await tooltip.show();
+ const text = await tooltip.getTooltipText();
+ await tooltip.hide();
+ return text;
+ }
+
+ private async findRowIndex(id: string, occurrence: number): Promise {
+ const ids = await this.getRowIds();
+ let seen = 0;
+ for (let index = 0; index < ids.length; index++) {
+ if (ids[index] === id) {
+ if (seen === occurrence) {
+ return index;
+ }
+ seen++;
+ }
+ }
+ throw new Error(`Row "${id}" (occurrence ${occurrence}) not found in [${ids.join(', ')}].`);
+ }
+}
+
+class ComponentTreeSectionHarness extends ComponentHarness {
+ static hostSelector = '[role="tree"]';
+
+ private readonly getRowHarnesses = this.locatorForAll(ComponentTreeRowHarness);
+
+ async getSummary(): Promise {
+ const rows = await Promise.all((await this.getRowHarnesses()).map(row => row.getSummary()));
+ return {
+ label: await (await this.host()).getAttribute('aria-label'),
+ rowIds: rows.map(row => row.id),
+ tabStops: rows.filter(row => row.tabIndex === 0).map(row => row.id),
+ };
+ }
+}
+
+class ComponentTreeRowHarness extends ComponentHarness {
+ static hostSelector = '.tree-row';
+
+ private readonly getViaElement = this.locatorForOptional('.via');
+ private readonly getTypeElement = this.locatorFor('.type');
+ private readonly getIdElement = this.locatorFor('.id');
+ private readonly getBadgeElements = this.locatorForAll('.badge');
+ private readonly getToggleElement = this.locatorForOptional('.toggle');
+ private readonly getNestedInteractiveElements = this.locatorForAll(
+ 'button, [role="button"], a[href]',
+ );
+
+ async getSummary(): Promise {
+ const host = await this.host();
+ const viaElement = await this.getViaElement();
+ const typeElement = await this.getTypeElement();
+ const idElement = await this.getIdElement();
+ const badgeElements = await this.getBadgeElements();
+ const toggleElement = await this.getToggleElement();
+ const nestedInteractiveElements = await this.getNestedInteractiveElements();
+
+ const expandedAttribute = await host.getAttribute('aria-expanded');
+ const levelAttribute = await host.getAttribute('aria-level');
+ const tabIndexAttribute = await host.getAttribute('tabindex');
+
+ return {
+ via: viaElement ? await viaElement.text() : null,
+ type: await typeElement.text(),
+ id: await idElement.text(),
+ badges: await Promise.all(badgeElements.map(badge => badge.text())),
+ missing: await host.hasClass('missing'),
+ cycle: await host.hasClass('cycle'),
+ expanded: expandedAttribute === null ? null : expandedAttribute === 'true',
+ selected: (await host.getAttribute('aria-selected')) === 'true',
+ level: levelAttribute === null ? null : Number(levelAttribute),
+ tabIndex: tabIndexAttribute === null ? null : Number(tabIndexAttribute),
+ focused: await host.isFocused(),
+ hasNestedInteractive: nestedInteractiveElements.length > 0,
+ toggleAriaHidden: toggleElement ? await toggleElement.getAttribute('aria-hidden') : null,
+ };
+ }
+
+ async getId(): Promise {
+ return (await this.getIdElement()).text();
+ }
+
+ async select(): Promise {
+ await (await this.host()).click();
+ }
+
+ async focus(): Promise {
+ await (await this.host()).focus();
+ }
+
+ async pressKey(key: string | TestKey): Promise {
+ await (await this.host()).sendKeys(key);
+ }
+
+ async toggle(): Promise {
+ const toggle = await this.getToggleElement();
+ if (!toggle) {
+ throw new Error(`Row ${await this.getId()} does not have an expand/collapse toggle.`);
+ }
+ await toggle.click();
+ }
+}
diff --git a/shell/src/app/gallery/gallery-example.spec.ts b/shell/src/app/gallery/gallery-example.spec.ts
index 4747d773b..d66ab8999 100644
--- a/shell/src/app/gallery/gallery-example.spec.ts
+++ b/shell/src/app/gallery/gallery-example.spec.ts
@@ -15,14 +15,9 @@
*/
import {describe, it, expect} from 'vitest';
-import {
- createDefaultGalleryValue,
- describeUneditableValue,
- galleryPropertyControl,
- parseGalleryExample,
-} from './gallery-example';
+import {parseGalleryExample} from './gallery-example';
import {ErrorLogger} from '../debug/error-logger.service';
-import {Catalog, CatalogComponentSchema} from '../storage/models/catalog-storage.model';
+import {Catalog} from '../storage/models/catalog-storage.model';
const catalog: Catalog = {
catalogId: 'custom://notice',
@@ -158,190 +153,3 @@ describe('parseGalleryExample', () => {
expect(() => parseGalleryExample(text, catalog, errorLogger)).toThrow(reason);
});
});
-
-// Shapes as CatalogSchemaResolver returns them for the basic catalog's common types.
-const binding: CatalogComponentSchema = {type: 'object', properties: {path: {type: 'string'}}};
-const call: CatalogComponentSchema = {type: 'object', properties: {call: {type: 'string'}}};
-const dynamic = (literal: CatalogComponentSchema): CatalogComponentSchema => ({
- oneOf: [literal, binding, call],
-});
-const v1Binding: CatalogComponentSchema = {type: 'object', properties: {'@path': {type: 'string'}}};
-const v1Call: CatalogComponentSchema = {type: 'object', properties: {'@call': {type: 'string'}}};
-const dynamicV1 = (literal: CatalogComponentSchema): CatalogComponentSchema => ({
- anyOf: [literal, v1Binding, v1Call],
-});
-
-describe('galleryPropertyControl', () => {
- it.each([
- ['a string enum', {type: 'string', enum: ['checkbox', 'chips']}, 'enum'],
- ['a boolean', {type: 'boolean'}, 'boolean'],
- ['an integer', {type: 'integer'}, 'number'],
- ['a string', {type: 'string'}, 'string'],
- ['a DynamicString', dynamic({type: 'string'}), 'string'],
- ['a v1.0 DynamicString', dynamicV1({type: 'string'}), 'string'],
- ['a DynamicBoolean', dynamic({type: 'boolean'}), 'boolean'],
- ['a v1.0 DynamicBoolean', dynamicV1({type: 'boolean'}), 'boolean'],
- ['a DynamicNumber', dynamic({type: 'number'}), 'number'],
- ['a v1.0 DynamicNumber', dynamicV1({type: 'number'}), 'number'],
- ['an enum inside a union', {anyOf: [{type: 'string', enum: ['a', 'b']}, binding]}, 'enum'],
- ['an array of options', {type: 'array', items: {type: 'object'}}, 'array'],
- ['a DynamicStringList', dynamic({type: 'array', items: {type: 'string'}}), 'array'],
- ['a ChildList', {oneOf: [{type: 'array'}, {type: 'object'}]}, 'array'],
- [
- 'an object with properties',
- {type: 'object', properties: {label: {type: 'string'}, count: {type: 'number'}}},
- 'object',
- ],
- [
- 'an object inside a dynamic union',
- dynamic({type: 'object', properties: {label: {type: 'string'}}}),
- 'object',
- ],
- ['an object without properties (e.g. style)', {type: 'object'}, 'json'],
- [
- 'an object with only additionalProperties',
- {type: 'object', additionalProperties: {type: 'string'}},
- 'json',
- ],
- ['a DynamicValue', {oneOf: [{type: 'string'}, {type: 'number'}, binding]}, 'json'],
- ['an untyped schema', {}, 'json'],
- ['a missing schema', undefined, 'json'],
- ])('edits $0 with a $2 control', (_name, schema, kind) => {
- expect(galleryPropertyControl(schema as CatalogComponentSchema | undefined).kind).toBe(kind);
- });
-
- it('recursively resolves array item controls and nested object properties while skipping const fields', () => {
- const control = galleryPropertyControl({
- type: 'array',
- items: {
- type: 'object',
- properties: {
- kind: {const: 'item'},
- label: dynamic({type: 'string'}),
- context: {type: 'object'},
- },
- required: ['label'],
- },
- });
- expect(control.kind).toBe('array');
- expect(control.itemControl).toEqual({
- kind: 'object',
- options: [],
- properties: [
- {name: 'label', required: true, control: {kind: 'string', options: []}},
- {name: 'context', required: false, control: {kind: 'json', options: []}},
- ],
- });
- });
-
- it('falls back to a json control when encountering a cyclic schema', () => {
- const cyclic: CatalogComponentSchema = {type: 'object', properties: {}};
- (cyclic['properties'] as Record)['self'] = cyclic;
- expect(galleryPropertyControl(cyclic)).toEqual({
- kind: 'object',
- options: [],
- properties: [{name: 'self', required: false, control: {kind: 'json', options: []}}],
- });
- });
-
- it('falls back to the current value type when the catalog declares no schema', () => {
- expect(galleryPropertyControl(undefined, 'Initial').kind).toBe('string');
- expect(galleryPropertyControl(undefined, 3).kind).toBe('number');
- expect(galleryPropertyControl(undefined, true).kind).toBe('boolean');
- expect(galleryPropertyControl(undefined, ['a', 'b']).kind).toBe('array');
- expect(galleryPropertyControl(undefined, {label: 'Hi'}).kind).toBe('object');
- expect(galleryPropertyControl(undefined, {path: '/x'}).kind).toBe('json');
- });
-
- it('keeps enum options in catalog order', () => {
- expect(galleryPropertyControl({type: 'string', enum: ['checkbox', 'chips']}).options).toEqual([
- 'checkbox',
- 'chips',
- ]);
- });
-});
-
-describe('createDefaultGalleryValue', () => {
- it('builds brand-new default items based on the control type', () => {
- expect(createDefaultGalleryValue(undefined)).toBe('');
- expect(createDefaultGalleryValue({kind: 'string', options: []})).toBe('');
- expect(createDefaultGalleryValue({kind: 'number', options: []})).toBe(0);
- expect(createDefaultGalleryValue({kind: 'boolean', options: []})).toBe(false);
- expect(createDefaultGalleryValue({kind: 'enum', options: ['a', 'b']})).toBe('a');
- expect(createDefaultGalleryValue({kind: 'enum', options: []})).toBe('');
- expect(createDefaultGalleryValue({kind: 'array', options: []})).toEqual([]);
- expect(createDefaultGalleryValue({kind: 'json', options: []})).toEqual({});
- expect(
- createDefaultGalleryValue({
- kind: 'object',
- options: [],
- properties: [
- {name: 'label', required: true, control: {kind: 'string', options: []}},
- {name: 'context', required: false, control: {kind: 'json', options: []}},
- ],
- }),
- ).toEqual({label: '', context: {}});
- });
-});
-
-describe('describeUneditableValue', () => {
- const text = galleryPropertyControl(dynamic({type: 'string'}));
- const list = galleryPropertyControl(dynamic({type: 'array', items: {type: 'string'}}));
- const group = galleryPropertyControl({
- type: 'object',
- properties: {label: {type: 'string'}},
- });
-
- it('allows literals, arrays, objects and unset values that the control can edit', () => {
- expect(describeUneditableValue('Hello', text)).toBeNull();
- expect(describeUneditableValue(undefined, text)).toBeNull();
- expect(describeUneditableValue(['a', 'b'], list)).toBeNull();
- expect(describeUneditableValue({label: 'Hello'}, group)).toBeNull();
- expect(describeUneditableValue({any: 'shape'}, {kind: 'json', options: []})).toBeNull();
- expect(describeUneditableValue('a', {kind: 'enum', options: ['a']})).toBeNull();
- });
-
- it('protects bindings, function calls and values outside the control', () => {
- expect(describeUneditableValue({path: '/user/name'}, text)).toContain('Bound to /user/name');
- expect(describeUneditableValue({'@path': '/user/name'}, text)).toContain('Bound to /user/name');
- expect(describeUneditableValue({path: '/items'}, list)).toContain('Bound to /items');
- expect(describeUneditableValue({'@path': '/items'}, list)).toContain('Bound to /items');
- expect(describeUneditableValue({path: '/group'}, group)).toContain('Bound to /group');
- expect(describeUneditableValue({'@path': '/group'}, group)).toContain('Bound to /group');
- expect(describeUneditableValue({call: 'formatDate'}, text)).toContain('formatDate()');
- expect(describeUneditableValue({'@call': 'formatDate'}, text)).toContain('formatDate()');
- expect(describeUneditableValue(3, text)).toContain('JSON editor');
- expect(describeUneditableValue('other', {kind: 'enum', options: ['a']})).toContain(
- 'JSON editor',
- );
- });
-
- it('does not misclassify domain objects with path or call fields alongside other properties as bindings', () => {
- const routeSchema = {
- type: 'object',
- properties: {
- path: {type: 'string'},
- label: {type: 'string'},
- },
- };
- const routeControl = galleryPropertyControl(routeSchema);
- expect(routeControl.kind).toBe('object');
- expect(routeControl.properties?.map(prop => prop.name)).toEqual(['path', 'label']);
- expect(describeUneditableValue({path: '/home', label: 'Home'}, routeControl)).toBeNull();
-
- const inferredControl = galleryPropertyControl(undefined, {path: '/home', label: 'Home'});
- expect(inferredControl.kind).toBe('object');
- expect(describeUneditableValue({path: '/home', label: 'Home'}, inferredControl)).toBeNull();
-
- const webhookSchema = {
- type: 'object',
- properties: {
- call: {type: 'string'},
- timeoutMs: {type: 'number'},
- },
- };
- const webhookControl = galleryPropertyControl(webhookSchema);
- expect(webhookControl.kind).toBe('object');
- expect(describeUneditableValue({call: 'ping', timeoutMs: 500}, webhookControl)).toBeNull();
- });
-});
diff --git a/shell/src/app/gallery/gallery-example.ts b/shell/src/app/gallery/gallery-example.ts
index 3100ba30d..9aed5bca4 100644
--- a/shell/src/app/gallery/gallery-example.ts
+++ b/shell/src/app/gallery/gallery-example.ts
@@ -16,29 +16,9 @@
import {ComponentUsage} from 'a2ui-bridge';
import {ErrorLogger} from '../debug/error-logger.service';
-import {Catalog, CatalogComponentSchema} from '../storage/models/catalog-storage.model';
+import {matchesSimpleSchema} from '../shared/property-editor/property-control';
+import {Catalog} from '../storage/models/catalog-storage.model';
import {CatalogSchemaResolver} from './schema/catalog-schema-resolver';
-import {describeAnyDynamicValue, isAnyDynamicValue} from './protocol/gallery-protocol-strategy';
-
-type Literal = string | number | boolean;
-
-/** A named property inside an object schema that declares explicit `properties`. */
-export interface GalleryObjectProperty {
- name: string;
- required: boolean;
- control: GalleryPropertyControl;
-}
-
-/** The control the Gallery property editor renders for one catalog property. */
-export interface GalleryPropertyControl {
- kind: 'enum' | 'boolean' | 'number' | 'string' | 'array' | 'object' | 'json';
- /** The allowed literals when `kind` is `'enum'`, otherwise empty. */
- options: Literal[];
- /** The control rendered for each element when `kind` is `'array'`. */
- itemControl?: GalleryPropertyControl;
- /** The nested property controls when `kind` is `'object'`. */
- properties?: GalleryObjectProperty[];
-}
/**
* Checks if a value is a non-null object and not an array.
@@ -103,326 +83,3 @@ export function parseGalleryExample(
}
return {usage, ...(data !== undefined ? {data} : {})};
}
-
-/**
- * Picks the property editor control from the resolved schema rather than the current value.
- * Literal-or-binding unions such as DynamicString edit their single literal branch; arrays
- * render dynamic item lists; objects with explicit `properties` recursively render nested
- * controls; objects without `properties` and multi-literal unions fall back to JSON textareas.
- */
-export function galleryPropertyControl(
- schema: CatalogComponentSchema | undefined,
- value?: unknown,
- visited: Set = new Set(),
-): GalleryPropertyControl {
- if (!schema) {
- return inferControlFromValue(value, visited);
- }
- if (visited.has(schema)) {
- return {kind: 'json', options: []};
- }
- const nextVisited = new Set(visited);
- nextVisited.add(schema);
-
- const choices = schema['enum'];
- if (Array.isArray(choices) && choices.length > 0 && choices.every(isLiteral)) {
- return {kind: 'enum', options: choices};
- }
- const alternatives = schema['anyOf'] ?? schema['oneOf'];
- if (Array.isArray(alternatives)) {
- const records = alternatives.filter((option): option is CatalogComponentSchema =>
- isRecord(option),
- );
- const literals = records.filter(isLiteralSchema);
- if (literals.length === 1) {
- return galleryPropertyControl(literals[0], value, nextVisited);
- }
- if (literals.length > 1) {
- return {kind: 'json', options: []};
- }
- const nonBindings = records.filter(option => !isBindingOrCallSchema(option));
- const arrays = nonBindings.filter(
- option => option['type'] === 'array' || isRecord(option['items']),
- );
- if (arrays.length === 1) {
- return galleryPropertyControl(arrays[0], value, nextVisited);
- }
- const objectsWithProps = nonBindings.filter(option =>
- hasEditableObjectProperties(option, nextVisited),
- );
- if (objectsWithProps.length === 1) {
- return galleryPropertyControl(objectsWithProps[0], value, nextVisited);
- }
- return {kind: 'json', options: []};
- }
- if (schema['type'] === 'array' || isRecord(schema['items'])) {
- const itemsSchema =
- isRecord(schema['items']) && Object.keys(schema['items']).length > 0
- ? (schema['items'] as CatalogComponentSchema)
- : undefined;
- const sample = Array.isArray(value) && value.length > 0 ? value[value.length - 1] : undefined;
- const itemControl: GalleryPropertyControl = itemsSchema
- ? galleryPropertyControl(itemsSchema, sample, nextVisited)
- : sample !== undefined
- ? inferControlFromValue(sample, nextVisited)
- : {kind: 'string', options: []};
- return {kind: 'array', options: [], itemControl};
- }
- if (schema['type'] === 'object' || isRecord(schema['properties'])) {
- const properties = resolveObjectProperties(schema, value, nextVisited);
- if (properties.length > 0) {
- return {kind: 'object', options: [], properties};
- }
- return {kind: 'json', options: []};
- }
- switch (schema['type']) {
- case 'boolean':
- return {kind: 'boolean', options: []};
- case 'number':
- case 'integer':
- return {kind: 'number', options: []};
- case 'string':
- return {kind: 'string', options: []};
- default:
- return {kind: 'json', options: []};
- }
-}
-
-/**
- * Creates a brand-new default value for a control when adding an entry to an empty array.
- */
-export function createDefaultGalleryValue(control: GalleryPropertyControl | undefined): unknown {
- if (!control) {
- return '';
- }
- switch (control.kind) {
- case 'string':
- return '';
- case 'number':
- return 0;
- case 'boolean':
- return false;
- case 'enum':
- return control.options[0] ?? '';
- case 'array':
- return [];
- case 'object': {
- const result: Record = {};
- for (const prop of control.properties ?? []) {
- result[prop.name] = createDefaultGalleryValue(prop.control);
- }
- return result;
- }
- case 'json':
- default:
- return {};
- }
-}
-
-/**
- * Explains why a control cannot show a value, such as a data binding or function call,
- * so the editor never overwrites it. Returns null when the control can edit the value.
- */
-export function describeUneditableValue(
- value: unknown,
- control: GalleryPropertyControl,
-): string | null {
- // Unset values and raw JSON textareas are always editable.
- if (value === undefined || control.kind === 'json') {
- return null;
- }
- // Enum select controls can edit the value if it matches one of the allowed options.
- if (control.kind === 'enum' && control.options.some(option => option === value)) {
- return null;
- }
- // Array controls can edit the value if it is an actual array (not a binding or call).
- if (control.kind === 'array' && Array.isArray(value)) {
- return null;
- }
- // Object field controls can edit plain objects, excluding data bindings and function calls.
- if (control.kind === 'object' && isRecord(value) && !isAnyDynamicValue(value)) {
- return null;
- }
- // Primitive controls ('string', 'number', 'boolean') can edit values of the matching JS typeof.
- if (
- (control.kind === 'string' || control.kind === 'number' || control.kind === 'boolean') &&
- typeof value === control.kind
- ) {
- return null;
- }
- // Otherwise, the control cannot edit this value—explain why in a read-only note.
- const dynamicDescription = describeAnyDynamicValue(value);
- if (dynamicDescription !== null) {
- return dynamicDescription;
- }
- return 'This value can only be edited in the JSON editor.';
-}
-
-/**
- * Falls back to inferring an editor control from teh runtime values when no schema is provided.
- * This is usually for array types or for any value when the schema is missing.
- */
-function inferControlFromValue(
- value: unknown,
- visited: Set,
-): GalleryPropertyControl {
- if (Array.isArray(value)) {
- const sample = value[value.length - 1];
- return {
- kind: 'array',
- options: [],
- itemControl:
- sample !== undefined
- ? inferControlFromValue(sample, visited)
- : {kind: 'string', options: []},
- };
- }
- if (isRecord(value) && !isAnyDynamicValue(value) && Object.keys(value).length > 0) {
- return {
- kind: 'object',
- options: [],
- properties: Object.entries(value).map(([name, subValue]) => ({
- name,
- required: false,
- control: inferControlFromValue(subValue, visited),
- })),
- };
- }
- const type = typeof value;
- return type === 'string' || type === 'number' || type === 'boolean'
- ? {kind: type, options: []}
- : {kind: 'json', options: []};
-}
-
-/**
- * Extracts editable child property controls from an object schema, skips fixed `const` fields.
- * This is used for object types in order to render form inputs for each nested field in object types
- * instead of using single raw JSON textarea.
- */
-function resolveObjectProperties(
- schema: CatalogComponentSchema,
- value: unknown,
- visited: Set,
-): GalleryObjectProperty[] {
- const rawProps = isRecord(schema['properties']) ? schema['properties'] : null;
- if (!rawProps) {
- return [];
- }
- const requiredSet = new Set(
- Array.isArray(schema['required'])
- ? schema['required'].filter((req): req is string => typeof req === 'string')
- : [],
- );
- const recordValue = isRecord(value) ? value : undefined;
- const properties: GalleryObjectProperty[] = [];
- for (const [name, propSchema] of Object.entries(rawProps)) {
- if (isRecord(propSchema) && propSchema['const'] !== undefined) {
- continue;
- }
- properties.push({
- name,
- required: requiredSet.has(name),
- control: galleryPropertyControl(
- isRecord(propSchema) ? (propSchema as CatalogComponentSchema) : undefined,
- recordValue?.[name],
- visited,
- ),
- });
- }
- return properties;
-}
-
-/**
- * Returns true if schema has editable object properties, false otherwise.
- */
-function hasEditableObjectProperties(
- schema: CatalogComponentSchema,
- visited: Set,
-): boolean {
- return resolveObjectProperties(schema, undefined, visited).length > 0;
-}
-
-const FUNCTION_CALL_KEYS = new Set(['call', 'args', 'returnType']);
-
-/**
- * Returns true if schema represents a data binding or function call schema, false otherwise.
- */
-function isBindingOrCallSchema(schema: CatalogComponentSchema): boolean {
- const props = isRecord(schema['properties']) ? schema['properties'] : null;
- if (!props) {
- return false;
- }
- const keys = Object.keys(props);
- if (keys.length === 1 && (keys[0] === 'path' || keys[0] === '@path')) {
- return true;
- }
- if ('@call' in props) {
- return true;
- }
- return 'call' in props && keys.every(key => FUNCTION_CALL_KEYS.has(key));
-}
-
-/**
- * Returns true if value is a literal, false otherwise.
- */
-function isLiteral(value: unknown): value is Literal {
- return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
-}
-
-/**
- * Returns true if schema represents a literal schema, false otherwise.
- */
-function isLiteralSchema(schema: CatalogComponentSchema): boolean {
- const type = schema['type'];
- return (
- Array.isArray(schema['enum']) ||
- type === 'string' ||
- type === 'number' ||
- type === 'integer' ||
- type === 'boolean'
- );
-}
-
-/**
- * Returns true if value matches schema, false otherwise.
- */
-function matchesSimpleSchema(value: unknown, schema: CatalogComponentSchema): boolean {
- if (typeof schema === 'boolean') {
- return schema;
- }
- const alternatives = schema['anyOf'] ?? schema['oneOf'];
- if (Array.isArray(alternatives)) {
- return alternatives.some(option => isRecord(option) && matchesSimpleSchema(value, option));
- }
- if (
- Array.isArray(schema['enum']) &&
- !schema['enum'].some(option => JSON.stringify(option) === JSON.stringify(value))
- ) {
- return false;
- }
- if ('const' in schema && JSON.stringify(schema['const']) !== JSON.stringify(value)) {
- return false;
- }
- const type = schema['type'];
- if (Array.isArray(type)) {
- return type.some(option => matchesSimpleSchema(value, {...schema, ['type']: option}));
- }
- switch (type) {
- case 'string':
- return typeof value === 'string';
- case 'number':
- return typeof value === 'number' && Number.isFinite(value);
- case 'integer':
- return typeof value === 'number' && Number.isInteger(value);
- case 'boolean':
- return typeof value === 'boolean';
- case 'object':
- return isRecord(value);
- case 'array':
- return Array.isArray(value);
- case 'null':
- return value === null;
- default:
- return true;
- }
-}
diff --git a/shell/src/app/gallery/gallery.ng.html b/shell/src/app/gallery/gallery.ng.html
index 4744eb438..7c0535027 100644
--- a/shell/src/app/gallery/gallery.ng.html
+++ b/shell/src/app/gallery/gallery.ng.html
@@ -125,272 +125,14 @@ {{ selectedComponentKey() }}
Fix the JSON in the Edit JSON tab to enable property editing again.
}
- @if (editableProperties().length) {
-
- @for (prop of editableProperties(); track prop.name) {
- @if (prop.firstCommon) {
-
Common properties
- }
-
-
-
-
-
- @if (
- !prop.required && prop.value !== undefined && prop.kind !== 'enum'
- ) {
-
- }
- @if (jsonFieldErrors()[prop.name]; as fieldError) {
-
- {{ fieldError.message }}
-
- } @else if (prop.required && prop.value === undefined) {
-
- Required, but this example doesn't set it.
-
- }
-
- }
-
- }
-
- @if (describeUneditableValue(value, control); as nestedNote) {
-
- {{ nestedNote }}
-
- } @else if (control.kind === 'enum') {
-
- } @else if (control.kind === 'boolean') {
-
- } @else if (control.kind === 'number') {
-
- } @else if (control.kind === 'string') {
-
- } @else if (control.kind === 'array') {
-
- @for (itemValue of ensureArray(value); track $index) {
-
- }
-
-
- } @else if (control.kind === 'object') {
-
- @for (subProp of control.properties; track subProp.name) {
-
-
-
-
- }
-
- } @else {
-
-
- @if (
- path.length > 1 && jsonFieldErrors()[pathKey];
- as nestedFieldError
- ) {
-
- {{ nestedFieldError.message }}
-
- }
-
- }
-
+