From 28c1a764a77b9ef3b678426860e7edd2bf788c26 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 11 Nov 2026 14:09:26 -0800 Subject: [PATCH 01/50] Extract property editor to a standalone component --- shell/src/app/gallery/gallery-example.spec.ts | 196 +------ shell/src/app/gallery/gallery-example.ts | 347 +----------- shell/src/app/gallery/gallery.ng.html | 274 +-------- shell/src/app/gallery/gallery.scss | 192 ------- shell/src/app/gallery/gallery.ts | 407 +------------- .../property-editor/property-editor-utils.ts | 368 ++++++++++++ .../property-editor/property-editor.ng.html | 253 +++++++++ .../property-editor/property-editor.scss | 212 +++++++ .../property-editor/property-editor.spec.ts | 483 ++++++++++++++++ .../shared/property-editor/property-editor.ts | 530 ++++++++++++++++++ .../test/property-editor.harness.ts | 222 ++++++++ 11 files changed, 2105 insertions(+), 1379 deletions(-) create mode 100644 shell/src/app/shared/property-editor/property-editor-utils.ts create mode 100644 shell/src/app/shared/property-editor/property-editor.ng.html create mode 100644 shell/src/app/shared/property-editor/property-editor.scss create mode 100644 shell/src/app/shared/property-editor/property-editor.spec.ts create mode 100644 shell/src/app/shared/property-editor/property-editor.ts create mode 100644 shell/src/app/shared/property-editor/test/property-editor.harness.ts 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..cf95bee7e 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-editor-utils'; +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..1f6345dbb 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. +

