diff --git a/main.js b/main.js index f0fd035..eef8d9e 100644 --- a/main.js +++ b/main.js @@ -4,32 +4,23 @@ module.exports = class RibbonClasp extends Plugin { async onload() { this.settings = Object.assign({ order: [] }, await this.loadData()); this.enforcing = false; + this.alive = true; + this.register(() => { this.alive = false; }); // icons can attach within milliseconds of each other on startup // (resetTimer, or it fires 200ms after the first one instead of the last) this.debouncedEnforce = debounce(() => this.enforceOrder(), 200, true); + // disconnecting the observer doesn't stop an already-scheduled call + this.register(() => this.debouncedEnforce.cancel()); this.app.workspace.onLayoutReady(() => { // not tied to our lifecycle; still fires if we were disabled during boot - if (this.unloaded) return; + if (!this.alive) return; this.patchRibbon(); this.enforceOrder(); this.observeRibbon(); }); } - onunload() { - this.unloaded = true; - this.observer?.disconnect(); - // disconnect doesn't stop an already-scheduled call - this.debouncedEnforce?.cancel(); - - const ribbon = this.getRibbon(); - // don't restore over someone else's patch, just go inert instead - if (ribbon && ribbon.onChange === this.wrapper) { - ribbon.onChange = this.originalOnChange; - } - } - getRibbon() { return this.app.workspace.leftRibbon ?? null; } @@ -44,8 +35,9 @@ module.exports = class RibbonClasp extends Plugin { const containerEl = this.getRibbonContainerEl(ribbon); if (!containerEl) return; - this.observer = new MutationObserver(() => this.debouncedEnforce()); - this.observer.observe(containerEl, { childList: true }); + const observer = new MutationObserver(() => this.debouncedEnforce()); + observer.observe(containerEl, { childList: true }); + this.register(() => observer.disconnect()); } // hook the ribbon's own onChange so drags and hide/show toggles update @@ -57,13 +49,18 @@ module.exports = class RibbonClasp extends Plugin { const original = ribbon.onChange.bind(ribbon); this.originalOnChange = original; - this.wrapper = (save) => { + const wrapper = (save) => { original(save); - if (save && !this.enforcing && !this.unloaded) { + if (save && !this.enforcing && this.alive) { this.recordOrder(ribbon); } }; - ribbon.onChange = this.wrapper; + ribbon.onChange = wrapper; + + this.register(() => { + // don't restore over someone else's patch, just go inert instead + if (ribbon.onChange === wrapper) ribbon.onChange = original; + }); } enforceOrder() {