CD — Deployment / deploy (push) Successful in 23s
PR automatique de chore/code-cleanup vers main. --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #25 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
87 lines
2.5 KiB
TypeScript
87 lines
2.5 KiB
TypeScript
import {
|
|
createContext,
|
|
useCallback,
|
|
useContext,
|
|
useState,
|
|
type ReactNode,
|
|
} from "react";
|
|
import { useI18n } from "../lib/i18n.js";
|
|
import { Modal } from "./feedback.js";
|
|
import { IconAction } from "./IconAction.js";
|
|
import { CloseIcon, TrashIcon, MoveIcon } from "./icons.js";
|
|
|
|
export interface ConfirmOptions {
|
|
title?: string;
|
|
message: ReactNode;
|
|
confirmLabel?: string;
|
|
cancelLabel?: string;
|
|
tone?: "default" | "danger";
|
|
confirmIcon?: ReactNode;
|
|
}
|
|
|
|
type ConfirmFn = (options: ConfirmOptions) => Promise<boolean>;
|
|
|
|
interface PendingConfirm {
|
|
options: ConfirmOptions;
|
|
resolve: (value: boolean) => void;
|
|
}
|
|
|
|
const ConfirmContext = createContext<ConfirmFn | null>(null);
|
|
|
|
export const ConfirmProvider = ({ children }: { children: ReactNode }) => {
|
|
const { t } = useI18n();
|
|
const [pending, setPending] = useState<PendingConfirm | null>(null);
|
|
|
|
const confirm = useCallback<ConfirmFn>(
|
|
(options) => new Promise<boolean>((resolve) => setPending({ options, resolve })),
|
|
[],
|
|
);
|
|
|
|
const answer = (value: boolean) => {
|
|
if (pending) pending.resolve(value);
|
|
setPending(null);
|
|
};
|
|
|
|
const tone = pending?.options.tone ?? "default";
|
|
|
|
return (
|
|
<ConfirmContext.Provider value={confirm}>
|
|
{children}
|
|
<Modal
|
|
open={pending !== null}
|
|
title={pending?.options.title ?? t("Confirmation")}
|
|
onClose={() => answer(false)}
|
|
>
|
|
<div className="flex flex-col gap-5">
|
|
<p className="text-sm leading-relaxed text-muted-foreground">
|
|
{pending?.options.message}
|
|
</p>
|
|
<div className="grid grid-cols-2 gap-2">
|
|
<IconAction
|
|
label={pending?.options.cancelLabel ?? t("Annuler")}
|
|
icon={<CloseIcon className="h-4 w-4" />}
|
|
className="w-full"
|
|
onClick={() => answer(false)}
|
|
/>
|
|
<IconAction
|
|
label={pending?.options.confirmLabel ?? t("Confirmer")}
|
|
icon={
|
|
pending?.options.confirmIcon ??
|
|
(tone === "danger" ? <TrashIcon className="h-4 w-4" /> : <MoveIcon className="h-4 w-4" />)
|
|
}
|
|
className="w-full bg-accent text-accent-foreground hover:bg-accent"
|
|
onClick={() => answer(true)}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
</ConfirmContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useConfirm = (): ConfirmFn => {
|
|
const context = useContext(ConfirmContext);
|
|
if (!context) throw new Error("useConfirm doit etre utilise sous ConfirmProvider");
|
|
return context;
|
|
};
|