Skip to content

Cratis Arc React dialogs and user decisions

Cratis Arc React dialogs let a caller open a dialog and await the user’s decision without managing its visibility. You supply the UI and close it with a result and optional response data. Use your own renderer or a component library; Arc does not require Components or PrimeReact.

Start with a dialog that asks the user to accept a name. This example uses native <dialog open>, which is nonmodal: it does not block interaction with the rest of the page. For a modal dialog, choose an accessible renderer that manages focus, dismissal and labeling, such as Components dialogs.

import { DialogResult, useDialog, useDialogContext } from '@cratis/arc.react/dialogs';
type NameRequest = { currentName: string };
function NameDialog({ currentName }: NameRequest) {
const { closeDialog } = useDialogContext<NameRequest, string>();
return (
<dialog open aria-label="Confirm name">
<p>Use {currentName}?</p>
<button onClick={() => closeDialog(DialogResult.Ok, currentName)}>Use name</button>
<button onClick={() => closeDialog(DialogResult.Cancelled)}>Cancel</button>
</dialog>
);
}
export function Feature() {
const [NameDialogWrapper, showNameDialog] = useDialog<string, NameRequest>(NameDialog);
async function choose() {
const [result, response] = await showNameDialog({ currentName: 'Ada' });
if (result === DialogResult.Ok && response !== undefined) {
console.log(response);
}
}
return (
<>
<button onClick={() => void choose()}>Choose name</button>
<NameDialogWrapper />
</>
);
}

useDialog<TResponse, TInput>(Component) returns [Wrapper, showDialog, context]. Render the wrapper as Feature does above; calling showDialog alone cannot display the dialog. The wrapper mounts the dialog while it is visible.

showDialog(input) passes the request to the dialog and waits for closeDialog(result, response?). Its promise resolves to [DialogResult, response?], so the caller checks both the result and the optional value before using the name. Canceling can return no response. A hook shows one request at a time: calling showDialog while an earlier call is still waiting replaces it, and the earlier promise resolves to [DialogResult.Cancelled, undefined].

Inside the dialog, read input through props or useDialogContext<TInput, TResponse>(), which also supplies closeDialog. The type parameters are reversed from useDialog: input comes first in the context hook.

Every showDialog call starts a new opening. The context identifies it as opening, a DialogOpening with a unique id and an isOpen flag. The opening is the same object for as long as that opening lasts and a different one for the next. Compare the objects to identify an opening; id is unique among the openings started through one loaded copy of the package.

A new opening always mounts the dialog component again, also when the dialog closes and reopens in the same React update with an equal request, or when showDialog replaces a request that is still waiting. Component state, effects and a dialog view model therefore belong to one opening and start fresh for the next.

The closeDialog a dialog gets belongs to its opening. Once that opening is closed or replaced, calling it does nothing: it neither resolves the newer request nor hides the dialog. Work that finishes late, such as a submission that completes after the user closed and reopened the dialog, therefore cannot close the wrong opening.

Asynchronous work can still finish after its opening has ended. Use the opening to keep such work bound to the request that started it:

import { useState } from 'react';
import { DialogResult, useDialogContext } from '@cratis/arc.react/dialogs';
type NameRequest = { name: string };
declare function save(name: string): Promise<void>;
declare function notifySaved(name: string): void;
export const SavingNameDialog = ({ name }: NameRequest) => {
const { opening, closeDialog } = useDialogContext<NameRequest, string>();
const [currentName, setCurrentName] = useState(name);
const [saving, setSaving] = useState(false);
const submit = async () => {
setSaving(true);
await save(currentName);
if (!opening?.isOpen) return;
notifySaved(currentName);
closeDialog(DialogResult.Ok, currentName);
};
return (
<div>
<input value={currentName} onChange={event => setCurrentName(event.target.value)} />
<button disabled={saving} onClick={submit}>Save</button>
<button onClick={() => closeDialog(DialogResult.Cancelled)}>Cancel</button>
</div>
);
};

If the user closes and reopens the dialog while save is running, the closeDialog that submit holds belongs to the earlier opening and leaves the new one alone. opening.isOpen guards everything else that must not outlive its opening, here the notification.

The third element useDialog returns to the host is different: its closeDialog is the same function for the lifetime of the hook and closes whichever opening is waiting, and its opening is undefined while none is.

A shared dialog renderer may live far from the feature that opened it. useDialog captures the caller’s slice scope and gives the dialog a child scope, so useSliceContext() inside the dialog starts with the owning feature’s location. Commands and queries in the dialog refine that location just as they do on a page.

