Skip to content
This repository has been archived by the owner on Oct 25, 2022. It is now read-only.

Commit

Permalink
feat: Faster script init
Browse files Browse the repository at this point in the history
We now utilize the `game/start` event to initialize the script a bit earlier than before.
  • Loading branch information
oliversalzburg committed Oct 10, 2022
1 parent 40c1cb8 commit a5dea05
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
25 changes: 21 additions & 4 deletions packages/userscript/source/UserScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ declare global {
let unsafeWindow: Window | undefined;
const dojo: {
clone: <T>(subject: T) => T;
subscribe: (event: string, handler: () => void) => void;
};
interface Window {
gamePage?: Maybe<GamePage>;
Expand Down Expand Up @@ -61,9 +62,14 @@ export class UserScript {
* Signals whether the options have been changed since they were last saved.
*/
private _optionsDirty = false;

private _intervalSaveSettings: number | undefined = undefined;

/**
* Stores if we caught the `game/start` signal from the game.
*/
private static _gameStartSignal: Promise<boolean>;
private static _gameStartSignalResolver: undefined | ((value: boolean) => void);

private _userInterface: UserInterface;
engine: Engine;

Expand Down Expand Up @@ -174,17 +180,28 @@ export class UserScript {
}

static async waitForGame(timeout = 30000): Promise<GamePage> {
cdebug(`Waiting for game... (timeout: ${Math.round(timeout / 1000)}s)`);
if (isNil(UserScript._gameStartSignal)) {
UserScript._gameStartSignal = new Promise(resolve => {
UserScript._gameStartSignalResolver = resolve;
});

dojo.subscribe("game/start", () => {
cdebug("`game/start` signal caught. Fast-tracking script load...");
mustExist(UserScript._gameStartSignalResolver)(true);
});
}

if (timeout < 0) {
throw new Error("Unable to find game page.");
throw new Error("Unable to find game page. Giving up.");
}

if (UserScript._isGameLoaded()) {
return mustExist(UserScript._window.gamePage);
}

await sleep(2000);
cdebug(`Waiting for game... (timeout: ${Math.round(timeout / 1000)}s)`);

await Promise.race([UserScript._gameStartSignal, sleep(2000)]);
return UserScript.waitForGame(timeout - 2000);
}

Expand Down
4 changes: 2 additions & 2 deletions packages/userscript/source/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SettingsStorage } from "./options/SettingsStorage";
import { cinfo } from "./tools/Log";
import { cerror, cinfo } from "./tools/Log";
import { isNil } from "./tools/Maybe";
import { SavegameLoader } from "./tools/SavegameLoader";
import { UserScript } from "./UserScript";
Expand Down Expand Up @@ -31,4 +31,4 @@ const devSavegame = KG_SAVEGAME ?? null;

userScript.validateGame();
userScript.run();
})().catch(console.error);
})().catch(cerror);

0 comments on commit a5dea05

Please sign in to comment.