45 lines
1.7 KiB
React
45 lines
1.7 KiB
React
import React, { forwardRef, useImperativeHandle, useState, useRef } from 'react';
|
|
import './NotificationPro.css';
|
|
|
|
const ICON = { success: '✓', error: '✕', warning: '!', info: 'i' };
|
|
|
|
const NotificationPro = forwardRef(function NotificationPro({ duration = 4500 }, ref) {
|
|
const [list, setList] = useState([]);
|
|
const idRef = useRef(0);
|
|
|
|
function close(id) { setList(l => l.filter(m => m.id !== id)); }
|
|
function open(opts) {
|
|
const id = ++idRef.current;
|
|
setList(l => [...l, { id, type: opts.type || 'info', title: opts.title, desc: opts.desc }]);
|
|
const d = opts.duration == null ? duration : opts.duration;
|
|
if (d > 0) setTimeout(() => close(id), d);
|
|
return id;
|
|
}
|
|
|
|
useImperativeHandle(ref, () => ({
|
|
open,
|
|
close,
|
|
success: (t, d, dur) => open({ type: 'success', title: t, desc: d, duration: dur }),
|
|
error: (t, d, dur) => open({ type: 'error', title: t, desc: d, duration: dur }),
|
|
warning: (t, d, dur) => open({ type: 'warning', title: t, desc: d, duration: dur }),
|
|
info: (t, d, dur) => open({ type: 'info', title: t, desc: d, duration: dur })
|
|
}));
|
|
|
|
return (
|
|
<div className="aa-notification-wrap">
|
|
{list.map(m => (
|
|
<div key={m.id} className={`aa-notification is-${m.type}`}>
|
|
<span className="aa-notification-icon">{ICON[m.type] || 'i'}</span>
|
|
<div className="aa-notification-body">
|
|
<div className="aa-notification-title">{m.title}</div>
|
|
{m.desc ? <div className="aa-notification-desc">{m.desc}</div> : null}
|
|
</div>
|
|
<span className="aa-notification-close" onClick={() => close(m.id)}>✕</span>
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
});
|
|
|
|
export default NotificationPro;
|