koval-ui
Version:
React components collection with minimalistic design. Supports theming, layout, and input validation.
76 lines (75 loc) • 2.51 kB
JavaScript
"use client";
import { useState as p, useCallback as N, useEffect as C } from "react";
import { useNotificationContext as m } from "./NotificationContext.js";
import { Actions as s } from "./NotificationReducer.js";
import { useNotificationProps as T } from "./useNotificationProps.js";
import { useNotificationInstance as w } from "./useNotificationInstance.js";
const E = (t) => {
const { state: e } = m();
return t(e);
}, u = (t) => new window.Notification(t.title, {
icon: t.icon,
body: t.body,
requireInteraction: t.requireInteraction
}), F = (t) => {
const { dispatch: e } = m(), o = w(t), c = T(t), r = E(
(n) => n.open.some((i) => i === t)
), [l, a] = p(), f = N(() => {
e({
type: s.NOTIFICATION_CLOSE,
id: t
});
}, [e, t]);
C(() => (o?.addEventListener("close", f), () => {
o?.removeEventListener("close", f);
}), [f, o]);
const I = N(() => {
const n = window?.Notification?.permission;
r && o?.close(), n === "granted" ? (e({
type: s.NOTIFICATION_OPEN,
id: t,
instance: u(c)
}), a(n)) : n !== "denied" ? window?.Notification?.requestPermission().then((i) => {
a(i), i === "granted" && e({
type: s.NOTIFICATION_OPEN,
id: t,
instance: u(c)
});
}) : n === "denied" && a(n);
}, [e, t, o, r, c]), O = N(() => {
o?.close(), e({ type: s.NOTIFICATION_CLOSE, id: t });
}, [e, t, o]);
return {
/**
* Show a notification to the user.
* Warning! Will not work from a component scope. Needs to be run as an effect
* @example
* const {openNotificaton} = useNotificationState(id);
* const handleClick = useCallback(() => {
* openNotification();
* }, [openNotification]);
*/
openNotification: I,
/**
* Hide a notification.
* Warning! Will not work from a component scope. Needs to be run as an effect
* @example
* const {closeNotification} = useNotificationState(id);
* const handleClick = useCallback(() => {
* closeNotification();
* }, [closeNotification]);
*/
closeNotification: O,
/** Current visibility of notification */
isOpen: r,
/**
* 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: l
};
};
export {
F as useNotificationState
};
//# sourceMappingURL=useNotificationState.js.map