diff --git a/Documentation/CommandDialog/advanced-features.md b/Documentation/CommandDialog/advanced-features.md index 84f3a2f7..e9aa6ed1 100644 --- a/Documentation/CommandDialog/advanced-features.md +++ b/Documentation/CommandDialog/advanced-features.md @@ -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. ` for one result and `There are problems. First: ` for more. If no field is marked invalid, focus returns to the confirm button. diff --git a/Documentation/CommandDialog/index.md b/Documentation/CommandDialog/index.md index cc92cdfb..d6888046 100644 --- a/Documentation/CommandDialog/index.md +++ b/Documentation/CommandDialog/index.md @@ -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 diff --git a/Documentation/ComponentPicker/index.md b/Documentation/ComponentPicker/index.md index df972c56..c6ed98e0 100644 --- a/Documentation/ComponentPicker/index.md +++ b/Documentation/ComponentPicker/index.md @@ -17,7 +17,9 @@ The picker recognizes a component by `data-cratis-component=""` 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 diff --git a/Documentation/Notifications/index.md b/Documentation/Notifications/index.md index ce6df09d..e3c45d2f 100644 --- a/Documentation/Notifications/index.md +++ b/Documentation/Notifications/index.md @@ -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 = { + '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 diff --git a/Source/Canvas/Canvas.tsx b/Source/Canvas/Canvas.tsx index 4f55d968..93519aa0 100644 --- a/Source/Canvas/Canvas.tsx +++ b/Source/Canvas/Canvas.tsx @@ -166,6 +166,7 @@ function Canvas({ return (
return (
({ + 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][])( + '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); + }); + }, +); diff --git a/Source/Notifications/toastCommandResult.ts b/Source/Notifications/toastCommandResult.ts index 8f1b9247..89fa8d8b 100644 --- a/Source/Notifications/toastCommandResult.ts +++ b/Source/Notifications/toastCommandResult.ts @@ -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`. */ @@ -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). * @@ -55,6 +60,7 @@ export function toastCommandResult( successDescription, unauthorizedTitle = 'Not authorized', validationTitle = 'Validation failed', + validationDescription, exceptionTitle = 'Something went wrong', showSuccess = true, } = options; @@ -72,11 +78,8 @@ export function toastCommandResult( } 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; } @@ -87,3 +90,17 @@ export function toastCommandResult( 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); +} diff --git a/Source/ObjectContentEditor/ObjectContentEditor.tsx b/Source/ObjectContentEditor/ObjectContentEditor.tsx index 59b1cbff..78cb25de 100644 --- a/Source/ObjectContentEditor/ObjectContentEditor.tsx +++ b/Source/ObjectContentEditor/ObjectContentEditor.tsx @@ -660,6 +660,7 @@ export const ObjectContentEditor = ({ return (
diff --git a/Source/ObjectNavigationalBar/ObjectNavigationalBar.tsx b/Source/ObjectNavigationalBar/ObjectNavigationalBar.tsx index b672399b..8da4d153 100644 --- a/Source/ObjectNavigationalBar/ObjectNavigationalBar.tsx +++ b/Source/ObjectNavigationalBar/ObjectNavigationalBar.tsx @@ -54,7 +54,7 @@ export function ObjectNavigationalBar({ : 'cratis-object-navigational-bar cratis:px-4 cratis:py-2 cratis:mb-2'; return ( -
+