DEV: Cleanup ace-editor event listeners (#27844)

- set in constructor so they're guaranteed to be present, even if async-import hasn't finished yet
- ensure they're all cleaned up properly
- combine two cleanup methods into one
This commit is contained in:
David Taylor 2024-07-11 10:14:01 +01:00 committed by GitHub
parent 5ec227334a
commit 374279b93e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 17 additions and 24 deletions

View File

@ -2,7 +2,7 @@ import Component from "@ember/component";
import { action } from "@ember/object";
import { next } from "@ember/runloop";
import { classNames } from "@ember-decorators/component";
import { observes, on } from "@ember-decorators/object";
import { observes } from "@ember-decorators/object";
import loadAce from "discourse/lib/load-ace-editor";
import { bind } from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
@ -19,6 +19,14 @@ export default class AceEditor extends Component {
_editor = null;
_skipContentChangeEvent = null;
constructor() {
super(...arguments);
this.appEvents.on("ace:resize", this.resize);
window.addEventListener("resize", this.resize);
this._darkModeListener = window.matchMedia("(prefers-color-scheme: dark)");
this._darkModeListener.addListener(this.setAceTheme);
}
@observes("editorId")
editorIdChanged() {
if (this.autofocus) {
@ -73,17 +81,6 @@ export default class AceEditor extends Component {
}
}
@on("willDestroyElement")
_destroyEditor() {
if (this._editor) {
this._editor.destroy();
this._editor = null;
}
this.appEvents.off("ace:resize", this.resize);
window.removeEventListener("resize", this.resize);
}
@action
resize() {
if (this._editor) {
@ -145,29 +142,25 @@ export default class AceEditor extends Component {
this.changeDisabledState();
this.warnSCSSDeprecations();
window.addEventListener("resize", this.resize);
this.appEvents.on("ace:resize", this.resize);
if (this.autofocus) {
this.send("focus");
}
this.setAceTheme();
this._darkModeListener = window.matchMedia(
"(prefers-color-scheme: dark)"
);
this._darkModeListener.addListener(this.setAceTheme);
});
}
willDestroyElement() {
if (this._editor) {
this._editor.destroy();
this._editor = null;
}
super.willDestroyElement(...arguments);
this._darkModeListener?.removeListener(this.setAceTheme);
window.addEventListener("resize", () => {
this.appEvents.trigger("ace:resize");
});
window.removeEventListener("resize", this.resize);
this.appEvents.off("ace:resize", this.resize);
}
get aceTheme() {