@kopexa/alert-dialog
Version:
A modal dialog that interrupts the user with important content and expects a response.
92 lines (89 loc) • 2.07 kB
JavaScript
"use client";
import {
ConfirmInternalProvider
} from "./chunk-KY5A23F3.mjs";
import {
ConfirmDialog
} from "./chunk-SKOKGOQJ.mjs";
// src/confirm.tsx
import { useCallback, useMemo, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
var defaultOptions = {
title: "Are you sure?",
children: "This action cannot be undone.",
confirmButtonContent: "OK",
cancelButtonContent: "Cancel",
confirmButtonType: "destructive",
confirmButtonVariant: "solid"
};
var ConfirmDialogProvider = ({
children
}) => {
const [dialogState, setDialogState] = useState({
isOpen: false,
config: defaultOptions,
resolver: null
});
const confirm = useCallback((options) => {
setDialogState((prev) => ({
isOpen: true,
config: { ...defaultOptions, ...options },
resolver: prev.resolver
}));
return new Promise((resolve) => {
setDialogState((prev) => ({
...prev,
resolver: resolve
}));
});
}, []);
const handleCancel = useCallback(() => {
setDialogState((prev) => {
if (prev.resolver) {
prev.resolver(false);
}
return {
...prev,
isOpen: false,
resolver: null
};
});
}, []);
const handleOpenChange = useCallback(
(open) => {
if (!open) {
handleCancel();
}
},
[handleCancel]
);
const handleConfirm = useCallback(() => {
setDialogState((prev) => {
if (prev.resolver) {
prev.resolver(true);
}
return {
...prev,
isOpen: false,
resolver: null
};
});
}, []);
const context = useMemo(() => ({ confirm }), [confirm]);
return /* @__PURE__ */ jsxs(ConfirmInternalProvider, { value: context, children: [
children,
/* @__PURE__ */ jsx(
ConfirmDialog,
{
isOpen: dialogState.isOpen,
onOpenChange: handleOpenChange,
onConfirm: handleConfirm,
onCancel: handleCancel,
config: dialogState.config || {}
}
)
] });
};
export {
ConfirmDialogProvider
};