aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/toast.js
blob: 0e9da9ca17e3a27d95760893c11184ff3f73020a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// ==================== Baby Tracker Toast Notifications ====================
document.addEventListener('alpine:init', () => {
  Alpine.store('toast', {
    messages: [],
    _seq: 0,
 
    show(message, type = 'info', duration = 0) {
      if (!message) return;
      const defaults = { success: 2800, error: 4500, warning: 3500, info: 2800 };
      const id = `${Date.now()}-${++this._seq}`;
      this.messages.push({ id, message, type, visible: true });
 
      // Cap queue length to avoid stacking forever
      if (this.messages.length > 5) {
        const oldest = this.messages[0];
        this.dismiss(oldest.id);
      }
 
      const ms = duration > 0 ? duration : (defaults[type] || 2800);
      setTimeout(() => this.dismiss(id), ms);
    },
 
    dismiss(id) {
      const msg = this.messages.find(m => m.id === id);
      if (!msg || !msg.visible) return;
      msg.visible = false;
      setTimeout(() => {
        this.messages = this.messages.filter(m => m.id !== id);
      }, 300);
    },
 
    success(msg) { this.show(msg, 'success'); },
    error(msg) { this.show(msg, 'error'); },
    warning(msg) { this.show(msg, 'warning'); },
    info(msg) { this.show(msg, 'info'); }
  });
});