Skip to content

Commit

Permalink
Call deconstructors on plugin unload (#89)
Browse files Browse the repository at this point in the history
* Call deconstructors on plugin unload

* Fix linter

* Fix linter
  • Loading branch information
mnaoumov committed Jun 7, 2024
1 parent 84b4b9d commit ea92d8d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
14 changes: 9 additions & 5 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import * as obsidian from 'obsidian';
import compareVersions from 'compare-versions';
import debuggableEval from 'debuggable-eval';
import { CustomJSType } from './types';

interface CustomJSSettings {
jsFiles: string;
Expand Down Expand Up @@ -40,7 +41,7 @@ export default class CustomJS extends Plugin {
settings: CustomJSSettings;
deconstructorsOfLoadedFiles: { deconstructor: () => void; name: string }[] =
[];
loaderPromise: Promise<void>|null = null;
loaderPromise: Promise<void> | null = null;

async onload() {
// eslint-disable-next-line no-console
Expand All @@ -52,11 +53,13 @@ export default class CustomJS extends Plugin {
await this.initCustomJS();
};

window.cJS = async (moduleOrCallback?: string|Function) => {
window.cJS = async (
moduleOrCallback?: string | ((customJS: CustomJSType) => void),
) => {
if (!window.customJS?.state?._ready) {
await this.initCustomJS();
}

if (moduleOrCallback) {
if ('string' === typeof moduleOrCallback) {
return window.customJS[moduleOrCallback];
Expand Down Expand Up @@ -88,7 +91,8 @@ export default class CustomJS extends Plugin {
}
}

onunload() {
async onunload() {
await this.deconstructLoadedFiles();
delete window.customJS;
}

Expand Down Expand Up @@ -225,7 +229,7 @@ export default class CustomJS extends Plugin {
this.loaderPromise = null;
});
}

await this.loaderPromise;
}

Expand Down
18 changes: 11 additions & 7 deletions types.d.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import * as obsidian from 'obsidian';
import { DataviewAPI } from 'obsidian-dataview';

export type CustomJSType = {
obsidian?: typeof obsidian;
app?: obsidian.App;
state?: Record<string, unknown>;
[scriptName: string]: unknown;
};

declare global {
interface Window {
forceLoadCustomJS?: () => Promise<void>;
cJS?: (moduleOrCallback?: string|Function) => Promise<any>;
customJS?: {
obsidian?: typeof obsidian;
app?: obsidian.App;
state?: Record<string, unknown>;
[scriptName: string]: unknown;
};
cJS?: (
moduleOrCallback?: string | ((customJS: CustomJSType) => void),
) => Promise<unknown>;
customJS?: CustomJSType;
}
}

Expand Down

0 comments on commit ea92d8d

Please sign in to comment.