Home-Toolbox-Plugin/components/ui/message/index.tsx

45 lines
1.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { type MessageItem, addFn, removeFn } from "./utils";
import styles from "./message.module.less";
function Message() {
const [message, setMessage] = useState<MessageItem>();
useEffect(() => {
const fn = (nextMessage: MessageItem) => {
const key = `${Math.ceil(performance.now())}-${Math.round(Math.random() * 100)}`;
setMessage({ ...nextMessage, key });
setTimeout(() => {
onClose();
}, nextMessage.duration || 5000);
};
addFn(fn);
return () => {
removeFn(fn);
};
}, []);
const onClose = () => {
setMessage(undefined);
}
return createPortal((
<div className={styles.message}>
{message && (
<div key={message.key} className={styles.item}>
<span className={styles.content}>{message.content}</span>
<button className={styles.close} onClick={() => onClose()}>×</button>
</div>
)}
</div>
), document.body);
}
export default Message;