Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Documentation/CommandDialog/advanced-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ On failure, the dialog awaits callbacks in this order, skipping any that do not

A validation failure therefore calls `onFailed` before `onValidationFailure`, not `onSuccess`. After the failure callbacks finish, the dialog applies the result to the form so matching fields show the server's validation messages. It does not automatically close on failure. See [Dialog Callbacks](index.md#dialog-callbacks) for the close decision and [Confirm before executing](index.md#confirm-before-executing) for guard failures before a command runs.

### When a result callback rejects

The busy state ends as soon as the command settles, before any result callback runs. The busy-state disabling is therefore lifted (normal validity rules still apply to confirm) while `onSuccess`, `onFailed` and the other result callbacks are awaited, so a slow callback should show its own progress if it needs to.

The command has already run by then, and a callback cannot undo it. If a callback throws or returns a rejected promise, the dialog stops at that point:

- Later callbacks in the same sequence do not run. A rejected `onFailed` skips `onException`, `onUnauthorized` and `onValidationFailure`; a rejected `onSuccess` skips `onConfirm` and the `onClose` fallback.
- After a failed command, the result is not applied to the form, so server validation messages do not appear on the fields.
- The dialog does not close automatically and does not announce a refusal. It stays open with its current values.

The command's outcome is unchanged: a successful command stays successful even when `onSuccess` rejects. Catch errors inside your callbacks when the rest of the sequence must still run, and report them in your own UI.

### Announcing validation failures

