diff --git a/Documentation/ComponentPicker/index.md b/Documentation/ComponentPicker/index.md
index c6ed98e0..62565666 100644
--- a/Documentation/ComponentPicker/index.md
+++ b/Documentation/ComponentPicker/index.md
@@ -133,6 +133,12 @@ Components with descriptors today:
| --- | --- | --- |
| `Button` | `Button` | `label`, `tooltip`, `variant`, `tone`, `shape`, `size` |
| `IconButton` | `IconButton` | `tooltip`, `variant`, `tone`, `shape`, `size` |
+| `Badge` | `Badge` | `severity`, `size`, `shape` |
+| `Chip` | `Chip` | `label`, `removeAriaLabel` |
+| `Avatar` | `Avatar` | `label`, `alt`, `size` |
+| `Tag` | `Tag` | `severity`, `rounded` |
+| `Skeleton` | `Skeleton` | `width`, `height`, `borderRadius`, `circle` |
+| `ProgressSpinner` | `ProgressSpinner` | `aria-label` |
| `TextInput` | `TextInput` | `placeholder`, `invalid`, `disabled`, `readOnly`, `type` |
| `TextArea` | `TextArea` | `placeholder`, `rows`, `invalid`, `disabled`, `readOnly` |
| `Dialog` | `Dialog` | `title`, `placement`, `width`, `okLabel`, `cancelLabel` |
diff --git a/Source/Chat/ChatConversation.tsx b/Source/Chat/ChatConversation.tsx
index ebeb300e..afa1d8c5 100644
--- a/Source/Chat/ChatConversation.tsx
+++ b/Source/Chat/ChatConversation.tsx
@@ -182,22 +182,24 @@ interface MessageRenderInfo {
showTimestamp: boolean;
}
+const hasSameAuthor = (left: ChatMessage, right: ChatMessage): boolean =>
+ chatIdentifierString(left.authorId) === chatIdentifierString(right.authorId);
+
+const startsAuthorGroup = (message: ChatMessage, previous: ChatMessage | undefined): boolean =>
+ !previous || !hasSameAuthor(previous, message);
+
+const endsTimestampGroup = (message: ChatMessage, next: ChatMessage | undefined): boolean =>
+ !next || !hasSameAuthor(next, message) || !sameMinute(timestampOf(message), timestampOf(next));
+
const computeRenderInfo = (messages: ChatMessage[]): MessageRenderInfo[] =>
messages.map((message, index) => {
const previous = index > 0 ? messages[index - 1] : undefined;
const next = index < messages.length - 1 ? messages[index + 1] : undefined;
- const showAuthor =
- !previous ||
- chatIdentifierString(previous.authorId) !==
- chatIdentifierString(message.authorId);
- const showTimestamp =
- !next ||
- chatIdentifierString(next.authorId) !==
- chatIdentifierString(message.authorId) ||
- !sameMinute(timestampOf(message), timestampOf(next));
-
- return { showAuthor, showTimestamp };
+ return {
+ showAuthor: startsAuthorGroup(message, previous),
+ showTimestamp: endsTimestampGroup(message, next),
+ };
});
/**
@@ -236,12 +238,15 @@ const conversationStatusLabel = (
}
};
+const showsStatusAlongsideMessages = (status: ChatStatus): boolean =>
+ status === ChatStatus.Failed || status === ChatStatus.Unauthorized;
+
const renderConversationStatus = (
messageCount: number,
status: ChatStatus,
labels: ChatConversationLabels | undefined,
) => {
- if (messageCount > 0 && status !== ChatStatus.Failed && status !== ChatStatus.Unauthorized) return null;
+ if (messageCount > 0 && !showsStatusAlongsideMessages(status)) return null;
return (
{conversationStatusLabel(status, labels)}
@@ -249,6 +254,21 @@ const renderConversationStatus = (
);
};
+const authorFor = (
+ authorId: ChatIdentifier,
+ authorOf: ChatConversationProps['authorOf'],
+): ChatAuthor => authorOf?.(authorId) ?? {
+ name: chatIdentifierString(authorId),
+ kind: ChatAuthorKind.User,
+};
+
+const availableActionsFor = (
+ message: TMessage,
+ actions: ChatMessageAction[] | undefined,
+): ChatMessageAction[] => (actions ?? []).filter(
+ action => action.isAvailable?.(message) ?? true,
+);
+
interface ConversationMessageProps extends Pick,
'renderAvatar' | 'renderAuthorName' | 'renderMessageExtra' | 'buildAvatarUrl' | 'labels'> {
message: TMessage;
@@ -375,12 +395,6 @@ export const ChatConversation = ({
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}, [messages, typingAuthors.length]);
- const authorFor = (authorId: ChatIdentifier): ChatAuthor =>
- authorOf?.(authorId) ?? {
- name: chatIdentifierString(authorId),
- kind: ChatAuthorKind.User,
- };
-
const send = (text: string, mentioned: MentionCandidate[]) =>
onSendMessage(
text,
@@ -401,10 +415,8 @@ export const ChatConversation = ({
0 || undefined}>
{renderConversationStatus(messages.length, status, labels)}
{status !== ChatStatus.Unauthorized && messages.map((message, index) => {
- const author = authorFor(message.authorId);
- const availableActions = (actions ?? []).filter(
- (action) => action.isAvailable?.(message) ?? true,
- );
+ const author = authorFor(message.authorId, authorOf);
+ const availableActions = availableActionsFor(message, actions);
return renderConversationMessage({
message,
author,
diff --git a/Source/Chat/for_ChatConversation/when_grouping_adjacent_messages.ts b/Source/Chat/for_ChatConversation/when_grouping_adjacent_messages.ts
new file mode 100644
index 00000000..f460a6a9
--- /dev/null
+++ b/Source/Chat/for_ChatConversation/when_grouping_adjacent_messages.ts
@@ -0,0 +1,46 @@
+// Copyright (c) Cratis. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+// @vitest-environment jsdom
+
+import { createElement } from 'react';
+import { ChatConversation } from '../ChatConversation';
+import type { ChatMessage } from '../ChatMessage';
+import { render, unmount, type ConversationInTheDom } from './given/a_conversation_in_the_dom';
+
+const messages: ChatMessage[] = [
+ { id: 'message-1', topicId: 'topic-1', authorId: 'author-1', body: 'First example', timestamp: new Date('2026-01-01T10:00:00Z') },
+ { id: 'message-2', topicId: 'topic-1', authorId: { toString: () => 'author-1' }, body: 'Second example', timestamp: new Date('2026-01-01T10:00:30Z') },
+ { id: 'message-3', topicId: 'topic-1', authorId: 'author-1', body: 'Third example', timestamp: new Date('2026-01-01T10:01:00Z') },
+ { id: 'message-4', topicId: 'topic-1', authorId: 'author-2', body: 'Fourth example', timestamp: new Date('2026-01-01T10:01:30Z') },
+];
+
+const messageRows = () => Array.from(document.querySelectorAll('.cratis-chat-message'));
+
+describe('when grouping adjacent messages', () => {
+ let conversation: ConversationInTheDom;
+
+ beforeEach(async () => {
+ conversation = await render(createElement(ChatConversation, {
+ messages,
+ onSendMessage: () => {},
+ }));
+ });
+
+ afterEach(async () => unmount(conversation));
+
+ it('should group authors by their string identifiers even across minutes', () => {
+ messageRows().map(row => row.classList.contains('cratis-chat-message--continuation'))
+ .should.deep.equal([false, true, true, false]);
+ });
+
+ it('should fall back to the author identifier when no resolver is supplied', () => {
+ Array.from(document.querySelectorAll('.cratis-chat-message__author-name'))
+ .map(author => author.textContent).should.deep.equal(['author-1', 'author-2']);
+ });
+
+ it('should show timestamps at minute changes, author changes and the last message', () => {
+ messageRows().map(row => row.querySelectorAll('.cratis-chat-message__time').length)
+ .should.deep.equal([0, 1, 1, 1]);
+ });
+});
diff --git a/Source/ComponentPicker/for_ComponentPicker/given/display_components.tsx b/Source/ComponentPicker/for_ComponentPicker/given/display_components.tsx
new file mode 100644
index 00000000..194d5e7d
--- /dev/null
+++ b/Source/ComponentPicker/for_ComponentPicker/given/display_components.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Cratis. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+import React, { type ReactElement } from 'react';
+import { Avatar } from '../../../Display/Avatar';
+import { Badge } from '../../../Display/Badge';
+import { Chip } from '../../../Display/Chip';
+import { ProgressSpinner } from '../../../Display/ProgressSpinner';
+import { Skeleton } from '../../../Display/Skeleton';
+import { Tag } from '../../../Display/Tag';
+import type { PresentationPropertyDescriptor } from '../../../configuration/identity/PresentationPropertyDescriptor';
+import type { PresentationPropertyValue } from '../../../configuration/identity/PresentationPropertyValue';
+
+interface DisplayComponentCase {
+ component: string;
+ element: ReactElement;
+ properties: readonly PresentationPropertyDescriptor
>[];
+ current: Record;
+ preview: Record;
+ read: (element: HTMLElement) => unknown;
+ rendered: unknown;
+ previewed: unknown;
+}
+
+export const displayComponents: readonly DisplayComponentCase[] = [
+ {
+ component: 'Badge',
+ element: ,
+ properties: [
+ { name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'info', 'success', 'warn', 'danger', 'contrast'], defaultValue: 'secondary' },
+ { name: 'size', label: 'Size', type: 'enum', values: ['small', 'large', 'xlarge'], defaultValue: 'small' },
+ { name: 'shape', label: 'Shape', type: 'enum', values: ['circle'] },
+ ],
+ current: { severity: 'info', size: 'large', shape: 'circle' },
+ preview: { severity: 'success', size: 'xlarge', shape: undefined },
+ read: (element) => [element.dataset.severity, element.dataset.size, element.dataset.shape, element.textContent],
+ rendered: ['info', 'large', 'circle', '7'],
+ previewed: ['success', 'xlarge', undefined, '7'],
+ },
+ {
+ component: 'Chip',
+ element: undefined} />,
+ properties: [
+ { name: 'label', label: 'Label', type: 'string' },
+ { name: 'removeAriaLabel', label: 'Remove accessible name', type: 'string', defaultValue: 'Remove' },
+ ],
+ current: { label: 'Example Project', removeAriaLabel: 'Remove example' },
+ preview: { label: 'Demo Assistant', removeAriaLabel: 'Remove preview' },
+ read: (element) => [element.querySelector('[data-cratis-part="label"]')?.textContent, element.querySelector('button')?.getAttribute('aria-label')],
+ rendered: ['Example Project', 'Remove example'],
+ previewed: ['Demo Assistant', 'Remove preview'],
+ },
+ {
+ component: 'Avatar',
+ element: ,
+ properties: [
+ { name: 'label', label: 'Label', type: 'string' },
+ { name: 'alt', label: 'Alternative text', type: 'string', defaultValue: '' },
+ { name: 'size', label: 'Size', type: 'enum', values: ['normal', 'large', 'xlarge'], defaultValue: 'normal' },
+ ],
+ current: { label: 'SU', alt: 'Sample User', size: 'large' },
+ preview: { label: 'DA', size: 'xlarge' },
+ read: (element) => [element.textContent, element.dataset.size],
+ rendered: ['SU', 'large'],
+ previewed: ['DA', 'xlarge'],
+ },
+ {
+ component: 'Tag',
+ element: ,
+ properties: [
+ { name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'success', 'info', 'warn', 'danger', 'contrast'], defaultValue: 'secondary' },
+ { name: 'rounded', label: 'Rounded', type: 'boolean' },
+ ],
+ current: { severity: 'info', rounded: false },
+ preview: { severity: 'success', rounded: true },
+ read: (element) => [element.dataset.severity, element.dataset.rounded, element.textContent],
+ rendered: ['info', undefined, 'Example status'],
+ previewed: ['success', 'true', 'Example status'],
+ },
+ {
+ component: 'Skeleton',
+ element: ,
+ properties: [
+ { name: 'width', label: 'Width', type: 'string', defaultValue: '100%' },
+ { name: 'height', label: 'Height', type: 'string', defaultValue: '1rem' },
+ { name: 'borderRadius', label: 'Border radius', type: 'string' },
+ { name: 'circle', label: 'Circle', type: 'boolean' },
+ ],
+ current: { width: '4rem', height: '2rem', borderRadius: '1px', circle: false },
+ preview: { width: '6rem', height: '3rem', borderRadius: '2px' },
+ read: (element) => [element.style.width, element.style.height, element.style.borderRadius, element.dataset.circle],
+ rendered: ['4rem', '2rem', '1px', undefined],
+ previewed: ['6rem', '3rem', '2px', undefined],
+ },
+ {
+ component: 'ProgressSpinner',
+ element: ,
+ properties: [
+ { name: 'aria-label', label: 'Accessible name', type: 'string', defaultValue: 'Loading' },
+ ],
+ current: { 'aria-label': 'Loading example' },
+ preview: { 'aria-label': 'Loading preview' },
+ read: (element) => element.getAttribute('aria-label'),
+ rendered: 'Loading example',
+ previewed: 'Loading preview',
+ },
+];
diff --git a/Source/ComponentPicker/for_ComponentPicker/when_picking_display_components.tsx b/Source/ComponentPicker/for_ComponentPicker/when_picking_display_components.tsx
new file mode 100644
index 00000000..103babbc
--- /dev/null
+++ b/Source/ComponentPicker/for_ComponentPicker/when_picking_display_components.tsx
@@ -0,0 +1,148 @@
+// Copyright (c) Cratis. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+// @vitest-environment jsdom
+
+import React, { act } from 'react';
+import { expect } from 'chai';
+import { vi } from 'vitest';
+import { Avatar } from '../../Display/Avatar';
+import { Badge } from '../../Display/Badge';
+import { Chip } from '../../Display/Chip';
+import { ProgressSpinner } from '../../Display/ProgressSpinner';
+import { Skeleton } from '../../Display/Skeleton';
+import { Tag } from '../../Display/Tag';
+import {
+ knownComponentDescriptors,
+ previewPresentationChanges,
+ registeredComponentFor,
+} from '../../configuration/identity/componentInstances';
+import type { PresentationChange } from '../../configuration/identity/PresentationChange';
+import { describeComponentElement } from '../describeComponentElement';
+import { displayComponents } from './given/display_components';
+import { click, hover, mountScreen, startPicking, unmountScreen, type ScreenInTheDom } from './given/a_screen_in_the_dom';
+
+for (const example of displayComponents) {
+ describe(`when picking a ${example.component}`, () => {
+ let screen: ScreenInTheDom;
+ let element: HTMLElement;
+
+ beforeEach(async () => {
+ screen = await mountScreen(<>{example.element}{example.element}>);
+ element = screen.container.querySelector(`[data-cratis-component="${example.component}"]`)!;
+ });
+
+ afterEach(async () => {
+ screen.picker().cancel();
+ await unmountScreen(screen);
+ });
+
+ it('should register exactly its typed presentation properties and allowed values', () => {
+ registeredComponentFor(element)!.descriptor.properties.should.deep.equal(example.properties);
+ });
+
+ it('should make its static descriptor discoverable', () => {
+ knownComponentDescriptors().find((descriptor) => descriptor.component === example.component)!
+ .should.equal(registeredComponentFor(element)!.descriptor);
+ });
+
+ it('should report current values through the picker', async () => {
+ const pending = await startPicking(screen);
+ await hover(element);
+ await click(element);
+ const picked = (await pending.result)!;
+ picked.component.should.equal(example.component);
+ picked.presentationProperties.map(({ name, value, editable }) => ({ name, value, editable }))
+ .should.deep.equal(Object.entries(example.current).map(([name, value]) => ({ name, value, editable: true })));
+ });
+
+ it('should read props from the registry rather than DOM attributes', () => {
+ element.setAttribute('data-size', 'DOM-only');
+ element.setAttribute('data-severity', 'DOM-only');
+ element.setAttribute('aria-label', 'DOM-only');
+ Object.fromEntries(describeComponentElement(element).presentationProperties.map(({ name, value }) => [name, value]))
+ .should.deep.equal(example.current);
+ });
+
+ it('should preview and revert without changing the registered props or another instance', async () => {
+ const changes: PresentationChange[] = Object.entries(example.preview).map(([property, to]) => ({
+ property, from: example.current[property], to,
+ }));
+ const original = registeredComponentFor(element)!.props;
+ const other = screen.container.querySelectorAll(`[data-cratis-component="${example.component}"]`)[1];
+ let revert!: () => void;
+ expect(example.read(element)).to.deep.equal(example.rendered);
+ await act(async () => { revert = previewPresentationChanges(element, changes); });
+ expect(example.read(element)).to.deep.equal(example.previewed);
+ expect(example.read(other)).to.deep.equal(example.rendered);
+ registeredComponentFor(element)!.props.should.equal(original);
+ Object.fromEntries(describeComponentElement(element).presentationProperties.map(({ name, value }) => [name, value]))
+ .should.deep.equal(example.current);
+ await act(async () => { revert(); revert(); });
+ expect(example.read(element)).to.deep.equal(example.rendered);
+ });
+
+ it('should unregister when unmounted', async () => {
+ await act(async () => screen.root.render(<>>));
+ expect(registeredComponentFor(element)).to.equal(undefined);
+ });
+ });
+}
+
+describe('when previewing display presentation details', () => {
+ let screen: ScreenInTheDom;
+
+ afterEach(async () => { await unmountScreen(screen); });
+
+ it('should preserve the existing defaults when there is no preview', async () => {
+ screen = await mountScreen(<>>);
+ screen.container.querySelector('[data-cratis-component="Avatar"]')!.getAttribute('data-size')!.should.equal('normal');
+ const badge = screen.container.querySelector('[data-cratis-component="Badge"]')!;
+ badge.getAttribute('data-severity')!.should.equal('secondary');
+ badge.getAttribute('data-size')!.should.equal('small');
+ screen.container.querySelector('button')!.getAttribute('aria-label')!.should.equal('Remove');
+ screen.container.querySelector('[data-cratis-component="Tag"]')!.getAttribute('data-severity')!.should.equal('secondary');
+ const skeleton = screen.container.querySelector('[data-cratis-component="Skeleton"]')!;
+ skeleton.style.width.should.equal('100%');
+ skeleton.style.height.should.equal('1rem');
+ screen.container.querySelector('[role="status"]')!.getAttribute('aria-label')!.should.equal('Loading');
+ expect(describeComponentElement(badge).presentationProperties[0].value).to.equal(undefined);
+ });
+
+ it('should preview and revert image alternative text', async () => {
+ screen = await mountScreen();
+ const element = screen.container.querySelector('[data-cratis-component="Avatar"]')!;
+ let revert!: () => void;
+ await act(async () => {
+ revert = previewPresentationChanges(element, [{ property: 'alt', from: 'Sample User', to: 'Demo Assistant' }]);
+ });
+ element.querySelector('img')!.alt.should.equal('Demo Assistant');
+ await act(async () => revert());
+ element.querySelector('img')!.alt.should.equal('Sample User');
+ });
+
+ it('should preview and revert a circular skeleton', async () => {
+ screen = await mountScreen();
+ const element = screen.container.querySelector('[data-cratis-component="Skeleton"]')!;
+ let revert!: () => void;
+ await act(async () => {
+ revert = previewPresentationChanges(element, [{ property: 'circle', from: undefined, to: true }]);
+ });
+ element.style.width.should.equal('2rem');
+ element.style.borderRadius.should.equal('50%');
+ element.getAttribute('data-circle')!.should.equal('true');
+ await act(async () => revert());
+ element.style.width.should.equal('4rem');
+ element.style.borderRadius.should.equal('1px');
+ expect(element.getAttribute('data-circle')).to.equal(null);
+ });
+
+ it('should preserve the chip remove callback during preview', async () => {
+ const onRemove = vi.fn();
+ screen = await mountScreen();
+ const element = screen.container.querySelector('[data-cratis-component="Chip"]')!;
+ await act(async () => { previewPresentationChanges(element, [{ property: 'label', from: 'Example Project', to: 'Demo Assistant' }]); });
+ await click(element.querySelector('button')!);
+ onRemove.mock.calls.length.should.equal(1);
+ });
+});
diff --git a/Source/Display/Avatar.tsx b/Source/Display/Avatar.tsx
index 5494957f..bad6e0f8 100644
--- a/Source/Display/Avatar.tsx
+++ b/Source/Display/Avatar.tsx
@@ -2,6 +2,8 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import type { ReactNode } from 'react';
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
/** Props for {@link Avatar}. */
export interface AvatarProps {
@@ -19,36 +21,39 @@ export interface AvatarProps {
className?: string;
}
+const avatarDescriptor = describeComponent('Avatar', [
+ { name: 'label', label: 'Label', type: 'string' },
+ { name: 'alt', label: 'Alternative text', type: 'string', defaultValue: '' },
+ { name: 'size', label: 'Size', type: 'enum', values: ['normal', 'large', 'xlarge'] satisfies NonNullable[], defaultValue: 'normal' },
+]);
+
/** A user or entity avatar with an image and text/icon fallback. */
-export const Avatar = ({
- image,
- label,
- icon,
- alt = '',
- size = 'normal',
- className,
-}: AvatarProps) => (
-
- {image ? (
-
- ) : (
-
- {icon ?? label}
-
- )}
-
-);
+export const Avatar = (props: AvatarProps) => {
+ const [presentation, marker] = useComponentPresentation(avatarDescriptor, props);
+ const { image, label, icon, alt = '', size = 'normal', className } = presentation;
+ return (
+
+ {image ? (
+
+ ) : (
+
+ {icon ?? label}
+
+ )}
+
+ );
+};
diff --git a/Source/Display/Badge.tsx b/Source/Display/Badge.tsx
index e16f920e..ba39d0d1 100644
--- a/Source/Display/Badge.tsx
+++ b/Source/Display/Badge.tsx
@@ -2,6 +2,8 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import type { ReactNode } from 'react';
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
/** Severity tone of a {@link Badge}. */
export type BadgeSeverity =
@@ -23,23 +25,26 @@ export interface BadgeProps {
children?: ReactNode;
}
+const badgeDescriptor = describeComponent('Badge', [
+ { name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'info', 'success', 'warn', 'danger', 'contrast'] satisfies NonNullable[], defaultValue: 'secondary' },
+ { name: 'size', label: 'Size', type: 'enum', values: ['small', 'large', 'xlarge'] satisfies NonNullable[], defaultValue: 'small' },
+ { name: 'shape', label: 'Shape', type: 'enum', values: ['circle'] satisfies NonNullable[] },
+]);
+
/** A compact count or status badge. */
-export const Badge = ({
- value,
- severity = 'secondary',
- size = 'small',
- shape,
- className,
- children,
-}: BadgeProps) => (
-
- {value ?? children}
-
-);
+export const Badge = (props: BadgeProps) => {
+ const [presentation, marker] = useComponentPresentation(badgeDescriptor, props);
+ const { value, severity = 'secondary', size = 'small', shape, className, children } = presentation;
+ return (
+
+ {value ?? children}
+
+ );
+};
diff --git a/Source/Display/Chip.tsx b/Source/Display/Chip.tsx
index 8fa05bb9..204a8eea 100644
--- a/Source/Display/Chip.tsx
+++ b/Source/Display/Chip.tsx
@@ -3,6 +3,8 @@
import type { ReactNode } from 'react';
import { useCratisIcon } from '../configuration/useCratisIcon';
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
/** Props for {@link Chip}. */
export interface ChipProps {
@@ -20,21 +22,21 @@ export interface ChipProps {
className?: string;
}
+const chipDescriptor = describeComponent('Chip', [
+ { name: 'label', label: 'Label', type: 'string' },
+ { name: 'removeAriaLabel', label: 'Remove accessible name', type: 'string', defaultValue: 'Remove' },
+]);
+
/** A labeled, optionally removable chip. */
-export const Chip = ({
- label,
- icon,
- removable,
- onRemove,
- removeAriaLabel = 'Remove',
- className,
-}: ChipProps) => {
+export const Chip = (props: ChipProps) => {
+ const [presentation, marker] = useComponentPresentation(chipDescriptor, props);
+ const { label, icon, removable, onRemove, removeAriaLabel = 'Remove', className } = presentation;
const resolveIcon = useCratisIcon();
return (
{icon && (
diff --git a/Source/Display/ProgressSpinner.tsx b/Source/Display/ProgressSpinner.tsx
index 91d51993..33d11bda 100644
--- a/Source/Display/ProgressSpinner.tsx
+++ b/Source/Display/ProgressSpinner.tsx
@@ -2,6 +2,8 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import type { CSSProperties } from 'react';
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
/** Props for {@link ProgressSpinner}. */
export interface ProgressSpinnerProps {
@@ -13,42 +15,46 @@ export interface ProgressSpinnerProps {
'aria-label'?: string;
}
+const progressSpinnerDescriptor = describeComponent('ProgressSpinner', [
+ { name: 'aria-label', label: 'Accessible name', type: 'string', defaultValue: 'Loading' },
+]);
+
/** An indeterminate loading spinner. */
-export const ProgressSpinner = ({
- style,
- className,
- 'aria-label': ariaLabel = 'Loading',
-}: ProgressSpinnerProps) => (
-
-
-
-);
+
+
+ );
+};
diff --git a/Source/Display/Skeleton.tsx b/Source/Display/Skeleton.tsx
index f1d09f2e..3289e1e8 100644
--- a/Source/Display/Skeleton.tsx
+++ b/Source/Display/Skeleton.tsx
@@ -1,6 +1,9 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
+
/** Props for {@link Skeleton}. */
export interface SkeletonProps {
/** Width, any CSS length. Defaults to `'100%'`. */
@@ -15,24 +18,29 @@ export interface SkeletonProps {
className?: string;
}
+const skeletonDescriptor = describeComponent('Skeleton', [
+ { name: 'width', label: 'Width', type: 'string', defaultValue: '100%' },
+ { name: 'height', label: 'Height', type: 'string', defaultValue: '1rem' },
+ { name: 'borderRadius', label: 'Border radius', type: 'string' },
+ { name: 'circle', label: 'Circle', type: 'boolean' },
+]);
+
/** A loading placeholder that reserves content layout. */
-export const Skeleton = ({
- width = '100%',
- height = '1rem',
- borderRadius,
- circle,
- className,
-}: SkeletonProps) => (
-
-);
+export const Skeleton = (props: SkeletonProps) => {
+ const [presentation, marker] = useComponentPresentation(skeletonDescriptor, props);
+ const { width = '100%', height = '1rem', borderRadius, circle, className } = presentation;
+ return (
+
+ );
+};
diff --git a/Source/Display/Tag.tsx b/Source/Display/Tag.tsx
index a9382f7b..4c7b91f1 100644
--- a/Source/Display/Tag.tsx
+++ b/Source/Display/Tag.tsx
@@ -3,6 +3,8 @@
import type { ReactNode } from 'react';
import { IconDisplay } from '../Common/Icon';
+import { describeComponent } from '../configuration/identity/describeComponent';
+import { useComponentPresentation } from '../configuration/identity/useComponentPresentation';
/** Severity tone of a {@link Tag}. */
export type TagSeverity =
@@ -27,29 +29,31 @@ export interface TagProps {
children?: ReactNode;
}
+const tagDescriptor = describeComponent('Tag', [
+ { name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'success', 'info', 'warn', 'danger', 'contrast'] satisfies NonNullable[], defaultValue: 'secondary' },
+ { name: 'rounded', label: 'Rounded', type: 'boolean' },
+]);
+
/** A small colored status label. */
-export const Tag = ({
- value,
- severity = 'secondary',
- rounded,
- icon,
- className,
- children,
-}: TagProps) => (
-
- {icon && (
-
-
+export const Tag = (props: TagProps) => {
+ const [presentation, marker] = useComponentPresentation(tagDescriptor, props);
+ const { value, severity = 'secondary', rounded, icon, className, children } = presentation;
+ return (
+
+ {icon && (
+
+
+
+ )}
+
+ {value ?? children}
- )}
-
- {value ?? children}
-
-);
+ );
+};
diff --git a/Source/SchemaEditor/Tree/TreeSchemaEditor.tsx b/Source/SchemaEditor/Tree/TreeSchemaEditor.tsx
index e0d53ef7..c3534290 100644
--- a/Source/SchemaEditor/Tree/TreeSchemaEditor.tsx
+++ b/Source/SchemaEditor/Tree/TreeSchemaEditor.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
+import { useEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from 'react';
import { FaPlus } from 'react-icons/fa6';
import type { ChangeHandler } from '../../types/ChangeHandler';
import type { JsonSchema } from '../../types/JsonSchema';
@@ -177,6 +177,143 @@ function allowance(flag: TreeSchemaEditorProps['allowKeyProperty'], callback: un
return allowed ? () => true : never;
}
+const createOwnedOperations = (
+ latest: RefObject,
+ apply: (next: Property[]) => void,
+ { onPropertyRemoved, onPropertyRenamed }: Pick,
+): SchemaEditorOperations => ({
+ addChild: (parentId, type, concept) =>
+ apply(addChildProperty(latest.current, parentId, type, totalPropertyCount(latest.current), concept)),
+ remove: propertyId => {
+ const removed = findPropertyById(latest.current, propertyId);
+ apply(removeProperty(latest.current, propertyId));
+ if (removed) onPropertyRemoved?.(removed);
+ },
+ rename: (propertyId, name) => {
+ const previousName = findPropertyById(latest.current, propertyId)?.name;
+ const next = renameProperty(latest.current, propertyId, name);
+ apply(next);
+ const renamed = findPropertyById(next, propertyId);
+ if (renamed && previousName !== undefined) onPropertyRenamed?.(renamed, previousName);
+ },
+ changeType: (propertyId, type, concept) => apply(changePropertyType(latest.current, propertyId, type, concept)),
+ setKey: propertyId => apply(setKeyProperty(latest.current, propertyId)),
+ setGenerated: (propertyId, isGenerated) => apply(setGeneratedProperty(latest.current, propertyId, isGenerated)),
+ setRequired: (propertyId, isRequired) => apply(setRequiredProperty(latest.current, propertyId, isRequired)),
+});
+
+const useOwnedPropertyTree = (
+ { schema, onChange, onPropertiesChange, onPropertyRemoved, onPropertyRenamed }: Pick,
+ isControlled: boolean,
+) => {
+ const [properties, setProperties] = useState(() => jsonSchemaToProperties(schema));
+ // The latest tree, kept synchronously so two edits in one event apply one after the other.
+ const latest = useRef(properties);
+ useEffect(() => { latest.current = properties; }, [properties]);
+
+ // A schema from outside replaces the tree only when it says something the editor does not already show:
+ // handing back what was reported, or the same schema again, must not throw away the property ids.
+ const incomingSchema = schema === undefined ? undefined : JSON.stringify(schema);
+ const [seenSchema, setSeenSchema] = useState(incomingSchema);
+ if (!isControlled && incomingSchema !== seenSchema) {
+ setSeenSchema(incomingSchema);
+ if (schema !== undefined && incomingSchema !== JSON.stringify(propertiesToJsonSchema(properties, schema))) {
+ setProperties(jsonSchemaToProperties(schema));
+ }
+ }
+
+ const apply = (next: Property[]) => {
+ latest.current = next;
+ setProperties(next);
+ onChange?.(propertiesToJsonSchema(next, schema), { source: 'user' });
+ onPropertiesChange?.(next);
+ };
+
+ return {
+ properties,
+ operations: createOwnedOperations(latest, apply, { onPropertyRemoved, onPropertyRenamed }),
+ addRoot: (type: PropertyType, concept?: string) =>
+ apply(addProperty(latest.current, type, totalPropertyCount(latest.current), concept)),
+ };
+};
+
+const renderEditorProperties = ({ properties, labels, parts: pt }: SchemaEditorContextValue) => (
+ properties.length === 0 ? (
+
+ {labels.emptyMessage}
+
+ ) : (
+
+ {properties.map(property => (
+
+ ))}
+
+ )
+);
+
+const renderEditorActions = (
+ { labels, concepts, parts: pt, readOnly }: SchemaEditorContextValue,
+ footer: ReactNode,
+ addRoot: TreeSchemaEditorProps['onAddProperty'],
+) => (
+ (footer || (!readOnly && addRoot)) && (
+
+ {!readOnly && addRoot && (
+
+
+ {labels.addProperty}
+
+ )}
+ {footer && (
+
+ {footer}
+
+ )}
+
+ )
+);
+
+const renderTreeEditor = (
+ contextValue: SchemaEditorContextValue,
+ { header, footer, 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, className }: Pick,
+ addRoot: TreeSchemaEditorProps['onAddProperty'],
+) => {
+ const { labels, parts: pt, readOnly } = contextValue;
+ return (
+
+
+ {header && (
+
+ {header}
+
+ )}
+
+ {renderEditorProperties(contextValue)}
+
+ {renderEditorActions(contextValue, footer, addRoot)}
+
+
+ );
+};
+
/**
* The tree layout of the {@link SchemaEditor} (`layout='tree'`). Edits the properties of a JSON Schema as a tree: names, types, nested objects and lists of objects, and
* optionally concepts, the key, and whether a property is required.
@@ -227,50 +364,8 @@ export const TreeSchemaEditor = ({
const providedConcepts = useOptionalPropertyConcepts();
const concepts = suppliedConcepts ?? providedConcepts;
const isControlled = controlledProperties !== undefined;
- const [ownedProperties, setOwnedProperties] = useState(() => jsonSchemaToProperties(schema));
- // The latest tree, kept synchronously so two edits in one event apply one after the other.
- const latest = useRef(ownedProperties);
- useEffect(() => { latest.current = ownedProperties; }, [ownedProperties]);
- const properties = isControlled ? controlledProperties : ownedProperties;
-
- // A schema from outside replaces the tree only when it says something the editor does not already show:
- // handing back what was reported, or the same schema again, must not throw away the property ids.
- const incomingSchema = schema === undefined ? undefined : JSON.stringify(schema);
- const [seenSchema, setSeenSchema] = useState(incomingSchema);
- if (!isControlled && incomingSchema !== seenSchema) {
- setSeenSchema(incomingSchema);
- if (schema !== undefined && incomingSchema !== JSON.stringify(propertiesToJsonSchema(ownedProperties, schema))) {
- setOwnedProperties(jsonSchemaToProperties(schema));
- }
- }
-
- const apply = (next: Property[]) => {
- latest.current = next;
- setOwnedProperties(next);
- onChange?.(propertiesToJsonSchema(next, schema), { source: 'user' });
- onPropertiesChange?.(next);
- };
-
- const ownedOperations: SchemaEditorOperations = {
- addChild: (parentId, type, concept) =>
- apply(addChildProperty(latest.current, parentId, type, totalPropertyCount(latest.current), concept)),
- remove: propertyId => {
- const removed = findPropertyById(latest.current, propertyId);
- apply(removeProperty(latest.current, propertyId));
- if (removed) onPropertyRemoved?.(removed);
- },
- rename: (propertyId, name) => {
- const previousName = findPropertyById(latest.current, propertyId)?.name;
- const next = renameProperty(latest.current, propertyId, name);
- apply(next);
- const renamed = findPropertyById(next, propertyId);
- if (renamed && previousName !== undefined) onPropertyRenamed?.(renamed, previousName);
- },
- changeType: (propertyId, type, concept) => apply(changePropertyType(latest.current, propertyId, type, concept)),
- setKey: propertyId => apply(setKeyProperty(latest.current, propertyId)),
- setGenerated: (propertyId, isGenerated) => apply(setGeneratedProperty(latest.current, propertyId, isGenerated)),
- setRequired: (propertyId, isRequired) => apply(setRequiredProperty(latest.current, propertyId, isRequired)),
- };
+ const owned = useOwnedPropertyTree({ schema, onChange, onPropertiesChange, onPropertyRemoved, onPropertyRenamed }, isControlled);
+ const properties = isControlled ? controlledProperties : owned.properties;
const controlledOperations: SchemaEditorOperations = {
addChild: onAddChildProperty,
@@ -282,11 +377,8 @@ export const TreeSchemaEditor = ({
setRequired: onSetRequiredProperty,
};
- const operations = isControlled ? controlledOperations : ownedOperations;
- const addRoot = isControlled
- ? onAddProperty
- : (type: PropertyType, concept?: string) =>
- apply(addProperty(latest.current, type, totalPropertyCount(latest.current), concept));
+ const operations = isControlled ? controlledOperations : owned.operations;
+ const addRoot = isControlled ? onAddProperty : owned.addRoot;
const contextValue: SchemaEditorContextValue = {
labels,
@@ -309,59 +401,11 @@ export const TreeSchemaEditor = ({
renderTypeBadge: renderPropertyTypeBadge,
};
- return (
-
-
- {header && (
-
- {header}
-
- )}
-
- {properties.length === 0 ? (
-
- {labels.emptyMessage}
-
- ) : (
-
- {properties.map(property => (
-
- ))}
-
- )}
-
- {(footer || (!readOnly && addRoot)) && (
-
- {!readOnly && addRoot && (
-
-
- {labels.addProperty}
-
- )}
- {footer && (
-
- {footer}
-
- )}
-
- )}
-
-
- );
+ return renderTreeEditor(contextValue, {
+ header,
+ footer,
+ 'aria-label': ariaLabel,
+ 'aria-labelledby': ariaLabelledBy,
+ className,
+ }, addRoot);
};
diff --git a/Source/SchemaEditor/Tree/for_TreeSchemaEditor/when_applying_owned_edits_in_one_event.tsx b/Source/SchemaEditor/Tree/for_TreeSchemaEditor/when_applying_owned_edits_in_one_event.tsx
new file mode 100644
index 00000000..78b9eeb8
--- /dev/null
+++ b/Source/SchemaEditor/Tree/for_TreeSchemaEditor/when_applying_owned_edits_in_one_event.tsx
@@ -0,0 +1,69 @@
+// Copyright (c) Cratis. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+// @vitest-environment jsdom
+
+import { expect } from 'chai';
+import { afterEach, beforeEach, describe, it } from 'vitest';
+import { SchemaEditor } from '../../SchemaEditor';
+import { useSchemaEditorContext } from '../SchemaEditorContext';
+import { Mount } from './Mount';
+
+const EditTwice = () => {
+ const { properties, operations } = useSchemaEditorContext();
+ const propertyId = properties[0].id;
+ return (
+
+ );
+};
+
+describe('when applying owned edits in one event', () => {
+ const mount = new Mount();
+ let notifications: string[];
+ let sources: Array;
+
+ beforeEach(async () => {
+ mount.setup();
+ notifications = [];
+ sources = [];
+ await mount.render(
+ }
+ onChange={(schema, change) => {
+ notifications.push(`schema:${Object.keys(schema.properties!).join(',')}`);
+ sources.push(change?.source);
+ }}
+ onPropertiesChange={properties => notifications.push(`properties:${properties.map(property => property.name).join(',')}`)}
+ onPropertyRenamed={(property, previousName) => notifications.push(`rename:${previousName}:${property.name}`)}
+ onPropertyRemoved={property => notifications.push(`remove:${property.name}`)} />);
+ await mount.click(document.querySelector('[data-testid="edit-twice"]')!);
+ });
+
+ afterEach(() => mount.teardown());
+
+ it('should notify schema and property changes before each edit notification', () => {
+ expect(notifications).to.deep.equal([
+ 'schema:renamed,second',
+ 'properties:renamed,second',
+ 'rename:first:renamed',
+ 'schema:second',
+ 'properties:second',
+ 'remove:renamed',
+ ]);
+ });
+
+ it('should report each change as user initiated', () => {
+ expect(sources).to.deep.equal(['user', 'user']);
+ });
+
+ it('should apply the second edit to the tree produced by the first', () => {
+ expect(mount.names()).to.deep.equal(['second']);
+ });
+});
diff --git a/Source/for_component_identity/when_checking_presentation_descriptors.ts b/Source/for_component_identity/when_checking_presentation_descriptors.ts
new file mode 100644
index 00000000..d6183856
--- /dev/null
+++ b/Source/for_component_identity/when_checking_presentation_descriptors.ts
@@ -0,0 +1,34 @@
+// Copyright (c) Cratis. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+
+import { readdirSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const sourceRoot = fileURLToPath(new URL('../', import.meta.url));
+const MINIMUM_DESCRIBED_COMPONENTS = 13;
+
+const descriptorNames = (source: string): string[] =>
+ [...source.matchAll(/describeComponent<\w+>\(\s*'(\w+)'/gu)].map((match) => match[1]);
+
+const descriptorsIn = (directory: string): string[] => readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ if (entry.isDirectory()) {
+ return ['node_modules', 'dist'].includes(entry.name) || entry.name.startsWith('for_') || entry.name.startsWith('.')
+ ? []
+ : descriptorsIn(`${directory}${entry.name}/`);
+ }
+ return /\.tsx?$/u.test(entry.name) && !entry.name.includes('.stories.')
+ ? descriptorNames(readFileSync(`${directory}${entry.name}`, 'utf8'))
+ : [];
+});
+
+describe('when checking presentation descriptor coverage', () => {
+ it('should recognize typed declarations rather than identity markers alone', () => {
+ descriptorNames("describeComponent('Example', []); data-cratis-component='MarkerOnly'")
+ .should.deep.equal(['Example']);
+ });
+
+ it('should retain at least thirteen statically described component types', () => {
+ const described = new Set(descriptorsIn(sourceRoot));
+ described.size.should.be.at.least(MINIMUM_DESCRIBED_COMPONENTS);
+ });
+});