@nullpixel/ui
Version:
A UI Library for Modern Web Apps, powered by Vue & Tailwind CSS.
63 lines (62 loc) • 1.44 kB
JavaScript
import { ref, nextTick } from "vue";
import { useState } from "#imports";
export function useToast() {
const toasts = useState("toasts", () => []);
const maxToasts = 5;
const running = ref(false);
const queue = [];
const generateId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
async function processQueue() {
if (running.value || queue.length === 0) {
return;
}
running.value = true;
while (queue.length > 0) {
const toast = queue.shift();
await nextTick();
toasts.value = [...toasts.value, toast].slice(-maxToasts);
}
running.value = false;
}
function add(toast) {
const body = {
id: generateId(),
open: true,
...toast
};
queue.push(body);
processQueue();
return body;
}
function update(id, toast) {
const index = toasts.value.findIndex((t) => t.id === id);
if (index !== -1) {
toasts.value[index] = {
...toasts.value[index],
...toast
};
}
}
function remove(id) {
const index = toasts.value.findIndex((t) => t.id === id);
if (index !== -1) {
toasts.value[index] = {
...toasts.value[index],
open: false
};
}
setTimeout(() => {
toasts.value = toasts.value.filter((t) => t.id !== id);
}, 200);
}
function clear() {
toasts.value = [];
}
return {
toasts,
add,
update,
remove,
clear
};
}