Add popup model

This commit is contained in:
MrKBear 2022-03-21 23:29:46 +08:00
parent 7570e965cf
commit 04060902e0

View File

@ -1,4 +1,7 @@
import { ReactNode } from "react"; import { ReactNode } from "react";
import { Emitter } from "@Model/Emitter";
type IPopupConstructor = new (controller: PopupController, id: string) => Popup;
/** /**
* *
@ -23,7 +26,7 @@ class Popup {
/** /**
* *
*/ */
public index: number = 0; public index: number = Infinity;
/** /**
* react * react
@ -51,10 +54,14 @@ class Popup {
} }
} }
interface IPopupControllerEvent {
popupChange: void;
}
/** /**
* *
*/ */
class PopupController { class PopupController extends Emitter<IPopupControllerEvent> {
/** /**
* ID * ID
@ -66,20 +73,54 @@ class PopupController {
*/ */
public popups: Popup[] = []; public popups: Popup[] = [];
/**
*
*/
public sortPopup() { public sortPopup() {
this.popups = this.popups.sort((a, b) => a.index - b.index); this.popups = this.popups.sort((a, b) => a.index - b.index);
this.popups = this.popups.map((popup, index) => {
popup.index = (index + 1);
return popup;
});
} }
public newPopup(): Popup { /**
let newPopup = new Popup(this, `P-${this.idIndex ++}`); *
*/
public showPopup<P extends IPopupConstructor>(popup?: P): Popup {
let newPopup = new (popup ?? Popup)(this, `P-${this.idIndex ++}`);
this.popups.push(newPopup); this.popups.push(newPopup);
this.emit("popupChange");
return newPopup; return newPopup;
} }
public closePopup(popup: Popup | string) { /**
*
*/
public closePopup(popup: Popup | string): Popup | undefined {
let id: string;
if (popup instanceof Popup) {
id = popup.id;
} else {
id = popup;
}
let closePopup: Popup | undefined;
this.popups = this.popups.filter(
currentPopup => {
let isDelete = currentPopup.id === id;
if (isDelete) {
closePopup = currentPopup;
return false;
} else {
return true;
}
}
);
if (closePopup) {
this.emit("popupChange");
}
return closePopup;
} }
} }
export { Popup, PopupController } export { Popup, PopupController }