Files
OpenVPN-Monitoring-Simple/APP_UI/src/composables/useToast.js
T
ayurishchevandClaude Sonnet 5.5 dcc3d7f2d5 UI: shared toast notifications in the bottom-right corner
- useToast composable and ToastContainer (mounted once in App.vue):
  stacked toasts with icon, close button and progress bar, hover pause,
  slide-in animation, aria roles, full width on phones.
- Light and dark theme colour tokens; old .toast-message styles removed.
- PKIConfig, VPNConfig, ServerManagement and Certificates use the shared
  toast through thin showMessage/showToast wrappers.
- Docs: plan and summary in DOCS/Changes, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 21:05:41 +03:00

65 lines
1.9 KiB
JavaScript

import { reactive } from 'vue';
const MAX_VISIBLE = 4;
const DEFAULT_TIMEOUT = 5000;
const ERROR_TIMEOUT = 8000;
// Module-level state: every caller (views, ToastContainer) shares the same list
const toasts = reactive([]);
const timers = new Map(); // id -> { handle, startedAt, remaining }
let nextId = 1;
const clearTimer = (id) => {
const t = timers.get(id);
if (t) clearTimeout(t.handle);
timers.delete(id);
};
const dismiss = (id) => {
clearTimer(id);
const idx = toasts.findIndex((t) => t.id === id);
if (idx !== -1) toasts.splice(idx, 1);
};
const startTimer = (id, ms) => {
clearTimer(id);
timers.set(id, { handle: setTimeout(() => dismiss(id), ms), startedAt: Date.now(), remaining: ms });
};
// Stop the countdown (mouse over the toast); the progress bar is paused by CSS
const pause = (id) => {
const t = timers.get(id);
if (!t) return;
clearTimeout(t.handle);
t.remaining = Math.max(0, t.remaining - (Date.now() - t.startedAt));
t.handle = null;
};
const resume = (id) => {
const t = timers.get(id);
if (!t || t.handle !== null) return;
startTimer(id, t.remaining);
};
const show = (text, type = 'success', timeout) => {
const kind = ['success', 'warning', 'error', 'info'].includes(type) ? type : 'info';
const duration = timeout ?? (kind === 'error' ? ERROR_TIMEOUT : DEFAULT_TIMEOUT);
const id = nextId++;
toasts.push({ id, text: String(text ?? ''), type: kind, timeout: duration });
while (toasts.length > MAX_VISIBLE) dismiss(toasts[0].id);
if (duration > 0) startTimer(id, duration);
return id;
};
// Drop everything and release all timers (container unmount)
const clear = () => {
timers.forEach((t) => clearTimeout(t.handle));
timers.clear();
toasts.splice(0, toasts.length);
};
export function useToast() {
return { toasts, show, dismiss, pause, resume, clear };
}