import { useDialog, useDialogSliceLocation } from '@cratis/arc.react/dialogs';
const EditOrderDialog = () => {
const location = useDialogSliceLocation(); // Orders/Editing/ChangeOrder
return <header>Edit order <small>{location.toString()}</small></header>;
};
const ChangeOrder = () => {
const [EditOrder, showEditOrder] = useDialog(EditOrderDialog, { title: 'Edit order' });
return <><button onClick={() => showEditOrder()}>Edit</button><EditOrder /></>;
};

A dialog can declare its own location, which wins over the inherited one:

useDialog(AddressDialog, { slice: { module: 'Orders', feature: 'Shipping', slice: 'Address' } });

useDialog takes these options as a second argument:

Option Description
slice An explicit location for the dialog. Parts not given are empty.
title The title reported in the application context.
trackInApplicationContext Set to false to keep the open dialog out of the application context. Defaults to true. The built-in confirmation and busy indicator dialogs of DialogComponents do not track.

Tracked dialogs appear in useApplicationContext().dialogs, bottom first. The application’s focused location follows the top-most dialog; closing it restores the dialog below or the page. Changing an open dialog’s title or slice updates its entry without changing the stack order.

For a shared dialog header, use useDialogSliceLocation() to read the containing dialog’s location directly. The helper needs an application layer context, and an untracked dialog clears that context while keeping its slice scope, so the helper returns SliceLocation.empty there, even when nested inside a tracked dialog. Outside a dialog it also returns SliceLocation.empty. Custom confirmation or busy-indicator chrome is affected because the built-in dialogs use untracked options.

When sliceMarkers is enabled on <Arc>, the dialog content is wrapped in the marker element too. Renderers that portal the content elsewhere can use sliceMarkerAttributes(useDialogSliceLocation()) on their own element when the dialog is tracked; for an untracked dialog the helper returns SliceLocation.empty, so that marker carries no location.

DialogButtons supports Ok, OkCancel, YesNo, and YesNoCancel. DialogResult supports None, Ok, Yes, No, and Cancelled, not Cancel.

useConfirmationDialog(title?, message?, buttons?) returns [showConfirmation]. Call showConfirmation() to use those defaults, or pass overrides for that request. Its promise resolves to DialogResult alone, so there is no response tuple to unpack.

Configure one shared confirmation renderer with DialogComponents. This example renders each button configuration using the same nonmodal native presentation as the name dialog:

import {
ConfirmationDialogRequest, DialogButtons, DialogResult,
DialogComponents, useConfirmationDialog, useDialogContext
} from '@cratis/arc.react/dialogs';
function ConfirmationDialog() {
const { request, closeDialog } = useDialogContext<ConfirmationDialogRequest>();
const yesNo = request.buttons === DialogButtons.YesNo || request.buttons === DialogButtons.YesNoCancel;
const cancel = request.buttons === DialogButtons.OkCancel || request.buttons === DialogButtons.YesNoCancel;
return (
<dialog open aria-label={request.title}>
<p>{request.message}</p>
{yesNo ? <>
<button onClick={() => closeDialog(DialogResult.Yes)}>Yes</button>
<button onClick={() => closeDialog(DialogResult.No)}>No</button>
</> : <button onClick={() => closeDialog(DialogResult.Ok)}>OK</button>}
{cancel && <button onClick={() => closeDialog(DialogResult.Cancelled)}>Cancel</button>}
</dialog>
);
}
function ConfirmButton() {
const [showConfirmation] = useConfirmationDialog('Continue?', 'Use these settings?', DialogButtons.YesNoCancel);
async function confirm() {
const result = await showConfirmation();
if (result === DialogResult.Yes) console.log('Confirmed');
}
return <button onClick={() => void confirm()}>Confirm settings</button>;
}
export const ConfirmationExample = () => (
<DialogComponents confirmation={ConfirmationDialog}>
<ConfirmButton />
</DialogComponents>
);

DialogComponents mounts the renderer and supplies its request. Place it above components that call useConfirmationDialog; without a configured renderer, the caller has no usable confirmation UI.

Configure a busyIndicator renderer on DialogComponents. Inside it, read useDialogContext<BusyIndicatorDialogRequest>() for request.title and request.message.

useBusyIndicator(title?, message?) returns [showBusyIndicator, closeBusyIndicator]. Your application still owns the operation. Close the indicator in finally so a failed operation does not leave it visible; closing the indicator neither cancels the work nor proves it succeeded.

If your application uses view models, continue with MVVM dialogs to open dialogs through request classes and the IDialogs service.