Adds SnackbarVariant enum

This commit is contained in:
Heinous Tugboat 2022-04-08 23:42:07 -04:00
parent 758b0e1127
commit 5b96cedd0c
11 changed files with 46 additions and 31 deletions

@ -2,7 +2,7 @@ import { Player } from "./Player";
import { Router } from "./ui/GameRoot"; import { Router } from "./ui/GameRoot";
import { removeLeadingSlash } from "./Terminal/DirectoryHelpers"; import { removeLeadingSlash } from "./Terminal/DirectoryHelpers";
import { Terminal } from "./Terminal"; import { Terminal } from "./Terminal";
import { SnackbarEvents } from "./ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "./ui/React/Snackbar";
import { IMap, IReturnStatus } from "./types"; import { IMap, IReturnStatus } from "./types";
import { GetServer } from "./Server/AllServers"; import { GetServer } from "./Server/AllServers";
import { ImportPlayerData, SaveData, saveObject } from "./SaveObject"; import { ImportPlayerData, SaveData, saveObject } from "./SaveObject";
@ -111,8 +111,7 @@ function initAppNotifier(): void {
if (!fn) fn = Terminal.print; if (!fn) fn = Terminal.print;
fn.bind(Terminal)(message); fn.bind(Terminal)(message);
}, },
toast: (message: string, type: "info" | "success" | "warning" | "error", duration = 2000) => toast: (message: string, type: SnackbarVariant, duration = 2000) => SnackbarEvents.emit(message, type, duration),
SnackbarEvents.emit(message, type, duration),
}; };
// Will be consumud by the electron wrapper. // Will be consumud by the electron wrapper.
@ -127,7 +126,7 @@ function initSaveFunctions(): void {
saveObject.exportGame(); saveObject.exportGame();
} catch (error) { } catch (error) {
console.log(error); console.log(error);
SnackbarEvents.emit("Could not export game.", "error", 2000); SnackbarEvents.emit("Could not export game.", SnackbarVariant.ERROR, 2000);
} }
}, },
triggerScriptsExport: (): void => exportScripts("*", Player.getHomeComputer()), triggerScriptsExport: (): void => exportScripts("*", Player.getHomeComputer()),
@ -176,7 +175,7 @@ function initElectronBridge(): void {
}) })
.catch((error: any) => { .catch((error: any) => {
console.log(error); console.log(error);
SnackbarEvents.emit("Could not save game.", "error", 2000); SnackbarEvents.emit("Could not save game.", SnackbarVariant.ERROR, 2000);
}); });
}); });
bridge.receive("trigger-game-export", () => { bridge.receive("trigger-game-export", () => {
@ -184,7 +183,7 @@ function initElectronBridge(): void {
(window as any).appSaveFns.triggerGameExport(); (window as any).appSaveFns.triggerGameExport();
} catch (error) { } catch (error) {
console.log(error); console.log(error);
SnackbarEvents.emit("Could not export game.", "error", 2000); SnackbarEvents.emit("Could not export game.", SnackbarVariant.ERROR, 2000);
} }
}); });
bridge.receive("trigger-scripts-export", () => { bridge.receive("trigger-scripts-export", () => {
@ -192,7 +191,7 @@ function initElectronBridge(): void {
(window as any).appSaveFns.triggerScriptsExport(); (window as any).appSaveFns.triggerScriptsExport();
} catch (error) { } catch (error) {
console.log(error); console.log(error);
SnackbarEvents.emit("Could not export scripts.", "error", 2000); SnackbarEvents.emit("Could not export scripts.", SnackbarVariant.ERROR, 2000);
} }
}); });
} }

