Files
ThreadNet-Web/src/stores/ToastStore.ts
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

79 lines
2.6 KiB
TypeScript
Raw Normal View History

/*
2024-09-09 14:57:16 +01:00
Copyright 2024 New Vector Ltd.
Copyright 2020 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
2024-09-09 14:57:16 +01:00
Please see LICENSE files in the repository root for full details.
*/
import EventEmitter from "events";
import { logger } from "matrix-js-sdk/src/logger";
import { type JSX } from "react";
2021-10-22 17:23:32 -05:00
2025-02-05 13:25:06 +00:00
import type React from "react";
import { type ComponentClass } from "../@types/common";
2020-07-29 12:43:35 -06:00
export interface IToast<C extends ComponentClass> {
key: string;
// higher priority number will be shown on top of lower priority
priority: number;
2021-07-24 13:04:06 +02:00
title?: string;
icon?: JSX.Element;
component: C;
className?: string;
2021-07-26 12:21:58 +02:00
bodyClassName?: string;
2020-06-29 11:34:58 +01:00
props?: Omit<React.ComponentProps<C>, "toastKey">; // toastKey is injected by ToastContainer
}
/**
* Holds the active toasts
*/
export default class ToastStore extends EventEmitter {
private toasts: IToast<any>[] = [];
public static sharedInstance(): ToastStore {
2020-07-20 20:43:49 +01:00
if (!window.mxToastStore) window.mxToastStore = new ToastStore();
return window.mxToastStore;
}
public reset(): void {
this.toasts = [];
}
/**
* Add or replace a toast
* If a toast with the same toastKey already exists, the given toast will replace it
* Toasts are always added underneath any toasts of the same priority, so existing
* toasts stay at the top unless a higher priority one arrives (better to not change the
* toast unless necessary).
*
* @param {object} newToast The new toast
*/
public addOrReplaceToast<C extends ComponentClass>(newToast: IToast<C>): void {
const oldIndex = this.toasts.findIndex((t) => t.key === newToast.key);
if (oldIndex === -1) {
logger.info(`Opening toast with key '${newToast.key}': title '${newToast.title}'`);
let newIndex = this.toasts.length;
2020-05-23 09:02:35 +01:00
while (newIndex > 0 && this.toasts[newIndex - 1].priority < newToast.priority) --newIndex;
this.toasts.splice(newIndex, 0, newToast);
} else {
logger.info(`Replacing existing toast with key '${newToast.key}': title now '${newToast.title}'`);
this.toasts[oldIndex] = newToast;
}
this.emit("update");
}
public dismissToast(key: string): void {
const length = this.toasts.length;
this.toasts = this.toasts.filter((t) => t.key !== key);
if (length !== this.toasts.length) {
logger.info(`Removed toast with key '${key}'`);
this.emit("update");
}
}
public getToasts(): IToast<any>[] {
return this.toasts;
}
}