+ } +
+ } + +} + + @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..2d949c236 --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.scss @@ -0,0 +1,212 @@ +/** + * 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; + min-width: 0; +} + +// One property per row: property name stacked on top of its UI control. +.property-list { + display: flex; + flex-direction: column; + margin-bottom: 20px; +} + +.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-missing { + grid-column: 1 / -1; + margin: 0; + color: var(--mat-sys-error); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); +} + +.property-error { + grid-column: 1 / -1; + margin: 0; + color: var(--mat-sys-error); + font: var(--mat-sys-body-small); + letter-spacing: var(--mat-sys-body-small-tracking); +} + +.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..eca75443d --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -0,0 +1,483 @@ +/** + * 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 {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; +import {provideNoopAnimations} from '@angular/platform-browser/animations'; +import {signal} from '@angular/core'; +import {describe, it, expect, beforeEach, vi} from 'vitest'; +import {PropertyEditor, PropertyChangeEvent} from './property-editor'; +import { + createDefaultPropertyValue, + describeUneditableValue, + resolvePropertyControl, +} from './property-editor-utils'; +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); +} + +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}, + }, + }, + ], + }, + }, +}; + +describe('PropertyEditor Component', () => { + let fixture: ComponentFixture; + let harness: PropertyEditorHarness; + let catalogManagementMock: MockCatalogManagement; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [PropertyEditor], + providers: [ + provideNoopAnimations(), + {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']); + }); + + it('resolves properties using explicit catalog and componentKey inputs when provided', async () => { + catalogManagementMock.activeCatalog.set(null); + fixture.componentRef.setInput('catalog', jsonCatalog); + fixture.componentRef.setInput('componentKey', 'StyledBox'); + fixture.componentRef.setInput('component', { + id: 'box-override', + style: {padding: 8}, + }); + fixture.detectChanges(); + + expect(await harness.getPropertyNames()).toEqual(['style', 'weight']); + }); + + it('blocks property edits when disabled input is true', async () => { + const propertyChanges: PropertyChangeEvent[] = []; + fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); + 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(propertyChanges).toEqual([]); + }); + + it('emits propertyChange and componentChange when a property is edited', async () => { + const propertyChanges: PropertyChangeEvent[] = []; + const componentChanges: Array> = []; + fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); + 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(propertyChanges.at(-1)).toEqual({name: 'label', value: 'Updated Size'}); + expect(componentChanges.at(-1)).toEqual({ + ...initial, + label: 'Updated Size', + }); + }); + + it('emits propertyChange and componentChange without the removed key when an optional property is removed', async () => { + const propertyChanges: PropertyChangeEvent[] = []; + const componentChanges: Array> = []; + fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); + 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(propertyChanges.at(-1)).toEqual({name: 'filterable', value: undefined}); + expect(componentChanges.at(-1)).toEqual({ + id: 'picker-1', + component: 'ChoicePicker', + label: 'Size', + options: [{label: 'Small', value: 's'}], + value: ['s'], + }); + }); + + it('surfaces inline error and suppresses propertyChange 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.propertyChange.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).toHaveBeenLastCalledWith(''); + 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(); + }); +}); + +// 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], +}); + +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 DynamicBoolean', dynamicSchema({type: 'boolean'}), 'boolean'], + ['a DynamicNumber', dynamicSchema({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'); + }); + + 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: '/items'}, list)).toContain('Bound to /items'); + expect(describeUneditableValue({path: '/group'}, group)).toContain('Bound to /group'); + 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(); + }); +}); 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..0661c06fb --- /dev/null +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -0,0 +1,530 @@ +/** + * 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, + Signal, + WritableSignal, + computed, + inject, + input, + linkedSignal, + output, +} from '@angular/core'; +import {NgTemplateOutlet} from '@angular/common'; +import {FormsModule} from '@angular/forms'; +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-editor-utils'; +import {ErrorLogger} from '../../debug/error-logger.service'; +import {formatJson} from '../../utils/json'; +import {stableStringify} from '../../storage/stable-stringify/stable-stringify'; + +type PropertyPath = ReadonlyArray; + +/** + * Payload emitted when a top-level property on the target component is edited or removed. + */ +export interface PropertyChangeEvent { + name: string; + value: unknown; +} + +/** + * Metadata and control state for one editable catalog property of the selected component. + */ +export interface EditableProperty { + name: string; + required: boolean; + control: PropertyControl; + kind: PropertyControl['kind']; + options: PropertyControl['options']; + /** The current value, or undefined when the example omits the property. */ + value: unknown; + /** Formatted JSON representation of the value, or empty string when undefined. */ + json: string; + /** 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); + + /** The A2UI component object being inspected and edited. */ + readonly component = input | null | undefined>(null); + + /** + * Optional override for the component type key; defaults to `component()['component']`. + */ + readonly componentKey = input(undefined); + + /** + * Optional catalog override; defaults to `CatalogManagement.activeCatalog()`. + */ + readonly catalog = input(undefined); + + /** + * Optional pre-resolved property specifications; when omitted, resolved automatically + * from the active catalog and `componentKey`. + */ + 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); + + /** Emits `{name, value}` when a top-level property is updated or removed (`undefined`). */ + readonly propertyChange = output(); + + /** 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 formatJson = formatJson; + protected readonly describeUneditableValue = describeUneditableValue; + + private readonly activeCatalog: Signal = computed(() => { + const explicitCatalog = this.catalog(); + return explicitCatalog !== undefined ? explicitCatalog : this.catalogManagement.activeCatalog(); + }); + + private readonly catalogSignature: Signal = computed(() => { + const catalog = this.activeCatalog(); + return catalog ? stableStringify(catalog) : null; + }); + + private readonly resolvedComponentKey: Signal = computed(() => { + const explicitKey = this.componentKey(); + if (typeof explicitKey === 'string' && explicitKey) { + return explicitKey; + } + const target = this.component(); + const typeName = target?.['component']; + return typeof typeName === 'string' && typeName ? typeName : 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.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> => ({}), + }); + + /** + * 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, + options: control.options, + value, + json: value === undefined ? '' : formatJson(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, + ); + }); + + /** + * Clears any pending inline JSON field validation errors. + */ + clearErrors(): void { + this.jsonFieldErrors.set({}); + } + + /** + * 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): string | null { + const target = this.component(); + 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.statusMessage.emit(''); + const schema = this.selectedComponentSchemas()[name]; + if (value !== undefined && schema && !matchesSimpleSchema(value, schema)) { + const componentId = + typeof target['id'] === 'string' && target['id'].trim() + ? target['id'] + : (this.resolvedComponentKey() ?? 'target'); + const reason = `"${name}" on "${componentId}" does not match its catalog property type or choices.`; + this.statusMessage.emit(`${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; + } + this.propertyChange.emit({name, value}); + this.componentChange.emit(updatedComponent); + return null; + } + + /** + * Updates a top-level or nested property at `path`. + */ + protected editAtPath(path: PropertyPath, value: unknown): 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); + } + const currentRoot = this.component()?.[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); + } + + /** + * 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); + } + + /** + * 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 (value !== null && Number.isFinite(value)) { + this.editAtPath(path, value); + } else if (!required) { + this.editAtPath(path, undefined); + } else { + this.statusMessage.emit(`Enter a number for ${label}. Preview keeps its previous value.`); + } + } + + /** + * 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 { + const setError = (message: string) => { + this.jsonFieldErrors.update(errors => ({...errors, [pathKey]: {text, message}})); + }; + let value: unknown; + if (!text.trim()) { + if (required) { + setError(`${label} is required.`); + return; + } + value = undefined; + } else { + try { + value = JSON.parse(text); + } catch { + setError('Invalid JSON. The example keeps its previous value.'); + return; + } + } + const error = this.editAtPath(path, value); + if (error) { + this.statusMessage.emit(''); + 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.component(); + 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..7a9cdc6a8 --- /dev/null +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -0,0 +1,222 @@ +/** + * 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. + */ + async editProperty(name: string, value: string): Promise { + const input = await this.locatorFor(`[data-property="${name}"]`)(); + await input.setInputValue(value); + await input.dispatchEvent('input'); + } + + /** + * 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 byId = await this.locatorForOptional(`[id="gallery-property-error-${name}"]`)(); + if (byId) { + return byId.text(); + } + const error = await this.locatorForOptional(`[data-property-row="${name}"] .property-error`)(); + 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'); + } + + /** + * 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')); + } +} From 5b7ac86e0b8d2680b385954197932ea70948cec6 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 11 Nov 2026 15:17:27 -0800 Subject: [PATCH 02/50] Fix test --- shell/src/app/shared/property-editor/property-editor.spec.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index eca75443d..a73cd58b3 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -16,7 +16,6 @@ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; -import {provideNoopAnimations} from '@angular/platform-browser/animations'; import {signal} from '@angular/core'; import {describe, it, expect, beforeEach, vi} from 'vitest'; import {PropertyEditor, PropertyChangeEvent} from './property-editor'; @@ -129,7 +128,6 @@ describe('PropertyEditor Component', () => { await TestBed.configureTestingModule({ imports: [PropertyEditor], providers: [ - provideNoopAnimations(), {provide: CatalogManagement, useClass: MockCatalogManagement}, ErrorLogger, ], From 12d1f16d09254338d0caab4354634b9e8a1de840 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 13:53:36 -0800 Subject: [PATCH 03/50] Add emitStatus parameter to editProperty --- .../property-editor/property-editor.spec.ts | 7 ++----- .../app/shared/property-editor/property-editor.ts | 15 ++++++++------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index a73cd58b3..e75c6d275 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -127,10 +127,7 @@ describe('PropertyEditor Component', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [PropertyEditor], - providers: [ - {provide: CatalogManagement, useClass: MockCatalogManagement}, - ErrorLogger, - ], + providers: [{provide: CatalogManagement, useClass: MockCatalogManagement}, ErrorLogger], }).compileComponents(); fixture = TestBed.createComponent(PropertyEditor); @@ -264,7 +261,7 @@ describe('PropertyEditor Component', () => { 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).toHaveBeenLastCalledWith(''); + expect(statusSpy.mock.calls).toEqual([['']]); expect(changeSpy).not.toHaveBeenCalled(); }); diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 0661c06fb..199b6234c 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -309,7 +309,7 @@ export class PropertyEditor { /** * Sets one property on the target component, or removes it when value is undefined. */ - protected editProperty(name: string, value: unknown): string | null { + protected editProperty(name: string, value: unknown, emitStatus = true): string | null { const target = this.component(); if (!target || this.disabled()) { return null; @@ -329,7 +329,9 @@ export class PropertyEditor { ? target['id'] : (this.resolvedComponentKey() ?? 'target'); const reason = `"${name}" on "${componentId}" does not match its catalog property type or choices.`; - this.statusMessage.emit(`${reason} Preview keeps its previous value.`); + if (emitStatus) { + this.statusMessage.emit(`${reason} Preview keeps its previous value.`); + } return reason; } let updatedComponent: Record; @@ -347,7 +349,7 @@ export class PropertyEditor { /** * Updates a top-level or nested property at `path`. */ - protected editAtPath(path: PropertyPath, value: unknown): string | null { + protected editAtPath(path: PropertyPath, value: unknown, emitStatus = true): string | null { if (path.length === 0) { return null; } @@ -356,7 +358,7 @@ export class PropertyEditor { return null; } if (rest.length === 0) { - return this.editProperty(rootName, value); + return this.editProperty(rootName, value, emitStatus); } const currentRoot = this.component()?.[rootName]; const topProp = this.editableProperties().find(prop => prop.name === rootName); @@ -367,7 +369,7 @@ export class PropertyEditor { topProp?.control, topProp?.required ?? false, ); - return this.editProperty(rootName, updatedRoot); + return this.editProperty(rootName, updatedRoot, emitStatus); } /** @@ -423,9 +425,8 @@ export class PropertyEditor { return; } } - const error = this.editAtPath(path, value); + const error = this.editAtPath(path, value, false); if (error) { - this.statusMessage.emit(''); setError(`${error} The example keeps its previous value.`); return; } From 91a4f6bd441fdbc2ed9bf9a047a4330275e14799 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 14:53:48 -0800 Subject: [PATCH 04/50] Remove unused input bindings --- .../property-editor/property-editor.spec.ts | 13 --------- .../shared/property-editor/property-editor.ts | 28 +++---------------- 2 files changed, 4 insertions(+), 37 deletions(-) diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index e75c6d275..beb275395 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -159,19 +159,6 @@ describe('PropertyEditor Component', () => { expect(await harness.getPropertySectionHeadings()).toEqual(['Common properties']); }); - it('resolves properties using explicit catalog and componentKey inputs when provided', async () => { - catalogManagementMock.activeCatalog.set(null); - fixture.componentRef.setInput('catalog', jsonCatalog); - fixture.componentRef.setInput('componentKey', 'StyledBox'); - fixture.componentRef.setInput('component', { - id: 'box-override', - style: {padding: 8}, - }); - fixture.detectChanges(); - - expect(await harness.getPropertyNames()).toEqual(['style', 'weight']); - }); - it('blocks property edits when disabled input is true', async () => { const propertyChanges: PropertyChangeEvent[] = []; fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 199b6234c..09d57bd62 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -108,19 +108,9 @@ export class PropertyEditor { /** The A2UI component object being inspected and edited. */ readonly component = input | null | undefined>(null); - /** - * Optional override for the component type key; defaults to `component()['component']`. - */ - readonly componentKey = input(undefined); - - /** - * Optional catalog override; defaults to `CatalogManagement.activeCatalog()`. - */ - readonly catalog = input(undefined); - /** * Optional pre-resolved property specifications; when omitted, resolved automatically - * from the active catalog and `componentKey`. + * from the active catalog and `component()['component']`. */ readonly properties = input(undefined); @@ -144,23 +134,13 @@ export class PropertyEditor { protected readonly formatJson = formatJson; protected readonly describeUneditableValue = describeUneditableValue; - private readonly activeCatalog: Signal = computed(() => { - const explicitCatalog = this.catalog(); - return explicitCatalog !== undefined ? explicitCatalog : this.catalogManagement.activeCatalog(); - }); - private readonly catalogSignature: Signal = computed(() => { - const catalog = this.activeCatalog(); + const catalog = this.catalogManagement.activeCatalog(); return catalog ? stableStringify(catalog) : null; }); private readonly resolvedComponentKey: Signal = computed(() => { - const explicitKey = this.componentKey(); - if (typeof explicitKey === 'string' && explicitKey) { - return explicitKey; - } - const target = this.component(); - const typeName = target?.['component']; + const typeName = this.component()?.['component']; return typeof typeName === 'string' && typeName ? typeName : null; }); @@ -171,7 +151,7 @@ export class PropertyEditor { resolver: CatalogSchemaResolver; common: Set; } | null> = computed(() => { - const catalog = this.activeCatalog(); + const catalog = this.catalogManagement.activeCatalog(); if (!catalog) { return null; } From 9250dddbbf1c4b38b0cb34ad64180a7d9eca0605 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 15:26:14 -0800 Subject: [PATCH 05/50] Revise EditableProperty --- shell/src/app/shared/property-editor/property-editor.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 09d57bd62..bb29dfa30 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -57,16 +57,13 @@ export interface PropertyChangeEvent { /** * Metadata and control state for one editable catalog property of the selected component. */ -export interface EditableProperty { +interface EditableProperty { name: string; required: boolean; control: PropertyControl; kind: PropertyControl['kind']; - options: PropertyControl['options']; /** The current value, or undefined when the example omits the property. */ value: unknown; - /** Formatted JSON representation of the value, or empty string when undefined. */ - json: string; /** 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. */ @@ -226,9 +223,7 @@ export class PropertyEditor { required: prop.required, control, kind: control.kind, - options: control.options, value, - json: value === undefined ? '' : formatJson(value), note: describeUneditableValue(value, control), common: !prop.required && common.has(prop.name), firstCommon: false, From f0828e4c7e5fb14e4ad0cf58c3bb62d3f33e83f0 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 16:11:41 -0800 Subject: [PATCH 06/50] Modify gallery harness to use property editor harness --- shell/src/app/gallery/test/gallery.harness.ts | 101 +++++------------- 1 file changed, 28 insertions(+), 73 deletions(-) diff --git a/shell/src/app/gallery/test/gallery.harness.ts b/shell/src/app/gallery/test/gallery.harness.ts index 98a572b84..1fcedf5dc 100644 --- a/shell/src/app/gallery/test/gallery.harness.ts +++ b/shell/src/app/gallery/test/gallery.harness.ts @@ -18,8 +18,8 @@ import {ComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {MatNavListHarness} from '@angular/material/list/testing'; import {MatTableHarness} from '@angular/material/table/testing'; import {MatButtonHarness} from '@angular/material/button/testing'; -import {MatSlideToggleHarness} from '@angular/material/slide-toggle/testing'; import {RenderedFrameHarness} from '../../preview/rendered/test/rendered-frame.harness'; +import {PropertyEditorHarness} from '../../shared/property-editor/test/property-editor.harness'; /** * Harness for interacting with the Gallery component in unit tests. @@ -52,6 +52,8 @@ export class GalleryHarness extends ComponentHarness { new HarnessPredicate(RenderedFrameHarness, {ancestor: '.preview-card'}), ); + private readonly getPropertyEditor = this.locatorFor(PropertyEditorHarness); + /** * Retrieves the text labels of all category subheaders. */ @@ -251,9 +253,7 @@ export class GalleryHarness extends ComponentHarness { * Edits a supported literal property using its visible control. */ async editProperty(name: string, value: string): Promise { - const input = await this.locatorFor(`[data-property="${name}"]`)(); - await input.setInputValue(value); - await input.dispatchEvent('input'); + return (await this.getPropertyEditor()).editProperty(name, value); } /** @@ -296,184 +296,139 @@ export class GalleryHarness extends ComponentHarness { * 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'); + return (await this.getPropertyEditor()).selectPropertyOption(name, index); } /** * 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())); + return (await this.getPropertyEditor()).getPropertyOptions(name); } /** * 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(); + return (await this.getPropertyEditor()).toggleProperty(name); } /** - * Lists the editable property names in display order. + * 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())); + return (await this.getPropertyEditor()).getPropertySectionHeadings(); } + /** + * 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())); + return (await this.getPropertyEditor()).getPropertyNames(); } /** * 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'); + return (await this.getPropertyEditor()).getPropertyControlKind(name); } /** * 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; + return (await this.getPropertyEditor()).getArrayItemCount(name); } /** * 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(); + return (await this.getPropertyEditor()).addArrayItem(name); } /** * 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(); + return (await this.getPropertyEditor()).deleteArrayItem(name, index); } /** * 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())); + return (await this.getPropertyEditor()).getObjectPropertyNames(name); } /** * Whether a property shows the "required" marker. */ async isPropertyRequired(name: string): Promise { - return !!(await this.locatorForOptional( - `[data-property-row="${name}"] > .property-name .required-marker`, - )()); + return (await this.getPropertyEditor()).isPropertyRequired(name); } /** * Whether a property offers a remove action. */ async canRemoveProperty(name: string): Promise { - return !!(await this.locatorForOptional(`[data-remove-property="${name}"]`)()); + return (await this.getPropertyEditor()).canRemoveProperty(name); } /** * Removes an optional property through its remove action. */ async removeProperty(name: string): Promise { - await (await this.locatorFor(`[data-remove-property="${name}"]`)()).click(); + return (await this.getPropertyEditor()).removeProperty(name); } /** * 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'); + return (await this.getPropertyEditor()).editJsonProperty(name, text); } /** * 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', - ); + return (await this.getPropertyEditor()).getJsonPropertyText(name); } /** * Reads the inline error under a property, if any. */ async getPropertyError(name: string): Promise { - const byId = await this.locatorForOptional(`[id="gallery-property-error-${name}"]`)(); - if (byId) { - return byId.text(); - } - const error = await this.locatorForOptional(`[data-property-row="${name}"] .property-error`)(); - return error ? error.text() : null; + return (await this.getPropertyEditor()).getPropertyError(name); } /** * 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; + return (await this.getPropertyEditor()).getPropertyNote(name); } /** * 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'); + return (await this.getPropertyEditor()).getPropertyLabelFor(name); } /** * 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; + return (await this.getPropertyEditor()).isPropertyMissing(name); } /** * 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')); + return (await this.getPropertyEditor()).isPropertyInline(name); } } From a320ee92bcba0fda0cca149f3ee7aec6a7b29d8e Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 16:38:53 -0800 Subject: [PATCH 07/50] Remove propertyChange output --- shell/src/app/gallery/gallery.ng.html | 2 +- shell/src/app/gallery/gallery.ts | 17 +++++--------- .../property-editor/property-editor.spec.ts | 22 +++++++------------ .../shared/property-editor/property-editor.ts | 12 ---------- 4 files changed, 14 insertions(+), 39 deletions(-) diff --git a/shell/src/app/gallery/gallery.ng.html b/shell/src/app/gallery/gallery.ng.html index 1f6345dbb..7c0535027 100644 --- a/shell/src/app/gallery/gallery.ng.html +++ b/shell/src/app/gallery/gallery.ng.html @@ -130,7 +130,7 @@

{{ selectedComponentKey() }}

[properties]="selectedComponentProperties()" [disabled]="!!draft().error" [resetKey]="draftSource().identity" - (propertyChange)="editProperty($event.name, $event.value)" + (componentChange)="updateEditableComponent($event)" (statusMessage)="actionMessage.set($event)" />
diff --git a/shell/src/app/gallery/gallery.ts b/shell/src/app/gallery/gallery.ts index 1f342579d..eeb07fc4d 100644 --- a/shell/src/app/gallery/gallery.ts +++ b/shell/src/app/gallery/gallery.ts @@ -270,24 +270,17 @@ export class Gallery implements OnInit, OnDestroy { } /** - * Sets one property on the selected component, or removes it when value is undefined. + * Replaces the editable component in the draft with its updated record. */ - protected editProperty(name: string, value: unknown): string | null { + protected updateEditableComponent(updatedComponent: Record): string | null { const preset = this.draft().preset; const target = this.editableComponent(); if (!preset || !target || this.draft().error) { return null; } - const components = preset.usage.map(component => { - if (component !== target) { - return component; - } - if (value !== undefined) { - return {...component, [name]: value}; - } - const {[name]: _removed, ...rest} = component; - return rest; - }); + const components = preset.usage.map(component => + component === target ? updatedComponent : component, + ); return this.editDraft( formatJson({ ['components']: components, diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index beb275395..5c7eccea0 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -18,7 +18,7 @@ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {signal} from '@angular/core'; import {describe, it, expect, beforeEach, vi} from 'vitest'; -import {PropertyEditor, PropertyChangeEvent} from './property-editor'; +import {PropertyEditor} from './property-editor'; import { createDefaultPropertyValue, describeUneditableValue, @@ -160,8 +160,8 @@ describe('PropertyEditor Component', () => { }); it('blocks property edits when disabled input is true', async () => { - const propertyChanges: PropertyChangeEvent[] = []; - fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); + const componentChanges: Array> = []; + fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); fixture.componentRef.setInput('disabled', true); fixture.componentRef.setInput('component', { id: 'picker-1', @@ -175,13 +175,11 @@ describe('PropertyEditor Component', () => { await harness.removeProperty('filterable'); - expect(propertyChanges).toEqual([]); + expect(componentChanges).toEqual([]); }); - it('emits propertyChange and componentChange when a property is edited', async () => { - const propertyChanges: PropertyChangeEvent[] = []; + it('emits componentChange when a property is edited', async () => { const componentChanges: Array> = []; - fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); const initial = { id: 'picker-1', @@ -196,17 +194,14 @@ describe('PropertyEditor Component', () => { await harness.editProperty('label', 'Updated Size'); - expect(propertyChanges.at(-1)).toEqual({name: 'label', value: 'Updated Size'}); expect(componentChanges.at(-1)).toEqual({ ...initial, label: 'Updated Size', }); }); - it('emits propertyChange and componentChange without the removed key when an optional property is removed', async () => { - const propertyChanges: PropertyChangeEvent[] = []; + it('emits componentChange without the removed key when an optional property is removed', async () => { const componentChanges: Array> = []; - fixture.componentInstance.propertyChange.subscribe(event => propertyChanges.push(event)); fixture.componentInstance.componentChange.subscribe(comp => componentChanges.push(comp)); fixture.componentRef.setInput('component', { id: 'picker-1', @@ -220,7 +215,6 @@ describe('PropertyEditor Component', () => { await harness.removeProperty('filterable'); - expect(propertyChanges.at(-1)).toEqual({name: 'filterable', value: undefined}); expect(componentChanges.at(-1)).toEqual({ id: 'picker-1', component: 'ChoicePicker', @@ -230,7 +224,7 @@ describe('PropertyEditor Component', () => { }); }); - it('surfaces inline error and suppresses propertyChange when a JSON field violates the catalog schema', async () => { + 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', @@ -241,7 +235,7 @@ describe('PropertyEditor Component', () => { const statusSpy = vi.fn(); const changeSpy = vi.fn(); fixture.componentInstance.statusMessage.subscribe(statusSpy); - fixture.componentInstance.propertyChange.subscribe(changeSpy); + fixture.componentInstance.componentChange.subscribe(changeSpy); await harness.editJsonProperty('style', '123'); diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index bb29dfa30..efef427e1 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -46,14 +46,6 @@ import {stableStringify} from '../../storage/stable-stringify/stable-stringify'; type PropertyPath = ReadonlyArray; -/** - * Payload emitted when a top-level property on the target component is edited or removed. - */ -export interface PropertyChangeEvent { - name: string; - value: unknown; -} - /** * Metadata and control state for one editable catalog property of the selected component. */ @@ -119,9 +111,6 @@ export class PropertyEditor { */ readonly resetKey = input(null); - /** Emits `{name, value}` when a top-level property is updated or removed (`undefined`). */ - readonly propertyChange = output(); - /** Emits the updated component record when a property is updated or removed. */ readonly componentChange = output>(); @@ -316,7 +305,6 @@ export class PropertyEditor { const {[name]: _removed, ...rest} = target; updatedComponent = rest; } - this.propertyChange.emit({name, value}); this.componentChange.emit(updatedComponent); return null; } From c06f4ace630fb9aacee33742b72f73110ec88bca Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 18:45:59 -0800 Subject: [PATCH 08/50] Use mergedActiveCatalog before falling back to activeCatalog --- .../property-editor/property-editor.spec.ts | 29 +++++++++++++++++++ .../shared/property-editor/property-editor.ts | 6 ++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index 5c7eccea0..363620dda 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -31,6 +31,7 @@ import {ErrorLogger} from '../../debug/error-logger.service'; class MockCatalogManagement { readonly activeCatalog = signal(null); + readonly mergedActiveCatalog = signal(null); } const dynamic = (literal: Record) => ({ @@ -159,6 +160,20 @@ describe('PropertyEditor Component', () => { expect(await harness.getPropertySectionHeadings()).toEqual(['Common properties']); }); + 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)); @@ -289,6 +304,11 @@ const call: CatalogComponentSchema = {type: 'object', properties: {call: {type: 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([ @@ -297,8 +317,11 @@ describe('resolvePropertyControl', () => { ['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'], @@ -367,6 +390,8 @@ describe('resolvePropertyControl', () => { 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', () => { @@ -419,9 +444,13 @@ describe('describeUneditableValue', () => { 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', diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index efef427e1..9775bad36 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -121,7 +121,8 @@ export class PropertyEditor { protected readonly describeUneditableValue = describeUneditableValue; private readonly catalogSignature: Signal = computed(() => { - const catalog = this.catalogManagement.activeCatalog(); + const catalog = + this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); return catalog ? stableStringify(catalog) : null; }); @@ -137,7 +138,8 @@ export class PropertyEditor { resolver: CatalogSchemaResolver; common: Set; } | null> = computed(() => { - const catalog = this.catalogManagement.activeCatalog(); + const catalog = + this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); if (!catalog) { return null; } From 035407a3411799c2b3db0cd08590a8180095808c Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 19:26:43 -0800 Subject: [PATCH 09/50] Rename property-editor-utils to property-control --- .../{property-editor-utils.ts => property-control.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename shell/src/app/shared/property-editor/{property-editor-utils.ts => property-control.ts} (100%) diff --git a/shell/src/app/shared/property-editor/property-editor-utils.ts b/shell/src/app/shared/property-editor/property-control.ts similarity index 100% rename from shell/src/app/shared/property-editor/property-editor-utils.ts rename to shell/src/app/shared/property-editor/property-control.ts From 1f202551854011d45aff27ecb9cc36d87d097529 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 19:27:06 -0800 Subject: [PATCH 10/50] Update property-control imports --- shell/src/app/gallery/gallery-example.ts | 2 +- shell/src/app/shared/property-editor/property-editor.spec.ts | 2 +- shell/src/app/shared/property-editor/property-editor.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/shell/src/app/gallery/gallery-example.ts b/shell/src/app/gallery/gallery-example.ts index cf95bee7e..9aed5bca4 100644 --- a/shell/src/app/gallery/gallery-example.ts +++ b/shell/src/app/gallery/gallery-example.ts @@ -16,7 +16,7 @@ import {ComponentUsage} from 'a2ui-bridge'; import {ErrorLogger} from '../debug/error-logger.service'; -import {matchesSimpleSchema} from '../shared/property-editor/property-editor-utils'; +import {matchesSimpleSchema} from '../shared/property-editor/property-control'; import {Catalog} from '../storage/models/catalog-storage.model'; import {CatalogSchemaResolver} from './schema/catalog-schema-resolver'; diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index 363620dda..274cd6b50 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -23,7 +23,7 @@ import { createDefaultPropertyValue, describeUneditableValue, resolvePropertyControl, -} from './property-editor-utils'; +} 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'; diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 9775bad36..470732f49 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -39,7 +39,7 @@ import { matchesSimpleSchema, PropertyControl, resolvePropertyControl, -} from './property-editor-utils'; +} from './property-control'; import {ErrorLogger} from '../../debug/error-logger.service'; import {formatJson} from '../../utils/json'; import {stableStringify} from '../../storage/stable-stringify/stable-stringify'; From 8338993c932991a783c6b4e757f6f4c6882fa6a7 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 19:42:32 -0800 Subject: [PATCH 11/50] Add optional input for empty state placeholder message --- .../property-editor/property-editor.ng.html | 4 +++ .../property-editor/property-editor.scss | 7 +++++ .../property-editor/property-editor.spec.ts | 30 +++++++++++++++++++ .../shared/property-editor/property-editor.ts | 3 ++ .../test/property-editor.harness.ts | 8 +++++ 5 files changed, 52 insertions(+) diff --git a/shell/src/app/shared/property-editor/property-editor.ng.html b/shell/src/app/shared/property-editor/property-editor.ng.html index 6a940f7a3..54dfead1c 100644 --- a/shell/src/app/shared/property-editor/property-editor.ng.html +++ b/shell/src/app/shared/property-editor/property-editor.ng.html @@ -80,6 +80,10 @@

Common properties

} +} @else { +

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

} { '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 () => { diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 470732f49..26082b79f 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -111,6 +111,9 @@ export class PropertyEditor { */ 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.'); + /** Emits the updated component record when a property is updated or removed. */ readonly componentChange = output>(); 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 index 7a9cdc6a8..e2a1a02e0 100644 --- a/shell/src/app/shared/property-editor/test/property-editor.harness.ts +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -219,4 +219,12 @@ export class PropertyEditorHarness extends ComponentHarness { const row = await this.locatorFor(`[data-property-row="${name}"]`)(); return !(await row.hasClass('property-row-multiline')); } + + /** + * Reads the empty-state placeholder message when no editable properties are rendered, if any. + */ + async getEmptyStateText(): Promise { + const empty = await this.locatorForOptional('[data-property-empty-state]')(); + return empty ? (await empty.text()).trim() : null; + } } From ca4ea727d9df3baffddb39a20b73cf495ef74020 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 20:21:04 -0800 Subject: [PATCH 12/50] Add instance specific idPrefixes --- shell/src/app/gallery/gallery.spec.ts | 8 ++-- .../property-editor/property-editor.ng.html | 32 +++++++++------ .../property-editor/property-editor.spec.ts | 40 +++++++++++++++++++ .../shared/property-editor/property-editor.ts | 3 ++ .../test/property-editor.harness.ts | 30 +++++++++++--- 5 files changed, 92 insertions(+), 21 deletions(-) diff --git a/shell/src/app/gallery/gallery.spec.ts b/shell/src/app/gallery/gallery.spec.ts index 0f1eed24b..dd107ab60 100644 --- a/shell/src/app/gallery/gallery.spec.ts +++ b/shell/src/app/gallery/gallery.spec.ts @@ -1851,8 +1851,8 @@ describe('Gallery Component', () => { expect(await harness.getPropertyLabelFor('label')).toBeNull(); expect(await harness.getPropertyNote('options.0.label')).toContain('Bound to /optionLabel'); expect(await harness.getPropertyLabelFor('options.0.label')).toBeNull(); - expect(await harness.getPropertyLabelFor('options.0.value')).toBe( - 'gallery-property-options.0.value', + expect(await harness.getPropertyLabelFor('options.0.value')).toMatch( + /^property-editor-\d+-options\.0\.value$/, ); await harness.selectPropertyOption('displayStyle', 1); expect((await target()).label).toEqual({path: '/sizeLabel'}); @@ -2080,8 +2080,8 @@ describe('Gallery Component', () => { expect(await harness.getPropertyControlKind('options.0.label')).toBeNull(); expect(await harness.getPropertyLabelFor('options.0.label')).toBeNull(); expect(await harness.getPropertyControlKind('options.0.value')).toBe('text'); - expect(await harness.getPropertyLabelFor('options.0.value')).toBe( - 'gallery-property-options.0.value', + expect(await harness.getPropertyLabelFor('options.0.value')).toMatch( + /^property-editor-\d+-options\.0\.value$/, ); expect(await harness.getPropertyNote('value.0')).toBe( diff --git a/shell/src/app/shared/property-editor/property-editor.ng.html b/shell/src/app/shared/property-editor/property-editor.ng.html index 54dfead1c..6254988fa 100644 --- a/shell/src/app/shared/property-editor/property-editor.ng.html +++ b/shell/src/app/shared/property-editor/property-editor.ng.html @@ -32,7 +32,7 @@

Common properties

[attr.for]=" prop.note || prop.kind === 'array' || prop.kind === 'object' ? null - : 'gallery-property-' + prop.name + : idPrefix + prop.name " > {{ prop.name }} @@ -69,7 +69,12 @@

Common properties

} @if (jsonFieldErrors()[prop.name]; as fieldError) { - } @else if (prop.required && prop.value === undefined) { @@ -100,7 +105,7 @@

Common properties

} @else if (control.kind === 'enum') { } @else if (control.kind === 'boolean') { Common properties Common properties Common properties subProp.control.kind === 'array' || subProp.control.kind === 'object' ? null - : 'gallery-property-' + pathKey + '.' + subProp.name + : idPrefix + pathKey + '.' + subProp.name " > {{ subProp.name }} @@ -235,20 +240,23 @@

Common properties

#jsonField class="property-json" spellcheck="false" - [id]="'gallery-property-' + pathKey" + [id]="idPrefix + pathKey" [attr.aria-label]="label + ' (JSON)'" [attr.data-property]="pathKey" [placeholder]="required ? '' : 'Not set'" [value]="jsonFieldErrors()[pathKey]?.text ?? formatJson(value)" (change)="editJsonAtPath(path, pathKey, required, label, jsonField.value)" [attr.aria-invalid]="!!jsonFieldErrors()[pathKey]" - [attr.aria-describedby]=" - jsonFieldErrors()[pathKey] ? 'gallery-property-error-' + pathKey : null - " + [attr.aria-describedby]="jsonFieldErrors()[pathKey] ? idPrefix + 'error-' + pathKey : null" [disabled]="disabled()" > @if (path.length > 1 && jsonFieldErrors()[pathKey]; as nestedFieldError) { - } diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index b4a295f33..a402bd001 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -326,6 +326,46 @@ describe('PropertyEditor Component', () => { 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(); + } + }); }); // Shapes as CatalogSchemaResolver returns them for the basic catalog's common types. diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 26082b79f..5855ed98d 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -46,6 +46,8 @@ import {stableStringify} from '../../storage/stable-stringify/stable-stringify'; type PropertyPath = ReadonlyArray; +let nextPropertyEditorId = 0; + /** * Metadata and control state for one editable catalog property of the selected component. */ @@ -120,6 +122,7 @@ export class PropertyEditor { /** 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; 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 index e2a1a02e0..d8bc311ac 100644 --- a/shell/src/app/shared/property-editor/test/property-editor.harness.ts +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -179,11 +179,7 @@ export class PropertyEditorHarness extends ComponentHarness { * Reads the inline error under a property, if any. */ async getPropertyError(name: string): Promise { - const byId = await this.locatorForOptional(`[id="gallery-property-error-${name}"]`)(); - if (byId) { - return byId.text(); - } - const error = await this.locatorForOptional(`[data-property-row="${name}"] .property-error`)(); + const error = await this.locatorForOptional(`[data-property-error="${name}"]`)(); return error ? error.text() : null; } @@ -205,6 +201,30 @@ export class PropertyEditorHarness extends ComponentHarness { 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. */ From 887b1faeed0a818fea791106a4908a730bfefc95 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Tue, 17 Nov 2026 20:52:05 -0800 Subject: [PATCH 13/50] Add missing test cases --- .../property-editor/property-editor.spec.ts | 368 ++++++++++++++++++ 1 file changed, 368 insertions(+) diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index a402bd001..35bf7458f 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -22,6 +22,7 @@ import {PropertyEditor} from './property-editor'; import { createDefaultPropertyValue, describeUneditableValue, + matchesSimpleSchema, resolvePropertyControl, } from './property-control'; import {PropertyEditorHarness} from './test/property-editor.harness'; @@ -117,6 +118,28 @@ const jsonCatalog: Catalog = { }, ], }, + 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'}, + }, + }, + }, + }, + ], + }, }, }; @@ -269,6 +292,284 @@ describe('PropertyEditor Component', () => { }); }); + 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', { @@ -556,3 +857,70 @@ describe('describeUneditableValue', () => { 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); + }); +}); From 638baa53de45747986797bcd2f8149d1d42785f2 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Thu, 12 Nov 2026 16:49:36 -0800 Subject: [PATCH 14/50] Add component tree --- shell/e2e/workspace-layout-recovery.e2e.ts | 6 +- .../component-tree-builder.spec.ts | 200 +++++++++ .../component-tree/component-tree-builder.ts | 383 ++++++++++++++++++ .../component-tree/component-tree.ng.html | 107 +++++ .../debug/component-tree/component-tree.scss | 127 ++++++ .../debug/component-tree/component-tree.ts | 92 +++++ .../composer-dockview.service.ts | 16 +- .../composer-workspace/composer-panel-id.ts | 1 + .../composer-workspace.spec.ts | 4 +- shell/src/global_styles.scss | 8 + 10 files changed, 939 insertions(+), 5 deletions(-) create mode 100644 shell/src/app/debug/component-tree/component-tree-builder.spec.ts create mode 100644 shell/src/app/debug/component-tree/component-tree-builder.ts create mode 100644 shell/src/app/debug/component-tree/component-tree.ng.html create mode 100644 shell/src/app/debug/component-tree/component-tree.scss create mode 100644 shell/src/app/debug/component-tree/component-tree.ts diff --git a/shell/e2e/workspace-layout-recovery.e2e.ts b/shell/e2e/workspace-layout-recovery.e2e.ts index 4d4d8d510..69658096a 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(8); 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 8 tabs are present + await expect(page.locator('.dv-tab')).toHaveCount(8); // 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..7cbc7c22e --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -0,0 +1,200 @@ +/** + * 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} 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([]); + }); +}); 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..9fc3e3879 --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -0,0 +1,383 @@ +/** + * 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` / `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 (its reference path from the root). */ + 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_LIST_DEF = 'ChildList'; +const LOCAL_DEFS_PREFIX = '#/$defs/'; +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)) 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; + }; + 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(); + } + const update = asRecord(record['updateComponents']); + if (update && typeof update['surfaceId'] === 'string' && Array.isArray(update['components'])) { + const state = surfaceFor(update['surfaceId']); + for (const component of update['components']) { + const c = asRecord(component); + if (c && typeof c['id'] === 'string') state.components.set(c['id'], c); + } + } + const del = asRecord(record['deleteSurface']); + if (del && typeof del['surfaceId'] === 'string') { + surfaces.delete(del['surfaceId']); + } + } + return surfaces; +} + +/** 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[] { + if (!this.cache.has(type)) { + const schema = this.catalog?.components?.[type]; + let slots: ReferenceSlot[] | null = null; + if (schema) { + slots = []; + this.walk(schema, [], slots, new Set()); + slots = slots.filter(s => !(s.path.length === 1 && s.path[0] === 'id')); + } + this.cache.set(type, slots); + } + return this.cache.get(type) ?? FALLBACK_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; + } + if (ref.startsWith(LOCAL_DEFS_PREFIX)) { + const name = ref.slice(LOCAL_DEFS_PREFIX.length); + if (!visitingDefs.has(name)) { + visitingDefs.add(name); + this.walk(this.catalog?.$defs?.[name], path, out, visitingDefs); + visitingDefs.delete(name); + } + } + } + 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); + } + } +} + +/** 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); +} + +/** + * 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 = new ReferenceSchema(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, 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, `~${id}`, new Set())); + } + + return { + surfaceId, + root, + unreachable, + componentCount: components.size, + truncated, + }; +} 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..d5009dc36 --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -0,0 +1,107 @@ + + +
+ @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 }} + } + @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..0ac73b89b --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree.scss @@ -0,0 +1,127 @@ +/** + * 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: default; + white-space: nowrap; + + &:hover { + background: var(--mat-sys-surface-container-high); + } + + &.missing .type, + &.cycle .type { + color: var(--mat-sys-error); + } +} + +.toggle, +.toggle-spacer { + flex: none; + width: 16px; +} + +.toggle { + padding: 0; + border: none; + background: none; + color: inherit; + cursor: pointer; + line-height: 16px; +} + +.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.ts b/shell/src/app/debug/component-tree/component-tree.ts new file mode 100644 index 000000000..162304cf4 --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -0,0 +1,92 @@ +/** + * 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, signal} from '@angular/core'; +import {NgTemplateOutlet} from '@angular/common'; +import {MatTooltipModule} from '@angular/material/tooltip'; +import {StateSync} from '../../chat/state-sync/state-sync'; +import {CatalogManagement} from '../../storage/catalog-management/catalog-management'; +import {tryParseJsonArray} from '../../utils/json'; +import { + ComponentTreeNode, + SurfaceComponentTree, + buildComponentTrees, +} from './component-tree-builder'; + +/** + * A debug drawer 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); + + /** Keys of collapsed nodes (nodes are expanded by default). */ + protected readonly collapsed = signal>(new Set()); + + protected readonly parseError = computed(() => { + const result = tryParseJsonArray(this.stateSync.activeDraft()); + return result.success ? null : result.error.message; + }); + + protected readonly trees = computed(() => { + const result = tryParseJsonArray(this.stateSync.activeDraft()); + if (!result.success) return []; + return buildComponentTrees(result.data, this.catalogManagement.activeCatalog()); + }); + + protected isExpanded(node: ComponentTreeNode): boolean { + return !this.collapsed().has(node.key); + } + + 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 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/shell/composer-workspace/composer-dockview.service.ts b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts index 152499294..2cdba9dae 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -35,6 +35,7 @@ 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 {ComposerPanelId} from './composer-panel-id'; /** @@ -375,6 +376,9 @@ export class ComposerDockview { case ComposerPanelId.RawMessages: type = RawMessages; break; + case ComposerPanelId.ComponentTree: + type = ComponentTree; + break; } if (!type) { @@ -501,7 +505,7 @@ export class ComposerDockview { minimumHeight: PREVIEW_PANEL_MIN_HEIGHT, }); - // 3. Raw JSON editor tabbed within Rendered preview group + // 3. Raw JSON editor and Component Tree tabbed within Rendered preview group this.dockviewApi.addPanel({ id: ComposerPanelId.Raw, component: ComposerPanelId.Raw, @@ -512,6 +516,16 @@ export class ComposerDockview { }, inactive: true, }); + this.dockviewApi.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 this.dockviewApi.addPanel({ 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..a6a0e0141 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,7 @@ export enum ComposerPanelId { Events = 'events', Errors = 'errors', RawMessages = 'rawMessages', + ComponentTree = 'componentTree', } /** 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 9feca98c5..6ce1f51ae 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -50,6 +50,7 @@ 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'; class MockChatState { readonly chatHistory = signal([]); @@ -155,11 +156,12 @@ 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(8); 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); }); 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; +} From 60499089d47e0474e2dee22c05a183556e858043 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Fri, 13 Nov 2026 17:39:02 -0800 Subject: [PATCH 15/50] Add aria level to tree row --- shell/src/app/debug/component-tree/component-tree.ng.html | 1 + 1 file changed, 1 insertion(+) diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html index d5009dc36..fdfb6585d 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -57,6 +57,7 @@
Date: Mon, 16 Nov 2026 16:56:38 -0800 Subject: [PATCH 16/50] Remove tree roles --- shell/src/app/debug/component-tree/component-tree.ng.html | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html index fdfb6585d..60066c802 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -14,7 +14,7 @@ limitations under the License. --> -
+
@if (parseError(); as error) {
The A2UI JSON is invalid: {{ error }}
} @else if (trees().length === 0) { @@ -56,9 +56,6 @@
From 3a9dc41932d3160f6b831502ff6aadf37971305b Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 18:32:39 -0800 Subject: [PATCH 17/50] Add component tree to saved layouts --- .../composer-dockview.service.ts | 184 +++++++++--------- .../composer-workspace.spec.ts | 30 +++ 2 files changed, 125 insertions(+), 89 deletions(-) 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 2cdba9dae..bb7239343 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -24,7 +24,7 @@ import { inject, } 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'; @@ -479,99 +479,105 @@ 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 and Component Tree 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, - }); - this.dockviewApi.addPanel({ - id: ComposerPanelId.ComponentTree, - component: ComposerPanelId.ComponentTree, - title: 'Component Tree', - 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, + }); + + 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-workspace.spec.ts b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts index 6ce1f51ae..23fa90207 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -397,6 +397,36 @@ 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); + expect(componentTreePanel).toBeDefined(); + manager.api.removePanel(componentTreePanel!); + + const legacyLayout = manager.api.toJSON(); + expect(legacyLayout.panels[ComposerPanelId.ComponentTree]).toBeUndefined(); + fixture.destroy(); + storage.setItem(LocalStorageKey.DOCKVIEW_LAYOUT, JSON.stringify(legacyLayout)); + + const restored = await returnToWorkspace(); + const restoredRendered = restored.api.getGroupPanel(ComposerPanelId.Rendered); + const restoredComponentTree = restored.api.getGroupPanel(ComposerPanelId.ComponentTree); + + 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(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 => { From 161d446d7a74e095c14ba37e406765d5e27c7a6e Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 18:50:56 -0800 Subject: [PATCH 18/50] Prefix node keys with surfaceId --- .../component-tree-builder.spec.ts | 20 +++++++++++++++++++ .../component-tree/component-tree-builder.ts | 6 +++--- 2 files changed, 23 insertions(+), 3 deletions(-) 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 index 7cbc7c22e..a1cbe168b 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -197,4 +197,24 @@ describe('buildComponentTrees', () => { ]); 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); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index 9fc3e3879..decd87803 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -42,7 +42,7 @@ export type ComponentTreeNodeStatus = 'ok' | 'missing' | 'cycle'; /** A component occurrence in the expanded tree. */ export interface ComponentTreeNode { - /** Unique key of this occurrence (its reference path from the root). */ + /** Unique key of this occurrence (surface-scoped reference path). */ readonly key: string; /** The referenced component id. */ readonly id: string; @@ -349,7 +349,7 @@ function buildSurfaceTree( }; const root = components.has(ROOT_COMPONENT_ID) - ? expand(ROOT_COMPONENT_ID, null, null, ROOT_COMPONENT_ID, new Set()) + ? expand(ROOT_COMPONENT_ID, null, null, `${surfaceId}/${ROOT_COMPONENT_ID}`, new Set()) : null; // Unreachable components: start from those no other unreachable component @@ -370,7 +370,7 @@ function buildSurfaceTree( truncated = true; break; } - unreachable.push(expand(id, null, null, `~${id}`, new Set())); + unreachable.push(expand(id, null, null, `${surfaceId}/~${id}`, new Set())); } return { From b534a04c91247d10a0b17cdffc0aea8339b31b69 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 14:26:53 -0800 Subject: [PATCH 19/50] Seed state.components in createSurface --- .../component-tree-builder.spec.ts | 54 +++++++++++++++++++ .../component-tree/component-tree-builder.ts | 16 ++++-- 2 files changed, 65 insertions(+), 5 deletions(-) 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 index a1cbe168b..29fe47a28 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -217,4 +217,58 @@ describe('buildComponentTrees', () => { 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); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index decd87803..a700fb789 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -137,6 +137,15 @@ function collectSurfaces(messages: readonly unknown[]): Map { + 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; @@ -144,14 +153,11 @@ function collectSurfaces(messages: readonly unknown[]): Map Date: Wed, 18 Nov 2026 14:59:08 -0800 Subject: [PATCH 20/50] Add Child matching to referenceKindOf --- .../component-tree-builder.spec.ts | 37 +++++++++++++++++++ .../component-tree/component-tree-builder.ts | 9 +++-- 2 files changed, 42 insertions(+), 4 deletions(-) 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 index 29fe47a28..b347073c7 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -271,4 +271,41 @@ describe('buildComponentTrees', () => { ]); 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([]); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index a700fb789..f9d1d28dd 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -32,9 +32,9 @@ import {asRecord} from '../../utils/json'; * - components not reachable from `root` (`unreachable`). * * Reference properties are discovered from the catalog's JSON schema - * (`$ref`s to `ComponentId` / `ChildList`, at any depth, e.g. `tabs[].child`), - * falling back to the conventional `child` / `children` properties for - * components whose schema is unknown. + * (`$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. */ @@ -81,6 +81,7 @@ export const ROOT_COMPONENT_ID = 'root'; const MAX_NODES = 5000; const COMPONENT_ID_DEF = 'ComponentId'; +const CHILD_DEF = 'Child'; const CHILD_LIST_DEF = 'ChildList'; const LOCAL_DEFS_PREFIX = '#/$defs/'; const ANY_INDEX = '*'; @@ -96,7 +97,7 @@ type ReferenceKind = 'single' | 'list'; 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)) return 'single'; + if (is(COMPONENT_ID_DEF) || is(CHILD_DEF)) return 'single'; if (is(CHILD_LIST_DEF)) return 'list'; return null; } From 3d089576cd1e5f8eea1f2902d2488b0dc8f6a400 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 15:24:29 -0800 Subject: [PATCH 21/50] Add mergedActiveCatalog --- .../component-tree/component-tree.spec.ts | 118 ++++++++++++++++++ .../debug/component-tree/component-tree.ts | 4 +- 2 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 shell/src/app/debug/component-tree/component-tree.spec.ts 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..52cd3f8af --- /dev/null +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -0,0 +1,118 @@ +/** + * 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 {signal, WritableSignal} from '@angular/core'; +import {beforeEach, describe, expect, it} from 'vitest'; +import {StateSync} from '../../chat/state-sync/state-sync'; +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'; + +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`}}}, + 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 activeDraft: WritableSignal; + let activeCatalog: WritableSignal; + let mergedActiveCatalog: WritableSignal; + + const getRowIds = (): Array => + Array.from(fixture.nativeElement.querySelectorAll('.tree-row .id')).map( + element => element.textContent, + ); + + const getRowViaLabels = (): Array => + Array.from(fixture.nativeElement.querySelectorAll('.tree-row .via')).map( + element => element.textContent, + ); + + beforeEach(async () => { + activeDraft = signal(formatJson(SECONDARY_MODAL_MESSAGES)); + activeCatalog = signal(null); + mergedActiveCatalog = signal(null); + + await TestBed.configureTestingModule({ + imports: [ComponentTree], + providers: [ + {provide: StateSync, useValue: {activeDraft}}, + {provide: CatalogManagement, useValue: {activeCatalog, mergedActiveCatalog}}, + ], + }).compileComponents(); + + fixture = TestBed.createComponent(ComponentTree); + }); + + it('prefers mergedActiveCatalog over activeCatalog so secondary catalog reference slots are expanded', () => { + activeCatalog.set(PRIMARY_CATALOG); + mergedActiveCatalog.set(MERGED_CATALOG); + + fixture.detectChanges(); + + expect(getRowIds()).toEqual(['#root', '#modal', '#open', '#body']); + expect(getRowViaLabels()).toEqual(['children:', 'trigger:', 'content:']); + expect(fixture.nativeElement.querySelector('.unreachable-header')).toBeNull(); + }); + + it('falls back to activeCatalog when mergedActiveCatalog is null', () => { + activeCatalog.set(MERGED_CATALOG); + mergedActiveCatalog.set(null); + + fixture.detectChanges(); + + expect(getRowIds()).toEqual(['#root', '#modal', '#open', '#body']); + expect(getRowViaLabels()).toEqual(['children:', 'trigger:', 'content:']); + expect(fixture.nativeElement.querySelector('.unreachable-header')).toBeNull(); + }); +}); diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index 162304cf4..9b0988af8 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -55,7 +55,9 @@ export class ComponentTree { protected readonly trees = computed(() => { const result = tryParseJsonArray(this.stateSync.activeDraft()); if (!result.success) return []; - return buildComponentTrees(result.data, this.catalogManagement.activeCatalog()); + const catalog = + this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); + return buildComponentTrees(result.data, catalog); }); protected isExpanded(node: ComponentTreeNode): boolean { From e4a4eb596f6b0eb58716d3555c10f649cc33d470 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 15:50:25 -0800 Subject: [PATCH 22/50] Guard $defs with Object.hasOwn and support #/definitions/ prefix --- .../component-tree-builder.spec.ts | 73 +++++++++++++++++++ .../component-tree/component-tree-builder.ts | 30 ++++++-- 2 files changed, 95 insertions(+), 8 deletions(-) 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 index b347073c7..cea5d77bc 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -308,4 +308,77 @@ describe('buildComponentTrees', () => { ]); 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']); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index f9d1d28dd..b9590b741 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -84,6 +84,7 @@ 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'; @@ -176,7 +177,8 @@ class ReferenceSchema { slotsFor(type: string): readonly ReferenceSlot[] { if (!this.cache.has(type)) { - const schema = this.catalog?.components?.[type]; + const components = this.catalog?.components; + const schema = components && Object.hasOwn(components, type) ? components[type] : undefined; let slots: ReferenceSlot[] | null = null; if (schema) { slots = []; @@ -203,13 +205,11 @@ class ReferenceSchema { out.push({path, kind}); return; } - if (ref.startsWith(LOCAL_DEFS_PREFIX)) { - const name = ref.slice(LOCAL_DEFS_PREFIX.length); - if (!visitingDefs.has(name)) { - visitingDefs.add(name); - this.walk(this.catalog?.$defs?.[name], path, out, visitingDefs); - visitingDefs.delete(name); - } + 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']) { @@ -228,6 +228,20 @@ class ReferenceSchema { 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. */ From fd91d631db90f92174826d9b4c251b91df0f8355 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 16:11:14 -0800 Subject: [PATCH 23/50] Fix docs, memoize ReferenceSchema, add parsedDraft signal --- .../component-tree-builder.spec.ts | 26 ++++++++++++++ .../component-tree/component-tree-builder.ts | 36 ++++++++++++------- .../component-tree/component-tree.spec.ts | 10 ++++++ .../debug/component-tree/component-tree.ts | 8 ++--- 4 files changed, 64 insertions(+), 16 deletions(-) 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 index cea5d77bc..7a122e4bb 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -381,4 +381,30 @@ describe('buildComponentTrees', () => { ]); 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']); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index b9590b741..c0ee5db40 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -171,23 +171,22 @@ function collectSurfaces(messages: readonly unknown[]): Map(); + private readonly cache = new Map(); constructor(private readonly catalog: Catalog | null) {} slotsFor(type: string): readonly ReferenceSlot[] { - if (!this.cache.has(type)) { - const components = this.catalog?.components; - const schema = components && Object.hasOwn(components, type) ? components[type] : undefined; - let slots: ReferenceSlot[] | null = null; - if (schema) { - slots = []; - this.walk(schema, [], slots, new Set()); - slots = slots.filter(s => !(s.path.length === 1 && s.path[0] === 'id')); - } + const components = this.catalog?.components; + const schema = components && Object.hasOwn(components, type) ? components[type] : undefined; + if (!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 this.cache.get(type) ?? FALLBACK_SLOTS; + return slots; } private walk( @@ -300,6 +299,19 @@ function collect( 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 @@ -309,7 +321,7 @@ export function buildComponentTrees( messages: readonly unknown[], catalog: Catalog | null, ): SurfaceComponentTree[] { - const schema = new ReferenceSchema(catalog); + const schema = referenceSchemaFor(catalog); const trees: SurfaceComponentTree[] = []; for (const [surfaceId, state] of collectSurfaces(messages)) { trees.push(buildSurfaceTree(surfaceId, state, schema)); diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 52cd3f8af..6e59978a1 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -115,4 +115,14 @@ describe('ComponentTree', () => { expect(getRowViaLabels()).toEqual(['children:', 'trigger:', 'content:']); expect(fixture.nativeElement.querySelector('.unreachable-header')).toBeNull(); }); + + it('renders a parse error message and no tree rows when the active draft is invalid JSON', () => { + activeDraft.set('{invalid'); + + fixture.detectChanges(); + + const errorMessage = fixture.nativeElement.querySelector('.tree-message.error'); + expect(errorMessage?.textContent).toContain('The A2UI JSON is invalid:'); + expect(getRowIds()).toEqual([]); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index 9b0988af8..c9213b0f5 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -27,8 +27,7 @@ import { } from './component-tree-builder'; /** - * A debug drawer panel showing the component tree of the current A2UI - * document. + * 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}. @@ -43,17 +42,18 @@ import { export class ComponentTree { private readonly stateSync = inject(StateSync); private readonly catalogManagement = inject(CatalogManagement); + private readonly parsedDraft = computed(() => tryParseJsonArray(this.stateSync.activeDraft())); /** Keys of collapsed nodes (nodes are expanded by default). */ protected readonly collapsed = signal>(new Set()); protected readonly parseError = computed(() => { - const result = tryParseJsonArray(this.stateSync.activeDraft()); + const result = this.parsedDraft(); return result.success ? null : result.error.message; }); protected readonly trees = computed(() => { - const result = tryParseJsonArray(this.stateSync.activeDraft()); + const result = this.parsedDraft(); if (!result.success) return []; const catalog = this.catalogManagement.mergedActiveCatalog() ?? this.catalogManagement.activeCatalog(); From 2f51f6aed88be0ee8c1b56c674baa53bed25cd8d Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 16:22:17 -0800 Subject: [PATCH 24/50] Add fallback item label --- .../component-tree/component-tree.ng.html | 2 +- .../component-tree/component-tree.spec.ts | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html index 60066c802..109ec099f 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -83,7 +83,7 @@ {{ node.type ?? '?' }} #{{ node.id }} @if (node.template !== null) { - each {{ node.template }} + each {{ node.template || 'item' }} } @if (node.shared) { shared diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 6e59978a1..da84febb1 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -125,4 +125,37 @@ describe('ComponentTree', () => { expect(errorMessage?.textContent).toContain('The A2UI JSON is invalid:'); expect(getRowIds()).toEqual([]); }); + + it('renders template badges with the data path or an item fallback when path is omitted', () => { + activeCatalog.set(PRIMARY_CATALOG); + activeDraft.set( + formatJson([ + { + version: '1.0', + createSurface: { + surfaceId: 's', + catalogId: 'primary-catalog', + components: [ + {id: 'root', component: 'Column', children: ['withPath', 'withoutPath']}, + { + id: 'withPath', + component: 'Column', + children: {componentId: 'rowA', path: '/items'}, + }, + {id: 'withoutPath', component: 'Column', children: {componentId: 'rowB'}}, + {id: 'rowA', component: 'Text', text: 'A'}, + {id: 'rowB', component: 'Text', text: 'B'}, + ], + }, + }, + ]), + ); + + fixture.detectChanges(); + + const badges = Array.from( + fixture.nativeElement.querySelectorAll('.tree-row .badge'), + ).map(element => element.textContent); + expect(badges).toEqual(['each /items', 'each item']); + }); }); From 8ee50f621b623260c221aff9141cc13efbc83abb Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 17:52:16 -0800 Subject: [PATCH 25/50] Add missing tests, e2e test --- shell/e2e/component-tree.e2e.ts | 80 ++++++++ .../component-tree-builder.spec.ts | 19 ++ .../component-tree/component-tree.spec.ts | 177 ++++++++++++++---- .../test/component-tree.harness.ts | 177 ++++++++++++++++++ 4 files changed, 417 insertions(+), 36 deletions(-) create mode 100644 shell/e2e/component-tree.e2e.ts create mode 100644 shell/src/app/debug/component-tree/test/component-tree.harness.ts diff --git a/shell/e2e/component-tree.e2e.ts b/shell/e2e/component-tree.e2e.ts new file mode 100644 index 000000000..46eb20e5b --- /dev/null +++ b/shell/e2e/component-tree.e2e.ts @@ -0,0 +1,80 @@ +/** + * 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 {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('button.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([]); + }); +}); 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 index 7a122e4bb..18f5e339f 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -407,4 +407,23 @@ describe('buildComponentTrees', () => { 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([]); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index da84febb1..24c27ddde 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -14,14 +14,16 @@ * limitations under the License. */ -import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {signal, WritableSignal} from '@angular/core'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; import {beforeEach, describe, expect, it} from 'vitest'; import {StateSync} from '../../chat/state-sync/state-sync'; 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'; @@ -29,6 +31,7 @@ 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'}}}, }, }; @@ -64,20 +67,11 @@ const SECONDARY_MODAL_MESSAGES = [ describe('ComponentTree', () => { let fixture: ComponentFixture; + let harness: ComponentTreeHarness; let activeDraft: WritableSignal; let activeCatalog: WritableSignal; let mergedActiveCatalog: WritableSignal; - const getRowIds = (): Array => - Array.from(fixture.nativeElement.querySelectorAll('.tree-row .id')).map( - element => element.textContent, - ); - - const getRowViaLabels = (): Array => - Array.from(fixture.nativeElement.querySelectorAll('.tree-row .via')).map( - element => element.textContent, - ); - beforeEach(async () => { activeDraft = signal(formatJson(SECONDARY_MODAL_MESSAGES)); activeCatalog = signal(null); @@ -92,41 +86,89 @@ describe('ComponentTree', () => { }).compileComponents(); fixture = TestBed.createComponent(ComponentTree); + fixture.detectChanges(); + harness = await TestbedHarnessEnvironment.harnessForFixture(fixture, ComponentTreeHarness); }); - it('prefers mergedActiveCatalog over activeCatalog so secondary catalog reference slots are expanded', () => { + it('prefers mergedActiveCatalog over activeCatalog so secondary catalog reference slots are expanded', async () => { activeCatalog.set(PRIMARY_CATALOG); mergedActiveCatalog.set(MERGED_CATALOG); - fixture.detectChanges(); - expect(getRowIds()).toEqual(['#root', '#modal', '#open', '#body']); - expect(getRowViaLabels()).toEqual(['children:', 'trigger:', 'content:']); - expect(fixture.nativeElement.querySelector('.unreachable-header')).toBeNull(); + 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', () => { + it('falls back to activeCatalog when mergedActiveCatalog is null', async () => { activeCatalog.set(MERGED_CATALOG); mergedActiveCatalog.set(null); - fixture.detectChanges(); - expect(getRowIds()).toEqual(['#root', '#modal', '#open', '#body']); - expect(getRowViaLabels()).toEqual(['children:', 'trigger:', 'content:']); - expect(fixture.nativeElement.querySelector('.unreachable-header')).toBeNull(); + 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', () => { + 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.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.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.getRowIds()).toEqual(['#orphan']); + }); + it('collapses and re-expands child rows when toggling a branch node', async () => { + activeCatalog.set(MERGED_CATALOG); fixture.detectChanges(); - const errorMessage = fixture.nativeElement.querySelector('.tree-message.error'); - expect(errorMessage?.textContent).toContain('The A2UI JSON is invalid:'); - expect(getRowIds()).toEqual([]); + 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('renders template badges with the data path or an item fallback when path is omitted', () => { + it('renders badges and tooltips for missing, cyclic, template, and shared nodes', async () => { activeCatalog.set(PRIMARY_CATALOG); activeDraft.set( formatJson([ @@ -136,26 +178,89 @@ describe('ComponentTree', () => { surfaceId: 's', catalogId: 'primary-catalog', components: [ - {id: 'root', component: 'Column', children: ['withPath', 'withoutPath']}, { - id: 'withPath', + id: 'root', component: 'Column', - children: {componentId: 'rowA', path: '/items'}, + children: ['ghost', 'loop', 'templatedPath', 'templatedNoPath', 'sharedLeaf'], }, - {id: 'withoutPath', component: 'Column', children: {componentId: 'rowB'}}, - {id: 'rowA', component: 'Text', text: 'A'}, - {id: 'rowB', component: 'Text', text: 'B'}, + {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(); - const badges = Array.from( - fixture.nativeElement.querySelectorAll('.tree-row .badge'), - ).map(element => element.textContent); - expect(badges).toEqual(['each /items', 'each item']); + expect(await harness.hasTruncatedBadge()).toBe(true); + expect(await harness.getRowIds()).toEqual(['#root']); }); }); 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..791cabf8a --- /dev/null +++ b/shell/src/app/debug/component-tree/test/component-tree.harness.ts @@ -0,0 +1,177 @@ +/** + * 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 {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; +} + +/** + * 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 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 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())); + } + + /** + * Clicks the expand/collapse toggle button 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 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 getToggleButton = this.locatorForOptional('button.toggle'); + + 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 toggleButton = await this.getToggleButton(); + + const expandedAttr = toggleButton ? await toggleButton.getAttribute('aria-expanded') : null; + + 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: expandedAttr === null ? null : expandedAttr === 'true', + }; + } + + async getId(): Promise { + return (await this.getIdElement()).text(); + } + + async toggle(): Promise { + const button = await this.getToggleButton(); + if (!button) { + throw new Error(`Row ${await this.getId()} does not have an expand/collapse toggle button.`); + } + await button.click(); + } +} From c6d78ab2994290807951cbe17da2a01029171172 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 25 Nov 2026 15:40:44 -0800 Subject: [PATCH 26/50] Fall back to child/children slots for stub schemas in ReferenceSchema --- .../component-tree-builder.spec.ts | 25 +++++++++++++++++++ .../component-tree/component-tree-builder.ts | 9 ++++++- 2 files changed, 33 insertions(+), 1 deletion(-) 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 index 18f5e339f..6388a3ca0 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -426,4 +426,29 @@ describe('buildComponentTrees', () => { 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([]); + }); }); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index c0ee5db40..6dc7bd3de 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -169,6 +169,13 @@ function collectSurfaces(messages: readonly unknown[]): Map Object.hasOwn(record, key)); +} + /** Discovers the reference slots of each component type from the catalog. */ class ReferenceSchema { private readonly cache = new Map(); @@ -178,7 +185,7 @@ class ReferenceSchema { slotsFor(type: string): readonly ReferenceSlot[] { const components = this.catalog?.components; const schema = components && Object.hasOwn(components, type) ? components[type] : undefined; - if (!schema) return FALLBACK_SLOTS; + if (!hasSchemaStructure(schema)) return FALLBACK_SLOTS; let slots = this.cache.get(type); if (!slots) { const discovered: ReferenceSlot[] = []; From d67de381eca06f47f40eaebb36a05da417a9a55f Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 25 Nov 2026 16:14:38 -0800 Subject: [PATCH 27/50] Treat blank drafts as empty message lists in ComponentTree --- .../debug/component-tree/component-tree.spec.ts | 15 +++++++++++++++ .../app/debug/component-tree/component-tree.ts | 7 +++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 24c27ddde..c285ae96d 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -130,6 +130,21 @@ describe('ComponentTree', () => { 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( diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index c9213b0f5..1f43cc4b0 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -19,7 +19,7 @@ import {NgTemplateOutlet} from '@angular/common'; import {MatTooltipModule} from '@angular/material/tooltip'; import {StateSync} from '../../chat/state-sync/state-sync'; import {CatalogManagement} from '../../storage/catalog-management/catalog-management'; -import {tryParseJsonArray} from '../../utils/json'; +import {JsonParseResult, tryParseJsonArray} from '../../utils/json'; import { ComponentTreeNode, SurfaceComponentTree, @@ -42,7 +42,10 @@ import { export class ComponentTree { private readonly stateSync = inject(StateSync); private readonly catalogManagement = inject(CatalogManagement); - private readonly parsedDraft = computed(() => tryParseJsonArray(this.stateSync.activeDraft())); + private readonly parsedDraft = computed>(() => { + const draft = this.stateSync.activeDraft(); + return draft.trim() ? tryParseJsonArray(draft) : {success: true, data: []}; + }); /** Keys of collapsed nodes (nodes are expanded by default). */ protected readonly collapsed = signal>(new Set()); From 05488cd11267216cba37ac05f4d0f6237c981f94 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Mon, 16 Nov 2026 19:12:16 -0800 Subject: [PATCH 28/50] Add component tree --- shell/src/app/debug/component-tree/component-tree.ng.html | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html index 109ec099f..125fcc6ca 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -14,7 +14,7 @@ limitations under the License. --> -
+
@if (parseError(); as error) {
The A2UI JSON is invalid: {{ error }}
} @else if (trees().length === 0) { @@ -56,6 +56,8 @@
From 1e2f38bae5a425ea75cbc9c21b233a910c8a51e5 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 25 Nov 2026 16:20:43 -0800 Subject: [PATCH 29/50] Open property editor on node select --- shell/e2e/workspace-layout-recovery.e2e.ts | 6 +- .../component-tree-builder.spec.ts | 76 +++++++- .../component-tree/component-tree-builder.ts | 56 ++++++ .../component-tree/component-tree.ng.html | 33 +++- .../debug/component-tree/component-tree.scss | 17 +- .../component-tree/component-tree.spec.ts | 176 +++++++++++++++++- .../debug/component-tree/component-tree.ts | 130 ++++++++++++- .../property-editor/property-editor.scss | 8 + .../composer-dockview.service.ts | 51 ++++- .../composer-workspace/composer-panel-id.ts | 1 + .../composer-workspace.spec.ts | 87 ++++++++- 11 files changed, 614 insertions(+), 27 deletions(-) diff --git a/shell/e2e/workspace-layout-recovery.e2e.ts b/shell/e2e/workspace-layout-recovery.e2e.ts index 69658096a..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(8); + 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 8 tabs are present - await expect(page.locator('.dv-tab')).toHaveCount(8); + // 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 index 6388a3ca0..83bc85fa2 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -16,7 +16,12 @@ import {describe, it, expect} from 'vitest'; import {Catalog} from '../../storage/models/catalog-storage.model'; -import {ComponentTreeNode, buildComponentTrees} from './component-tree-builder'; +import { + ComponentTreeNode, + buildComponentTrees, + getSurfaceComponent, + updateSurfaceComponent, +} from './component-tree-builder'; const COMMON = 'https://a2ui.org/specification/v0_9/common_types.json#/$defs'; @@ -452,3 +457,72 @@ describe('buildComponentTrees', () => { 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 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('leaves messages unchanged when the component is not found', () => { + const messages = surface([{id: 'root', component: 'Column', children: []}]); + + const updatedMessages = updateSurfaceComponent(messages, 's', 'missing', { + id: 'missing', + component: 'Text', + text: 'No-op', + }); + + expect(updatedMessages).toEqual(messages); + }); +}); diff --git a/shell/src/app/debug/component-tree/component-tree-builder.ts b/shell/src/app/debug/component-tree/component-tree-builder.ts index 6dc7bd3de..e8df0ef79 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -421,3 +421,59 @@ function buildSurfaceTree( 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; +} + +/** + * Returns a copy of [messages] with component [componentId] in [surfaceId] + * replaced by [updatedComponent] in its latest `updateComponents` message. + */ +export function updateSurfaceComponent( + messages: readonly unknown[], + surfaceId: string, + componentId: string, + updatedComponent: Record, +): 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 components = updateComponents['components']; + 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; + const nextMessages = [...messages]; + nextMessages[messageIndex] = { + ...record, + updateComponents: { + ...updateComponents, + components: nextComponents, + }, + }; + return nextMessages; + } + } + } + const createSurface = asRecord(record['createSurface']); + if (createSurface && createSurface['surfaceId'] === surfaceId) 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 index 125fcc6ca..1308e7f61 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -34,7 +34,7 @@ @if (tree.root; as root) { } @else {
No root component.
@@ -45,7 +45,7 @@ @for (node of tree.unreachable; track node.key) { } } @@ -53,11 +53,22 @@ }
- +
@if (node.children.length > 0) { + } @else { } diff --git a/shell/src/app/debug/component-tree/component-tree.scss b/shell/src/app/debug/component-tree/component-tree.scss index b017c2ed7..66898a2cd 100644 --- a/shell/src/app/debug/component-tree/component-tree.scss +++ b/shell/src/app/debug/component-tree/component-tree.scss @@ -101,12 +101,10 @@ code { } .toggle { - padding: 0; - border: none; - background: none; - color: inherit; cursor: pointer; line-height: 16px; + text-align: center; + user-select: none; } .via { 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 index d7fc8cf2c..85d07a10c 100644 --- a/shell/src/app/debug/component-tree/test/component-tree.harness.ts +++ b/shell/src/app/debug/component-tree/test/component-tree.harness.ts @@ -151,7 +151,7 @@ export class ComponentTreeHarness extends ComponentHarness { } /** - * Clicks the expand/collapse toggle button on the matching `#id` row (at the given occurrence). + * 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); @@ -212,7 +212,7 @@ class ComponentTreeRowHarness extends ComponentHarness { private readonly getTypeElement = this.locatorFor('.type'); private readonly getIdElement = this.locatorFor('.id'); private readonly getBadgeElements = this.locatorForAll('.badge'); - private readonly getToggleButton = this.locatorForOptional('button.toggle'); + private readonly getToggleElement = this.locatorForOptional('.toggle'); async getSummary(): Promise { const host = await this.host(); @@ -257,10 +257,10 @@ class ComponentTreeRowHarness extends ComponentHarness { } async toggle(): Promise { - const button = await this.getToggleButton(); - if (!button) { - throw new Error(`Row ${await this.getId()} does not have an expand/collapse toggle button.`); + const toggle = await this.getToggleElement(); + if (!toggle) { + throw new Error(`Row ${await this.getId()} does not have an expand/collapse toggle.`); } - await button.click(); + await toggle.click(); } } From 0e4f2b38a28b9b8518770a082c28373746a8732b Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 21:12:33 -0800 Subject: [PATCH 35/50] Add showHeader and showStatus options to property editor --- .../component-tree/component-tree.spec.ts | 17 ++ .../test/component-tree.harness.ts | 9 + .../property-editor/property-editor.ng.html | 15 ++ .../property-editor/property-editor.scss | 42 ++++- .../property-editor/property-editor.spec.ts | 178 ++++++++++++++++++ .../shared/property-editor/property-editor.ts | 55 +++++- .../test/property-editor.harness.ts | 29 ++- .../composer-dockview.service.ts | 2 + .../composer-workspace.spec.ts | 2 + 9 files changed, 333 insertions(+), 16 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 5faa6ca87..bce864200 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -394,6 +394,23 @@ describe('ComponentTree', () => { 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'); 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 index 85d07a10c..69223b0b1 100644 --- a/shell/src/app/debug/component-tree/test/component-tree.harness.ts +++ b/shell/src/app/debug/component-tree/test/component-tree.harness.ts @@ -32,6 +32,8 @@ export interface ComponentTreeRowSummary { readonly level: number | null; readonly tabIndex: number | null; readonly focused: boolean; + readonly hasNestedInteractive: boolean; + readonly toggleAriaHidden: string | null; } /** @@ -213,6 +215,9 @@ class ComponentTreeRowHarness extends ComponentHarness { 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(); @@ -220,6 +225,8 @@ class ComponentTreeRowHarness extends ComponentHarness { 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'); @@ -237,6 +244,8 @@ class ComponentTreeRowHarness extends ComponentHarness { 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, }; } diff --git a/shell/src/app/shared/property-editor/property-editor.ng.html b/shell/src/app/shared/property-editor/property-editor.ng.html index 6254988fa..50a847331 100644 --- a/shell/src/app/shared/property-editor/property-editor.ng.html +++ b/shell/src/app/shared/property-editor/property-editor.ng.html @@ -14,6 +14,21 @@ limitations under the License. --> +@if (showHeader() && componentHeader(); as header) { +
+ {{ header.type }} + @if (header.id) { + {{ ' ' }}#{{ header.id }} + } +
+} +@if (showStatus()) { +
+ @if (inlineStatusMessage(); as status) { +

{{ status }}

+ } +
+} @if (editableProperties().length) {
@for (prop of editableProperties(); track prop.name) { diff --git a/shell/src/app/shared/property-editor/property-editor.scss b/shell/src/app/shared/property-editor/property-editor.scss index 1f64d086a..5c710eea9 100644 --- a/shell/src/app/shared/property-editor/property-editor.scss +++ b/shell/src/app/shared/property-editor/property-editor.scss @@ -27,6 +27,38 @@ padding: 8px 12px; } +.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; @@ -203,20 +235,18 @@ letter-spacing: var(--mat-sys-body-small-tracking); } -.property-missing { - grid-column: 1 / -1; - margin: 0; +.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; - color: var(--mat-sys-error); - font: var(--mat-sys-body-small); - letter-spacing: var(--mat-sys-body-small-tracking); } .property-control input:focus-visible, diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index 35bf7458f..c358cdd7e 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -667,6 +667,184 @@ describe('PropertyEditor Component', () => { 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(); + }); }); // Shapes as CatalogSchemaResolver returns them for the basic catalog's common types. diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 5855ed98d..60d0f4211 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -116,6 +116,12 @@ export class PropertyEditor { /** 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>(); @@ -137,6 +143,11 @@ export class PropertyEditor { 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. */ @@ -196,6 +207,23 @@ export class PropertyEditor { 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, + ); + /** * Every catalog property of the selected component except its identity and constants. */ @@ -240,10 +268,11 @@ export class PropertyEditor { }); /** - * Clears any pending inline JSON field validation errors. + * Clears any pending inline JSON field validation errors and status feedback. */ clearErrors(): void { this.jsonFieldErrors.set({}); + this.setStatusMessage(''); } /** @@ -293,16 +322,13 @@ export class PropertyEditor { ), ); } - this.statusMessage.emit(''); + this.setStatusMessage(''); const schema = this.selectedComponentSchemas()[name]; if (value !== undefined && schema && !matchesSimpleSchema(value, schema)) { - const componentId = - typeof target['id'] === 'string' && target['id'].trim() - ? target['id'] - : (this.resolvedComponentKey() ?? 'target'); + const componentId = this.resolvedComponentId() ?? this.resolvedComponentKey() ?? 'target'; const reason = `"${name}" on "${componentId}" does not match its catalog property type or choices.`; if (emitStatus) { - this.statusMessage.emit(`${reason} Preview keeps its previous value.`); + this.setStatusMessage(`${reason} Preview keeps its previous value.`); } return reason; } @@ -359,15 +385,23 @@ export class PropertyEditor { required: boolean, label: string, ): void { + if (!this.component() || this.disabled()) { + return; + } if (value !== null && Number.isFinite(value)) { this.editAtPath(path, value); } else if (!required) { this.editAtPath(path, undefined); } else { - this.statusMessage.emit(`Enter a number for ${label}. Preview keeps its previous value.`); + 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. */ @@ -378,12 +412,16 @@ export class PropertyEditor { 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; } @@ -392,6 +430,7 @@ export class PropertyEditor { try { value = JSON.parse(text); } catch { + this.setStatusMessage(''); setError('Invalid JSON. The example keeps its previous value.'); return; } 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 index d8bc311ac..7940c93d2 100644 --- a/shell/src/app/shared/property-editor/test/property-editor.harness.ts +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -240,11 +240,36 @@ export class PropertyEditorHarness extends ComponentHarness { 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 { - const empty = await this.locatorForOptional('[data-property-empty-state]')(); - return empty ? (await empty.text()).trim() : null; + 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 120d97358..2511aaddb 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -453,6 +453,8 @@ export class ComposerDockview { inputBinding('component', () => this.componentTreeInstance()?.selectedComponent() ?? null), inputBinding('resetKey', () => this.componentTreeInstance()?.selected()?.surfaceId ?? null), inputBinding('disabled', () => this.chatState.isProgrammaticStreamActive()), + inputBinding('showHeader', () => true), + inputBinding('showStatus', () => true), outputBinding>('componentChange', updatedComponent => { this.componentTreeInstance()?.updateSelectedComponent(updatedComponent); }), 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 fa6c2973e..97fa747df 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -960,6 +960,8 @@ describe('ComposerWorkspace Dashboard', () => { const propertyEditorPanel = manager.api.getGroupPanel(ComposerPanelId.PropertyEditor); expect(propertyEditorPanel?.group.activePanel?.id).toBe(ComposerPanelId.PropertyEditor); expect(propertyEditor.resetKey()).toBe('s'); + expect(propertyEditor.showHeader()).toBe(true); + expect(propertyEditor.showStatus()).toBe(true); expect(propertyEditor.component()).toEqual({ id: 'title', component: 'Text', From ae78ad37072a8930b8a45b2345d5e02e9043e266 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 21:47:14 -0800 Subject: [PATCH 36/50] Re-resolve selection when tree() changes --- .../component-tree/component-tree.spec.ts | 101 ++++++++++++++++++ .../debug/component-tree/component-tree.ts | 28 ++++- 2 files changed, 126 insertions(+), 3 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index bce864200..959d37463 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -386,6 +386,107 @@ describe('ComponentTree', () => { expect(component.selected()?.id).toBe('root'); }); + const surfaceDraft = (components: Array>) => + formatJson([ + { + version: '1.0', + createSurface: {surfaceId: 's', catalogId: 'primary-catalog', components}, + }, + ]); + + 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('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(); diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index b18603cdd..347d1ed24 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import {Component, computed, inject, signal} from '@angular/core'; +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'; @@ -57,8 +57,30 @@ export class ComponentTree { return draft.trim() ? tryParseJsonArray(draft) : {success: true, data: []}; }); - /** Reference to the currently selected tree node, if any. */ - readonly selected = signal(null); + /** Reference to the currently selected tree node, re-resolved when the tree changes. */ + readonly selected = linkedSignal({ + source: () => (this.parsedDraft().success ? this.trees() : null), + computation: (trees, previous) => { + const current = previous?.value ?? null; + 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; + }, + }); /** The component definition for the currently selected tree node, if defined. */ readonly selectedComponent = computed | null>(() => { From e27acd3d24c1c52a4f6800b5969350873fd38635 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 21:54:16 -0800 Subject: [PATCH 37/50] Add missing getSurfaceComponent test for v1.0 --- .../component-tree-builder.spec.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) 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 index 36327f1c0..7142d33a8 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -485,6 +485,27 @@ describe('getSurfaceComponent', () => { }); }); + 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: []}]); From 44aebb8ffe5988045208205a522075b0774281f3 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 22:08:43 -0800 Subject: [PATCH 38/50] Scope PropertyEditor resetKey by occurrence key and draft revision --- .../composer-dockview.service.ts | 12 +++- .../composer-workspace.spec.ts | 65 ++++++++++++++++++- 2 files changed, 75 insertions(+), 2 deletions(-) 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 2511aaddb..8e90bf66e 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -24,6 +24,7 @@ import { Binding, inject, inputBinding, + linkedSignal, outputBinding, signal, } from '@angular/core'; @@ -33,6 +34,7 @@ import {LocalStorageInteractions} from '../../storage/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'; @@ -123,6 +125,7 @@ export class ComposerDockview { private readonly cdr = inject(ChangeDetectorRef); private readonly chatPanelComponent = inject(CHAT_PANEL_COMPONENT); private readonly chatState = inject(ChatState); + private readonly stateSync = inject(StateSync); private rootEl?: HTMLElement; private dockviewApi!: DockviewComponent; @@ -133,6 +136,10 @@ export class ComposerDockview { private eventsInstance?: Events; private errorsInstance?: Errors; private readonly componentTreeInstance = signal(undefined); + private readonly draftRevision = linkedSignal<[string, number], number>({ + source: () => [this.stateSync.activeDraft(), this.stateSync.sessionResetNonce()], + computation: (_source, previous) => (previous?.value ?? -1) + 1, + }); private resizeObserver?: ResizeObserver; private animationFrameId?: number; @@ -451,7 +458,10 @@ export class ComposerDockview { private getPropertyEditorBindings(): Binding[] { return [ inputBinding('component', () => this.componentTreeInstance()?.selectedComponent() ?? null), - inputBinding('resetKey', () => this.componentTreeInstance()?.selected()?.surfaceId ?? null), + inputBinding('resetKey', () => { + const selected = this.componentTreeInstance()?.selected(); + return selected ? `${selected.surfaceId}:${selected.key}:${this.draftRevision()}` : null; + }), inputBinding('disabled', () => this.chatState.isProgrammaticStreamActive()), inputBinding('showHeader', () => true), inputBinding('showStatus', () => true), 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 97fa747df..dc95e620e 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -959,7 +959,7 @@ describe('ComposerWorkspace Dashboard', () => { const propertyEditorPanel = manager.api.getGroupPanel(ComposerPanelId.PropertyEditor); expect(propertyEditorPanel?.group.activePanel?.id).toBe(ComposerPanelId.PropertyEditor); - expect(propertyEditor.resetKey()).toBe('s'); + expect(propertyEditor.resetKey()).toBe('s:s/root/0:title:0'); expect(propertyEditor.showHeader()).toBe(true); expect(propertyEditor.showStatus()).toBe(true); expect(propertyEditor.component()).toEqual({ @@ -988,6 +988,69 @@ describe('ComposerWorkspace Dashboard', () => { }); }); + 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('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); + }); + it('disables the Property Editor when a programmatic stream starts', () => { const chatState = TestBed.inject(ChatState) as unknown as MockChatState; From 419bf5b1394b9e64e1b4a25e37d0f920929bb59d Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 22:16:30 -0800 Subject: [PATCH 39/50] Export TreeNodeRef and refine JSDoc --- shell/src/app/debug/component-tree/component-tree.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index 347d1ed24..d90b84312 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -29,8 +29,11 @@ import { updateSurfaceComponent, } from './component-tree-builder'; -/** Reference to a node occurrence in a surface's component tree. */ -interface TreeNodeRef { +/** + * 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; From 0996b007534c7728e20f199f5445f5aa9d0159bc Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Wed, 18 Nov 2026 22:34:41 -0800 Subject: [PATCH 40/50] Fix selected signal encapsulation violation and session reset clearing, add missing node message --- .../component-tree/component-tree.spec.ts | 19 ++++++++++++ .../debug/component-tree/component-tree.ts | 24 ++++++++++----- .../composer-dockview.service.ts | 11 +++++++ .../composer-workspace.spec.ts | 30 +++++++++++++++++++ 4 files changed, 77 insertions(+), 7 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 959d37463..3b30b8e16 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -72,12 +72,14 @@ describe('ComponentTree', () => { 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)); @@ -89,6 +91,7 @@ describe('ComponentTree', () => { provide: StateSync, useValue: { activeDraft, + sessionResetNonce, updateDraft: updateDraftSpy, }, }, @@ -467,6 +470,22 @@ describe('ComponentTree', () => { 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'); diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index d90b84312..1ebb43315 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -60,11 +60,17 @@ export class ComponentTree { return draft.trim() ? tryParseJsonArray(draft) : {success: true, data: []}; }); - /** Reference to the currently selected tree node, re-resolved when the tree changes. */ - readonly selected = linkedSignal({ - source: () => (this.parsedDraft().success ? this.trees() : null), - computation: (trees, previous) => { - const current = previous?.value ?? null; + 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; @@ -85,6 +91,9 @@ export class ComponentTree { }, }); + /** 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(); @@ -100,7 +109,8 @@ export class ComponentTree { /** Reference to the currently focused tree node for roving tabindex. */ protected readonly focused = signal(null); - protected readonly parseError = computed(() => { + /** 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; }); @@ -151,7 +161,7 @@ export class ComponentTree { event?.preventDefault(); const ref: TreeNodeRef = {surfaceId, key: node.key, id: node.id}; this.focused.set(ref); - this.selected.set(ref); + this._selected.set(ref); window.dispatchEvent(new OpenPanelEvent(ComposerPanelId.PropertyEditor)); } 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 8e90bf66e..ef47cea4d 100644 --- a/shell/src/app/shell/composer-workspace/composer-dockview.service.ts +++ b/shell/src/app/shell/composer-workspace/composer-dockview.service.ts @@ -463,6 +463,17 @@ export class ComposerDockview { 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 => { 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 dc95e620e..59d3dbe52 100644 --- a/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts +++ b/shell/src/app/shell/composer-workspace/composer-workspace.spec.ts @@ -1049,6 +1049,36 @@ describe('ComposerWorkspace Dashboard', () => { 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', () => { From 31c7a2bf2b281aee9002090b8170fd3ac8694eb4 Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Thu, 19 Nov 2026 14:56:23 -0800 Subject: [PATCH 41/50] Skip no-op updateDraft calls & throttle text input side effects --- .../component-tree-builder.spec.ts | 14 +- .../component-tree/component-tree-builder.ts | 7 +- .../component-tree/component-tree.spec.ts | 27 +- .../debug/component-tree/component-tree.ts | 1 + .../property-editor/property-editor.ng.html | 2 + .../property-editor/property-editor.spec.ts | 341 +++++++++++++++++- .../shared/property-editor/property-editor.ts | 95 ++++- .../test/property-editor.harness.ts | 25 +- 8 files changed, 482 insertions(+), 30 deletions(-) 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 index 7142d33a8..5267e63a3 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.spec.ts @@ -625,6 +625,7 @@ describe('updateSurfaceComponent', () => { }, }, ]; + const snapshot = structuredClone(messages); const updatedMessages = updateSurfaceComponent(messages, 's', 'title', { id: 'title', @@ -632,7 +633,8 @@ describe('updateSurfaceComponent', () => { text: 'Edited', }); - expect(updatedMessages).toEqual(messages); + expect(updatedMessages).toBe(messages); + expect(messages).toEqual(snapshot); }); it('does not mutate components after a surface was deleted', () => { @@ -640,6 +642,7 @@ describe('updateSurfaceComponent', () => { ...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', @@ -647,11 +650,13 @@ describe('updateSurfaceComponent', () => { text: 'Edited', }); - expect(updatedMessages).toEqual(messages); + expect(updatedMessages).toBe(messages); + expect(messages).toEqual(snapshot); }); - it('leaves messages unchanged when the component is not found', () => { + 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', @@ -659,6 +664,7 @@ describe('updateSurfaceComponent', () => { text: 'No-op', }); - expect(updatedMessages).toEqual(messages); + 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 index 476da4459..196c646b9 100644 --- a/shell/src/app/debug/component-tree/component-tree-builder.ts +++ b/shell/src/app/debug/component-tree/component-tree-builder.ts @@ -452,14 +452,15 @@ function replaceLastMatchingComponent( /** * Returns a copy of [messages] with component [componentId] in [surfaceId] * replaced by [updatedComponent] in its latest `updateComponents` or inline - * `createSurface` message. + * `createSurface` message, or [messages] unchanged if no matching component is + * found. */ export function updateSurfaceComponent( messages: readonly unknown[], surfaceId: string, componentId: string, updatedComponent: Record, -): unknown[] { +): readonly unknown[] { for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex--) { const record = asRecord(messages[messageIndex]); if (!record) continue; @@ -511,5 +512,5 @@ export function updateSurfaceComponent( break; } } - return [...messages]; + return messages; } diff --git a/shell/src/app/debug/component-tree/component-tree.spec.ts b/shell/src/app/debug/component-tree/component-tree.spec.ts index 3b30b8e16..cadef16cd 100644 --- a/shell/src/app/debug/component-tree/component-tree.spec.ts +++ b/shell/src/app/debug/component-tree/component-tree.spec.ts @@ -313,6 +313,14 @@ describe('ComponentTree', () => { }); 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(); @@ -379,6 +387,17 @@ describe('ComponentTree', () => { ]); }); + 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'); @@ -389,14 +408,6 @@ describe('ComponentTree', () => { expect(component.selected()?.id).toBe('root'); }); - const surfaceDraft = (components: Array>) => - formatJson([ - { - version: '1.0', - createSurface: {surfaceId: 's', catalogId: 'primary-catalog', components}, - }, - ]); - it('keeps the highlight on the selected occurrence of a shared component when edited', async () => { activeDraft.set( surfaceDraft([ diff --git a/shell/src/app/debug/component-tree/component-tree.ts b/shell/src/app/debug/component-tree/component-tree.ts index 1ebb43315..d0ddf3639 100644 --- a/shell/src/app/debug/component-tree/component-tree.ts +++ b/shell/src/app/debug/component-tree/component-tree.ts @@ -176,6 +176,7 @@ export class ComponentTree { selected.id, updatedComponent, ); + if (updatedMessages === result.data) return; this.stateSync.updateDraft(formatJson(updatedMessages)); } diff --git a/shell/src/app/shared/property-editor/property-editor.ng.html b/shell/src/app/shared/property-editor/property-editor.ng.html index 50a847331..f37222370 100644 --- a/shell/src/app/shared/property-editor/property-editor.ng.html +++ b/shell/src/app/shared/property-editor/property-editor.ng.html @@ -153,6 +153,7 @@

Common properties

[placeholder]="required ? '' : 'Not set'" [ngModel]="value ?? null" (ngModelChange)="editNumberAtPath(path, $event, required, label)" + (blur)="flushPendingCommit()" [disabled]="disabled()" /> } @else if (control.kind === 'string') { @@ -165,6 +166,7 @@

Common properties

[placeholder]="required ? '' : 'Not set'" [ngModel]="value ?? ''" (ngModelChange)="editTextAtPath(path, $event, required)" + (blur)="flushPendingCommit()" [disabled]="disabled()" /> } @else if (control.kind === 'array') { diff --git a/shell/src/app/shared/property-editor/property-editor.spec.ts b/shell/src/app/shared/property-editor/property-editor.spec.ts index c358cdd7e..eb81c127e 100644 --- a/shell/src/app/shared/property-editor/property-editor.spec.ts +++ b/shell/src/app/shared/property-editor/property-editor.spec.ts @@ -17,7 +17,7 @@ import {ComponentFixture, TestBed} from '@angular/core/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {signal} from '@angular/core'; -import {describe, it, expect, beforeEach, vi} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {PropertyEditor} from './property-editor'; import { createDefaultPropertyValue, @@ -845,6 +845,345 @@ describe('PropertyEditor Component', () => { 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('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. diff --git a/shell/src/app/shared/property-editor/property-editor.ts b/shell/src/app/shared/property-editor/property-editor.ts index 60d0f4211..5e6539ecc 100644 --- a/shell/src/app/shared/property-editor/property-editor.ts +++ b/shell/src/app/shared/property-editor/property-editor.ts @@ -24,8 +24,11 @@ import { 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'; @@ -46,6 +49,13 @@ 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; /** @@ -224,6 +234,20 @@ export class PropertyEditor { : 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, + }); + + /** + * Component record read by edit mutations: layers any in-flight debounced edit on top of + * `component()` so discrete controls or sibling fields don't lose uncommitted keystrokes. + */ + private readonly activeComponent = computed(() => this.pendingCommit() ?? this.component()); + /** * Every catalog property of the selected component except its identity and constants. */ @@ -267,14 +291,44 @@ export class PropertyEditor { ); }); + 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 and status feedback. + * Clears any pending inline JSON field validation errors, status feedback, and debounced edits. */ clearErrors(): void { + this.pendingCommit.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): void { + this.pendingCommit.set(null); + const current = this.component(); + if (!current || stableStringify(updatedComponent) === stableStringify(current)) { + return; + } + this.componentChange.emit(updatedComponent); + } + /** * Property names every component in the catalog declares. */ @@ -310,8 +364,9 @@ export class PropertyEditor { /** * Sets one property on the target component, or removes it when value is undefined. */ - protected editProperty(name: string, value: unknown, emitStatus = true): string | null { - const target = this.component(); + 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; } @@ -325,6 +380,9 @@ export class PropertyEditor { 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) { @@ -339,14 +397,24 @@ export class PropertyEditor { const {[name]: _removed, ...rest} = target; updatedComponent = rest; } - this.componentChange.emit(updatedComponent); + if (debounce) { + this.pendingCommit.set(updatedComponent); + this.pendingCommit$.next(updatedComponent); + } else { + this.pendingCommit.set(null); + this.componentChange.emit(updatedComponent); + } return null; } /** * Updates a top-level or nested property at `path`. */ - protected editAtPath(path: PropertyPath, value: unknown, emitStatus = true): string | null { + protected editAtPath( + path: PropertyPath, + value: unknown, + options: EditOptions = {}, + ): string | null { if (path.length === 0) { return null; } @@ -355,9 +423,9 @@ export class PropertyEditor { return null; } if (rest.length === 0) { - return this.editProperty(rootName, value, emitStatus); + return this.editProperty(rootName, value, options); } - const currentRoot = this.component()?.[rootName]; + const currentRoot = this.activeComponent()?.[rootName]; const topProp = this.editableProperties().find(prop => prop.name === rootName); const updatedRoot = this.setDeepValue( currentRoot, @@ -366,14 +434,14 @@ export class PropertyEditor { topProp?.control, topProp?.required ?? false, ); - return this.editProperty(rootName, updatedRoot, emitStatus); + 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); + this.editAtPath(path, value === '' && !required ? undefined : value, {debounce: true}); } /** @@ -389,10 +457,11 @@ export class PropertyEditor { return; } if (value !== null && Number.isFinite(value)) { - this.editAtPath(path, value); + this.editAtPath(path, value, {debounce: true}); } else if (!required) { - this.editAtPath(path, undefined); + this.editAtPath(path, undefined, {debounce: true}); } else { + this.pendingCommit.set(null); this.setStatusMessage(`Enter a number for ${label}. Preview keeps its previous value.`); } } @@ -435,7 +504,7 @@ export class PropertyEditor { return; } } - const error = this.editAtPath(path, value, false); + const error = this.editAtPath(path, value, {emitStatus: false}); if (error) { setError(`${error} The example keeps its previous value.`); return; @@ -479,7 +548,7 @@ export class PropertyEditor { * Deep-gets a value from the editable component by the property path. */ private getValueAtPath(path: PropertyPath): unknown { - let current: unknown = this.component(); + let current: unknown = this.activeComponent(); for (const segment of path) { if (typeof segment === 'number') { if (!Array.isArray(current)) { 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 index 7940c93d2..dcc810ad3 100644 --- a/shell/src/app/shared/property-editor/test/property-editor.harness.ts +++ b/shell/src/app/shared/property-editor/test/property-editor.harness.ts @@ -24,14 +24,37 @@ export class PropertyEditorHarness extends ComponentHarness { static hostSelector = 'a2ui-composer-property-editor'; /** - * Edits a supported literal property using its visible control. + * 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. */ From b47e699fc0c3968407fab1f0c3475fb560411f3c Mon Sep 17 00:00:00 2001 From: Dustin Huang Date: Thu, 19 Nov 2026 15:42:08 -0800 Subject: [PATCH 42/50] Add first/last node keyboard navigation via Home/End --- .../component-tree/component-tree.ng.html | 2 + .../component-tree/component-tree.spec.ts | 56 +++++++++++++++++++ .../debug/component-tree/component-tree.ts | 21 +++++-- 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/shell/src/app/debug/component-tree/component-tree.ng.html b/shell/src/app/debug/component-tree/component-tree.ng.html index d433c8492..3543cf942 100644 --- a/shell/src/app/debug/component-tree/component-tree.ng.html +++ b/shell/src/app/debug/component-tree/component-tree.ng.html @@ -91,6 +91,8 @@ (keydown.arrowUp)="focusPreviousNode($event)" (keydown.arrowLeft)="collapseNode(node, parentRow, $event)" (keydown.arrowRight)="expandNode(node, $event)" + (keydown.home)="focusFirstNode($event)" + (keydown.end)="focusLastNode($event)" > @if (node.children.length > 0) {