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) { +
+
+ Surface {{ tree.surfaceId }} + · {{ tree.componentCount }} components + @if (tree.truncated) { + truncated + } +
+ + @if (tree.root; as root) { +
+ +
+ } @else { +
No root component.
+ } + + @if (tree.unreachable.length > 0) { +
Not reachable from root
+
+ @for (node of tree.unreachable; track node.key) { + + } +
+ } +
+ } +
+ + +
+ @if (node.children.length > 0) { + + } @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) { - - } @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 - ) { - - } -
- } -
+
+ } + @if (jsonFieldErrors()[prop.name]; as fieldError) { + + } @else if (prop.required && prop.value === undefined) { +

+ Required, but this example doesn't set it. +

+ } +
+ } + +} @else { +

+ {{ !component() ? emptyMessage() : 'No editable properties for this component.' }} +

+} + + @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) { + + } +
+ } +
diff --git a/shell/src/app/shared/property-editor/property-editor.scss b/shell/src/app/shared/property-editor/property-editor.scss new file mode 100644 index 000000000..32d188ded --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.scss @@ -0,0 +1,254 @@ +/** + * 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 { + box-sizing: border-box; + display: block; + height: 100%; + min-width: 0; + overflow: auto; + padding: 8px 12px; + width: 100%; +} + +.property-header { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 6px; + min-width: 0; + margin-bottom: 8px; + padding-bottom: 6px; + border-bottom: 1px solid var(--mat-sys-outline-variant); +} + +.property-header-type { + min-width: 0; + overflow-wrap: anywhere; + font: var(--mat-sys-title-small); + letter-spacing: var(--mat-sys-title-small-tracking); + color: var(--mat-sys-on-surface); +} + +.property-header-id { + min-width: 0; + overflow-wrap: anywhere; + font: var(--mat-sys-body-small); + font-family: 'Roboto Mono', monospace; + color: var(--mat-sys-on-surface-variant); +} + +.property-status { + margin: 0 0 8px; + overflow-wrap: anywhere; +} + +// One property per row: property name stacked on top of its UI control. +.property-list { + display: flex; + flex-direction: column; + margin-bottom: 20px; +} + +.property-empty-state { + margin: 8px 0 16px; + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); +} + +.property-section-heading { + margin: 16px 0 4px; + font: var(--mat-sys-title-small); + letter-spacing: var(--mat-sys-title-small-tracking); + color: var(--mat-sys-on-surface-variant); +} + +.property-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + column-gap: 8px; + row-gap: 6px; + padding: 10px 0; + border-bottom: 1px solid var(--mat-sys-outline-variant); + + &:last-child { + border-bottom: none; + } +} + +.property-name { + grid-column: 1 / -1; + display: flex; + align-items: baseline; + flex-wrap: wrap; + column-gap: 8px; + min-width: 0; + overflow-wrap: anywhere; + color: var(--mat-sys-on-surface); + font: var(--mat-sys-label-large); + letter-spacing: var(--mat-sys-label-large-tracking); +} + +.required-marker { + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-small); + letter-spacing: var(--mat-sys-label-small-tracking); +} + +.property-control { + grid-column: 1; + display: flex; + min-width: 0; + + input:not([type='checkbox']), + select, + textarea { + box-sizing: border-box; + width: 100%; + min-height: 40px; + border: 1px solid var(--mat-sys-outline-variant); + border-radius: 8px; + padding: 8px 10px; + background: var(--mat-sys-surface); + color: var(--mat-sys-on-surface); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); + } + + .property-json { + min-height: 88px; + resize: vertical; + font-family: 'Spline Sans Mono', monospace; + } +} + +.json-control-wrapper { + display: flex; + flex-direction: column; + gap: 4px; + width: 100%; + min-width: 0; +} + +.array-control { + display: flex; + flex-direction: column; + gap: 8px; + width: 100%; + min-width: 0; +} + +.array-item-row { + display: flex; + align-items: flex-start; + gap: 8px; + width: 100%; + min-width: 0; +} + +.array-item-control { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; +} + +.delete-array-item { + flex-shrink: 0; + color: var(--mat-sys-error); + --mat-icon-button-state-layer-size: 40px; + width: 40px; + height: 40px; + padding: 8px; +} + +.add-array-item { + align-self: flex-start; +} + +.object-control { + box-sizing: border-box; + display: flex; + flex-direction: column; + gap: 10px; + width: 100%; + min-width: 0; + padding: 12px; + border: 1px solid var(--mat-sys-outline-variant); + border-radius: 8px; + background: var(--mat-sys-surface-container-lowest, transparent); +} + +.object-property-field { + display: flex; + flex-direction: column; + gap: 4px; + width: 100%; + min-width: 0; +} + +.object-property-label { + display: flex; + align-items: baseline; + flex-wrap: wrap; + column-gap: 6px; + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-label-medium); + letter-spacing: var(--mat-sys-label-medium-tracking); +} + +.remove-property { + grid-column: 2; + color: var(--mat-sys-on-surface-variant); + --mat-icon-button-state-layer-size: 40px; + width: 40px; + height: 40px; + padding: 8px; +} + +.property-row-multiline { + align-items: start; +} + +.property-note { + margin: 0; + color: var(--mat-sys-on-surface-variant); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); +} + +.property-status, +.property-missing, +.property-error { + color: var(--mat-sys-error); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); +} + +.property-missing, +.property-error { + grid-column: 1 / -1; + margin: 0; +} + +.property-control input:focus-visible, +.property-control select:focus-visible, +.property-control textarea:focus-visible { + outline: 2px solid var(--mat-sys-primary); + outline-offset: 2px; +} diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts new file mode 100644 index 000000000..67cc8703b --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -0,0 +1,1484 @@ +/** + * 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 {ComponentFixture, TestBed} from '@angular/core/testing'; +import {manualChangeDetection} from '@angular/cdk/testing'; +import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; +import {signal} from '@angular/core'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {PropertyEditor} from './property-editor'; +import { + createDefaultPropertyValue, + describeUneditableValue, + matchesSimpleSchema, + resolvePropertyControl, +} from './property-control'; +import {PropertyEditorHarness} from './test/property-editor.harness'; +import {CatalogManagement} from '../../storage/catalog-management/catalog-management'; +import {Catalog, CatalogComponentSchema} from '../../storage/models/catalog-storage.model'; +import {ErrorLogger} from '../../debug/error-logger.service'; + +class MockCatalogManagement { + readonly activeCatalog = signal(null); + readonly mergedActiveCatalog = signal(null); +} + +const dynamic = (literal: Record) => ({ + oneOf: [literal, {$ref: '#/$defs/DataBinding'}, {$ref: '#/$defs/FunctionCall'}], +}); + +const basicCatalog: Catalog = { + catalogId: 'https://a2ui.org/basic_catalog.json', + $defs: { + DataBinding: {type: 'object', properties: {path: {type: 'string'}}, required: ['path']}, + FunctionCall: {type: 'object', properties: {call: {type: 'string'}}, required: ['call']}, + DynamicString: dynamic({type: 'string'}), + DynamicStringList: dynamic({type: 'array', items: {type: 'string'}}), + ComponentCommon: { + type: 'object', + properties: {id: {type: 'string'}, weight: {type: 'number'}}, + required: ['id'], + }, + }, + components: { + ChoicePicker: { + type: 'object', + allOf: [ + {$ref: '#/$defs/ComponentCommon'}, + { + type: 'object', + properties: { + component: {const: 'ChoicePicker'}, + label: {$ref: '#/$defs/DynamicString'}, + variant: {type: 'string', enum: ['multipleSelection', 'mutuallyExclusive']}, + options: { + type: 'array', + items: { + type: 'object', + properties: {label: {$ref: '#/$defs/DynamicString'}, value: {type: 'string'}}, + required: ['label', 'value'], + }, + }, + value: {$ref: '#/$defs/DynamicStringList'}, + displayStyle: {type: 'string', enum: ['checkbox', 'chips']}, + filterable: {type: 'boolean'}, + }, + required: ['component', 'options', 'value'], + }, + ], + }, + DateTimeInput: { + type: 'object', + allOf: [ + {$ref: '#/$defs/ComponentCommon'}, + { + type: 'object', + properties: { + component: {const: 'DateTimeInput'}, + value: {$ref: '#/$defs/DynamicString'}, + enableDate: {type: 'boolean'}, + enableTime: {type: 'boolean'}, + min: {$ref: '#/$defs/DynamicString'}, + label: {$ref: '#/$defs/DynamicString'}, + }, + required: ['component', 'value'], + }, + ], + }, + }, +}; + +const jsonCatalog: Catalog = { + ...basicCatalog, + components: { + ...basicCatalog.components, + StyledBox: { + type: 'object', + allOf: [ + {$ref: '#/$defs/ComponentCommon'}, + { + type: 'object', + required: ['component'], + properties: { + component: {const: 'StyledBox'}, + style: {type: 'object', additionalProperties: true}, + }, + }, + ], + }, + ActionBox: { + type: 'object', + allOf: [ + {$ref: '#/$defs/ComponentCommon'}, + { + type: 'object', + required: ['component', 'count', 'config'], + properties: { + component: {const: 'ActionBox'}, + count: {type: 'number'}, + config: {type: 'object', additionalProperties: true}, + metadata: { + type: 'object', + properties: { + hint: {type: 'string'}, + tag: {type: 'string'}, + }, + }, + }, + }, + ], + }, + }, +}; + +describe('PropertyEditor Component', () => { + let fixture: ComponentFixture; + let harness: PropertyEditorHarness; + let catalogManagementMock: MockCatalogManagement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [PropertyEditor], + providers: [{provide: CatalogManagement, useClass: MockCatalogManagement}, ErrorLogger], + }).compileComponents(); + + fixture = TestBed.createComponent(PropertyEditor); + catalogManagementMock = TestBed.inject(CatalogManagement) as unknown as MockCatalogManagement; + catalogManagementMock.activeCatalog.set(basicCatalog); + fixture.detectChanges(); + harness = await TestbedHarnessEnvironment.harnessForFixture(fixture, PropertyEditorHarness); + }); + + it('resolves properties automatically from the active catalog and component without explicit properties input', async () => { + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + options: [{label: 'Small', value: 's'}], + value: ['s'], + }); + fixture.detectChanges(); + + expect(await harness.getPropertyNames()).toEqual([ + 'options', + 'value', + 'variant', + 'displayStyle', + 'filterable', + 'weight', + 'label', + ]); + expect(await harness.getPropertySectionHeadings()).toEqual(['Common properties']); + expect(await harness.getEmptyStateText()).toBeNull(); + }); + + it('renders the selection prompt (or custom emptyMessage) when component is null or undefined', async () => { + expect(await harness.getEmptyStateText()).toBe('Select a component to inspect its properties.'); + + fixture.componentRef.setInput( + 'emptyMessage', + 'Click a component in the preview to edit its properties.', + ); + fixture.detectChanges(); + + expect(await harness.getEmptyStateText()).toBe( + 'Click a component in the preview to edit its properties.', + ); + }); + + it('renders a zero-properties message when a component has no editable catalog properties', async () => { + fixture.componentRef.setInput('component', { + id: 'divider-1', + component: 'Divider', + }); + fixture.componentRef.setInput('properties', [ + {name: 'id', description: '', type: 'string', required: true}, + {name: 'component', description: '', type: 'string', required: true}, + ]); + fixture.detectChanges(); + + expect(await harness.getPropertyNames()).toEqual([]); + expect(await harness.getEmptyStateText()).toBe('No editable properties for this component.'); + }); + + it('prefers mergedActiveCatalog over activeCatalog so secondary multi-catalog components resolve schemas', async () => { + catalogManagementMock.activeCatalog.set(basicCatalog); + catalogManagementMock.mergedActiveCatalog.set(jsonCatalog); + fixture.componentRef.setInput('component', { + id: 'box-secondary', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + + expect(await harness.getPropertyNames()).toEqual(['style', 'weight']); + expect(await harness.getPropertyControlKind('style')).toBe('json'); + }); + + it('blocks property edits when disabled input is true', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('disabled', true); + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + filterable: true, + options: [{label: 'Small', value: 's'}], + value: ['s'], + }); + fixture.detectChanges(); + + await harness.removeProperty('filterable'); + + expect(componentChanges).toEqual([]); + }); + + it('emits componentChange when a property is edited', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + const initial = { + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + filterable: true, + options: [{label: 'Small', value: 's'}], + value: ['s'], + }; + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.editProperty('label', 'Updated Size'); + + expect(componentChanges.at(-1)).toEqual({ + ...initial, + label: 'Updated Size', + }); + }); + + it('emits componentChange without the removed key when an optional property is removed', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + filterable: true, + options: [{label: 'Small', value: 's'}], + value: ['s'], + }); + fixture.detectChanges(); + + await harness.removeProperty('filterable'); + + expect(componentChanges.at(-1)).toEqual({ + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + options: [{label: 'Small', value: 's'}], + value: ['s'], + }); + }); + + it('updates nested object fields while preserving sibling fields', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {retry: true}, + metadata: {hint: 'Old', tag: 'v1'}, + }); + fixture.detectChanges(); + + await harness.editProperty('metadata.hint', 'Updated'); + + expect(componentChanges.at(-1)).toEqual({ + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {retry: true}, + metadata: {hint: 'Updated', tag: 'v1'}, + }); + }); + + it('prunes an optional parent object when its last nested field is cleared', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {retry: true}, + metadata: {hint: 'Only field'}, + }); + fixture.detectChanges(); + + await harness.editProperty('metadata.hint', ''); + + expect(componentChanges.at(-1)).toEqual({ + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {retry: true}, + }); + }); + + it('clones the last entry when adding an item to a non-empty array', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + const lastOption = {label: 'Large', value: 'l'}; + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + options: [{label: 'Small', value: 's'}, lastOption], + value: ['s'], + }); + fixture.detectChanges(); + + await harness.addArrayItem('options'); + + const updatedOptions = componentChanges.at(-1)?.['options'] as Array>; + expect(updatedOptions).toEqual([ + {label: 'Small', value: 's'}, + {label: 'Large', value: 'l'}, + {label: 'Large', value: 'l'}, + ]); + expect(updatedOptions[2]).not.toBe(lastOption); + }); + + it('creates a default entry from the item control when adding to an empty array', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + options: [], + value: [], + }); + fixture.detectChanges(); + + await harness.addArrayItem('options'); + + expect(componentChanges.at(-1)?.['options']).toEqual([{label: '', value: ''}]); + }); + + it('removes the targeted entry when deleting an array item', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'picker-1', + component: 'ChoicePicker', + options: [{label: 'Small', value: 's'}], + value: ['s', 'm', 'l'], + }); + fixture.detectChanges(); + + await harness.deleteArrayItem('value', 1); + + expect(componentChanges.at(-1)?.['value']).toEqual(['s', 'l']); + }); + + it('removes optional text properties when cleared', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'dt-1', + component: 'DateTimeInput', + value: '2026-01-01', + label: 'Start date', + }); + fixture.detectChanges(); + + await harness.editProperty('label', ''); + + expect(componentChanges.at(-1)).toEqual({ + id: 'dt-1', + component: 'DateTimeInput', + value: '2026-01-01', + }); + }); + + it('keeps required text properties as empty string when cleared', async () => { + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'dt-1', + component: 'DateTimeInput', + value: '2026-01-01', + }); + fixture.detectChanges(); + + await harness.editProperty('value', ''); + + expect(componentChanges.at(-1)).toEqual({ + id: 'dt-1', + component: 'DateTimeInput', + value: '', + }); + }); + + it('removes optional numbers when cleared', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + weight: 2, + config: {}, + }); + fixture.detectChanges(); + + await harness.editProperty('weight', ''); + + expect(componentChanges).toEqual([ + { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }, + ]); + }); + + it('emits statusMessage without componentChange when a required number is cleared', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const changeSpy = vi.fn(); + const statuses: string[] = []; + fixture.componentInstance.componentChange.subscribe(changeSpy); + fixture.componentInstance.statusMessage.subscribe(msg => statuses.push(msg)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + + await harness.editProperty('count', ''); + + expect(changeSpy).not.toHaveBeenCalled(); + expect(statuses).toEqual(['Enter a number for count. Preview keeps its previous value.']); + }); + + it('surfaces inline syntax error and preserves raw text across same-component updates for invalid JSON edits', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const changeSpy = vi.fn(); + fixture.componentInstance.componentChange.subscribe(changeSpy); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 1, + config: {retry: true}, + }); + fixture.detectChanges(); + + await harness.editJsonProperty('config', '{invalid'); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 1, + config: {retry: false}, + }); + fixture.detectChanges(); + + expect(await harness.getPropertyError('config')).toBe( + 'Invalid JSON. The example keeps its previous value.', + ); + expect(await harness.getJsonPropertyText('config')).toBe('{invalid'); + expect(changeSpy).not.toHaveBeenCalled(); + }); + + it('surfaces required-field error when a required JSON field is blank', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const changeSpy = vi.fn(); + fixture.componentInstance.componentChange.subscribe(changeSpy); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 1, + config: {retry: true}, + }); + fixture.detectChanges(); + + await harness.editJsonProperty('config', ' '); + + expect(await harness.getPropertyError('config')).toBe('config is required.'); + expect(changeSpy).not.toHaveBeenCalled(); + }); + + it('removes an optional JSON property when cleared with whitespace', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + + await harness.editJsonProperty('style', ' '); + + expect(await harness.getPropertyError('style')).toBeNull(); + expect(componentChanges).toEqual([ + { + id: 'box-1', + component: 'StyledBox', + }, + ]); + }); + + it('clears inline JSON error and emits componentChange when valid JSON is entered after an error', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); + fixture.componentRef.setInput('component', { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + await harness.editJsonProperty('style', '{invalid'); + + await harness.editJsonProperty('style', '{"padding": 16}'); + + expect(await harness.getPropertyError('style')).toBeNull(); + expect(componentChanges).toEqual([ + { + id: 'box-1', + component: 'StyledBox', + style: {padding: 16}, + }, + ]); + }); + + it('surfaces inline error and suppresses componentChange when a JSON field violates the catalog schema', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('component', { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + const statusSpy = vi.fn(); + const changeSpy = vi.fn(); + fixture.componentInstance.statusMessage.subscribe(statusSpy); + fixture.componentInstance.componentChange.subscribe(changeSpy); + + await harness.editJsonProperty('style', '123'); + + expect(await harness.getPropertyError('style')).toBe( + '"style" on "box-1" does not match its catalog property type or choices. The example keeps its previous value.', + ); + expect(statusSpy.mock.calls).toEqual([['']]); + expect(changeSpy).not.toHaveBeenCalled(); + }); + + it('clears inline JSON field errors when clearErrors() is called', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('component', { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + await harness.editJsonProperty('style', '123'); + + fixture.componentInstance.clearErrors(); + fixture.detectChanges(); + + expect(await harness.getPropertyError('style')).toBeNull(); + }); + + it('clears inline JSON field errors automatically when the target component identity changes', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('component', { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }); + fixture.detectChanges(); + await harness.editJsonProperty('style', '123'); + + fixture.componentRef.setInput('component', { + id: 'box-2', + component: 'StyledBox', + style: {padding: 16}, + }); + fixture.detectChanges(); + + expect(await harness.getPropertyError('style')).toBeNull(); + }); + + it('assigns distinct DOM id prefixes per instance so label[for] and aria-describedby do not collide', async () => { + const secondFixture = TestBed.createComponent(PropertyEditor); + try { + const secondHarness = await TestbedHarnessEnvironment.harnessForFixture( + secondFixture, + PropertyEditorHarness, + ); + const sample = { + id: 'box-1', + component: 'StyledBox', + style: {padding: 8}, + }; + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('component', sample); + secondFixture.componentRef.setInput('component', sample); + fixture.detectChanges(); + secondFixture.detectChanges(); + + await harness.editJsonProperty('style', '123'); + + const firstLabelFor = await harness.getPropertyLabelFor('style'); + const secondLabelFor = await secondHarness.getPropertyLabelFor('style'); + const firstControlId = await harness.getPropertyControlId('style'); + const secondControlId = await secondHarness.getPropertyControlId('style'); + const firstErrorId = await harness.getPropertyErrorId('style'); + const firstDescribedBy = await harness.getPropertyAriaDescribedBy('style'); + + expect(firstLabelFor).toMatch(/^property-editor-\d+-style$/); + expect(secondLabelFor).toMatch(/^property-editor-\d+-style$/); + expect(firstLabelFor).not.toBe(secondLabelFor); + expect(firstControlId).toBe(firstLabelFor); + expect(secondControlId).toBe(secondLabelFor); + expect(firstErrorId).toMatch(/^property-editor-\d+-error-style$/); + expect(firstDescribedBy).toBe(firstErrorId); + expect(await secondHarness.getPropertyError('style')).toBeNull(); + } finally { + secondFixture.destroy(); + } + }); + + it('hides the component header by default', async () => { + fixture.componentRef.setInput('component', { + id: 'date-1', + component: 'DateTimeInput', + value: '2026-01-01', + }); + fixture.detectChanges(); + + expect(await harness.getHeaderText()).toBeNull(); + }); + + it('renders Type #id when showHeader is true and trims id whitespace', async () => { + fixture.componentRef.setInput('showHeader', true); + fixture.componentRef.setInput('component', { + id: ' date-1 ', + component: 'DateTimeInput', + value: '2026-01-01', + }); + fixture.detectChanges(); + + expect(await harness.getHeaderText()).toBe('DateTimeInput #date-1'); + }); + + it('renders only Type when showHeader is true and the component has no id', async () => { + fixture.componentRef.setInput('showHeader', true); + fixture.componentRef.setInput('component', { + component: 'DateTimeInput', + value: '2026-01-01', + }); + fixture.detectChanges(); + + expect(await harness.getHeaderText()).toBe('DateTimeInput'); + }); + + it('hides the component header when no component is selected', async () => { + fixture.componentRef.setInput('showHeader', true); + fixture.componentRef.setInput('component', null); + fixture.detectChanges(); + + expect(await harness.getHeaderText()).toBeNull(); + }); + + it('keeps inline status and its live region hidden by default when showStatus is false', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const statuses: string[] = []; + fixture.componentInstance.statusMessage.subscribe(message => statuses.push(message)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + + await harness.editProperty('count', ''); + + expect(await harness.hasStatusLiveRegion()).toBe(false); + expect(await harness.getStatusText()).toBeNull(); + expect(statuses).toEqual(['Enter a number for count. Preview keeps its previous value.']); + }); + + it('keeps the status live region mounted and updates inline status on invalid and valid edits', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('showStatus', true); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + + expect(await harness.hasStatusLiveRegion()).toBe(true); + expect(await harness.getStatusText()).toBeNull(); + + await harness.editProperty('count', ''); + expect(await harness.getStatusText()).toBe( + 'Enter a number for count. Preview keeps its previous value.', + ); + + await harness.editProperty('count', '7'); + expect(await harness.hasStatusLiveRegion()).toBe(true); + expect(await harness.getStatusText()).toBeNull(); + }); + + it('clears inline status feedback and emits an empty statusMessage when clearErrors() is called', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const statuses: string[] = []; + fixture.componentInstance.statusMessage.subscribe(message => statuses.push(message)); + fixture.componentRef.setInput('showStatus', true); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + await harness.editProperty('count', ''); + expect(await harness.getStatusText()).toBe( + 'Enter a number for count. Preview keeps its previous value.', + ); + + fixture.componentInstance.clearErrors(); + fixture.detectChanges(); + + expect(await harness.getStatusText()).toBeNull(); + expect(statuses.at(-1)).toBe(''); + }); + + it('clears inline status feedback when the target component identity changes', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('showStatus', true); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + await harness.editProperty('count', ''); + expect(await harness.getStatusText()).toBe( + 'Enter a number for count. Preview keeps its previous value.', + ); + + fixture.componentRef.setInput('component', { + id: 'action-2', + component: 'ActionBox', + count: 1, + config: {}, + }); + fixture.detectChanges(); + + expect(await harness.getStatusText()).toBeNull(); + }); + + it('clears prior inline status feedback when a JSON property edit fails to parse', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + fixture.componentRef.setInput('showStatus', true); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + await harness.editProperty('count', ''); + expect(await harness.getStatusText()).toBe( + 'Enter a number for count. Preview keeps its previous value.', + ); + + await harness.editJsonProperty('config', '{invalid'); + + expect(await harness.getStatusText()).toBeNull(); + expect(await harness.getPropertyError('config')).toBe( + 'Invalid JSON. The example keeps its previous value.', + ); + }); + + it('ignores clearing a required number when disabled', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const statusSpy = vi.fn(); + fixture.componentInstance.statusMessage.subscribe(statusSpy); + fixture.componentRef.setInput('showStatus', true); + fixture.componentRef.setInput('disabled', true); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + + await harness.editProperty('count', ''); + + expect(await harness.getStatusText()).toBeNull(); + expect(statusSpy).not.toHaveBeenCalled(); + }); + + describe('debounced text and number edits', () => { + const debounceMs = 300; + + const createChoicePicker = ( + overrides: Record = {}, + ): Record => ({ + id: 'picker-1', + component: 'ChoicePicker', + options: [{label: 'Small', value: 's'}], + value: ['s'], + ...overrides, + }); + + const stepperCatalog: Catalog = { + ...basicCatalog, + components: { + ...basicCatalog.components, + Stepper: { + type: 'object', + allOf: [ + {$ref: '#/$defs/ComponentCommon'}, + { + type: 'object', + required: ['component', 'steps'], + properties: { + component: {const: 'Stepper'}, + steps: {type: 'integer'}, + enabled: {type: 'boolean'}, + }, + }, + ], + }, + }, + }; + + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('coalesces rapid text keystrokes and emits componentChange once after 300ms', async () => { + const initial = createChoicePicker({label: 'Size'}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'S'); + await vi.advanceTimersByTimeAsync(100); + await harness.typeProperty('label', 'Sm'); + await vi.advanceTimersByTimeAsync(100); + await harness.typeProperty('label', 'Small'); + await vi.advanceTimersByTimeAsync(debounceMs - 1); + const changesBeforeDebounce = [...componentChanges]; + await vi.advanceTimersByTimeAsync(1); + + expect(changesBeforeDebounce).toEqual([]); + expect(componentChanges).toEqual([{...initial, label: 'Small'}]); + }); + + it('coalesces rapid number edits and emits componentChange once after 300ms', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const initial = {id: 'action-1', component: 'ActionBox', count: 5, config: {}}; + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('count', '1'); + await vi.advanceTimersByTimeAsync(150); + await harness.typeProperty('count', '12'); + await vi.advanceTimersByTimeAsync(debounceMs - 1); + const changesBeforeDebounce = [...componentChanges]; + await vi.advanceTimersByTimeAsync(1); + + expect(changesBeforeDebounce).toEqual([]); + expect(componentChanges).toEqual([{...initial, count: 12}]); + }); + + it('skips emitting componentChange when a debounced edit reverts to the current value', async () => { + const initial = createChoicePicker({label: 'Size'}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Temp'); + await harness.typeProperty('label', 'Size'); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([]); + }); + + it('flushes a pending debounced text edit immediately on blur without re-emitting after 300ms', async () => { + const initial = createChoicePicker({label: 'Size'}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Updated'); + const changesBeforeBlur = [...componentChanges]; + await harness.blurProperty('label'); + const changesOnBlur = [...componentChanges]; + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(changesBeforeBlur).toEqual([]); + expect(changesOnBlur).toEqual([{...initial, label: 'Updated'}]); + expect(componentChanges).toHaveLength(1); + }); + + it('flushes a pending debounced number edit immediately on blur without re-emitting after 300ms', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const initial = {id: 'action-1', component: 'ActionBox', count: 5, config: {}}; + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('count', '12'); + const changesBeforeBlur = [...componentChanges]; + await harness.blurProperty('count'); + const changesOnBlur = [...componentChanges]; + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(changesBeforeBlur).toEqual([]); + expect(changesOnBlur).toEqual([{...initial, count: 12}]); + expect(componentChanges).toHaveLength(1); + }); + + it('preserves a pending debounced text edit when an immediate control is triggered before 300ms', async () => { + const initial = createChoicePicker({label: 'Size', filterable: true}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Updated'); + await harness.toggleProperty('filterable'); + const changesOnToggle = [...componentChanges]; + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(changesOnToggle).toEqual([{...initial, label: 'Updated', filterable: false}]); + expect(componentChanges).toHaveLength(1); + }); + + it('preserves a blur-flushed edit when a sibling control fires in the same frame before component updates', async () => { + const initial = createChoicePicker({label: 'Size', filterable: true}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Updated'); + await manualChangeDetection(async () => { + await harness.blurProperty('label'); + await harness.toggleProperty('filterable'); + }); + + expect(componentChanges).toEqual([ + {...initial, label: 'Updated'}, + {...initial, label: 'Updated', filterable: false}, + ]); + }); + + it('clears the committed edit after the next render when the host keeps the previous component', async () => { + const initial = createChoicePicker({label: 'Size', filterable: true}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.editProperty('label', 'Rejected'); + fixture.detectChanges(); + await harness.toggleProperty('filterable'); + + expect(componentChanges).toEqual([ + {...initial, label: 'Rejected'}, + {...initial, filterable: false}, + ]); + }); + + it('layers consecutive debounced edits to sibling nested object fields within 300ms', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {}, + metadata: {hint: 'Old', tag: 'v1'}, + }); + fixture.detectChanges(); + + await harness.typeProperty('metadata.hint', 'New'); + await harness.typeProperty('metadata.tag', 'v2'); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([ + { + id: 'action-1', + component: 'ActionBox', + count: 3, + config: {}, + metadata: {hint: 'New', tag: 'v2'}, + }, + ]); + }); + + it('preserves a pending debounced array item edit when adding an array item before 300ms', async () => { + const initial = createChoicePicker({value: ['s']}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('value.0', 'm'); + await harness.addArrayItem('value'); + const changesOnAdd = [...componentChanges]; + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(changesOnAdd).toEqual([{...initial, value: ['m', 'm']}]); + expect(componentChanges).toHaveLength(1); + }); + + it('drops a pending debounced edit and updates the input when the component updates externally before 300ms', async () => { + const initial = createChoicePicker({id: 'picker-1', label: 'Size'}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Stale'); + fixture.componentRef.setInput( + 'component', + createChoicePicker({id: 'picker-1', label: 'External'}), + ); + fixture.detectChanges(); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([]); + expect(await harness.getPropertyValue('label')).toBe('External'); + }); + + it('drops a pending debounced edit when disabled toggles before 300ms', async () => { + const initial = createChoicePicker({label: 'Size', filterable: true}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Stale'); + fixture.componentRef.setInput('disabled', true); + fixture.detectChanges(); + await vi.advanceTimersByTimeAsync(debounceMs); + fixture.componentRef.setInput('disabled', false); + fixture.detectChanges(); + await harness.toggleProperty('filterable'); + + expect(componentChanges).toEqual([{...initial, filterable: false}]); + }); + + it('drops a pending debounced edit when clearErrors() is called before 300ms', async () => { + const initial = createChoicePicker({label: 'Size'}); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', initial); + fixture.detectChanges(); + + await harness.typeProperty('label', 'Reset me'); + fixture.componentInstance.clearErrors(); + fixture.detectChanges(); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([]); + }); + + it('cancels a pending number edit without overwriting the input when a required number is cleared before 300ms', async () => { + catalogManagementMock.activeCatalog.set(jsonCatalog); + const componentChanges: Array> = []; + const statuses: string[] = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentInstance.statusMessage.subscribe(message => statuses.push(message)); + fixture.componentRef.setInput('component', { + id: 'action-1', + component: 'ActionBox', + count: 5, + config: {}, + }); + fixture.detectChanges(); + + await harness.typeProperty('count', '55'); + await harness.typeProperty('count', ''); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([]); + expect(await harness.getPropertyValue('count')).toBe(''); + expect(statuses.at(-1)).toBe('Enter a number for count. Preview keeps its previous value.'); + }); + + it('cancels a pending debounced edit without overwriting the input or flushing on blur when a schema-invalid value is entered', async () => { + catalogManagementMock.activeCatalog.set(stepperCatalog); + const componentChanges: Array> = []; + const statuses: string[] = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentInstance.statusMessage.subscribe(message => statuses.push(message)); + fixture.componentRef.setInput('component', {id: 'step-1', component: 'Stepper', steps: 2}); + fixture.detectChanges(); + + await harness.typeProperty('steps', '4'); + await harness.typeProperty('steps', '4.5'); + await harness.blurProperty('steps'); + await vi.advanceTimersByTimeAsync(debounceMs); + + expect(componentChanges).toEqual([]); + expect(await harness.getPropertyValue('steps')).toBe('4.5'); + expect(statuses.at(-1)).toBe( + '"steps" on "step-1" does not match its catalog property type or choices. Preview keeps its previous value.', + ); + }); + + it('does not leak a cancelled pending debounced edit into a subsequent discrete control edit', async () => { + catalogManagementMock.activeCatalog.set(stepperCatalog); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(updatedComponent => + componentChanges.push(updatedComponent), + ); + fixture.componentRef.setInput('component', { + id: 'step-1', + component: 'Stepper', + steps: 2, + enabled: false, + }); + fixture.detectChanges(); + + await harness.typeProperty('steps', '4'); + await harness.typeProperty('steps', '4.5'); + await harness.toggleProperty('enabled'); + + expect(componentChanges).toEqual([ + {id: 'step-1', component: 'Stepper', steps: 2, enabled: true}, + ]); + }); + }); +}); + +// 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 dynamicSchema = (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 dynamicSchemaV1 = (literal: CatalogComponentSchema): CatalogComponentSchema => ({ + anyOf: [literal, v1Binding, v1Call], +}); + +describe('resolvePropertyControl', () => { + 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', dynamicSchema({type: 'string'}), 'string'], + ['a v1.0 DynamicString', dynamicSchemaV1({type: 'string'}), 'string'], + ['a DynamicBoolean', dynamicSchema({type: 'boolean'}), 'boolean'], + ['a v1.0 DynamicBoolean', dynamicSchemaV1({type: 'boolean'}), 'boolean'], + ['a DynamicNumber', dynamicSchema({type: 'number'}), 'number'], + ['a v1.0 DynamicNumber', dynamicSchemaV1({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', dynamicSchema({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', + dynamicSchema({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(resolvePropertyControl(schema as CatalogComponentSchema | undefined).kind).toBe(kind); + }); + + it('recursively resolves array item controls and nested object properties while skipping const fields', () => { + const control = resolvePropertyControl({ + type: 'array', + items: { + type: 'object', + properties: { + kind: {const: 'item'}, + label: dynamicSchema({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(resolvePropertyControl(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(resolvePropertyControl(undefined, 'Initial').kind).toBe('string'); + expect(resolvePropertyControl(undefined, 3).kind).toBe('number'); + expect(resolvePropertyControl(undefined, true).kind).toBe('boolean'); + expect(resolvePropertyControl(undefined, ['a', 'b']).kind).toBe('array'); + expect(resolvePropertyControl(undefined, {label: 'Hi'}).kind).toBe('object'); + expect(resolvePropertyControl(undefined, {path: '/x'}).kind).toBe('json'); + expect(resolvePropertyControl(undefined, {'@path': '/x'}).kind).toBe('json'); + expect(resolvePropertyControl(undefined, {'@call': 'fn'}).kind).toBe('json'); + }); + + it('keeps enum options in catalog order', () => { + expect(resolvePropertyControl({type: 'string', enum: ['checkbox', 'chips']}).options).toEqual([ + 'checkbox', + 'chips', + ]); + }); +}); + +describe('createDefaultPropertyValue', () => { + it('builds brand-new default items based on the control type', () => { + expect(createDefaultPropertyValue(undefined)).toBe(''); + expect(createDefaultPropertyValue({kind: 'string', options: []})).toBe(''); + expect(createDefaultPropertyValue({kind: 'number', options: []})).toBe(0); + expect(createDefaultPropertyValue({kind: 'boolean', options: []})).toBe(false); + expect(createDefaultPropertyValue({kind: 'enum', options: ['a', 'b']})).toBe('a'); + expect(createDefaultPropertyValue({kind: 'enum', options: []})).toBe(''); + expect(createDefaultPropertyValue({kind: 'array', options: []})).toEqual([]); + expect(createDefaultPropertyValue({kind: 'json', options: []})).toEqual({}); + expect( + createDefaultPropertyValue({ + 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 = resolvePropertyControl(dynamicSchema({type: 'string'})); + const list = resolvePropertyControl(dynamicSchema({type: 'array', items: {type: 'string'}})); + const group = resolvePropertyControl({ + 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 = resolvePropertyControl(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 = resolvePropertyControl(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 = resolvePropertyControl(webhookSchema); + expect(webhookControl.kind).toBe('object'); + expect(describeUneditableValue({call: 'ping', timeoutMs: 500}, webhookControl)).toBeNull(); + }); +}); + +describe('matchesSimpleSchema', () => { + it('evaluates boolean JSON schemas directly', () => { + const allowAll = true as unknown as CatalogComponentSchema; + const denyAll = false as unknown as CatalogComponentSchema; + expect(matchesSimpleSchema('anything', allowAll)).toBe(true); + expect(matchesSimpleSchema(null, allowAll)).toBe(true); + expect(matchesSimpleSchema('anything', denyAll)).toBe(false); + expect(matchesSimpleSchema(123, denyAll)).toBe(false); + }); + + it('distinguishes integer and finite number types', () => { + expect(matchesSimpleSchema(4, {type: 'integer'})).toBe(true); + expect(matchesSimpleSchema(4.5, {type: 'integer'})).toBe(false); + expect(matchesSimpleSchema(Number.NaN, {type: 'integer'})).toBe(false); + expect(matchesSimpleSchema(4.5, {type: 'number'})).toBe(true); + expect(matchesSimpleSchema(Number.POSITIVE_INFINITY, {type: 'number'})).toBe(false); + expect(matchesSimpleSchema('4', {type: 'number'})).toBe(false); + }); + + it('validates null, primitive, array, object, and untyped schemas', () => { + expect(matchesSimpleSchema(null, {type: 'null'})).toBe(true); + expect(matchesSimpleSchema(undefined, {type: 'null'})).toBe(false); + expect(matchesSimpleSchema('ok', {type: 'string'})).toBe(true); + expect(matchesSimpleSchema(123, {type: 'string'})).toBe(false); + expect(matchesSimpleSchema(true, {type: 'boolean'})).toBe(true); + expect(matchesSimpleSchema('true', {type: 'boolean'})).toBe(false); + expect(matchesSimpleSchema([1, 2], {type: 'array'})).toBe(true); + expect(matchesSimpleSchema({}, {type: 'array'})).toBe(false); + expect(matchesSimpleSchema({a: 1}, {type: 'object'})).toBe(true); + expect(matchesSimpleSchema([1, 2], {type: 'object'})).toBe(false); + expect(matchesSimpleSchema(null, {type: 'object'})).toBe(false); + expect(matchesSimpleSchema('anything', {})).toBe(true); + }); + + it('validates array-valued type unions', () => { + const nullableString: CatalogComponentSchema = {type: ['string', 'null']}; + expect(matchesSimpleSchema('hello', nullableString)).toBe(true); + expect(matchesSimpleSchema(null, nullableString)).toBe(true); + expect(matchesSimpleSchema(42, nullableString)).toBe(false); + }); + + it('validates const and enum constraints', () => { + expect(matchesSimpleSchema('info', {const: 'info'})).toBe(true); + expect(matchesSimpleSchema('warn', {const: 'info'})).toBe(false); + + const enumSchema: CatalogComponentSchema = {type: 'string', enum: ['a', 'b']}; + expect(matchesSimpleSchema('a', enumSchema)).toBe(true); + expect(matchesSimpleSchema('c', enumSchema)).toBe(false); + }); + + it('validates anyOf and oneOf union schemas', () => { + const anyOfSchema: CatalogComponentSchema = { + anyOf: [{type: 'integer'}, {type: 'object'}], + }; + expect(matchesSimpleSchema(7, anyOfSchema)).toBe(true); + expect(matchesSimpleSchema({path: '/count'}, anyOfSchema)).toBe(true); + expect(matchesSimpleSchema(7.5, anyOfSchema)).toBe(false); + + const oneOfSchema: CatalogComponentSchema = { + oneOf: [{type: 'string'}, {type: 'boolean'}], + }; + expect(matchesSimpleSchema('ok', oneOfSchema)).toBe(true); + expect(matchesSimpleSchema(false, oneOfSchema)).toBe(true); + expect(matchesSimpleSchema(123, oneOfSchema)).toBe(false); + }); +}); diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts new file mode 100644 index 000000000..c6ca41cfb --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -0,0 +1,638 @@ +/** + * 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, + Injector, + Signal, + WritableSignal, + afterNextRender, + computed, + inject, + input, + linkedSignal, + output, +} from '@angular/core'; +import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; +import {NgTemplateOutlet} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +import {Subject} from 'rxjs'; +import {debounceTime} from 'rxjs/operators'; +import {MatInputModule} from '@angular/material/input'; +import {MatSlideToggleModule} from '@angular/material/slide-toggle'; +import {MatButtonModule} from '@angular/material/button'; +import {MatIconModule} from '@angular/material/icon'; +import {CatalogManagement} from '../../storage/catalog-management/catalog-management'; +import {Catalog, CatalogComponentSchema} from '../../storage/models/catalog-storage.model'; +import {CatalogSchemaResolver, ParsedProperty} from '../../gallery/schema/catalog-schema-resolver'; +import { + createDefaultPropertyValue, + describeUneditableValue, + matchesSimpleSchema, + PropertyControl, + resolvePropertyControl, +} from './property-control'; +import {ErrorLogger} from '../../debug/error-logger.service'; +import {formatJson} from '../../utils/json'; +import {stableStringify} from '../../storage/stable-stringify/stable-stringify'; + +type PropertyPath = ReadonlyArray; + +interface EditOptions { + readonly emitStatus?: boolean; + readonly debounce?: boolean; +} + +const TEXT_INPUT_DEBOUNCE_MS = 300; + +let nextPropertyEditorId = 0; + +/** + * Metadata and control state for one editable catalog property of the selected component. + */ +interface EditableProperty { + name: string; + required: boolean; + control: PropertyControl; + kind: PropertyControl['kind']; + /** The current value, or undefined when the example omits the property. */ + value: unknown; + /** Set when the value is a binding or call that only the JSON tab can edit. */ + note: string | null; + /** True for properties every component in the catalog shares, such as accessibility. */ + common: boolean; + /** True on the first common property, where the list starts its common section. */ + firstCommon: boolean; +} + +/** + * An unparsed JSON property edit, kept so the field shows what was typed. + */ +interface JsonFieldError { + text: string; + message: string; +} + +/** + * Standalone property editor component that renders schema-driven form controls + * for an A2UI component definition. + */ +@Component({ + selector: 'a2ui-composer-property-editor', + standalone: true, + imports: [ + NgTemplateOutlet, + FormsModule, + MatInputModule, + MatSlideToggleModule, + MatButtonModule, + MatIconModule, + ], + templateUrl: './property-editor.ng.html', + styleUrl: './property-editor.scss', +}) +export class PropertyEditor { + private readonly catalogManagement = inject(CatalogManagement); + private readonly errorLogger = inject(ErrorLogger); + private readonly injector = inject(Injector); + + /** The A2UI component object being inspected and edited. */ + readonly component = input | null | undefined>(null); + + /** + * Optional pre-resolved property specifications; when omitted, resolved automatically + * from the active catalog and `component()['component']`. + */ + readonly properties = input(undefined); + + /** Whether all property controls and actions are disabled. */ + readonly disabled = input(false); + + /** + * Optional identity key from the host that resets inline JSON field errors when changed. + */ + readonly resetKey = input(null); + + /** Message shown when no component is selected (`component()` is null or undefined). */ + readonly emptyMessage = input('Select a component to inspect its properties.'); + + /** Whether to render a header showing the selected component's type and id. */ + readonly showHeader = input(false); + + /** Whether to render emitted validation/status messages inline inside the editor. */ + readonly showStatus = input(false); + + /** Emits the updated component record when a property is updated or removed. */ + readonly componentChange = output>(); + + /** Emits a status or validation message when an edit requires user feedback. */ + readonly statusMessage = output(); + + protected readonly idPrefix = `property-editor-${nextPropertyEditorId++}-`; + protected readonly formatJson = formatJson; + protected readonly describeUneditableValue = describeUneditableValue; + + private readonly catalogSignature: Signal = computed(() => { + const catalog = + this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); + return catalog ? stableStringify(catalog) : null; + }); + + private readonly resolvedComponentKey: Signal = computed(() => { + const typeName = this.component()?.['component']; + return typeof typeName === 'string' && typeName ? typeName : null; + }); + + private readonly resolvedComponentId: Signal = computed(() => { + const rawId = this.component()?.['id']; + return typeof rawId === 'string' ? rawId.trim() || null : null; + }); + + /** + * Memoized schema resolver and shared property names, computed once per active catalog. + */ + private readonly activeCatalogResolver: Signal<{ + resolver: CatalogSchemaResolver; + common: Set; + } | null> = computed(() => { + const catalog = + this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); + if (!catalog) { + return null; + } + const resolver = new CatalogSchemaResolver(catalog, this.errorLogger); + return { + resolver, + common: this.commonPropertyNames(resolver, catalog), + }; + }); + + /** + * Memoized property schemas for the active component so keystrokes don't re-resolve schemas. + */ + private readonly selectedComponentSchemas: Signal> = + computed(() => { + const key = this.resolvedComponentKey(); + const resolved = this.activeCatalogResolver(); + return key && resolved ? resolved.resolver.resolveComponentPropertiesSchema(key) : {}; + }); + + private readonly resolvedProperties: Signal = computed(() => { + const explicitProperties = this.properties(); + if (explicitProperties) { + return explicitProperties; + } + const key = this.resolvedComponentKey(); + const resolved = this.activeCatalogResolver(); + return key && resolved ? resolved.resolver.resolveComponentProperties(key) : []; + }); + + private readonly contextIdentity: Signal = computed(() => { + const target = this.component(); + return JSON.stringify([ + this.catalogSignature(), + this.resolvedComponentKey(), + target?.['id'] ?? null, + this.resetKey(), + ]); + }); + + /** + * `jsonFieldErrors` tracks invalid per-property JSON edits keyed by property path, + * automatically resetting to `{}` whenever the component context identity changes. + */ + protected readonly jsonFieldErrors: WritableSignal>> = + linkedSignal({ + source: this.contextIdentity, + computation: (): Partial> => ({}), + }); + + /** + * Latest status or validation message emitted by the editor, resetting when the + * component context identity changes. + */ + protected readonly inlineStatusMessage: WritableSignal = linkedSignal({ + source: this.contextIdentity, + computation: () => '', + }); + + /** Type and optional id of the active component for the optional header. */ + protected readonly componentHeader: Signal<{type: string; id: string | null} | null> = computed( + () => + this.component() + ? {type: this.resolvedComponentKey() ?? '?', id: this.resolvedComponentId()} + : null, + ); + + private readonly pendingCommit$ = new Subject>(); + + /** Uncommitted debounced text/number edit awaiting its 300ms timer or input blur. */ + private readonly pendingCommit: WritableSignal | null> = linkedSignal({ + source: () => [this.component(), this.contextIdentity(), this.disabled()] as const, + computation: (): Record | null => null, + }); + + /** + * Latest emitted component record awaiting the next change-detection pass so a sibling + * control triggered in the same frame (e.g. blur + click) doesn't overwrite a flushed edit. + */ + private readonly lastCommitted: WritableSignal | null> = linkedSignal({ + source: () => [this.component(), this.contextIdentity(), this.disabled()] as const, + computation: (): Record | null => null, + }); + + /** + * Component record read by edit mutations: layers any in-flight debounced or just-committed + * edit on top of `component()` so discrete controls or sibling fields don't lose keystrokes. + */ + private readonly activeComponent = computed( + () => this.pendingCommit() ?? this.lastCommitted() ?? this.component(), + ); + + /** + * Every catalog property of the selected component except its identity and constants. + */ + protected readonly editableProperties: Signal = computed(() => { + const target = this.component(); + const resolved = this.activeCatalogResolver(); + if (!target || !resolved) { + return []; + } + const schemas = this.selectedComponentSchemas(); + const {common} = resolved; + const properties = this.resolvedProperties().flatMap(prop => { + const schema = schemas[prop.name]; + if (prop.name === 'id' || prop.name === 'component' || schema?.['const'] !== undefined) { + return []; + } + const value = target[prop.name]; + const control = resolvePropertyControl(schema, value); + return [ + { + name: prop.name, + required: prop.required, + control, + kind: control.kind, + value, + note: describeUneditableValue(value, control), + common: !prop.required && common.has(prop.name), + firstCommon: false, + }, + ]; + }); + // Required properties first, then the component's own, then the shared ones. + const rank = (prop: EditableProperty) => (prop.required ? 0 : prop.common ? 2 : 1); + const sorted = properties + .map((prop, index) => ({prop, index})) + .sort((a, b) => rank(a.prop) - rank(b.prop) || a.index - b.index) + .map(({prop}) => prop); + const firstCommon = sorted.findIndex(prop => prop.common); + return sorted.map((prop, index) => + index === firstCommon ? {...prop, firstCommon: true} : prop, + ); + }); + + constructor() { + this.pendingCommit$ + .pipe(debounceTime(TEXT_INPUT_DEBOUNCE_MS), takeUntilDestroyed()) + .subscribe(updatedComponent => { + if (this.pendingCommit() === updatedComponent) { + this.commitPending(updatedComponent); + } + }); + } + + /** + * Clears any pending inline JSON field validation errors, status feedback, and debounced edits. + */ + clearErrors(): void { + this.pendingCommit.set(null); + this.lastCommitted.set(null); + this.jsonFieldErrors.set({}); + this.setStatusMessage(''); + } + + /** + * Emits any pending debounced text/number edit immediately (for example on input blur). + */ + protected flushPendingCommit(): void { + const pending = this.pendingCommit(); + if (pending) { + this.commitPending(pending); + } + } + + private commitPending(updatedComponent: Record) { + this.pendingCommit.set(null); + const baseline = this.lastCommitted() ?? this.component(); + if (!baseline || stableStringify(updatedComponent) === stableStringify(baseline)) { + return; + } + this.emitComponentChange(updatedComponent); + } + + private emitComponentChange(updatedComponent: Record) { + this.lastCommitted.set(updatedComponent); + this.componentChange.emit(updatedComponent); + afterNextRender( + () => { + if (this.lastCommitted() === updatedComponent) { + this.lastCommitted.set(null); + } + }, + {injector: this.injector}, + ); + } + + /** + * Property names every component in the catalog declares. + */ + private commonPropertyNames(resolver: CatalogSchemaResolver, catalog: Catalog): Set { + const names = Object.keys(catalog.components ?? {}); + if (names.length < 2) { + return new Set(); + } + const [first, ...rest] = names.map( + name => new Set(Object.keys(resolver.resolveComponentPropertiesSchema(name))), + ); + return new Set([...first].filter(prop => rest.every(set => set.has(prop)))); + } + + /** + * Returns the array's elements for `@for` if it is set in the sample, or an empty + * list when an optional array property is unset (`undefined`). + */ + protected ensureArray(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; + } + + protected getObjectField(value: unknown, key: string): unknown { + return value !== null && typeof value === 'object' && !Array.isArray(value) + ? (value as Record)[key] + : undefined; + } + + protected appendPath(path: PropertyPath, segment: string | number): PropertyPath { + return [...path, segment]; + } + + /** + * Sets one property on the target component, or removes it when value is undefined. + */ + protected editProperty(name: string, value: unknown, options: EditOptions = {}): string | null { + const {emitStatus = true, debounce = false} = options; + const target = this.activeComponent(); + if (!target || this.disabled()) { + return null; + } + if (value === undefined) { + this.jsonFieldErrors.update(errors => + Object.fromEntries( + Object.entries(errors).filter(([key]) => key !== name && !key.startsWith(`${name}.`)), + ), + ); + } + this.setStatusMessage(''); + const schema = this.selectedComponentSchemas()[name]; + if (value !== undefined && schema && !matchesSimpleSchema(value, schema)) { + if (debounce) { + this.pendingCommit.set(null); + } + const componentId = this.resolvedComponentId() ?? this.resolvedComponentKey() ?? 'target'; + const reason = `"${name}" on "${componentId}" does not match its catalog property type or choices.`; + if (emitStatus) { + this.setStatusMessage(`${reason} Preview keeps its previous value.`); + } + return reason; + } + let updatedComponent: Record; + if (value !== undefined) { + updatedComponent = {...target, [name]: value}; + } else { + const {[name]: _removed, ...rest} = target; + updatedComponent = rest; + } + if (debounce) { + this.pendingCommit.set(updatedComponent); + this.pendingCommit$.next(updatedComponent); + } else { + this.pendingCommit.set(null); + this.emitComponentChange(updatedComponent); + } + return null; + } + + /** + * Updates a top-level or nested property at `path`. + */ + protected editAtPath( + path: PropertyPath, + value: unknown, + options: EditOptions = {}, + ): string | null { + if (path.length === 0) { + return null; + } + const [rootName, ...rest] = path; + if (typeof rootName !== 'string') { + return null; + } + if (rest.length === 0) { + return this.editProperty(rootName, value, options); + } + const currentRoot = this.activeComponent()?.[rootName]; + const topProp = this.editableProperties().find(prop => prop.name === rootName); + const updatedRoot = this.setDeepValue( + currentRoot, + rest, + value, + topProp?.control, + topProp?.required ?? false, + ); + return this.editProperty(rootName, updatedRoot, options); + } + + /** + * Empty optional text removes the property; required text may be empty. + */ + protected editTextAtPath(path: PropertyPath, value: string, required: boolean): void { + this.editAtPath(path, value === '' && !required ? undefined : value, {debounce: true}); + } + + /** + * Empty optional numbers remove the property; a required number keeps its value. + */ + protected editNumberAtPath( + path: PropertyPath, + value: number | null, + required: boolean, + label: string, + ): void { + if (!this.component() || this.disabled()) { + return; + } + if (value !== null && Number.isFinite(value)) { + this.editAtPath(path, value, {debounce: true}); + } else if (!required) { + this.editAtPath(path, undefined, {debounce: true}); + } else { + this.pendingCommit.set(null); + this.setStatusMessage(`Enter a number for ${label}. Preview keeps its previous value.`); + } + } + + private setStatusMessage(message: string): void { + this.inlineStatusMessage.set(message); + this.statusMessage.emit(message); + } + + /** + * Parses a structured JSON property; invalid JSON stays in its field and leaves the draft alone. + */ + protected editJsonAtPath( + path: PropertyPath, + pathKey: string, + required: boolean, + label: string, + text: string, + ): void { + if (!this.component() || this.disabled()) { + return; + } + const setError = (message: string) => { + this.jsonFieldErrors.update(errors => ({...errors, [pathKey]: {text, message}})); + }; + let value: unknown; + if (!text.trim()) { + if (required) { + this.setStatusMessage(''); + setError(`${label} is required.`); + return; + } + value = undefined; + } else { + try { + value = JSON.parse(text); + } catch { + this.setStatusMessage(''); + setError('Invalid JSON. The example keeps its previous value.'); + return; + } + } + const error = this.editAtPath(path, value, {emitStatus: false}); + if (error) { + setError(`${error} The example keeps its previous value.`); + return; + } + this.jsonFieldErrors.update(({[pathKey]: _cleared, ...errors}) => errors); + } + + /** + * Adds an entry to an array property: duplicates the latest entry if non-empty, or creates + * a brand-new item based on the array's item control type when empty. + */ + protected addArrayItem(path: PropertyPath, itemControl: PropertyControl | undefined): void { + const current = this.getValueAtPath(path); + const items = Array.isArray(current) ? current : []; + const nextItem = + items.length > 0 + ? structuredClone(items[items.length - 1]) + : createDefaultPropertyValue(itemControl); + this.editAtPath(path, [...items, nextItem]); + } + + /** + * Deletes the item at `index` from the array at `path`. + */ + protected removeArrayItem(path: PropertyPath, index: number): void { + const current = this.getValueAtPath(path); + if (!Array.isArray(current)) { + return; + } + const prefix = `${path.map(String).join('.')}.`; + this.jsonFieldErrors.update(errors => + Object.fromEntries(Object.entries(errors).filter(([key]) => !key.startsWith(prefix))), + ); + this.editAtPath( + path, + current.filter((_, idx) => idx !== index), + ); + } + + /** + * Deep-gets a value from the editable component by the property path. + */ + private getValueAtPath(path: PropertyPath): unknown { + let current: unknown = this.activeComponent(); + for (const segment of path) { + if (typeof segment === 'number') { + if (!Array.isArray(current)) { + return undefined; + } + current = current[segment]; + } else { + if (current === null || typeof current !== 'object' || Array.isArray(current)) { + return undefined; + } + current = (current as Record)[segment]; + } + } + return current; + } + + /** + * Deep-sets a value into the editable component at `path`, + * pruning optional branches that become empty. + */ + private setDeepValue( + current: unknown, + path: PropertyPath, + value: unknown, + control?: PropertyControl, + required = false, + ): unknown { + if (path.length === 0) { + return value; + } + const [head, ...tail] = path; + if (typeof head === 'number') { + const nextArray = Array.isArray(current) ? [...current] : []; + nextArray[head] = this.setDeepValue(nextArray[head], tail, value, control?.itemControl, true); + return nextArray; + } + const nextObject: Record = + current !== null && typeof current === 'object' && !Array.isArray(current) + ? {...(current as Record)} + : {}; + const subProp = control?.properties?.find(prop => prop.name === head); + const nextValue = this.setDeepValue( + nextObject[head], + tail, + value, + subProp?.control, + subProp?.required ?? false, + ); + if (nextValue === undefined) { + delete nextObject[head]; + } else { + nextObject[head] = nextValue; + } + if (!required && Object.keys(nextObject).length === 0) { + return undefined; + } + return nextObject; + } +} diff --git a/shell/src/app/shared/property-editor/test/property-editor.harness.ts b/shell/src/app/shared/property-editor/test/property-editor.harness.ts new file mode 100644 index 000000000..dcc810ad3 --- /dev/null +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -0,0 +1,298 @@ +/** + * 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} from '@angular/cdk/testing'; +import {MatSlideToggleHarness} from '@angular/material/slide-toggle/testing'; + +/** + * Test harness for the standalone PropertyEditor component. + */ +export class PropertyEditorHarness extends ComponentHarness { + static hostSelector = 'a2ui-composer-property-editor'; + + /** + * Edits a supported literal property using its visible control and blurs it to commit immediately. + */ + async editProperty(name: string, value: string): Promise { + await this.typeProperty(name, value); + await this.blurProperty(name); + } + + /** + * Types into a supported literal property control without blurring, leaving debounced edits pending. + */ + async typeProperty(name: string, value: string): Promise { + const input = await this.locatorFor(`[data-property="${name}"]`)(); + await input.setInputValue(value); + await input.dispatchEvent('input'); + } + + /** + * Blurs a supported literal property control to flush any pending debounced edit. + */ + async blurProperty(name: string): Promise { + const input = await this.locatorFor(`[data-property="${name}"]`)(); + await input.dispatchEvent('blur'); + } + + /** + * Reads the current DOM input value of a supported literal property control. + */ + async getPropertyValue(name: string): Promise { + return (await this.locatorFor(`[data-property="${name}"]`)()).getProperty('value'); + } + + /** + * Selects a literal enum option using the native form control. + */ + async selectPropertyOption(name: string, index: number): Promise { + const select = await this.locatorFor(`[data-property="${name}"]`)(); + await select.selectOptions(index); + await select.dispatchEvent('change'); + } + + /** + * Reads the option labels of an enum property, including "(not set)" when optional. + */ + async getPropertyOptions(name: string): Promise { + const options = await this.locatorForAll(`select[data-property="${name}"] option`)(); + return Promise.all(options.map(option => option.text())); + } + + /** + * Toggles a boolean property through its slide toggle. + */ + async toggleProperty(name: string): Promise { + const toggle = await this.locatorFor( + MatSlideToggleHarness.with({selector: `[data-property="${name}"]`}), + )(); + await toggle.toggle(); + } + + /** + * Lists the property section headings in display order. + */ + async getPropertySectionHeadings(): Promise { + const headings = await this.locatorForAll('.property-section-heading')(); + return Promise.all(headings.map(async heading => (await heading.text()).trim())); + } + + /** + * Lists the editable property names in display order. + */ + async getPropertyNames(): Promise { + const names = await this.locatorForAll('.property-name > span:first-child')(); + return Promise.all(names.map(name => name.text())); + } + + /** + * Reads which kind of control a property renders: array, object, select, checkbox, number, text or json. + */ + async getPropertyControlKind(name: string): Promise { + if (await this.locatorForOptional(`[data-property-array="${name}"]`)()) { + return 'array'; + } + if (await this.locatorForOptional(`[data-property-object="${name}"]`)()) { + return 'object'; + } + const control = await this.locatorForOptional(`[data-property="${name}"]`)(); + if (!control) { + return null; + } + const tagName = await control.getProperty('tagName'); + if (tagName === 'TEXTAREA') { + return 'json'; + } + if (tagName === 'SELECT') { + return 'select'; + } + if (tagName === 'MAT-SLIDE-TOGGLE') { + return 'checkbox'; + } + return control.getAttribute('type'); + } + + /** + * Returns the number of rendered rows in an array property control. + */ + async getArrayItemCount(name: string): Promise { + const items = await this.locatorForAll(`[data-property-array="${name}"] > .array-item-row`)(); + return items.length; + } + + /** + * Clicks the Add Entry button for an array property control. + */ + async addArrayItem(name: string): Promise { + await (await this.locatorFor(`[data-add-array-item="${name}"]`)()).click(); + } + + /** + * Clicks the Delete button for an item at `index` in an array property control. + */ + async deleteArrayItem(name: string, index: number): Promise { + await (await this.locatorFor(`[data-delete-array-item="${name}.${index}"]`)()).click(); + } + + /** + * Lists the nested sub-property names rendered inside an object control. + */ + async getObjectPropertyNames(name: string): Promise { + const labels = await this.locatorForAll( + `[data-property-object="${name}"] > .object-property-field > .object-property-label > span:first-child`, + )(); + return Promise.all(labels.map(label => label.text())); + } + + /** + * Whether a property shows the "required" marker. + */ + async isPropertyRequired(name: string): Promise { + return !!(await this.locatorForOptional( + `[data-property-row="${name}"] > .property-name .required-marker`, + )()); + } + + /** + * Whether a property offers a remove action. + */ + async canRemoveProperty(name: string): Promise { + return !!(await this.locatorForOptional(`[data-remove-property="${name}"]`)()); + } + + /** + * Removes an optional property through its remove action. + */ + async removeProperty(name: string): Promise { + await (await this.locatorFor(`[data-remove-property="${name}"]`)()).click(); + } + + /** + * Replaces a structured property's JSON and commits it like a blur would. + */ + async editJsonProperty(name: string, text: string): Promise { + const field = await this.locatorFor(`textarea[data-property="${name}"]`)(); + await field.setInputValue(text); + await field.dispatchEvent('change'); + } + + /** + * Reads the text shown in a structured property's JSON field. + */ + async getJsonPropertyText(name: string): Promise { + return (await this.locatorFor(`textarea[data-property="${name}"]`)()).getProperty( + 'value', + ); + } + + /** + * Reads the inline error under a property, if any. + */ + async getPropertyError(name: string): Promise { + const error = await this.locatorForOptional(`[data-property-error="${name}"]`)(); + return error ? error.text() : null; + } + + /** + * Reads the read-only note shown for a bound or computed value, if any. + */ + async getPropertyNote(name: string): Promise { + const note = await this.locatorForOptional(`[data-property-note="${name}"]`)(); + return note ? note.text() : null; + } + + /** + * Reads the `for` attribute of a top-level or nested object property's label. + */ + async getPropertyLabelFor(name: string): Promise { + const label = await this.locatorFor( + `[data-property-row="${name}"] > .property-name, [data-object-property="${name}"] > .object-property-label`, + )(); + return label.getAttribute('for'); + } + + /** + * Reads the DOM `id` of a property's form control, if rendered. + */ + async getPropertyControlId(name: string): Promise { + const control = await this.locatorForOptional(`[data-property="${name}"]`)(); + return control ? control.getAttribute('id') : null; + } + + /** + * Reads the `aria-describedby` attribute of a property's form control, if set. + */ + async getPropertyAriaDescribedBy(name: string): Promise { + const control = await this.locatorForOptional(`[data-property="${name}"]`)(); + return control ? control.getAttribute('aria-describedby') : null; + } + + /** + * Reads the DOM `id` of a property's inline error element, if rendered. + */ + async getPropertyErrorId(name: string): Promise { + const error = await this.locatorForOptional(`[data-property-error="${name}"]`)(); + return error ? error.getAttribute('id') : null; + } + + /** + * Whether a required property is flagged as missing from the example. + */ + async isPropertyMissing(name: string): Promise { + return (await this.locatorForOptional(`[data-property-missing="${name}"]`)()) !== null; + } + + /** + * Whether a property uses a single-line control rather than a JSON field or note. + */ + async isPropertyInline(name: string): Promise { + const row = await this.locatorFor(`[data-property-row="${name}"]`)(); + return !(await row.hasClass('property-row-multiline')); + } + + private async getOptionalText(selector: string): Promise { + const element = await this.locatorForOptional(selector)(); + return element ? (await element.text()).replace(/\s+/g, ' ').trim() : null; + } + + /** + * Reads the rendered component header (`Type #id`), or null when hidden or no component is set. + */ + async getHeaderText(): Promise { + return this.getOptionalText('[data-property-header]'); + } + + /** + * Whether the inline `role="status"` live region container is mounted. + */ + async hasStatusLiveRegion(): Promise { + return (await this.locatorForOptional('[role="status"]')()) !== null; + } + + /** + * Reads the inline status message rendered by the editor, if any. + */ + async getStatusText(): Promise { + return this.getOptionalText('[data-property-status]'); + } + + /** + * Reads the empty-state placeholder message when no editable properties are rendered, if any. + */ + async getEmptyStateText(): Promise { + return this.getOptionalText('[data-property-empty-state]'); + } +} diff --git a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts index 9956447d1..176f76fc5 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -21,14 +21,21 @@ import { ComponentRef, Type, ChangeDetectorRef, + Binding, OutputRefSubscription, inject, + inputBinding, + linkedSignal, + outputBinding, + signal, } from '@angular/core'; import {ErrorLogger} from '../../debug/error-logger.service'; -import {DockviewComponent} from 'dockview-core'; +import {AddPanelOptions, DockviewComponent} from 'dockview-core'; import {LocalStorageInteractions} from '../../storage/local-storage-interactions/local-storage-interactions'; import {LocalStorageKey} from '../../storage/models/local-storage-keys'; import {CHAT_PANEL_COMPONENT} from '../../chat/chat-panel/chat-panel-component.token'; +import {ChatState} from '../../chat/chat-state/chat-state'; +import {StateSync} from '../../chat/state-sync/state-sync'; import {RawFrame} from '../../preview/raw/raw-frame'; import {RenderedFrame, RenderedFrameSizing} from '../../preview/rendered/rendered-frame'; import {DefaultTarget} from '../host-communication/host-communication'; @@ -36,6 +43,8 @@ import {DataModel} from '../../debug/data-model/data-model'; import {Events} from '../../debug/events/events'; import {Errors} from '../../debug/errors/errors'; import {RawMessages} from '../../debug/raw-messages/raw-messages'; +import {ComponentTree} from '../../debug/component-tree/component-tree'; +import {PropertyEditor} from '../../shared/property-editor/property-editor'; import {PendingRpcRegistry} from '../../debug/events/pending-rpc-registry'; import {ComposerPanelId} from './composer-panel-id'; @@ -104,12 +113,12 @@ export interface DockviewManagerInitOptions { * * Layout Architecture: * - **Gemini Assistant (Chat)**: Left vertical panel, constrained initially to <= 1/3 viewport width. - * - **Rendered A2UI Preview & A2UI JSON Editor**: Central workspace area split to the right of Chat. - * Both panels share the same tab group (`direction: 'within'`), with "Rendered A2UI Preview" - * active by default and "A2UI JSON Editor" tabbed behind it (`inactive: true`). + * - **Rendered A2UI Preview, A2UI JSON Editor & Component Tree**: Central workspace area split to the + * right of Chat. All three panels share the same tab group (`direction: 'within'`), with + * "Rendered A2UI Preview" active by default and the others tabbed behind it (`inactive: true`). * - **Debug Drawer**: Bottom drawer positioned below the Preview (`direction: 'below'`), occupying ~28% - * of container height. Combines "Data Model" (initially active), "Events", "Errors", and "Raw Messages" - * in a single tabbed group (`direction: 'within'`, `inactive: true`). + * of container height. Combines "Data Model" (initially active), "Events", "Errors", "Raw Messages", + * and "Property Editor" in a single tabbed group (`direction: 'within'`, `inactive: true`). */ @Injectable() export class ComposerDockview { @@ -119,6 +128,8 @@ export class ComposerDockview { private readonly viewContainerRef = inject(ViewContainerRef); private readonly cdr = inject(ChangeDetectorRef); private readonly chatPanelComponent = inject(CHAT_PANEL_COMPONENT); + private readonly chatState = inject(ChatState); + private readonly stateSync = inject(StateSync); private readonly pendingRpcRegistry = inject(PendingRpcRegistry, {optional: true}); private rootEl?: HTMLElement; @@ -131,6 +142,25 @@ export class ComposerDockview { private eventsInstance?: Events; private errorsInstance?: Errors; private renderedFrameInstance?: RenderedFrame; + private readonly componentTreeInstance = signal(undefined); + private readonly lastPropertyEdit = signal<{readonly draft: string} | null>(null); + private readonly draftRevision = linkedSignal({ + source: () => ({ + draft: this.stateSync.activeDraft(), + resetNonce: this.stateSync.sessionResetNonce(), + propertyEdit: this.lastPropertyEdit(), + }), + computation: (current, previous): number => { + if (!previous) return 0; + const isOwnPropertyEdit = + current.propertyEdit !== previous.source.propertyEdit && + current.propertyEdit?.draft === current.draft; + const shouldBump = + current.resetNonce !== previous.source.resetNonce || + (current.draft !== previous.source.draft && !isOwnPropertyEdit); + return shouldBump ? previous.value + 1 : previous.value; + }, + }); private resizeObserver?: ResizeObserver; private animationFrameId?: number; @@ -361,6 +391,7 @@ export class ComposerDockview { */ private createPanelComponent(panelId: ComposerPanelId) { let type: Type | undefined; + let bindings: Binding[] | undefined; switch (panelId) { case ComposerPanelId.Chat: type = this.chatPanelComponent; @@ -383,6 +414,13 @@ export class ComposerDockview { case ComposerPanelId.RawMessages: type = RawMessages; break; + case ComposerPanelId.ComponentTree: + type = ComponentTree; + break; + case ComposerPanelId.PropertyEditor: + type = PropertyEditor; + bindings = this.getPropertyEditorBindings(); + break; } if (!type) { @@ -393,7 +431,7 @@ export class ComposerDockview { }; } - const componentRef = this.viewContainerRef.createComponent(type); + const componentRef = this.viewContainerRef.createComponent(type, {bindings}); this.componentRefs.push(componentRef); let renderStateResetSub: OutputRefSubscription | undefined; @@ -416,6 +454,9 @@ export class ComposerDockview { if (type === RawMessages) this.rawMessagesInstance = componentRef.instance as RawMessages; if (type === Events) this.eventsInstance = componentRef.instance as Events; if (type === Errors) this.errorsInstance = componentRef.instance as Errors; + if (type === ComponentTree) { + this.componentTreeInstance.set(componentRef.instance as ComponentTree); + } return { element: componentRef.location.nativeElement, @@ -445,12 +486,43 @@ export class ComposerDockview { this.renderedFrameInstance = undefined; this.options?.onPreviewPanelDisposed?.(win); } + if (componentRef.instance === this.componentTreeInstance()) { + this.componentTreeInstance.set(undefined); + } componentRef.destroy(); this.componentRefs = this.componentRefs.filter(r => r !== componentRef); }, }; } + private getPropertyEditorBindings(): Binding[] { + return [ + inputBinding('component', () => this.componentTreeInstance()?.selectedComponent() ?? null), + inputBinding('resetKey', () => { + const selected = this.componentTreeInstance()?.selected(); + return selected ? `${selected.surfaceId}:${selected.key}:${this.draftRevision()}` : null; + }), + inputBinding('disabled', () => this.chatState.isProgrammaticStreamActive()), + inputBinding('emptyMessage', () => { + const tree = this.componentTreeInstance(); + if (tree?.parseError()) { + return 'Fix the A2UI JSON to inspect component properties.'; + } + const selected = tree?.selected(); + if (selected && !tree?.selectedComponent()) { + return `Component #${selected.id} is not defined in surface "${selected.surfaceId}".`; + } + return 'Select a component to inspect its properties.'; + }), + inputBinding('showHeader', () => true), + inputBinding('showStatus', () => true), + outputBinding>('componentChange', updatedComponent => { + this.componentTreeInstance()?.updateSelectedComponent(updatedComponent); + this.lastPropertyEdit.set({draft: this.stateSync.activeDraft()}); + }), + ]; + } + /** * Retrieves the active RenderedFrame preview component instance if currently mounted. */ @@ -463,10 +535,11 @@ export class ComposerDockview { * * Layout Design: * 1. **Chat Panel (Gemini Assistant)**: Anchored left. Width <= 1/3 viewport (`chatWidth`). - * 2. **Rendered A2UI Preview & A2UI JSON Editor**: Placed right of Chat. Both are tabbed together - * (`direction: 'within'`), with Rendered active and JSON Editor `inactive: true`. + * 2. **Rendered A2UI Preview, A2UI JSON Editor & Component Tree**: Placed right of Chat. Tabbed + * together (`direction: 'within'`), with Rendered active and the others `inactive: true`. * 3. **Debug Drawer Group**: Placed below Rendered Preview (`direction: 'below'`), sized to ~28% - * container height. Houses Data Model (active), Events, Errors, and Raw Messages (`inactive: true`). + * container height. Houses Data Model (active), Events, Errors, Raw Messages, and Property Editor + * (`inactive: true`). * * @param width Viewport width in pixels. * @param height Viewport height in pixels. @@ -508,89 +581,115 @@ export class ComposerDockview { } } - if (!layoutRestored) { - const chatWidth = Math.floor(width * CHAT_PANEL_MAX_WIDTH_FRACTION); - const debugHeight = Math.round(height * DEBUG_DRAWER_HEIGHT_RATIO); - const previewHeight = height - debugHeight; - - // 1. Chat panel (Gemini Assistant) on the left - this.dockviewApi.addPanel({ - id: ComposerPanelId.Chat, - component: ComposerPanelId.Chat, - title: 'Gemini Assistant', - initialWidth: chatWidth, - minimumWidth: CHAT_PANEL_MIN_WIDTH, - }); + const chatWidth = Math.floor(width * CHAT_PANEL_MAX_WIDTH_FRACTION); + const debugHeight = Math.round(height * DEBUG_DRAWER_HEIGHT_RATIO); + const previewHeight = height - debugHeight; - // 2. Rendered preview split to the right of Chat - this.dockviewApi.addPanel({ - id: ComposerPanelId.Rendered, - component: ComposerPanelId.Rendered, - title: 'Rendered A2UI Preview', - position: {direction: 'right', referencePanel: ComposerPanelId.Chat}, - initialWidth: width - chatWidth, - initialHeight: previewHeight, - minimumWidth: PREVIEW_PANEL_MIN_WIDTH, - minimumHeight: PREVIEW_PANEL_MIN_HEIGHT, - }); + const addPanel = (options: AddPanelOptions) => { + if (!this.dockviewApi.getGroupPanel(options.id)) { + this.dockviewApi.addPanel(layoutRestored ? {...options, inactive: true} : options); + } + }; - // 3. Raw JSON editor tabbed within Rendered preview group - this.dockviewApi.addPanel({ - id: ComposerPanelId.Raw, - component: ComposerPanelId.Raw, - title: 'A2UI JSON Editor', - position: { - direction: 'within', - referencePanel: ComposerPanelId.Rendered, - }, - inactive: true, - }); + // 1. Chat panel (Gemini Assistant) on the left + addPanel({ + id: ComposerPanelId.Chat, + component: ComposerPanelId.Chat, + title: 'Gemini Assistant', + initialWidth: chatWidth, + minimumWidth: CHAT_PANEL_MIN_WIDTH, + }); - // 4. Debug drawer split below Rendered preview - this.dockviewApi.addPanel({ - id: ComposerPanelId.DataModel, - component: ComposerPanelId.DataModel, - title: 'Data Model', - position: { - direction: 'below', - referencePanel: ComposerPanelId.Rendered, - }, - initialHeight: debugHeight, - minimumHeight: DEBUG_DRAWER_MIN_HEIGHT, - }); + // 2. Rendered preview split to the right of Chat + addPanel({ + id: ComposerPanelId.Rendered, + component: ComposerPanelId.Rendered, + title: 'Rendered A2UI Preview', + position: {direction: 'right', referencePanel: ComposerPanelId.Chat}, + initialWidth: width - chatWidth, + initialHeight: previewHeight, + minimumWidth: PREVIEW_PANEL_MIN_WIDTH, + minimumHeight: PREVIEW_PANEL_MIN_HEIGHT, + }); - // 5. Secondary debug tabs placed within Data Model group - this.dockviewApi.addPanel({ - id: ComposerPanelId.Events, - component: ComposerPanelId.Events, - title: 'Events', - position: { - direction: 'within', - referencePanel: ComposerPanelId.DataModel, - }, - inactive: true, - }); - this.dockviewApi.addPanel({ - id: ComposerPanelId.Errors, - component: ComposerPanelId.Errors, - title: 'Errors', - position: { - direction: 'within', - referencePanel: ComposerPanelId.DataModel, - }, - inactive: true, - }); - this.dockviewApi.addPanel({ - id: ComposerPanelId.RawMessages, - component: ComposerPanelId.RawMessages, - title: 'Raw Messages', - position: { - direction: 'within', - referencePanel: ComposerPanelId.DataModel, - }, - inactive: true, - }); + // 3. Raw JSON editor and Component Tree tabbed within Rendered preview group + addPanel({ + id: ComposerPanelId.Raw, + component: ComposerPanelId.Raw, + title: 'A2UI JSON Editor', + position: { + direction: 'within', + referencePanel: ComposerPanelId.Rendered, + }, + inactive: true, + }); + addPanel({ + id: ComposerPanelId.ComponentTree, + component: ComposerPanelId.ComponentTree, + title: 'Component Tree', + position: { + direction: 'within', + referencePanel: ComposerPanelId.Rendered, + }, + inactive: true, + }); + // 4. Debug drawer split below Rendered preview + addPanel({ + id: ComposerPanelId.DataModel, + component: ComposerPanelId.DataModel, + title: 'Data Model', + position: { + direction: 'below', + referencePanel: ComposerPanelId.Rendered, + }, + initialHeight: debugHeight, + minimumHeight: DEBUG_DRAWER_MIN_HEIGHT, + }); + + // 5. Secondary debug tabs placed within Data Model group + addPanel({ + id: ComposerPanelId.Events, + component: ComposerPanelId.Events, + title: 'Events', + position: { + direction: 'within', + referencePanel: ComposerPanelId.DataModel, + }, + inactive: true, + }); + addPanel({ + id: ComposerPanelId.Errors, + component: ComposerPanelId.Errors, + title: 'Errors', + position: { + direction: 'within', + referencePanel: ComposerPanelId.DataModel, + }, + inactive: true, + }); + addPanel({ + id: ComposerPanelId.RawMessages, + component: ComposerPanelId.RawMessages, + title: 'Raw Messages', + position: { + direction: 'within', + referencePanel: ComposerPanelId.DataModel, + }, + inactive: true, + }); + addPanel({ + id: ComposerPanelId.PropertyEditor, + component: ComposerPanelId.PropertyEditor, + title: 'Property Editor', + position: { + direction: 'within', + referencePanel: ComposerPanelId.DataModel, + }, + inactive: true, + }); + + if (!layoutRestored) { // Explicitly activate default primary tabs for each panel group. // Secondary tabs were appended to their groups above, so activating the // default primary panels here cleanly executes Dockview's doSetActivePanel diff --git a/shell/src/app/shell/composer-workspace/composer-panel-id.ts b/shell/src/app/shell/composer-workspace/composer-panel-id.ts index 26f3f5a89..c6c420143 100644 --- a/shell/src/app/shell/composer-workspace/composer-panel-id.ts +++ b/shell/src/app/shell/composer-workspace/composer-panel-id.ts @@ -25,6 +25,8 @@ export enum ComposerPanelId { Events = 'events', Errors = 'errors', RawMessages = 'rawMessages', + ComponentTree = 'componentTree', + PropertyEditor = 'propertyEditor', } /** diff --git a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts index 13b7d0472..a7da33b3b 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -51,6 +51,9 @@ import {ChatPanel} from '../../chat/chat-panel/chat-panel'; import {RenderedFrame} from '../../preview/rendered/rendered-frame'; import {RawFrame} from '../../preview/raw/raw-frame'; import {DataModel} from '../../debug/data-model/data-model'; +import {ComponentTree} from '../../debug/component-tree/component-tree'; +import {ComponentTreeNode} from '../../debug/component-tree/component-tree-builder'; +import {PropertyEditor} from '../../shared/property-editor/property-editor'; import {PendingRpcRegistry} from '../../debug/events/pending-rpc-registry'; class MockChatState { @@ -158,12 +161,14 @@ describe('ComposerWorkspace Dashboard', () => { // so we verify they were instantiated by the Angular view container. const manager = fixture.debugElement.injector.get(ComposerDockview); const refs = manager.dynamicComponentRefs; - expect(refs.length).toBe(7); + expect(refs.length).toBe(9); const types = refs.map(r => r.componentType); expect(types).toContain(ChatPanel); expect(types).toContain(RenderedFrame); expect(types).toContain(RawFrame); + expect(types).toContain(ComponentTree); expect(types).toContain(DataModel); + expect(types).toContain(PropertyEditor); }); it('sizes the docked Rendered panel frame to fill its panel and replace the default target', () => { @@ -672,6 +677,45 @@ describe('ComposerWorkspace Dashboard', () => { expect(errorSpy).not.toHaveBeenCalled(); }); + it('adds missing panels as inactive tabs at their default positions when restoring an older layout', async () => { + const manager = fixture.debugElement.injector.get(ComposerDockview); + const errorSpy = vi.spyOn(TestBed.inject(ErrorLogger), 'error'); + manager.setPanelTitle(ComposerPanelId.Rendered, 'My preview'); + manager.openPanel(ComposerPanelId.Events); + const componentTreePanel = manager.api.getGroupPanel(ComposerPanelId.ComponentTree); + const propertyEditorPanel = manager.api.getGroupPanel(ComposerPanelId.PropertyEditor); + expect(componentTreePanel).toBeDefined(); + expect(propertyEditorPanel).toBeDefined(); + manager.api.removePanel(componentTreePanel!); + manager.api.removePanel(propertyEditorPanel!); + + const legacyLayout = manager.api.toJSON(); + expect(legacyLayout.panels[ComposerPanelId.ComponentTree]).toBeUndefined(); + expect(legacyLayout.panels[ComposerPanelId.PropertyEditor]).toBeUndefined(); + fixture.destroy(); + storage.setItem(LocalStorageKey.DOCKVIEW_LAYOUT, JSON.stringify(legacyLayout)); + + const restored = await returnToWorkspace(); + const restoredRendered = restored.api.getGroupPanel(ComposerPanelId.Rendered); + const restoredDataModel = restored.api.getGroupPanel(ComposerPanelId.DataModel); + const restoredComponentTree = restored.api.getGroupPanel(ComposerPanelId.ComponentTree); + const restoredPropertyEditor = restored.api.getGroupPanel(ComposerPanelId.PropertyEditor); + + expect(restoredRendered?.title).toBe('My preview'); + expect(restoredRendered?.group.activePanel?.id).toBe(ComposerPanelId.Rendered); + expect(restored.api.getGroupPanel(ComposerPanelId.Events)?.api.isActive).toBe(true); + expect(restoredComponentTree).toBeDefined(); + expect(restoredComponentTree?.group).toBe(restoredRendered?.group); + expect(restored.isPanelVisible(ComposerPanelId.ComponentTree)).toBe(false); + expect(restoredPropertyEditor).toBeDefined(); + expect(restoredPropertyEditor?.group).toBe(restoredDataModel?.group); + expect(restored.isPanelVisible(ComposerPanelId.PropertyEditor)).toBe(false); + expect(restored.api.panels.map(panel => panel.id).sort()).toEqual( + Object.values(ComposerPanelId).sort(), + ); + expect(errorSpy).not.toHaveBeenCalled(); + }); + it.each(['retired panel', 'mismatched panel ID'])( 'rejects a layout with a %s and opens usable default panels', async invalidState => { @@ -1011,6 +1055,7 @@ describe('ComposerWorkspace Dashboard', () => { ComposerPanelId.Events, ComposerPanelId.Errors, ComposerPanelId.RawMessages, + ComposerPanelId.PropertyEditor, ]); expect(debugGroup.activePanel?.id).toBe(ComposerPanelId.DataModel); }); @@ -1129,7 +1174,7 @@ describe('ComposerWorkspace Dashboard', () => { expect(dataModelPanel!.group.activePanel?.id).toBe(ComposerPanelId.DataModel); expect(chatPanel!.group.activePanel?.id).toBe(ComposerPanelId.Chat); - // Check all 7 panels exist + // Check all 9 default panels exist expect(manager.api.panels.map(p => p.id).sort()).toEqual( Object.values(ComposerPanelId).sort(), ); @@ -1139,5 +1184,233 @@ describe('ComposerWorkspace Dashboard', () => { expect(dataModelPanel!.group.height).toBeLessThan(renderedPanel!.group.height); }); }); + + describe('Property Editor Panel', () => { + const TITLE_NODE: ComponentTreeNode = { + key: 's/root/0:title', + id: 'title', + type: 'Text', + via: 'children', + status: 'ok', + shared: false, + template: null, + children: [], + }; + + let stateSync: MockStateSync; + let manager: ComposerDockview; + let componentTree: ComponentTree; + let propertyEditor: PropertyEditor; + + beforeEach(() => { + stateSync = TestBed.inject(StateSync) as unknown as MockStateSync; + stateSync.activeDraftSignal.set( + JSON.stringify([ + {version: 'v0.9', createSurface: {surfaceId: 's', catalogId: 'basic'}}, + { + version: 'v0.9', + updateComponents: { + surfaceId: 's', + components: [ + {id: 'root', component: 'Column', children: ['title']}, + {id: 'title', component: 'Text', text: 'Hello'}, + ], + }, + }, + ]), + ); + fixture.detectChanges(); + + manager = fixture.debugElement.injector.get(ComposerDockview); + componentTree = manager.dynamicComponentRefs.find( + ref => ref.componentType === ComponentTree, + )!.instance as ComponentTree; + propertyEditor = manager.dynamicComponentRefs.find( + ref => ref.componentType === PropertyEditor, + )!.instance as PropertyEditor; + }); + + it('activates the Property Editor panel and binds the selected component when a tree node is selected', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + + const propertyEditorPanel = manager.api.getGroupPanel(ComposerPanelId.PropertyEditor); + expect(propertyEditorPanel?.group.activePanel?.id).toBe(ComposerPanelId.PropertyEditor); + expect(propertyEditor.resetKey()).toBe('s:s/root/0:title:0'); + expect(propertyEditor.showHeader()).toBe(true); + expect(propertyEditor.showStatus()).toBe(true); + expect(propertyEditor.component()).toEqual({ + id: 'title', + component: 'Text', + text: 'Hello', + }); + }); + + it('updates the active draft when Property Editor emits componentChange', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + + propertyEditor.componentChange.emit({ + id: 'title', + component: 'Text', + text: 'Updated', + }); + fixture.detectChanges(); + + const updatedDraft = JSON.parse(stateSync.activeDraft()); + expect(updatedDraft[1].updateComponents.components[1]).toEqual({ + id: 'title', + component: 'Text', + text: 'Updated', + }); + }); + + it('changes resetKey when switching between occurrences of a shared component', () => { + stateSync.activeDraftSignal.set( + JSON.stringify([ + {version: 'v0.9', createSurface: {surfaceId: 's', catalogId: 'basic'}}, + { + version: 'v0.9', + updateComponents: { + surfaceId: 's', + components: [ + {id: 'root', component: 'Column', children: ['title', 'title']}, + {id: 'title', component: 'Text', text: 'Hello'}, + ], + }, + }, + ]), + ); + fixture.detectChanges(); + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + const firstResetKey = propertyEditor.resetKey(); + + componentTree.selectNode('s', {...TITLE_NODE, key: 's/root/1:title'}); + fixture.detectChanges(); + + expect(propertyEditor.resetKey()).not.toBe(firstResetKey); + }); + + it('changes resetKey when the active draft is modified externally', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + const initialResetKey = propertyEditor.resetKey(); + + stateSync.activeDraftSignal.set( + JSON.stringify([ + {version: 'v0.9', createSurface: {surfaceId: 's', catalogId: 'basic'}}, + { + version: 'v0.9', + updateComponents: { + surfaceId: 's', + components: [ + {id: 'root', component: 'Column', children: ['title']}, + {id: 'title', component: 'Text', text: 'External edit'}, + ], + }, + }, + ]), + ); + fixture.detectChanges(); + + expect(propertyEditor.resetKey()).not.toBe(initialResetKey); + }); + + it('keeps resetKey unchanged on Property Editor edits while still bumping on later external edits', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + const initialDraft = stateSync.activeDraft(); + const initialResetKey = propertyEditor.resetKey(); + + propertyEditor.componentChange.emit({ + id: 'title', + component: 'Text', + text: 'Edited in panel', + }); + fixture.detectChanges(); + const componentAfterPropertyEdit = propertyEditor.component(); + const propertyEditedDraft = stateSync.activeDraft(); + const resetKeyAfterPropertyEdit = propertyEditor.resetKey(); + + stateSync.activeDraftSignal.set(initialDraft); + fixture.detectChanges(); + const resetKeyAfterExternalEdit = propertyEditor.resetKey(); + + stateSync.activeDraftSignal.set(propertyEditedDraft); + fixture.detectChanges(); + const resetKeyAfterExternalRevert = propertyEditor.resetKey(); + + expect(componentAfterPropertyEdit).toEqual({ + id: 'title', + component: 'Text', + text: 'Edited in panel', + }); + expect(resetKeyAfterPropertyEdit).toBe(initialResetKey); + expect(resetKeyAfterExternalEdit).not.toBe(initialResetKey); + expect(resetKeyAfterExternalRevert).not.toBe(resetKeyAfterExternalEdit); + }); + + it('changes resetKey when the session resets even if the draft text is unchanged', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + const initialResetKey = propertyEditor.resetKey(); + + stateSync.sessionResetNonce.update(count => count + 1); + fixture.detectChanges(); + + expect(propertyEditor.resetKey()).not.toBe(initialResetKey); + expect(propertyEditor.emptyMessage()).toBe('Select a component to inspect its properties.'); + }); + + it('shows a missing-component emptyMessage when a selected node is not defined in the surface', () => { + componentTree.selectNode('s', { + ...TITLE_NODE, + key: 's/root/0:ghost', + id: 'ghost', + type: null, + status: 'missing', + }); + fixture.detectChanges(); + + expect(propertyEditor.component()).toBeNull(); + expect(propertyEditor.emptyMessage()).toBe( + 'Component #ghost is not defined in surface "s".', + ); + }); + + it('shows an invalid-JSON emptyMessage when the active draft fails to parse', () => { + componentTree.selectNode('s', TITLE_NODE); + fixture.detectChanges(); + + stateSync.activeDraftSignal.set('{invalid'); + fixture.detectChanges(); + + expect(propertyEditor.component()).toBeNull(); + expect(propertyEditor.emptyMessage()).toBe( + 'Fix the A2UI JSON to inspect component properties.', + ); + }); + + it('disables the Property Editor when a programmatic stream starts', () => { + const chatState = TestBed.inject(ChatState) as unknown as MockChatState; + + chatState.setProgrammaticStreamActive(true); + fixture.detectChanges(); + + expect(propertyEditor.disabled()).toBe(true); + }); + + it('re-enables the Property Editor when a programmatic stream ends', () => { + const chatState = TestBed.inject(ChatState) as unknown as MockChatState; + chatState.setProgrammaticStreamActive(true); + fixture.detectChanges(); + + chatState.setProgrammaticStreamActive(false); + fixture.detectChanges(); + + expect(propertyEditor.disabled()).toBe(false); + }); + }); }); }); diff --git a/shell/src/global_styles.scss b/shell/src/global_styles.scss index 8a065ea52..347f87c21 100644 --- a/shell/src/global_styles.scss +++ b/shell/src/global_styles.scss @@ -316,3 +316,11 @@ body .dv-dockview .dv-watermark-container { pointer-events: auto !important; } } + +// Component Tree panel tooltips can span multiple lines; they render in the +// global CDK overlay, so their styles must be global. +.component-tree-tooltip .mdc-tooltip__surface { + max-width: 640px; + white-space: pre-line; + text-align: left; +}