|
| 1 | +import { acceptHMRUpdate, defineStore } from "pinia"; |
| 2 | +import { v4 as uuid } from "uuid"; |
| 3 | + |
| 4 | +export type AlertStyle = "error" | "success" | "warning" | "info" | "none"; |
| 5 | + |
| 6 | +export interface AlertOptions { |
| 7 | + html?: boolean; |
| 8 | + closable?: boolean; |
| 9 | + timeout?: number | false; |
| 10 | + style?: AlertStyle; |
| 11 | +} |
| 12 | + |
| 13 | +const defaultOptions: Required<AlertOptions> = { |
| 14 | + closable: true, |
| 15 | + html: false, |
| 16 | + timeout: 3000, |
| 17 | + style: "info", |
| 18 | +}; |
| 19 | + |
| 20 | +export interface Alert extends AlertOptions { |
| 21 | + id: string; |
| 22 | + message: string; |
| 23 | +} |
| 24 | + |
| 25 | +export const useAlerts = defineStore("alerts", { |
| 26 | + state: () => ({ |
| 27 | + items: [] as Alert[], |
| 28 | + }), |
| 29 | + |
| 30 | + actions: { |
| 31 | + notify(message: string, style: AlertStyle, options?: AlertOptions) { |
| 32 | + options = { ...defaultOptions, style, ...options }; |
| 33 | + |
| 34 | + const id = uuid(); |
| 35 | + this.items.push({ |
| 36 | + message, |
| 37 | + id, |
| 38 | + ...options, |
| 39 | + }); |
| 40 | + |
| 41 | + if (options.timeout !== false) { |
| 42 | + setTimeout(() => { |
| 43 | + this.remove(id); |
| 44 | + }, options.timeout); |
| 45 | + } |
| 46 | + }, |
| 47 | + |
| 48 | + success(message: string, options?: AlertOptions) { |
| 49 | + this.notify(message, "success", options); |
| 50 | + }, |
| 51 | + |
| 52 | + error(message: string, options?: AlertOptions) { |
| 53 | + this.notify(message, "error", options); |
| 54 | + }, |
| 55 | + |
| 56 | + warning(message: string, options?: AlertOptions) { |
| 57 | + this.notify(message, "warning", options); |
| 58 | + }, |
| 59 | + |
| 60 | + info(message: string, options?: AlertOptions) { |
| 61 | + this.notify(message, "info", options); |
| 62 | + }, |
| 63 | + |
| 64 | + remove(id: string) { |
| 65 | + const index = this.items.findIndex((item) => item.id === id); |
| 66 | + if (index > -1) { |
| 67 | + this.items.splice(index, 1); |
| 68 | + } |
| 69 | + }, |
| 70 | + }, |
| 71 | +}); |
| 72 | + |
| 73 | +if (import.meta.hot) { |
| 74 | + import.meta.hot.accept(acceptHMRUpdate(useAlerts, import.meta.hot)); |
| 75 | +} |
0 commit comments