When a submit is refused with validation results, the dialog announces a summary in its polite live region and moves focus to the first invalid field: the first element in the dialog body marked `aria-invalid="true"`, or the first focusable element inside it. The default English text is `There is 1 problem. <message>` for one result and `There are <count> problems. First: <message>` for more. If no field is marked invalid, focus returns to the confirm button.
Expand Down
2 changes: 1 addition & 1 deletion Documentation/CommandDialog/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ Pressing `Enter` inside a text field does not submit the command. The footer but
- The header close and secondary buttons are disabled and the primary button shows a loading spinner. The primary button stays focusable but is `aria-disabled` and ignores activation, so focus stays inside the dialog while the command runs.
- The form fields are disabled and inert, so values cannot change while the command runs.
- Escape and backdrop dismissal are ignored while work is in flight.
- Once execution completes (success or failure), the buttons return to their normal state.
- Once execution completes (success or failure), the buttons return to their normal state. This happens before the result callbacks run; see [When a result callback rejects](advanced-features.md#when-a-result-callback-rejects).
- After a refused submit the dialog stays open, focus returns to the confirm button, and a polite live region announces `messages.dialog.refused` (default `'The action was not completed. Review the dialog and try again.'`). When the command result carries validation results, the live region instead announces how many problems there are and the first message, and focus moves to the first invalid field. See [Announcing validation failures](advanced-features.md#announcing-validation-failures). A successful submit follows the [dialog callback close decision](#dialog-callbacks).

## Context
Expand Down
4 changes: 3 additions & 1 deletion Documentation/ComponentPicker/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ The picker recognizes a component by `data-cratis-component="<Name>"` on its roo

`data-cratis-part` identifies a part inside the component, such as `label`, `title` or `close`; `data-cratis-component` identifies the component itself. Some public components do not yet have their own marker. For an unmarked element, the picker selects its nearest marked ancestor, if one exists. The package's identity specs track marker coverage and require new public components to be accounted for.

Chat composer, conversation, message body, message bubble, topic list, emoji picker, failed reply, mention suggestions, reactions, avatar, typing indicator, and property-type glyph roots expose their own markers. `ChatSidebarForObservableQueries` and `GlyphMenu` remain unmarked: the former delegates through a fragment, and the latter combines a trigger with portal content.
Chat composer, conversation, message body, message bubble, topic list, emoji picker, failed reply, mention suggestions, reactions, avatar, typing indicator, and property-type glyph roots expose their own markers. Canvas, minimap, events view, object content editor, object navigation, pivot viewer, both schema editor layouts, and the portaled toaster region also expose markers on their existing roots.

`ChatSidebarForObservableQueries` delegates identity to `ChatSidebar`. `ConfigurationEditor` renders the registered host editor or supplied fallback without its own root. `AutoCommandForm` uses the Arc form root, and `CanvasOverlay` portals caller-supplied children without a root of its own. `GlyphMenu` and `Region` remain pending because they render split roots; no wrapper is added solely for picker identity.

## Pick a component

Expand Down
22 changes: 22 additions & 0 deletions Documentation/Notifications/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,28 @@ if (toastCommandResult(result, { successTitle: 'Author registered' })) {

In this example, the panel closes only after success. Setting `showSuccess: false` suppresses the success notification without changing the return value. The helper checks success, authorization, validation, and exceptions in that order; it returns `false` without a toast if none of those branches matches.

Set `validationDescription` to a string for fixed copy, or to a function that maps `result.validationResults` to your application's copy. Without this option, non-empty validation messages are joined with `\n`. This excerpt reuses `result` from above and maps known messages while leaving others unchanged:

```ts
const validationCopy: Record<string, string> = {
'Name is required': 'Enter a name to continue.',
'Email is invalid': 'Enter a valid email address.',
};

toastCommandResult(result, {
validationDescription: (validationResults) => validationResults
.map((validationResult) => validationCopy[validationResult.message] ?? validationResult.message)
.filter(Boolean)
.join('\n'),
});
```

For a title-only validation toast, return `undefined` from the function. Returning an empty string also suppresses the description:

```ts
toastCommandResult(result, { validationDescription: () => undefined });
```

It needs a mounted toaster like any other toast. Exception details stay out of the notification; log `result.exceptionMessages` yourself if you need them.

## Accessible behavior
Expand Down
1 change: 1 addition & 0 deletions Source/Canvas/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ function Canvas<T extends CanvasItemData = CanvasItemData>({
return (
<div
ref={containerRef}
data-cratis-component='Canvas'
className={`${CANVAS_SURFACE_CLASS} cratis:relative cratis:overflow-hidden${className ? ` ${className}` : ''}`}
style={{ cursor: 'default', ...style }}
onPointerDown={handlePointerDown}
Expand Down
1 change: 1 addition & 0 deletions Source/Canvas/CanvasMinimap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ export const CanvasMinimap = forwardRef<CanvasMinimapHandle, CanvasMinimapProps>

return (
<div
data-cratis-component='CanvasMinimap'
className='canvas-minimap'
style={{
width: MINIMAP_WIDTH,
Expand Down
1 change: 1 addition & 0 deletions Source/Notifications/Toaster.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ export const Toaster = ({
<div
{...pt?.region}
className={classNames('cratis-toaster', pt?.region?.className)}
data-cratis-component='Toaster'
data-cratis-part='region'
data-position={position}
role='region'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import type { ICommandResult } from '@cratis/arc/commands';
import { beforeEach, describe, it, vi } from 'vitest';

const { toastCalls } = vi.hoisted(() => ({
toastCalls: {
success: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
}));

vi.mock('../toast', () => ({ toast: toastCalls }));

import { toastCommandResult } from '../toastCommandResult';

// SAFETY: toastCommandResult only reads messages from the validation results in these specs.
const validationResults = [
{ message: 'Name is required' },
{ message: '' },
{ message: 'Email is invalid' },
] as unknown as ICommandResult['validationResults'];

// SAFETY: These specs supply every command-result field read by toastCommandResult.
const result = {
isSuccess: false,
isAuthorized: true,
isValid: false,
hasExceptions: false,
validationResults,
exceptionMessages: [],
} as unknown as ICommandResult;

beforeEach(() => vi.clearAllMocks());

describe.each([' Review the highlighted fields.\nThen try again. ', ''])(
'when configuring the validation description with the string %j',
(validationDescription) => {
let returned: boolean;

beforeEach(() => {
returned = toastCommandResult(result, { validationDescription });
});

it('should use the string verbatim without changing the validation title', () => {
toastCalls.error.mock.calls.should.deep.equal([
[{ title: 'Validation failed', description: validationDescription }],
]);
});

it('should still return false', () => returned.should.be.false);
},
);

describe('when mapping the validation description with a function', () => {
const mapDescription = vi.fn((validationResults: ICommandResult['validationResults']) =>
`Please review ${validationResults.length} fields.`,
);

beforeEach(() => {
toastCommandResult(result, { validationDescription: mapDescription });
});

it('should pass the original validation results to the function once', () => {
mapDescription.mock.calls.should.have.lengthOf(1);
mapDescription.mock.calls[0][0].should.equal(validationResults);
});

it('should use the function result as the description', () => {
toastCalls.error.mock.calls.should.deep.equal([
[{ title: 'Validation failed', description: 'Please review 3 fields.' }],
]);
});
});

describe.each([
['undefined', undefined],
['an empty string', ''],
])('when the validation description function returns %s', (_label, description) => {
beforeEach(() => {
toastCommandResult(result, { validationDescription: () => description });
});

it('should show only the validation title without falling back to validation messages', () => {
toastCalls.error.mock.calls.should.deep.equal([
[{ title: 'Validation failed', description: undefined }],
]);
});
});

describe('when no validation description is supplied', () => {
beforeEach(() => {
toastCommandResult(result);
});

it('should join only non-empty validation messages with newlines', () => {
toastCalls.error.mock.calls.should.deep.equal([
[{ title: 'Validation failed', description: 'Name is required\nEmail is invalid' }],
]);
});
});

describe('when no validation messages or description are supplied', () => {
beforeEach(() => {
toastCommandResult({ ...result, validationResults: [] });
});

it('should show only the validation title', () => {
toastCalls.error.mock.calls.should.deep.equal([
[{ title: 'Validation failed', description: undefined }],
]);
});
});

describe.each([
['succeeded', { isSuccess: true }],
['was not authorized', { isAuthorized: false }],
['threw an exception', { isValid: true, hasExceptions: true }],
['had no matching flags', { isValid: true }],
] satisfies [string, Partial<ICommandResult>][])(
'when the command %s with a validation description function',
(_label, flags) => {
const mapDescription = vi.fn(() => 'Review the highlighted fields.');

beforeEach(() => {
toastCommandResult({ ...result, ...flags }, { validationDescription: mapDescription });
});

it('should not call the validation description function', () => {
mapDescription.mock.calls.should.have.lengthOf(0);
});
},
);
29 changes: 23 additions & 6 deletions Source/Notifications/toastCommandResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export interface ToastCommandResultOptions {
unauthorizedTitle?: string;
/** Title when the command failed validation. Defaults to `'Validation failed'`. */
validationTitle?: string;
/**
* Description when the command failed validation. Defaults to non-empty validation messages joined with `\n`.
* A string is used verbatim. A function receives the validation results; return `undefined` or an empty string for a title-only toast.
*/
validationDescription?: string | ((validationResults: ICommandResult['validationResults']) => string | undefined);
/** Title when the command threw. Defaults to `'Something went wrong'`. */
exceptionTitle?: string;
/** When false, no toast is shown on success. Defaults to `true`. */
Expand All @@ -27,7 +32,7 @@ export interface ToastCommandResultOptions {
*
* - **success** → a success toast (suppress with `showSuccess: false`);
* - **not authorized** → a warning toast;
* - **invalid** → an error toast listing the per-field validation messages;
* - **invalid** → an error toast listing the per-field validation messages (customize or suppress with `validationDescription`);
* - **exceptions** → a generic error toast (stack traces are never shown to
* users — log `result.exceptionMessages` yourself).
*
Expand Down Expand Up @@ -55,6 +60,7 @@ export function toastCommandResult<TResponse = object>(
successDescription,
unauthorizedTitle = 'Not authorized',
validationTitle = 'Validation failed',
validationDescription,
exceptionTitle = 'Something went wrong',
showSuccess = true,
} = options;
Expand All @@ -72,11 +78,8 @@ export function toastCommandResult<TResponse = object>(
}

if (!result.isValid) {
const description = result.validationResults
.map((validationResult) => validationResult.message)
.filter(Boolean)
.join('\n');
toast.error({ title: validationTitle, description: description || undefined });
const description = getValidationDescription(result.validationResults, validationDescription);
toast.error({ title: validationTitle, description });
return false;
}

Expand All @@ -87,3 +90,17 @@ export function toastCommandResult<TResponse = object>(

return false;
}

function getValidationDescription(
validationResults: ICommandResult['validationResults'],
validationDescription: ToastCommandResultOptions['validationDescription'],
): string | undefined {
if (typeof validationDescription === 'function') {
return validationDescription(validationResults) || undefined;
}

return validationDescription ?? (validationResults
.map((validationResult) => validationResult.message)
.filter(Boolean)
.join('\n') || undefined);
}
1 change: 1 addition & 0 deletions Source/ObjectContentEditor/ObjectContentEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,7 @@ export const ObjectContentEditor = ({

return (
<div
data-cratis-component='ObjectContentEditor'
className={className ? `order-content ${className}` : 'order-content'}
style={{ display: 'flex', flexDirection: 'column', height: '100%' }}
>
Expand Down
2 changes: 1 addition & 1 deletion Source/ObjectNavigationalBar/ObjectNavigationalBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export function ObjectNavigationalBar({
: 'cratis-object-navigational-bar cratis:px-4 cratis:py-2 cratis:mb-2';

return (
<div className={rootClassName}>
<div data-cratis-component='ObjectNavigationalBar' className={rootClassName}>
<div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
<Tooltip content={backLabel} position='top'>
<Button
Expand Down
2 changes: 1 addition & 1 deletion Source/PivotViewer/components/PivotViewerContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function PivotViewerContent<TItem extends object>({
const { labels } = viewer;

return (
<div className={viewerClassName} style={cssVariables}>
<div data-cratis-component='PivotViewer' className={viewerClassName} style={cssVariables}>
<FilterPanelContainer
isOpen={view.filtersOpen && hasFilters}
filterLabel={labels?.filters}
Expand Down
1 change: 1 addition & 0 deletions Source/SchemaEditor/SchemaEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ const TableSchemaEditor = ({

return (
<div
data-cratis-component='SchemaEditor'
className={className ? `schema-editor ${className}` : 'schema-editor'}
style={{ display: 'flex', flexDirection: 'column', height: '100%' }}
>
Expand Down
1 change: 1 addition & 0 deletions Source/SchemaEditor/Tree/TreeSchemaEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ export const TreeSchemaEditor = ({
aria-label={ariaLabelledBy ? undefined : ariaLabel ?? labels.schema}
aria-labelledby={ariaLabelledBy}
className={['cratis-schema-editor', pt?.root?.className, className].filter(Boolean).join(' ')}
data-cratis-component='SchemaEditor'
data-cratis-part='root'
data-readonly={readOnly || undefined}
>
Expand Down
1 change: 1 addition & 0 deletions Source/TimeMachine/EventsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export const EventsView = ({

return (
<div
data-cratis-component='EventsView'
className='events-view-container'
ref={containerRef}
role='group'
Expand Down
2 changes: 1 addition & 1 deletion Source/api-surface.json
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,7 @@
"defaultMarkdownFormats": "defaultMarkdownFormats: readonly (readonly MarkdownFormat[])[]"
},
"./Notifications": {
"ToastCommandResultOptions": "export interface ToastCommandResultOptions { successTitle?: string; successDescription?: string; unauthorizedTitle?: string; validationTitle?: string; exceptionTitle?: string; showSuccess?: boolean; }",
"ToastCommandResultOptions": "export interface ToastCommandResultOptions { successTitle?: string; successDescription?: string; unauthorizedTitle?: string; validationTitle?: string; validationDescription?: string | ((validationResults: ICommandResult['validationResults']) => string | undefined); exceptionTitle?: string; showSuccess?: boolean; }",
"ToastDispatch": "export interface ToastDispatch { show(options: ToastOptions): ToastId; update(id: ToastId, updates: Partial<ToastOptions>): ToastId; dismiss(id?: ToastId): void; promise<T>(promise: Promise<T>, options: ToastPromiseOptions<T>): Promise<T>; success(options: ToastOptions): ToastId; info(options: ToastOptions): ToastId; warn(options: ToastOptions): ToastId; error(options: ToastOptions): ToastId; secondary(options: ToastOptions): ToastId; contrast(options: ToastOptions): ToastId; }",
"ToastFunction": "export interface ToastFunction { (options: ToastOptions): ToastId; update(id: ToastId, updates: Partial<ToastOptions>): ToastId; dismiss(id?: ToastId): void; promise<T>(promise: Promise<T>, options: ToastPromiseOptions<T>): Promise<T>; success(options: ToastOptions): ToastId; info(options: ToastOptions): ToastId; warn(options: ToastOptions): ToastId; error(options: ToastOptions): ToastId; secondary(options: ToastOptions): ToastId; contrast(options: ToastOptions): ToastId; }",
"ToastId": "export type ToastId = string | number;",
Expand Down
Loading
Loading