@coinmeca/ui
Version:
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
104 lines • 3.11 kB
JSX
"use client";
import { createContext, useState } from "react";
export const NotificationContext = createContext({});
export default function Notification({ children }) {
const [notis, setNotiList] = useState([]);
const [toasts, setToasts] = useState([]);
const [nonce, setNonce] = useState(0);
const [read, setRead] = useState(false);
const [count, setCount] = useState(0);
function setNotis(notis) {
setNotiList(notis);
setNonce(notis.length);
}
function addToast(obj) {
if (!obj)
return;
if (!obj?.type)
obj.type = obj?.remain ? "notify" : "toast";
if (!obj?.id) {
const n = nonce + 1;
obj.id = `${Date.now()}` + `${n}`;
setNonce(n);
}
if (!obj?.date)
obj.date = Date.now();
setToasts([...toasts, obj]);
if (obj?.remain) {
setCount(count + 1);
setNotiList([...notis, obj]);
}
}
function addNotify(obj) {
if (!obj)
return;
if (!obj?.type)
obj.type = "notify";
if (!obj.id) {
const n = nonce + 1;
obj.id = `${Date.now()}` + `${n}`;
setNonce(n);
}
if (!obj.date)
obj.date = Date.now();
setCount(count + 1);
setNotiList([...notis, obj]);
}
function removeToast(id) {
if (!id)
return;
setTimeout(() => setToasts((states) => states.filter((n) => n?.id !== id)), 300);
}
function removeNotify(id) {
if (!id)
return;
let c = count;
notis.map((n, i) => {
if (n?.id === id && i >= notis.length - c)
c -= 1;
});
setCount(c);
setTimeout(() => setNotiList((states) => states.filter((n) => n?.id !== id)), 300);
}
function resetCount() {
setCount(0);
}
function saveNotis(key) {
if (key && key !== "") {
const list = JSON.stringify(notis);
localStorage.setItem(`${key}.noti.list`, list);
localStorage.setItem(`${key}.noti.count`, count?.toString());
}
}
function loadNotis(key) {
let list = [];
if (key && key !== "") {
list = JSON.parse(localStorage.getItem(`${key}.noti.list`) || "[]");
const count = parseInt(localStorage.getItem(`${key}.noti.count`) || "0");
if (list?.length > 0)
setNotis(list);
if (count > 0 && !isNaN(count))
setCount(count);
}
return list;
}
return (<NotificationContext.Provider value={{
notis,
toasts,
count,
read,
addNotify,
addToast,
removeNotify,
removeToast,
resetCount,
setNotis,
setToasts,
setRead,
saveNotis,
loadNotis,
}}>
{children}
</NotificationContext.Provider>);
}
//# sourceMappingURL=Notification.jsx.map