Files
online-energieausweis/src/components/Notifications/shared.ts
2024-12-23 16:36:58 +07:00

81 lines
1.6 KiB
TypeScript

import { Writable, writable } from "svelte/store";
import { v4 as uuid } from "uuid";
export const notifications: Writable<Record<string, Notification>> = writable({});
const defaults = {
message: "",
dismissable: false,
timeout: 4000,
subtext: "",
type: "error",
onUserDismiss: () => {}
};
export interface Notification {
message: string;
dismissable: boolean;
timeout: number;
subtext: string;
type: "error" | "success" | "info" | "warning";
onUserDismiss: () => any;
uid?: string;
selector?: string;
}
export function updateNotification(uid: string, updater: Partial<Notification>) {
notifications.update((value) => {
value[uid] = { ...defaults, ...value[uid], ...updater } as Notification;
return value;
})
}
export function addNotification(notification: Partial<Notification>): string {
let uid = uuid();
if (notification.uid) {
uid = notification.uid;
}
const object: Notification = { ...defaults, ...notification } as Notification;
notifications.update((value) => {
value[uid] = object;
return value;
})
if (object.timeout) {
setTimeout(() => {
deleteNotification(uid);
}, object.timeout);
}
return uid;
}
export function deleteNotification(uid: string) {
notifications.update((value) => {
delete value[uid];
return value;
})
}
export function showLinkedElement(query: string) {
const element = document.querySelector(query);
if (!element) {
return;
}
element.classList.add("linked");
}
export function hideLinkedElement(query: string) {
const element = document.querySelector(query);
if (!element) {
return;
}
element.classList.remove("linked");
}