Files
siftlode/frontend/src/components/ConfirmProvider.tsx
T
peter 3ef2c38eb4 feat(design): dialogs open by purpose and keep their commit row pinned (E28 S3f1)
Modal takes a required initialFocus (field / close / action), a field that
loads late takes the focus while it still rests on the close button, and
ModalFooter portals a dialog's commit row under the scrolling body from any
depth. The header and footer fades follow the body's scroll timeline, and the
viewport's interactive-widget=resizes-content keeps the footer above an
on-screen keyboard.
2026-09-27 01:33:37 +02:00

76 lines
2.8 KiB
TypeScript

import { useCallback, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import Modal, { ModalFooter } from "./ui/Modal";
import { Button } from "./ui/Button";
import { ChoiceContext, type ChoiceFn, type ChoiceOptions } from "./confirmContext";
// The dialog behind useConfirm()/useChoice() (see confirmContext.ts for the hooks and their contract).
export function ConfirmProvider({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const [state, setState] = useState<{
opts: ChoiceOptions;
resolve: (id: string | null) => void;
} | null>(null);
const ask = useCallback<ChoiceFn>(
(opts) => new Promise<string | null>((resolve) => setState({ opts, resolve })),
[],
);
function close(id: string | null) {
state?.resolve(id);
setState(null);
}
const choices = state?.opts.choices ?? [];
// Focus Cancel when any offered action is destructive: the confirm button used to take
// autoFocus unconditionally, so a stray Enter on an open dialog executed "Delete user" or
// "Clear audit log" without the user ever looking at it.
const anyDanger = choices.some((c) => c.danger);
const multi = choices.length > 1;
return (
<ChoiceContext.Provider value={ask}>
{children}
{state && (
<Modal
initialFocus="action"
title={state.opts.title ?? t("common.confirmTitle")}
onClose={() => close(null)}
maxWidth={choices.length > 1 ? "max-w-md" : "max-w-sm"}
>
<div className="text-sm text-muted leading-relaxed">{state.opts.message}</div>
{/* One action: the familiar Cancel/Confirm row. Two or more: a column, because side by
side they wrap raggedly and a wrapped button reads as a second, lesser group — and
these are peers. Ordered least to most destructive, top to bottom. */}
<ModalFooter
className={multi ? "flex flex-col gap-2" : "flex flex-wrap justify-end gap-2"}
>
<Button
variant="outline"
autoFocus={anyDanger}
onClick={() => close(null)}
fullWidth={multi}
className={multi ? "order-last" : ""}
>
{state.opts.cancelLabel ?? t("common.cancel")}
</Button>
{choices.map((c, i) => (
<Button
key={c.id}
variant={c.danger ? "danger" : "primary"}
autoFocus={!anyDanger && i === choices.length - 1}
onClick={() => close(c.id)}
fullWidth={multi}
>
{c.label || t("common.confirm")}
</Button>
))}
</ModalFooter>
</Modal>
)}
</ChoiceContext.Provider>
);
}