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
16 changes: 16 additions & 0 deletions design-system/packages/ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,22 @@ restores focus before dispatching `onSelect`; the host owns asynchronous work
and error handling. The popup flips and clamps to the viewport, keeps keyboard
navigation in the active menu, and supports safe pointer travel to either side.

For a simple destructive menu action, add `confirmation: { description,
confirmText, cancelText }` to its entry. `MenuConfirmItem` exposes the same
behavior for composed menus: the row changes to Cancel / Confirm, focuses
Cancel first, and Escape restores the original row. The confirmed action is
awaited with both controls disabled; the host owns error presentation.
Reopening a `MenuPopover` keeps that action disabled until it settles, and a late
completion does not close the newly opened menu.

Use `ConfirmDialog anchor={captureConfirmationAnchor(event.currentTarget)}`
when a single-item action needs a short explanation beside its trigger. Capture
the anchor before awaiting work or closing a menu. It retains the trigger's
rectangle and overlay owner, flips within the viewport, and restores focus to
the trigger or its surviving owner. Without an anchor the dialog remains modal;
keep this presentation for bulk deletion, overwrite, reset, and permission
decisions. Confirmations focus Cancel first when it is available.

Portals resolve through `DesignSystemProvider.portalHost`, then fall back to one
document-owned overlay host above application content. Stable `parts` wrappers preserve host data hooks;
they must forward all props and refs and retain public component ownership.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const confirmDialogMeta = {
maturity: "stable",
name: "ConfirmDialog",
props: [
{ name: "anchor", type: "ConfirmationAnchor" },
{ name: "open", type: "boolean" },
{ name: "title", type: "ReactNode" },
{ name: "message", type: "ReactNode" },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,14 @@ import {
type DialogCloseReason,
} from "../Dialog";
import styles from "./ConfirmDialog.module.css";
import type { ConfirmationAnchor } from "../../internal/confirmationAnchor";

export type ConfirmDialogCloseReason = DialogCloseReason | "cancel-button";
export type ConfirmDialogType = "info" | "warning" | "error" | "success";
export type ConfirmDialogAction = () => void | Promise<void>;

export interface ConfirmDialogProps {
anchor?: ConfirmationAnchor;
cancelText?: ReactNode;
closeOnEscape?: boolean;
closeOnPointerOutside?: boolean;
Expand Down Expand Up @@ -63,6 +65,7 @@ const defaultIcons: Record<ConfirmDialogType, ReactNode> = {

export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
function ConfirmDialog({
anchor,
cancelText,
closeOnEscape = true,
closeOnPointerOutside = true,
Expand All @@ -87,6 +90,8 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
}, ref) {
const designSystem = useDesignSystem();
const confirmButtonRef = useRef<HTMLButtonElement>(null);
const cancelButtonRef = useRef<HTMLButtonElement>(null);
const pendingRef = useRef(false);
const mountedRef = useRef(true);
const [internalPendingAction, setInternalPendingAction] = useState<"confirm" | "secondary" | null>(null);
const pendingAction = controlledPendingAction ?? internalPendingAction;
Expand All @@ -99,8 +104,9 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
const resolvedCancelText = cancelText ?? designSystem.messages.confirmCancel;
const resolvedConfirmText = confirmText ?? designSystem.messages.confirmAction;

useEffect(() => () => {
mountedRef.current = false;
useEffect(() => {
mountedRef.current = true;
return () => { mountedRef.current = false; };
}, []);

useEffect(() => {
Expand All @@ -111,7 +117,8 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
actionName: "confirm" | "secondary",
action: ConfirmDialogAction | undefined,
) => {
if (!action || busy) return;
if (!action || busy || pendingRef.current) return;
pendingRef.current = true;
try {
const result = action();
if (result && typeof result.then === "function") {
Expand All @@ -121,6 +128,7 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
} catch (error) {
onActionError?.(error, actionName);
} finally {
pendingRef.current = false;
if (mountedRef.current) setInternalPendingAction(null);
}
}, [busy, onActionError]);
Expand All @@ -131,7 +139,7 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(
}, [busy, onOpenChange]);

const cancelButton = showCancel ? (
<Button disabled={busy} onClick={() => requestClose("cancel-button")} variant="fill">
<Button ref={cancelButtonRef} disabled={busy} onClick={() => requestClose("cancel-button")} variant="fill">
{resolvedCancelText}
</Button>
) : null;
Expand Down Expand Up @@ -161,10 +169,11 @@ export const ConfirmDialog = forwardRef<HTMLDivElement, ConfirmDialogProps>(

return (
<Dialog
anchor={anchor}
closeOnEscape={!busy && closeOnEscape}
closeOnPointerOutside={!busy && closeOnPointerOutside}
data-testid={testId}
initialFocusRef={confirmButtonRef}
initialFocusRef={showCancel ? cancelButtonRef : confirmButtonRef}
onOpenChange={(_nextOpen, reason) => requestClose(reason)}
open={open}
ref={ref}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export {
type ConfirmDialogProps,
type ConfirmDialogType,
} from "./ConfirmDialog";
export { captureConfirmationAnchor, type ConfirmationAnchor } from "../../internal/confirmationAnchor";
21 changes: 21 additions & 0 deletions design-system/packages/ui/src/components/Dialog/Dialog.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@
.surface[data-size="xl"] { max-inline-size: var(--openbitfun-overlay-dialog-max-inline-size-xlarge); }
.surface[data-size="2xl"] { max-inline-size: var(--openbitfun-overlay-dialog-max-inline-size-xxlarge); }

.anchoredOverlay {
display: contents;
}

.anchoredSurface {
inline-size: min(var(--openbitfun-overlay-dialog-max-inline-size-small), calc(100vw - 2 * var(--openbitfun-space-2)));
box-shadow: var(--openbitfun-shadow-overlay);
transform-origin: top left;
animation: none;
}

.anchoredSurface[data-placement="top"] { transform-origin: bottom left; }

.anchoredSurface > .header,
.anchoredSurface > .body,
.anchoredSurface > .footer {
padding: var(--openbitfun-space-3);
}

.anchoredSurface > .body { padding-block-start: 0; }

.surface[data-preset="panel"] {
--_dialog-panel-title-gap: calc(var(--openbitfun-overlay-dialog-header-padding-block-start) + var(--openbitfun-space-4));

Expand Down
34 changes: 25 additions & 9 deletions design-system/packages/ui/src/components/Dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { useFocusScope } from "../../overlay/useFocusScope";
import { usePresence } from "../../overlay/usePresence";
import { IconButton, type IconButtonProps } from "../IconButton";
import { inertProps } from "../../internal/inert";
import { useAnchoredLayer } from "../../internal/useAnchoredLayer";
import type { ConfirmationAnchor } from "../../internal/confirmationAnchor";
import styles from "./Dialog.module.css";

const EXIT_DURATION_MS = 180;
Expand Down Expand Up @@ -68,6 +70,8 @@ interface OverlaySurfaceProps
closeOnEscape?: boolean;
closeOnPointerOutside?: boolean;
initialFocusRef?: RefObject<HTMLElement | null>;
/** A compact, non-modal confirmation attached to an explicit user action. */
anchor?: ConfirmationAnchor;
kind: "dialog" | "sheet";
onOpenChange: (open: false, reason: DialogCloseReason) => void;
/** Called after the closed surface has finished exiting and unmounted. */
Expand All @@ -94,6 +98,7 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
closeOnEscape = true,
closeOnPointerOutside = true,
initialFocusRef,
anchor,
kind,
onOpenChange,
onExitComplete,
Expand All @@ -115,15 +120,15 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
const titleId = `openbitfun-dialog-title-${useId()}`;
const descriptionId = `openbitfun-dialog-description-${useId()}`;
const { present, state } = usePresence(open, EXIT_DURATION_MS);
const presentation = { children, className, overlayProps, placement, preset, size, style };
const presentation = { children, className, overlayProps, placement, preset, size, style, anchor };
const lastOpenPresentation = useRef<typeof presentation | null>(null);
const wasPresent = useRef(present);
// Owners often clear selection or form state in the same update as closing.
// Retain the content and its geometry together until the exit finishes.
useLayoutEffect(() => {
if (open) lastOpenPresentation.current = { children, className, overlayProps, placement, preset, size, style };
if (open) lastOpenPresentation.current = { children, className, overlayProps, placement, preset, size, style, anchor };
else if (!present) lastOpenPresentation.current = null;
}, [children, className, open, overlayProps, placement, preset, present, size, style]);
}, [children, className, open, overlayProps, placement, preset, present, size, style, anchor]);
useEffect(() => {
const completed = wasPresent.current && !present && !open;
wasPresent.current = present;
Expand All @@ -133,6 +138,14 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
const renderedChildren = rendered.children;
const hasTitle = containsType(renderedChildren, DialogTitle);
const hasDescription = containsType(renderedChildren, DialogDescription);
const anchorRef = useRef<HTMLElement | null>(null);
const ownerRef = useRef<HTMLElement | null>(null);
const returnFocusRef = useRef<HTMLElement | null>(null);
anchorRef.current = rendered.anchor?.element ?? null;
ownerRef.current = rendered.anchor?.owner ?? null;
returnFocusRef.current = anchorRef.current?.isConnected ? anchorRef.current : ownerRef.current;
const anchored = Boolean(rendered.anchor);
const layout = useAnchoredLayer({ open: present && anchored, anchorRef, layerRef: surfaceRef, fallbackRect: rendered.anchor?.rect });

const close = useCallback((reason: DialogCloseReason) => {
if (open) onOpenChange(false, reason);
Expand Down Expand Up @@ -165,6 +178,7 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
autoFocus,
containerRef: surfaceRef,
initialFocusRef,
returnFocusRef: anchored ? returnFocusRef : undefined,
ownerDocument,
trapFocus,
restoreFocus,
Expand All @@ -174,10 +188,10 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
const exiting = state === "exiting";

return (
<Portal target={resolvedPortalHost} open={open} modal preventScroll={preventScroll}>
<Portal target={resolvedPortalHost} open={open} modal={!anchored} preventScroll={!anchored && preventScroll} ownerRef={anchored ? ownerRef : undefined}>
<div
{...rendered.overlayProps}
className={classNames(styles.overlay, rendered.overlayProps?.className)}
className={classNames(styles.overlay, anchored && styles.anchoredOverlay, rendered.overlayProps?.className)}
data-openbitfun-component={kind}
data-openbitfun-part="overlay"
data-openbitfun-native-webview-occlusion
Expand All @@ -193,17 +207,19 @@ const OverlaySurface = forwardRef<HTMLDivElement, OverlaySurfaceProps>(function
aria-hidden={exiting || undefined}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledBy ?? (!ariaLabel && hasTitle ? titleId : undefined)}
aria-modal="true"
className={classNames(styles.surface, rendered.className)}
aria-modal={!anchored}
className={classNames(styles.surface, anchored && styles.anchoredSurface, rendered.className)}
data-openbitfun-component={kind}
data-openbitfun-part="surface"
data-placement={rendered.placement}
data-placement={anchored ? layout?.placement : rendered.placement}
data-presentation={anchored ? "anchored" : "modal"}
data-openbitfun-native-webview-occlusion={anchored || undefined}
data-preset={rendered.preset}
data-size={rendered.size}
data-state={exiting ? "exiting" : "open"}
ref={setSurfaceRef}
role={role}
style={rendered.style}
style={anchored ? { ...rendered.style, ...layout?.style, visibility: layout ? undefined : "hidden" } : rendered.style}
tabIndex={-1}
>
{renderedChildren}
Expand Down
12 changes: 12 additions & 0 deletions design-system/packages/ui/src/components/Menu/Menu.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,18 @@
border-radius: var(--openbitfun-overlay-menu-item-radius);
}

.confirmation {
display: grid;
grid-template-columns: minmax(0, 1fr) var(--openbitfun-border-width-default) minmax(0, 1fr);
align-items: center;
}
.confirmationButton { text-align: center; }
.confirmationDivider {
align-self: stretch;
margin-block: var(--openbitfun-space-2);
background: var(--openbitfun-color-border-subtle);
}

.item > [data-openbitfun-part="trigger"] {
gap: var(--openbitfun-overlay-menu-item-gap);
}
Expand Down
76 changes: 76 additions & 0 deletions design-system/packages/ui/src/components/Menu/MenuConfirmItem.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { useLayoutEffect, useRef, useState } from "react";
import { MenuItem, MenuList, type MenuItemProps } from "./Menu";
import { useDesignSystem } from "../../overlay/useDesignSystem";
import styles from "./Menu.module.css";

export interface MenuConfirmation {
description: string;
confirmText?: string;
cancelText?: string;
}

export interface MenuConfirmItemProps extends Omit<MenuItemProps, "onClick"> {
confirmation: MenuConfirmation;
onConfirm: (trigger: HTMLButtonElement) => void | Promise<void>;
onActionError?: (error: unknown) => void;
}

/** The action stays in its menu row until the user explicitly confirms it. */
export function MenuConfirmItem({ confirmation, onConfirm, onActionError, disabled, ...props }: MenuConfirmItemProps) {
const { messages } = useDesignSystem();
const [confirming, setConfirming] = useState(false);
const [pending, setPending] = useState(false);
const pendingRef = useRef(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const cancelRef = useRef<HTMLButtonElement>(null);
const confirmRef = useRef<HTMLButtonElement>(null);
const restoreFocus = useRef(false);
useLayoutEffect(() => {
if (confirming) cancelRef.current?.focus({ preventScroll: true });
else if (restoreFocus.current) {
triggerRef.current?.focus({ preventScroll: true });
restoreFocus.current = false;
}
}, [confirming]);
const cancel = () => {
if (pendingRef.current) return;
restoreFocus.current = true;
setConfirming(false);
};
const confirm = async (trigger: HTMLButtonElement) => {
if (disabled || pendingRef.current) return;
pendingRef.current = true;
setPending(true);
try { await onConfirm(trigger); }
catch (error) { onActionError?.(error); }
finally {
pendingRef.current = false;
restoreFocus.current = true;
setPending(false);
setConfirming(false);
}
};
if (!confirming) return <MenuItem {...props} disabled={disabled} ref={triggerRef} title={confirmation.description}
onClick={event => { event.stopPropagation(); setConfirming(true); }} />;

return <div data-openbitfun-component="menu" data-openbitfun-part="items" data-openbitfun-menu-confirmation="">
<MenuList className={styles.confirmation} role="group" aria-label={confirmation.description} aria-busy={pending}
onKeyDown={event => {
if (event.key === "Escape" && !pending) { event.preventDefault(); event.stopPropagation(); cancel(); }
else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault(); event.stopPropagation();
(event.key === "ArrowLeft" ? cancelRef : confirmRef).current?.focus({ preventScroll: true });
}
}}>
<MenuItem ref={cancelRef} disabled={disabled || pending} triggerClassName={styles.confirmationButton}
data-openbitfun-menu-confirmation-cancel="" onClick={event => { event.stopPropagation(); cancel(); }}>
{confirmation.cancelText ?? messages.confirmCancel}
</MenuItem>
<span className={styles.confirmationDivider} aria-hidden="true" />
<MenuItem ref={confirmRef} disabled={disabled || pending} tone="danger" title={confirmation.description}
triggerClassName={styles.confirmationButton} onClick={event => { event.stopPropagation(); void confirm(event.currentTarget); }}>
{confirmation.confirmText ?? messages.confirmAction}
</MenuItem>
</MenuList>
</div>;
}
Loading
Loading