Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call deconstructors on plugin unload #89

Merged
merged 3 commits into from
Jun 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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