claritykit-svelte
Version:
A comprehensive Svelte component library focused on accessibility, ADHD-optimized design, developer experience, and full SSR compatibility
87 lines (86 loc) • 2.49 kB
JavaScript
import { writable } from 'svelte/store';
class ToastManager {
constructor() {
Object.defineProperty(this, "state", {
enumerable: true,
configurable: true,
writable: true,
value: writable({
toasts: [],
maxToasts: 5,
defaultPosition: 'top-right',
defaultDuration: 5000
})
});
Object.defineProperty(this, "idCounter", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
// Subscribe to state changes
Object.defineProperty(this, "subscribe", {
enumerable: true,
configurable: true,
writable: true,
value: this.state.subscribe
});
}
// Add a new toast
add(options) {
const id = `toast-${++this.idCounter}`;
const toast = {
id,
timestamp: Date.now(),
...options
};
this.state.update(state => {
const newToasts = [...state.toasts, toast];
// Remove oldest toasts if we exceed maxToasts
if (newToasts.length > state.maxToasts) {
newToasts.splice(0, newToasts.length - state.maxToasts);
}
return {
...state,
toasts: newToasts
};
});
return id;
}
// Remove a toast by ID
remove(id) {
this.state.update(state => ({
...state,
toasts: state.toasts.filter(toast => toast.id !== id)
}));
}
// Clear all toasts
clear() {
this.state.update(state => ({
...state,
toasts: []
}));
}
// Convenience methods for different toast types
success(message, options) {
return this.add({ ...options, type: 'success', message });
}
error(message, options) {
return this.add({ ...options, type: 'error', message });
}
warning(message, options) {
return this.add({ ...options, type: 'warning', message });
}
info(message, options) {
return this.add({ ...options, type: 'info', message });
}
// Update manager configuration
configure(config) {
this.state.update(state => ({
...state,
...config
}));
}
}
// Export singleton instance
export const toastManager = new ToastManager();