@ -24,7 +24,7 @@ import { joinFaction } from "../../Faction/FactionHelpers";
import { use } from "../../ui/Context"; import { use } from "../../ui/Context";
import { dialogBoxCreate } from "../../ui/React/DialogBox"; import { dialogBoxCreate } from "../../ui/React/DialogBox";
import { SnackbarEvents } from "../../ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "../../ui/React/Snackbar";
import { N00dles } from "../../utils/helpers/N00dles"; import { N00dles } from "../../utils/helpers/N00dles";
import { Exploit } from "../../Exploits/Exploit"; import { Exploit } from "../../Exploits/Exploit";
import { applyAugmentation } from "../../Augmentation/AugmentationHelpers"; import { applyAugmentation } from "../../Augmentation/AugmentationHelpers";
@ -91,7 +91,7 @@ export function SpecialLocation(props: IProps): React.ReactElement {
function renderNoodleBar(): React.ReactElement { function renderNoodleBar(): React.ReactElement {
function EatNoodles(): void { function EatNoodles(): void {
SnackbarEvents.emit("You ate some delicious noodles and feel refreshed", "success", 2000); SnackbarEvents.emit("You ate some delicious noodles and feel refreshed", SnackbarVariant.SUCCESS, 2000);
N00dles(); // This is the true power of the noodles. N00dles(); // This is the true power of the noodles.
if (player.sourceFiles.length > 0) player.giveExploit(Exploit.N00dles); if (player.sourceFiles.length > 0) player.giveExploit(Exploit.N00dles);
if (player.sourceFileLvl(5) > 0 || player.bitNodeN === 5) { if (player.sourceFileLvl(5) > 0 || player.bitNodeN === 5) {

@ -93,7 +93,8 @@ import { NetscriptSingularity } from "./NetscriptFunctions/Singularity";
import { toNative } from "./NetscriptFunctions/toNative"; import { toNative } from "./NetscriptFunctions/toNative";
import { dialogBoxCreate } from "./ui/React/DialogBox"; import { dialogBoxCreate } from "./ui/React/DialogBox";
import { SnackbarEvents } from "./ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "./ui/React/Snackbar";
import { checkEnum } from "./utils/helpers/checkEnum";
import { Flags } from "./NetscriptFunctions/Flags"; import { Flags } from "./NetscriptFunctions/Flags";
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence"; import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
@ -2262,13 +2263,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const message = helper.string("alert", "message", _message); const message = helper.string("alert", "message", _message);
dialogBoxCreate(message); dialogBoxCreate(message);
}, },
toast: function (_message: unknown, _variant: unknown = "success", duration: any = 2000): void { toast: function (_message: unknown, _variant: unknown = SnackbarVariant.SUCCESS, duration: any = 2000): void {
updateDynamicRam("toast", getRamCost(Player, "toast")); updateDynamicRam("toast", getRamCost(Player, "toast"));
const message = helper.string("toast", "message", _message); const message = helper.string("toast", "message", _message);
const variant = helper.string("toast", "variant", _variant); const variant = helper.string("toast", "variant", _variant);
if (!["success", "info", "warning", "error"].includes(variant)) if (!checkEnum(SnackbarVariant, variant))
throw new Error(`variant must be one of "success", "info", "warning", or "error"`); throw new Error(`variant must be one of ${Object.values(SnackbarVariant).join(", ")}`);
SnackbarEvents.emit(message, variant as any, duration); SnackbarEvents.emit(message, variant, duration);
}, },
prompt: function (_txt: unknown, options?: { type?: string; options?: string[] }): Promise<boolean | string> { prompt: function (_txt: unknown, options?: { type?: string; options?: string[] }): Promise<boolean | string> {
updateDynamicRam("prompt", getRamCost(Player, "prompt")); updateDynamicRam("prompt", getRamCost(Player, "prompt"));

@ -62,7 +62,7 @@ import { Money } from "../../ui/React/Money";
import React from "react"; import React from "react";
import { serverMetadata } from "../../Server/data/servers"; import { serverMetadata } from "../../Server/data/servers";
import { SnackbarEvents } from "../../ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "../../ui/React/Snackbar";
import { calculateClassEarnings } from "../formulas/work"; import { calculateClassEarnings } from "../formulas/work";
import { achievements } from "../../Achievements/Achievements"; import { achievements } from "../../Achievements/Achievements";
import { FactionNames } from "../../Faction/data/FactionNames"; import { FactionNames } from "../../Faction/data/FactionNames";
@ -1734,7 +1734,11 @@ export function regenerateHp(this: IPlayer, amt: number): void {
export function hospitalize(this: IPlayer): number { export function hospitalize(this: IPlayer): number {
const cost = getHospitalizationCost(this); const cost = getHospitalizationCost(this);
SnackbarEvents.emit(`You've been Hospitalized for ${numeralWrapper.formatMoney(cost)}`, "warning", 2000); SnackbarEvents.emit(
`You've been Hospitalized for ${numeralWrapper.formatMoney(cost)}`,
SnackbarVariant.WARNING,
2000,
);
this.loseMoney(cost, "hospitalization"); this.loseMoney(cost, "hospitalization");
this.hp = this.max_hp; this.hp = this.max_hp;
@ -2709,7 +2713,7 @@ export function canAccessGrafting(this: IPlayer): boolean {
export function giveExploit(this: IPlayer, exploit: Exploit): void { export function giveExploit(this: IPlayer, exploit: Exploit): void {
if (!this.exploits.includes(exploit)) { if (!this.exploits.includes(exploit)) {
this.exploits.push(exploit); this.exploits.push(exploit);
SnackbarEvents.emit("SF -1 acquired!", "success", 2000); SnackbarEvents.emit("SF -1 acquired!", SnackbarVariant.SUCCESS, 2000);
} }
} }
@ -2718,7 +2722,7 @@ export function giveAchievement(this: IPlayer, achievementId: string): void {
if (!achievement) return; if (!achievement) return;
if (!this.achievements.map((a) => a.ID).includes(achievementId)) { if (!this.achievements.map((a) => a.ID).includes(achievementId)) {
this.achievements.push({ ID: achievementId, unlockedOn: new Date().getTime() }); this.achievements.push({ ID: achievementId, unlockedOn: new Date().getTime() });
SnackbarEvents.emit(`Unlocked Achievement: "${achievement.Name}"`, "success", 2000); SnackbarEvents.emit(`Unlocked Achievement: "${achievement.Name}"`, SnackbarVariant.SUCCESS, 2000);
} }
} }

@ -11,7 +11,7 @@ import { SourceFileFlags } from "./SourceFile/SourceFileFlags";
import { loadStockMarket, StockMarket } from "./StockMarket/StockMarket"; import { loadStockMarket, StockMarket } from "./StockMarket/StockMarket";
import { staneksGift, loadStaneksGift } from "./CotMG/Helper"; import { staneksGift, loadStaneksGift } from "./CotMG/Helper";
import { SnackbarEvents } from "./ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "./ui/React/Snackbar";
import * as ExportBonus from "./ExportBonus"; import * as ExportBonus from "./ExportBonus";
@ -114,7 +114,7 @@ class BitburnerSaveObject {
pushGameSaved(saveData); pushGameSaved(saveData);
if (emitToastEvent) { if (emitToastEvent) {
SnackbarEvents.emit("Game Saved!", "info", 2000); SnackbarEvents.emit("Game Saved!", SnackbarVariant.INFO, 2000);
} }
return resolve(); return resolve();
}) })

@ -6183,7 +6183,7 @@ export interface NS extends Singularity {
* @param variant - Type of toast, must be one of success, info, warning, error. Defaults to success. * @param variant - Type of toast, must be one of success, info, warning, error. Defaults to success.
* @param duration - Duration of toast in ms. Can also be `null` to create a persistent toast. Defaults to 2000 * @param duration - Duration of toast in ms. Can also be `null` to create a persistent toast. Defaults to 2000
*/ */
toast(msg: any, variant?: string, duration?: number | null): void; toast(msg: any, variant?: "success" | "info" | "warning" | "error", duration?: number | null): void;
/** /**
* Download a file from the internet. * Download a file from the internet.

@ -11,7 +11,7 @@ import { StyleEditorButton } from "./StyleEditorButton";
import { ThemeEntry } from "./ThemeEntry"; import { ThemeEntry } from "./ThemeEntry";
import { ThemeCollaborate } from "./ThemeCollaborate"; import { ThemeCollaborate } from "./ThemeCollaborate";
import { Modal } from "../../ui/React/Modal"; import { Modal } from "../../ui/React/Modal";
import { SnackbarEvents } from "../../ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "../../ui/React/Snackbar";
interface IProps { interface IProps {
router: IRouter; router: IRouter;
@ -54,7 +54,7 @@ export function ThemeBrowser({ router }: IProps): React.ReactElement {
UNDO UNDO
</Button> </Button>
</>, </>,
"info", SnackbarVariant.INFO,
30000, 30000,
); );
} }

@ -50,7 +50,7 @@ import { calculateAchievements } from "./Achievements/Achievements";
import React from "react"; import React from "react";
import { setupUncaughtPromiseHandler } from "./UncaughtPromiseHandler"; import { setupUncaughtPromiseHandler } from "./UncaughtPromiseHandler";
import { Button, Typography } from "@mui/material"; import { Button, Typography } from "@mui/material";
import { SnackbarEvents } from "./ui/React/Snackbar"; import { SnackbarEvents, SnackbarVariant } from "./ui/React/Snackbar";
const Engine: { const Engine: {
_lastUpdate: number; _lastUpdate: number;
@ -495,7 +495,7 @@ function warnAutosaveDisabled(): void {
</Button> </Button>
</> </>
); );
SnackbarEvents.emit(warningToast, "warning", 5000); SnackbarEvents.emit(warningToast, SnackbarVariant.WARNING, 5000);
} }
export { Engine }; export { Engine };

@ -27,7 +27,7 @@ import PaletteIcon from "@mui/icons-material/Palette";
import { FileDiagnosticModal } from "../../Diagnostic/FileDiagnosticModal"; import { FileDiagnosticModal } from "../../Diagnostic/FileDiagnosticModal";
import { ConfirmationModal } from "./ConfirmationModal"; import { ConfirmationModal } from "./ConfirmationModal";
import { SnackbarEvents } from "./Snackbar"; import { SnackbarEvents, SnackbarVariant } from "./Snackbar";
import { Settings } from "../../Settings/Settings"; import { Settings } from "../../Settings/Settings";
import { DeleteGameButton } from "./DeleteGameButton"; import { DeleteGameButton } from "./DeleteGameButton";
@ -123,7 +123,7 @@ export function GameOptionsRoot(props: IProps): React.ReactElement {
setImportData(data); setImportData(data);
setImportSaveOpen(true); setImportSaveOpen(true);
} catch (ex: any) { } catch (ex: any) {
SnackbarEvents.emit(ex.toString(), "error", 5000); SnackbarEvents.emit(ex.toString(), SnackbarVariant.ERROR, 5000);
} }
} }
@ -133,7 +133,7 @@ export function GameOptionsRoot(props: IProps): React.ReactElement {
try { try {
await saveObject.importGame(importData.base64); await saveObject.importGame(importData.base64);
} catch (ex: any) { } catch (ex: any) {
SnackbarEvents.emit(ex.toString(), "error", 5000); SnackbarEvents.emit(ex.toString(), SnackbarVariant.ERROR, 5000);
} }
setImportSaveOpen(false); setImportSaveOpen(false);

@ -10,6 +10,13 @@ interface IProps {
children: React.ReactNode | React.ReactNode[]; children: React.ReactNode | React.ReactNode[];
} }
export enum SnackbarVariant {
SUCCESS = "success",
WARNING = "warning",
ERROR = "error",
INFO = "info",
}
const useStyles = makeStyles(() => ({ const useStyles = makeStyles(() => ({
snackbar: { snackbar: {
// Log popup z-index increments, so let's add a padding to be well above them. // Log popup z-index increments, so let's add a padding to be well above them.
@ -36,9 +43,7 @@ export function SnackbarProvider(props: IProps): React.ReactElement {
); );
} }
export const SnackbarEvents = new EventEmitter< export const SnackbarEvents = new EventEmitter<[string | React.ReactNode, SnackbarVariant, number]>();
[string | React.ReactNode, "success" | "warning" | "error" | "info", number]
>();
export function Snackbar(): React.ReactElement { export function Snackbar(): React.ReactElement {
const { enqueueSnackbar, closeSnackbar } = useSnackbar(); const { enqueueSnackbar, closeSnackbar } = useSnackbar();

@ -0,0 +1,6 @@
export function checkEnum<T extends string, TEnumValue extends string>(
enumVariable: { [key in T]: TEnumValue },
value: string,
): value is TEnumValue {
return Object.values(enumVariable).includes(value);
}