koval-ui
Version:
React components collection with minimalistic design. Supports theming, layout, and input validation.
77 lines (76 loc) • 2.65 kB
JavaScript
"use client";
import { useState as T, useCallback as N, useEffect as w } from "react";
import { useNotificationContext as I } from "./NotificationContext.js";
import { Actions as s } from "./NotificationReducer.js";
import { useNotificationProps as E } from "./useNotificationProps.js";
import { useNotificationInstance as d } from "./useNotificationInstance.js";
const y = (t) => {
const { state: e } = I();
return t(e);
}, l = (t) => new window.Notification(t.title, {
icon: t.icon,
body: t.body,
requireInteraction: t.requireInteraction
}), _ = (t) => {
const { dispatch: e } = I(), o = d(t), r = E(t), c = y(
(i) => i.open.some((n) => n === t)
), [O, f] = T(), a = N(() => {
e({
type: s.NOTIFICATION_CLOSE,
id: t
});
}, [e, t]);
w(() => (o == null || o.addEventListener("close", a), () => {
o == null || o.removeEventListener("close", a);
}), [a, o]);
const p = N(() => {
var n, u;
const i = (n = window == null ? void 0 : window.Notification) == null ? void 0 : n.permission;
c && (o == null || o.close()), i === "granted" ? (e({
type: s.NOTIFICATION_OPEN,
id: t,
instance: l(r)
}), f(i)) : i !== "denied" ? (u = window == null ? void 0 : window.Notification) == null || u.requestPermission().then((m) => {
f(m), m === "granted" && e({
type: s.NOTIFICATION_OPEN,
id: t,
instance: l(r)
});
}) : i === "denied" && f(i);
}, [e, t, o, c, r]), C = N(() => {
o == null || o.close(), e({ type: s.NOTIFICATION_CLOSE, id: t });
}, [e, t, o]);
return {
/**
* Show notification to the user.
* Warning! Will not work from component scope. Needs to be run as an effect
* @example
* const {openNotificaton} = useNotificationState(id);
* const handleClick = useCallback(() => {
* openNotification();
* }, [openNotification]);
*/
openNotification: p,
/**
* Hide notification.
* Warning! Will not work from component scope. Needs to be run as an effect
* @example
* const {openNotificaton} = useNotificationState(id);
* const handleClick = useCallback(() => {
* openNotification();
* }, [openNotification]);
*/
closeNotification: C,
/** Current visibility of notification */
isOpen: c,
/**
* Indicates the current permission granted by the user for the current origin to display web notifications
* @see https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission_static
*/
permission: O
};
};
export {
_ as useNotificationState
};
//# sourceMappingURL=useNotificationState.js.map