@codebayu/react-native-toast
Version:
The Package for creating dynamic and reusable styles in React Native App
75 lines (74 loc) • 2.49 kB
JavaScript
import { THROTTLE_DELAY } from './constant';
// Toast Manager Singleton
class ToastManagerSingleton {
static instance;
toastRef = null;
// private listeners: Set<(ref: ToastRef) => void> = new Set();
isAnimating = false;
queue = [];
lastToastTime = 0;
// Private constructor to prevent direct instantiation
constructor() {
// Initialize singleton instance
}
/** Get the singleton instance of ToastManager. */
static getInstance() {
if (!ToastManagerSingleton.instance) {
ToastManagerSingleton.instance = new ToastManagerSingleton();
}
return ToastManagerSingleton.instance;
}
setToastRef(ref) {
this.toastRef = ref;
}
setAnimating(isAnimating) {
this.isAnimating = isAnimating;
}
/** Process queued toast messages */
processQueue() {
if (!this.isAnimating && this.queue.length > 0 && this.toastRef) {
const nextToast = this.queue.shift();
if (nextToast && nextToast.message && nextToast.message.trim() !== '') {
this.isAnimating = true;
this.lastToastTime = Date.now();
this.toastRef.show(nextToast.message, nextToast.type, nextToast.options);
}
else {
// Skip empty messages and process next item
this.processQueue();
}
}
}
/** Show a toast message. */
show(message, type = 'warning', options) {
// Validasi pesan kosong
if (!message || message.trim() === '') {
return;
}
// Anti-spam check
const now = Date.now();
if (now - this.lastToastTime < THROTTLE_DELAY || this.isAnimating) {
return; // Skip jika masih dalam cooldown atau sedang animasi
}
// Update waktu toast terakhir
this.lastToastTime = now;
// Tampilkan toast
if (this.toastRef) {
this.isAnimating = true;
this.toastRef.show(message, type, options);
}
}
/** Hide the currently visible toast. */
hide(callback) {
if (this.toastRef) {
this.toastRef.hide(() => {
this.isAnimating = false;
if (callback)
callback();
this.processQueue();
});
}
}
}
/** Singleton instance to manage toasts globally. */
export const ToastManager = ToastManagerSingleton.getInstance();