DEV: Refactor complex initializers into classes (#28661)

We're working to remove all decorators from object-literal-properties. This commit refactors all initializers which were using these decorators into classes, where decorators are allowed. Also adds cleanup logic to the local-dates initializer, which was previously missing.
This commit is contained in:
David Taylor
2024-09-02 10:08:07 +01:00
committed by GitHub
parent 8b2009cd44
commit 583c932173
7 changed files with 180 additions and 88 deletions

View File

@ -1,23 +1,25 @@
import EmberObject from "@ember/object"; import EmberObject from "@ember/object";
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import PreloadStore from "discourse/lib/preload-store"; import PreloadStore from "discourse/lib/preload-store";
import { bind } from "discourse-common/utils/decorators"; import { bind } from "discourse-common/utils/decorators";
export default { class BannerInit {
after: "message-bus", @service site;
@service messageBus;
initialize(owner) { constructor(owner) {
this.site = owner.lookup("service:site"); setOwner(this, owner);
this.messageBus = owner.lookup("service:message-bus");
const banner = EmberObject.create(PreloadStore.get("banner") || {}); const banner = EmberObject.create(PreloadStore.get("banner") || {});
this.site.set("banner", banner); this.site.set("banner", banner);
this.messageBus.subscribe("/site/banner", this.onMessage); this.messageBus.subscribe("/site/banner", this.onMessage);
}, }
teardown() { teardown() {
this.messageBus.unsubscribe("/site/banner", this.onMessage); this.messageBus.unsubscribe("/site/banner", this.onMessage);
}, }
@bind @bind
onMessage(data) { onMessage(data) {
@ -26,5 +28,18 @@ export default {
} else { } else {
this.site.set("banner", null); this.site.set("banner", null);
} }
}
}
export default {
after: "message-bus",
initialize(owner) {
this.instance = new BannerInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,11 +1,15 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import discourseLater from "discourse-common/lib/later"; import discourseLater from "discourse-common/lib/later";
import { bind } from "discourse-common/utils/decorators"; import { bind } from "discourse-common/utils/decorators";
// Use the message bus for live reloading of components for faster development. // Use the message bus for live reloading of components for faster development.
export default { class LiveDevelopmentInit {
initialize(owner) { @service messageBus;
this.messageBus = owner.lookup("service:message-bus"); @service session;
this.session = owner.lookup("service:session");
constructor(owner) {
setOwner(this, owner);
const PRESERVED_QUERY_PARAMS = ["preview_theme_id", "pp", "safe_mode"]; const PRESERVED_QUERY_PARAMS = ["preview_theme_id", "pp", "safe_mode"];
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
@ -34,11 +38,11 @@ export default {
this.onFileChange, this.onFileChange,
this.session.mbLastFileChangeId this.session.mbLastFileChangeId
); );
}, }
teardown() { teardown() {
this.messageBus.unsubscribe("/file-change", this.onFileChange); this.messageBus.unsubscribe("/file-change", this.onFileChange);
}, }
@bind @bind
onFileChange(data) { onFileChange(data) {
@ -75,12 +79,22 @@ export default {
} }
} }
}); });
}, }
refreshCSS(node, newHref) { refreshCSS(node, newHref) {
const reloaded = node.cloneNode(true); const reloaded = node.cloneNode(true);
reloaded.href = newHref; reloaded.href = newHref;
node.insertAdjacentElement("afterend", reloaded); node.insertAdjacentElement("afterend", reloaded);
discourseLater(() => node?.parentNode?.removeChild(node), 500); discourseLater(() => node?.parentNode?.removeChild(node), 500);
}
}
export default {
initialize(owner) {
this.instance = new LiveDevelopmentInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,3 +1,5 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import logout from "discourse/lib/logout"; import logout from "discourse/lib/logout";
import { bind } from "discourse-common/utils/decorators"; import { bind } from "discourse-common/utils/decorators";
import I18n from "discourse-i18n"; import I18n from "discourse-i18n";
@ -5,13 +7,13 @@ import I18n from "discourse-i18n";
let _showingLogout = false; let _showingLogout = false;
// Subscribe to "logout" change events via the Message Bus // Subscribe to "logout" change events via the Message Bus
export default { class LogoutInit {
after: "message-bus", @service messageBus;
@service dialog;
@service currentUser;
initialize(owner) { constructor(owner) {
this.messageBus = owner.lookup("service:message-bus"); setOwner(this, owner);
this.dialog = owner.lookup("service:dialog");
this.currentUser = owner.lookup("service:current-user");
if (this.currentUser) { if (this.currentUser) {
this.messageBus.subscribe( this.messageBus.subscribe(
@ -19,7 +21,7 @@ export default {
this.onMessage this.onMessage
); );
} }
}, }
teardown() { teardown() {
if (this.currentUser) { if (this.currentUser) {
@ -28,7 +30,7 @@ export default {
this.onMessage this.onMessage
); );
} }
}, }
@bind @bind
onMessage() { onMessage() {
@ -45,5 +47,18 @@ export default {
didCancel: logout, didCancel: logout,
shouldDisplayCancel: false, shouldDisplayCancel: false,
}); });
}
}
export default {
after: "message-bus",
initialize(owner) {
this.instance = new LogoutInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,22 +1,37 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import { bind } from "discourse-common/utils/decorators"; import { bind } from "discourse-common/utils/decorators";
// Subscribe to "read-only" status change events via the Message Bus // Subscribe to "read-only" status change events via the Message Bus
export default { class ReadOnlyInit {
after: "message-bus", @service messageBus;
@service site;
initialize(owner) { constructor(owner) {
this.messageBus = owner.lookup("service:message-bus"); setOwner(this, owner);
this.site = owner.lookup("service:site");
this.messageBus.subscribe("/site/read-only", this.onMessage); this.messageBus.subscribe("/site/read-only", this.onMessage);
}, }
teardown() { teardown() {
this.messageBus.unsubscribe("/site/read-only", this.onMessage); this.messageBus.unsubscribe("/site/read-only", this.onMessage);
}, }
@bind @bind
onMessage(enabled) { onMessage(enabled) {
this.site.set("isReadOnly", enabled); this.site.set("isReadOnly", enabled);
}
}
export default {
after: "message-bus",
initialize(owner) {
this.instance = new ReadOnlyInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,4 +1,6 @@
// Subscribes to user events on the message bus // Subscribes to user events on the message bus
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import { import {
alertChannel, alertChannel,
disable as disableDesktopNotifications, disable as disableDesktopNotifications,
@ -14,24 +16,22 @@ import Notification from "discourse/models/notification";
import { isTesting } from "discourse-common/config/environment"; import { isTesting } from "discourse-common/config/environment";
import { bind } from "discourse-common/utils/decorators"; import { bind } from "discourse-common/utils/decorators";
export default { class SubscribeUserNotificationsInit {
after: "message-bus", @service currentUser;
@service messageBus;
@service store;
@service appEvents;
@service siteSettings;
@service site;
@service router;
initialize(owner) { constructor(owner) {
this.currentUser = owner.lookup("service:current-user"); setOwner(this, owner);
if (!this.currentUser) { if (!this.currentUser) {
return; return;
} }
this.messageBus = owner.lookup("service:message-bus");
this.store = owner.lookup("service:store");
this.messageBus = owner.lookup("service:message-bus");
this.appEvents = owner.lookup("service:app-events");
this.siteSettings = owner.lookup("service:site-settings");
this.site = owner.lookup("service:site");
this.router = owner.lookup("service:router");
this.reviewableCountsChannel = `/reviewable_counts/${this.currentUser.id}`; this.reviewableCountsChannel = `/reviewable_counts/${this.currentUser.id}`;
this.messageBus.subscribe( this.messageBus.subscribe(
@ -82,7 +82,7 @@ export default {
unsubscribePushNotifications(this.currentUser); unsubscribePushNotifications(this.currentUser);
} }
} }
}, }
teardown() { teardown() {
if (!this.currentUser) { if (!this.currentUser) {
@ -116,7 +116,7 @@ export default {
this.messageBus.unsubscribe("/client_settings", this.onClientSettings); this.messageBus.unsubscribe("/client_settings", this.onClientSettings);
this.messageBus.unsubscribe(alertChannel(this.currentUser), this.onAlert); this.messageBus.unsubscribe(alertChannel(this.currentUser), this.onAlert);
}, }
@bind @bind
onReviewableCounts(data) { onReviewableCounts(data) {
@ -128,7 +128,7 @@ export default {
"unseen_reviewable_count", "unseen_reviewable_count",
data.unseen_reviewable_count data.unseen_reviewable_count
); );
}, }
@bind @bind
onNotification(data) { onNotification(data) {
@ -210,22 +210,22 @@ export default {
stale.results.set("content", newNotifications); stale.results.set("content", newNotifications);
} }
}, }
@bind @bind
onUserDrafts(data) { onUserDrafts(data) {
this.currentUser.updateDraftProperties(data); this.currentUser.updateDraftProperties(data);
}, }
@bind @bind
onDoNotDisturb(data) { onDoNotDisturb(data) {
this.currentUser.updateDoNotDisturbStatus(data.ends_at); this.currentUser.updateDoNotDisturbStatus(data.ends_at);
}, }
@bind @bind
onUserStatus(data) { onUserStatus(data) {
this.appEvents.trigger("user-status:changed", data); this.appEvents.trigger("user-status:changed", data);
}, }
@bind @bind
onCategories(data) { onCategories(data) {
@ -251,12 +251,12 @@ export default {
(data.deleted_categories || []).forEach((id) => (data.deleted_categories || []).forEach((id) =>
this.site.removeCategory(id) this.site.removeCategory(id)
); );
}, }
@bind @bind
onClientSettings(data) { onClientSettings(data) {
this.siteSettings[data.name] = data.value; this.siteSettings[data.name] = data.value;
}, }
@bind @bind
onAlert(data) { onAlert(data) {
@ -268,5 +268,16 @@ export default {
this.appEvents this.appEvents
); );
} }
}
}
export default {
after: "message-bus",
initialize(owner) {
this.instance = new SubscribeUserNotificationsInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,3 +1,5 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service";
import { number } from "discourse/lib/formatter"; import { number } from "discourse/lib/formatter";
import { withPluginApi } from "discourse/lib/plugin-api"; import { withPluginApi } from "discourse/lib/plugin-api";
import { getOwnerWithFallback } from "discourse-common/lib/get-owner"; import { getOwnerWithFallback } from "discourse-common/lib/get-owner";
@ -14,18 +16,17 @@ const MIN_REFRESH_DURATION_MS = 180000; // 3 minutes
replaceIcon("d-chat", "comment"); replaceIcon("d-chat", "comment");
export default { class ChatSetupInit {
name: "chat-setup", @service router;
before: "hashtag-css-generator", @service("chat") chatService;
@service chatHistory;
@service site;
@service siteSettings;
@service currentUser;
@service appEvents;
initialize(container) { constructor(owner) {
this.router = container.lookup("service:router"); setOwner(this, owner);
this.chatService = container.lookup("service:chat");
this.chatHistory = container.lookup("service:chat-history");
this.site = container.lookup("service:site");
this.siteSettings = container.lookup("service:site-settings");
this.currentUser = container.lookup("service:current-user");
this.appEvents = container.lookup("service:app-events");
this.appEvents.on("discourse:focus-changed", this, "_handleFocusChanged"); this.appEvents.on("discourse:focus-changed", this, "_handleFocusChanged");
if (!this.chatService.userCanChat) { if (!this.chatService.userCanChat) {
@ -40,7 +41,7 @@ export default {
} }
}); });
api.registerHashtagType("channel", new ChannelHashtagType(container)); api.registerHashtagType("channel", new ChannelHashtagType(owner));
api.registerChatComposerButton({ api.registerChatComposerButton({
id: "chat-upload-btn", id: "chat-upload-btn",
@ -75,7 +76,7 @@ export default {
position: this.site.desktopView ? "inline" : "dropdown", position: this.site.desktopView ? "inline" : "dropdown",
context: "channel", context: "channel",
action() { action() {
const chatEmojiPickerManager = container.lookup( const chatEmojiPickerManager = owner.lookup(
"service:chat-emoji-picker-manager" "service:chat-emoji-picker-manager"
); );
chatEmojiPickerManager.open({ context: "channel" }); chatEmojiPickerManager.open({ context: "channel" });
@ -90,7 +91,7 @@ export default {
position: "dropdown", position: "dropdown",
context: "thread", context: "thread",
action() { action() {
const chatEmojiPickerManager = container.lookup( const chatEmojiPickerManager = owner.lookup(
"service:chat-emoji-picker-manager" "service:chat-emoji-picker-manager"
); );
chatEmojiPickerManager.open({ context: "thread" }); chatEmojiPickerManager.open({ context: "thread" });
@ -135,7 +136,7 @@ export default {
this.chatService.loadChannels(); this.chatService.loadChannels();
const chatNotificationManager = container.lookup( const chatNotificationManager = owner.lookup(
"service:chat-notification-manager" "service:chat-notification-manager"
); );
chatNotificationManager.start(); chatNotificationManager.start();
@ -172,12 +173,12 @@ export default {
} }
}); });
}); });
}, }
@bind @bind
documentTitleCountCallback() { documentTitleCountCallback() {
return this.chatService.getDocumentTitleCount(); return this.chatService.getDocumentTitleCount();
}, }
teardown() { teardown() {
this.appEvents.off("discourse:focus-changed", this, "_handleFocusChanged"); this.appEvents.off("discourse:focus-changed", this, "_handleFocusChanged");
@ -188,7 +189,7 @@ export default {
_lastForcedRefreshAt = null; _lastForcedRefreshAt = null;
clearChatComposerButtons(); clearChatComposerButtons();
}, }
@bind @bind
_handleFocusChanged(hasFocus) { _handleFocusChanged(hasFocus) {
@ -209,5 +210,17 @@ export default {
} }
_lastForcedRefreshAt = Date.now(); _lastForcedRefreshAt = Date.now();
}
}
export default {
name: "chat-setup",
before: "hashtag-css-generator",
initialize(owner) {
this.instance = new ChatSetupInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };

View File

@ -1,3 +1,4 @@
import { setOwner } from "@ember/owner";
import { service } from "@ember/service"; import { service } from "@ember/service";
import { htmlSafe } from "@ember/template"; import { htmlSafe } from "@ember/template";
import { downloadCalendar } from "discourse/lib/download-calendar"; import { downloadCalendar } from "discourse/lib/download-calendar";
@ -343,13 +344,22 @@ function _calculateDuration(element) {
return element.dataset === startDataset ? duration : -duration; return element.dataset === startDataset ? duration : -duration;
} }
export default { class LocalDatesInit {
name: "discourse-local-dates", @service siteSettings;
@service tooltip;
constructor(owner) {
setOwner(this, owner);
window.addEventListener("click", this.showDatePopover, { passive: true });
if (this.siteSettings.discourse_local_dates_enabled) {
withPluginApi("0.8.8", initializeDiscourseLocalDates);
}
}
@bind @bind
showDatePopover(event) { showDatePopover(event) {
const tooltip = this.container.lookup("service:tooltip");
if (event?.target?.classList?.contains("download-calendar")) { if (event?.target?.classList?.contains("download-calendar")) {
const dataset = event.target.dataset; const dataset = event.target.dataset;
downloadCalendar(dataset.title, [ downloadCalendar(dataset.title, [
@ -359,31 +369,30 @@ export default {
}, },
]); ]);
return tooltip.close("local-date"); return this.tooltip.close("local-date");
} }
if (!event?.target?.classList?.contains("discourse-local-date")) { if (!event?.target?.classList?.contains("discourse-local-date")) {
return; return;
} }
const siteSettings = this.container.lookup("service:site-settings"); return this.tooltip.show(event.target, {
return tooltip.show(event.target, {
identifier: "local-date", identifier: "local-date",
content: htmlSafe(buildHtmlPreview(event.target, siteSettings)), content: htmlSafe(buildHtmlPreview(event.target, this.siteSettings)),
}); });
}, }
initialize(container) {
this.container = container;
window.addEventListener("click", this.showDatePopover, { passive: true });
const siteSettings = container.lookup("service:site-settings");
if (siteSettings.discourse_local_dates_enabled) {
withPluginApi("0.8.8", initializeDiscourseLocalDates);
}
},
teardown() { teardown() {
window.removeEventListener("click", this.showDatePopover); window.removeEventListener("click", this.showDatePopover);
}
}
export default {
initialize(owner) {
this.instance = new LocalDatesInit(owner);
},
teardown() {
this.instance.teardown();
this.instance = null;
}, },
}; };