DEV: Convert core controllers to native class syntax (batch 1) (#28177)

Changes made using the ember-native-class-codemod, plus some manual tweaks
This commit is contained in:
David Taylor
2024-08-01 10:18:36 +01:00
committed by GitHub
parent 7b14cd98c7
commit 8c4db0d2f8
8 changed files with 334 additions and 334 deletions

View File

@ -3,11 +3,11 @@ import { alias, gt } from "@ember/object/computed";
import discourseComputed from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n"; import I18n from "discourse-i18n";
export default Controller.extend({ export default class AboutController extends Controller {
faqOverridden: gt("siteSettings.faq_url.length", 0), @gt("siteSettings.faq_url.length", 0) faqOverridden;
renameFaqToGuidelines: alias(
"siteSettings.experimental_rename_faq_to_guidelines" @alias("siteSettings.experimental_rename_faq_to_guidelines")
), renameFaqToGuidelines;
@discourseComputed("model.contact_url", "model.contact_email") @discourseComputed("model.contact_url", "model.contact_email")
contactInfo(url, email) { contactInfo(url, email) {
@ -22,5 +22,5 @@ export default Controller.extend({
} else { } else {
return null; return null;
} }
}, }
}); }

View File

@ -5,21 +5,21 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import { changeEmail } from "discourse/lib/user-activation"; import { changeEmail } from "discourse/lib/user-activation";
import discourseComputed from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
export default Controller.extend({ export default class AccountCreatedEditEmailController extends Controller {
router: service(), @service router;
accountCreated: null, accountCreated;
newEmail: null, newEmail;
@discourseComputed("newEmail", "accountCreated.email") @discourseComputed("newEmail", "accountCreated.email")
submitDisabled(newEmail, currentEmail) { submitDisabled(newEmail, currentEmail) {
return newEmail === currentEmail; return newEmail === currentEmail;
}, }
@action @action
updateNewEmail(email) { updateNewEmail(email) {
this.set("newEmail", email); this.set("newEmail", email);
}, }
@action @action
async changeEmail() { async changeEmail() {
@ -31,10 +31,10 @@ export default Controller.extend({
} catch (e) { } catch (e) {
popupAjaxError(e); popupAjaxError(e);
} }
}, }
@action @action
cancel() { cancel() {
this.router.transitionTo("account-created.index"); this.router.transitionTo("account-created.index");
}, }
}); }

View File

@ -1,4 +1,5 @@
import Controller from "@ember/controller"; import Controller from "@ember/controller";
import { action } from "@ember/object";
import { service } from "@ember/service"; import { service } from "@ember/service";
import { resendActivationEmail } from "discourse/lib/user-activation"; import { resendActivationEmail } from "discourse/lib/user-activation";
import { wavingHandURL } from "discourse/lib/waving-hand-url"; import { wavingHandURL } from "discourse/lib/waving-hand-url";
@ -6,28 +7,32 @@ import getUrl from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n"; import I18n from "discourse-i18n";
export default Controller.extend({ export default class AccountCreatedIndexController extends Controller {
router: service(), @service router;
envelopeImageUrl: getUrl("/images/envelope.svg"),
envelopeImageUrl = getUrl("/images/envelope.svg");
@discourseComputed @discourseComputed
welcomeTitle() { welcomeTitle() {
return I18n.t("invites.welcome_to", { return I18n.t("invites.welcome_to", {
site_name: this.siteSettings.title, site_name: this.siteSettings.title,
}); });
}, }
@discourseComputed @discourseComputed
wavingHandURL: () => wavingHandURL(), wavingHandURL() {
return wavingHandURL();
}
actions: { @action
sendActivationEmail() { sendActivationEmail() {
resendActivationEmail(this.get("accountCreated.username")).then(() => { resendActivationEmail(this.get("accountCreated.username")).then(() => {
this.router.transitionTo("account-created.resent"); this.router.transitionTo("account-created.resent");
}); });
}, }
editActivationEmail() {
this.router.transitionTo("account-created.edit-email"); @action
}, editActivationEmail() {
}, this.router.transitionTo("account-created.edit-email");
}); }
}

View File

@ -9,27 +9,23 @@ import discourseComputed from "discourse-common/utils/decorators";
const HIDE_SIDEBAR_KEY = "sidebar-hidden"; const HIDE_SIDEBAR_KEY = "sidebar-hidden";
export default Controller.extend({ export default class ApplicationController extends Controller {
queryParams: [{ navigationMenuQueryParamOverride: "navigation_menu" }], @service router;
@service footer;
@service header;
@service sidebarState;
showTop: true, queryParams = [{ navigationMenuQueryParamOverride: "navigation_menu" }];
router: service(), showTop = true;
footer: service(),
header: service(),
sidebarState: service(),
showSidebar: false,
sidebarDisabledRouteOverride: false,
navigationMenuQueryParamOverride: null,
showSiteHeader: true,
init() { showSidebar = this.calculateShowSidebar();
this._super(...arguments); sidebarDisabledRouteOverride = false;
this.showSidebar = this.calculateShowSidebar(); navigationMenuQueryParamOverride = null;
}, showSiteHeader = true;
get showFooter() { get showFooter() {
return this.footer.showFooter; return this.footer.showFooter;
}, }
set showFooter(value) { set showFooter(value) {
deprecated( deprecated(
@ -37,11 +33,11 @@ export default Controller.extend({
{ id: "discourse.application-show-footer" } { id: "discourse.application-show-footer" }
); );
this.footer.showFooter = value; this.footer.showFooter = value;
}, }
get showPoweredBy() { get showPoweredBy() {
return this.showFooter && this.siteSettings.enable_powered_by_discourse; return this.showFooter && this.siteSettings.enable_powered_by_discourse;
}, }
@discourseComputed @discourseComputed
canSignUp() { canSignUp() {
@ -50,26 +46,26 @@ export default Controller.extend({
this.siteSettings.allow_new_registrations && this.siteSettings.allow_new_registrations &&
!this.siteSettings.enable_discourse_connect !this.siteSettings.enable_discourse_connect
); );
}, }
@discourseComputed @discourseComputed
canDisplaySidebar() { canDisplaySidebar() {
return this.currentUser || !this.siteSettings.login_required; return this.currentUser || !this.siteSettings.login_required;
}, }
@discourseComputed @discourseComputed
loginRequired() { loginRequired() {
return this.siteSettings.login_required && !this.currentUser; return this.siteSettings.login_required && !this.currentUser;
}, }
@discourseComputed @discourseComputed
showFooterNav() { showFooterNav() {
return this.capabilities.isAppWebview || this.capabilities.isiOSPWA; return this.capabilities.isAppWebview || this.capabilities.isiOSPWA;
}, }
_mainOutletAnimate() { _mainOutletAnimate() {
document.body.classList.remove("sidebar-animate"); document.body.classList.remove("sidebar-animate");
}, }
get sidebarEnabled() { get sidebarEnabled() {
if (!this.canDisplaySidebar) { if (!this.canDisplaySidebar) {
@ -106,7 +102,7 @@ export default Controller.extend({
} }
return this.siteSettings.navigation_menu === "sidebar"; return this.siteSettings.navigation_menu === "sidebar";
}, }
calculateShowSidebar() { calculateShowSidebar() {
return ( return (
@ -114,7 +110,7 @@ export default Controller.extend({
!this.keyValueStore.getItem(HIDE_SIDEBAR_KEY) && !this.keyValueStore.getItem(HIDE_SIDEBAR_KEY) &&
!this.site.narrowDesktopView !this.site.narrowDesktopView
); );
}, }
@action @action
toggleSidebar() { toggleSidebar() {
@ -132,7 +128,7 @@ export default Controller.extend({
this.keyValueStore.setItem(HIDE_SIDEBAR_KEY, "true"); this.keyValueStore.setItem(HIDE_SIDEBAR_KEY, "true");
} }
} }
}, }
@action @action
trackDiscoursePainted() { trackDiscoursePainted() {
@ -152,5 +148,5 @@ export default Controller.extend({
console.warn("Failed to measure init-to-paint", e); console.warn("Failed to measure init-to-paint", e);
} }
}); });
}, }
}); }

View File

@ -1,4 +1,5 @@
import Controller from "@ember/controller"; import Controller from "@ember/controller";
import { action } from "@ember/object";
import { and } from "@ember/object/computed"; import { and } from "@ember/object/computed";
import { service } from "@ember/service"; import { service } from "@ember/service";
import { underscore } from "@ember/string"; import { underscore } from "@ember/string";
@ -7,31 +8,25 @@ import { NotificationLevels } from "discourse/lib/notification-levels";
import DiscourseURL from "discourse/lib/url"; import DiscourseURL from "discourse/lib/url";
import Category from "discourse/models/category"; import Category from "discourse/models/category";
import PermissionType from "discourse/models/permission-type"; import PermissionType from "discourse/models/permission-type";
import discourseComputed, { on } from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n"; import I18n from "discourse-i18n";
export default Controller.extend({ export default class EditCategoryTabsController extends Controller {
dialog: service(), @service dialog;
site: service(), @service site;
router: service(), @service router;
selectedTab: "general", selectedTab = "general";
saving: false, saving = false;
deleting: false, deleting = false;
panels: null, panels = [];
showTooltip: false, showTooltip = false;
createdCategory: false, createdCategory = false;
expandedMenu: false, expandedMenu = false;
parentParams: null, parentParams = null;
showDeleteReason: and("showTooltip", "model.cannot_delete_reason"), validators = [];
@on("init") @and("showTooltip", "model.cannot_delete_reason") showDeleteReason;
_initPanels() {
this.setProperties({
panels: [],
validators: [],
});
},
@discourseComputed("saving", "model.name", "model.color", "deleting") @discourseComputed("saving", "model.name", "model.color", "deleting")
disabled(saving, name, color, deleting) { disabled(saving, name, color, deleting) {
@ -45,18 +40,18 @@ export default Controller.extend({
return true; return true;
} }
return false; return false;
}, }
@discourseComputed("saving", "deleting") @discourseComputed("saving", "deleting")
deleteDisabled(saving, deleting) { deleteDisabled(saving, deleting) {
return deleting || saving || false; return deleting || saving || false;
}, }
@discourseComputed("name") @discourseComputed("name")
categoryName(name) { categoryName(name) {
name = name || ""; name = name || "";
return name.trim().length > 0 ? name : I18n.t("preview"); return name.trim().length > 0 ? name : I18n.t("preview");
}, }
@discourseComputed("saving", "model.id") @discourseComputed("saving", "model.id")
saveLabel(saving, id) { saveLabel(saving, id) {
@ -64,7 +59,7 @@ export default Controller.extend({
return "saving"; return "saving";
} }
return id ? "category.save" : "category.create"; return id ? "category.save" : "category.create";
}, }
@discourseComputed("model.id", "model.name") @discourseComputed("model.id", "model.name")
title(id, name) { title(id, name) {
@ -73,79 +68,82 @@ export default Controller.extend({
categoryName: name, categoryName: name,
}) })
: I18n.t("category.create"); : I18n.t("category.create");
}, }
@discourseComputed("selectedTab") @discourseComputed("selectedTab")
selectedTabTitle(tab) { selectedTabTitle(tab) {
return I18n.t(`category.${underscore(tab)}`); return I18n.t(`category.${underscore(tab)}`);
}, }
actions: { @action
registerValidator(validator) { registerValidator(validator) {
this.validators.push(validator); this.validators.push(validator);
}, }
saveCategory() { @action
if (this.validators.some((validator) => validator())) { saveCategory() {
return; if (this.validators.some((validator) => validator())) {
} return;
}
this.set("saving", true); this.set("saving", true);
this.model this.model
.save() .save()
.then((result) => { .then((result) => {
if (!this.model.id) { if (!this.model.id) {
this.model.setProperties({ this.model.setProperties({
slug: result.category.slug, slug: result.category.slug,
id: result.category.id, id: result.category.id,
can_edit: result.category.can_edit, can_edit: result.category.can_edit,
permission: PermissionType.FULL, permission: PermissionType.FULL,
notification_level: NotificationLevels.REGULAR, notification_level: NotificationLevels.REGULAR,
}); });
this.site.updateCategory(this.model); this.site.updateCategory(this.model);
this.router.transitionTo( this.router.transitionTo(
"editCategory", "editCategory",
Category.slugFor(this.model) Category.slugFor(this.model)
); );
} }
}) })
.catch((error) => { .catch((error) => {
popupAjaxError(error); popupAjaxError(error);
this.model.set("parent_category_id", undefined); this.model.set("parent_category_id", undefined);
}) })
.finally(() => { .finally(() => {
this.set("saving", false); this.set("saving", false);
});
},
deleteCategory() {
this.set("deleting", true);
this.dialog.yesNoConfirm({
message: I18n.t("category.delete_confirm"),
didConfirm: () => {
this.model
.destroy()
.then(() => {
this.router.transitionTo("discovery.categories");
})
.catch(() => {
this.displayErrors([I18n.t("category.delete_error")]);
})
.finally(() => {
this.set("deleting", false);
});
},
didCancel: () => this.set("deleting", false),
}); });
}, }
toggleDeleteTooltip() { @action
this.toggleProperty("showTooltip"); deleteCategory() {
}, this.set("deleting", true);
this.dialog.yesNoConfirm({
message: I18n.t("category.delete_confirm"),
didConfirm: () => {
this.model
.destroy()
.then(() => {
this.router.transitionTo("discovery.categories");
})
.catch(() => {
this.displayErrors([I18n.t("category.delete_error")]);
})
.finally(() => {
this.set("deleting", false);
});
},
didCancel: () => this.set("deleting", false),
});
}
goBack() { @action
DiscourseURL.routeTo(this.model.url); toggleDeleteTooltip() {
}, this.toggleProperty("showTooltip");
}, }
});
@action
goBack() {
DiscourseURL.routeTo(this.model.url);
}
}

View File

@ -8,17 +8,18 @@ import { getWebauthnCredential } from "discourse/lib/webauthn";
import getURL from "discourse-common/lib/get-url"; import getURL from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
export default Controller.extend({ export default class EmailLoginController extends Controller {
router: service(), @service router;
secondFactorMethod: null, secondFactorMethod;
secondFactorToken: null, secondFactorToken;
lockImageUrl: getURL("/images/lock.svg"),
lockImageUrl = getURL("/images/lock.svg");
@discourseComputed("model") @discourseComputed("model")
secondFactorRequired(model) { secondFactorRequired(model) {
return model.security_key_required || model.second_factor_required; return model.security_key_required || model.second_factor_required;
}, }
@action @action
async finishLogin() { async finishLogin() {
@ -62,7 +63,7 @@ export default Controller.extend({
} catch (e) { } catch (e) {
popupAjaxError(e); popupAjaxError(e);
} }
}, }
@action @action
authenticateSecurityKey() { authenticateSecurityKey() {
@ -77,5 +78,5 @@ export default Controller.extend({
this.set("model.error", errorMessage); this.set("model.error", errorMessage);
} }
); );
}, }
}); }

View File

@ -4,7 +4,7 @@ import { action } from "@ember/object";
import { alias, equal, gte, none } from "@ember/object/computed"; import { alias, equal, gte, none } from "@ember/object/computed";
import { schedule } from "@ember/runloop"; import { schedule } from "@ember/runloop";
import DiscourseURL from "discourse/lib/url"; import DiscourseURL from "discourse/lib/url";
import discourseComputed, { on } from "discourse-common/utils/decorators"; import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n"; import I18n from "discourse-i18n";
/** /**
@ -24,9 +24,26 @@ export class RouteException {
} }
// The controller for the nice error page // The controller for the nice error page
export default Controller.extend({ export default class ExceptionController extends Controller {
thrown: null, thrown;
lastTransition: null, lastTransition;
@equal("thrown.status", 404) isNotFound;
@equal("thrown.status", 403) isForbidden;
@gte("thrown.status", 500) isServer;
@none("isNetwork", "isServer") isUnknown;
// Handling for the detailed_404 setting (which actually creates 403s)
@alias("thrown.responseJSON.extras.html") errorHtml;
// TODO
// make ajax requests to /srv/status with exponential backoff
// if one succeeds, set networkFixed to true, which puts a "Fixed!" message on the page
networkFixed = false;
loading = false;
@alias("thrown.requestedUrl") requestUrl;
@discourseComputed("thrown") @discourseComputed("thrown")
isNetwork(thrown) { isNetwork(thrown) {
@ -41,26 +58,7 @@ export default Controller.extend({
} }
return false; return false;
}, }
isNotFound: equal("thrown.status", 404),
isForbidden: equal("thrown.status", 403),
isServer: gte("thrown.status", 500),
isUnknown: none("isNetwork", "isServer"),
// Handling for the detailed_404 setting (which actually creates 403s)
errorHtml: alias("thrown.responseJSON.extras.html"),
// TODO
// make ajax requests to /srv/status with exponential backoff
// if one succeeds, set networkFixed to true, which puts a "Fixed!" message on the page
networkFixed: false,
loading: false,
@on("init")
_init() {
this.set("loading", false);
},
@discourseComputed("isNetwork", "thrown.status", "thrown") @discourseComputed("isNetwork", "thrown.status", "thrown")
reason(isNetwork, thrownStatus, thrown) { reason(isNetwork, thrownStatus, thrown) {
@ -80,9 +78,7 @@ export default Controller.extend({
// TODO // TODO
return I18n.t("errors.reasons.unknown"); return I18n.t("errors.reasons.unknown");
} }
}, }
requestUrl: alias("thrown.requestedUrl"),
@discourseComputed( @discourseComputed(
"networkFixed", "networkFixed",
@ -112,7 +108,7 @@ export default Controller.extend({
// TODO // TODO
return I18n.t("errors.desc.unknown"); return I18n.t("errors.desc.unknown");
} }
}, }
@cached @cached
get buttons() { get buttons() {
@ -139,7 +135,7 @@ export default Controller.extend({
key: "errors.buttons.fixed", key: "errors.buttons.fixed",
}, },
}; };
}, }
@discourseComputed("networkFixed", "isNetwork", "lastTransition") @discourseComputed("networkFixed", "isNetwork", "lastTransition")
enabledButtons(networkFixed, isNetwork, lastTransition) { enabledButtons(networkFixed, isNetwork, lastTransition) {
@ -152,7 +148,7 @@ export default Controller.extend({
} else { } else {
return [this.buttons.ButtonBackBright, this.buttons.ButtonTryAgain]; return [this.buttons.ButtonBackBright, this.buttons.ButtonTryAgain];
} }
}, }
@action @action
back() { back() {
@ -165,7 +161,7 @@ export default Controller.extend({
} else { } else {
window.history.back(); window.history.back();
} }
}, }
@action @action
tryLoading() { tryLoading() {
@ -177,5 +173,5 @@ export default Controller.extend({
transition.retry(); transition.retry();
this.set("loading", false); this.set("loading", false);
}); });
}, }
}); }

View File

@ -1,5 +1,5 @@
import Controller, { inject as controller } from "@ember/controller"; import Controller, { inject as controller } from "@ember/controller";
import { action } from "@ember/object"; import { action, computed } from "@ember/object";
import { gt, or } from "@ember/object/computed"; import { gt, or } from "@ember/object/computed";
import { service } from "@ember/service"; import { service } from "@ember/service";
import { isEmpty } from "@ember/utils"; import { isEmpty } from "@ember/utils";
@ -52,41 +52,46 @@ export function registerFullPageSearchType(
customSearchTypes.push({ translationKey, searchTypeId, searchFunc }); customSearchTypes.push({ translationKey, searchTypeId, searchFunc });
} }
export default Controller.extend({ export default class FullPageSearchController extends Controller {
application: controller(), @service composer;
composer: service(), @service modal;
modal: service(), @service appEvents;
appEvents: service(), @service siteSettings;
siteSettings: service(), @service searchPreferencesManager;
searchPreferencesManager: service(), @service currentUser;
currentUser: service(), @controller application;
bulkSelectEnabled: null, bulkSelectEnabled = null;
loading: false, loading = false;
queryParams: [
queryParams = [
"q", "q",
"expanded", "expanded",
"context_id", "context_id",
"context", "context",
"skip_context", "skip_context",
"search_type", "search_type",
], ];
q: undefined,
context_id: null, q;
search_type: SEARCH_TYPE_DEFAULT, context_id = null;
context: null, search_type = SEARCH_TYPE_DEFAULT;
searching: false, context = null;
sortOrder: 0, searching = false;
sortOrders: SortOrders, sortOrder = 0;
invalidSearch: false, sortOrders = SortOrders;
page: 1, invalidSearch = false;
resultCount: null, page = 1;
searchTypes: null, resultCount = null;
additionalSearchResults: [], searchTypes = null;
error: null, additionalSearchResults = [];
error = null;
@gt("bulkSelectHelper.selected.length", 0) hasSelection;
@or("searching", "loading") searchButtonDisabled;
_searchOnSortChange = true;
init() { init() {
this._super(...arguments); super.init(...arguments);
this.set( this.set(
"sortOrder", "sortOrder",
@ -115,22 +120,22 @@ export default Controller.extend({
this.set("searchTypes", searchTypes); this.set("searchTypes", searchTypes);
this.bulkSelectHelper = new BulkSelectHelper(this); this.bulkSelectHelper = new BulkSelectHelper(this);
}, }
@discourseComputed("resultCount") @discourseComputed("resultCount")
hasResults(resultCount) { hasResults(resultCount) {
return (resultCount || 0) > 0; return (resultCount || 0) > 0;
}, }
@discourseComputed("expanded") @discourseComputed("expanded")
expandFilters(expanded) { expandFilters(expanded) {
return expanded === "true"; return expanded === "true";
}, }
@discourseComputed("q") @discourseComputed("q")
hasAutofocus(q) { hasAutofocus(q) {
return isEmpty(q); return isEmpty(q);
}, }
@discourseComputed("q") @discourseComputed("q")
highlightQuery(q) { highlightQuery(q) {
@ -141,17 +146,18 @@ export default Controller.extend({
.split(/\s+/) .split(/\s+/)
.filter((t) => t !== "l") .filter((t) => t !== "l")
.join(" "); .join(" ");
}, }
@discourseComputed("skip_context", "context") @computed("skip_context", "context")
searchContextEnabled: { get searchContextEnabled() {
get(skip, context) { return (
return (!skip && context) || skip === "false"; (!this.skip_context && this.context) || this.skip_context === "false"
}, );
set(val) { }
this.set("skip_context", !val);
}, set searchContextEnabled(val) {
}, this.set("skip_context", !val);
}
@discourseComputed("context", "context_id") @discourseComputed("context", "context_id")
searchContextDescription(context, id) { searchContextDescription(context, id) {
@ -165,32 +171,30 @@ export default Controller.extend({
name = category.get("name"); name = category.get("name");
} }
return searchContextDescription(context, name); return searchContextDescription(context, name);
}, }
@discourseComputed("q") @discourseComputed("q")
searchActive(q) { searchActive(q) {
return isValidSearchTerm(q, this.siteSettings); return isValidSearchTerm(q, this.siteSettings);
}, }
@discourseComputed("q") @discourseComputed("q")
noSortQ(q) { noSortQ(q) {
q = this.cleanTerm(q); q = this.cleanTerm(q);
return escapeExpression(q); return escapeExpression(q);
}, }
@discourseComputed("canCreateTopic", "siteSettings.login_required") @discourseComputed("canCreateTopic", "siteSettings.login_required")
showSuggestion(canCreateTopic, loginRequired) { showSuggestion(canCreateTopic, loginRequired) {
return canCreateTopic || !loginRequired; return canCreateTopic || !loginRequired;
}, }
_searchOnSortChange: true,
setSearchTerm(term) { setSearchTerm(term) {
this._searchOnSortChange = false; this._searchOnSortChange = false;
term = this.cleanTerm(term); term = this.cleanTerm(term);
this._searchOnSortChange = true; this._searchOnSortChange = true;
this.set("searchTerm", term); this.set("searchTerm", term);
}, }
cleanTerm(term) { cleanTerm(term) {
if (term) { if (term) {
@ -206,7 +210,7 @@ export default Controller.extend({
}); });
} }
return term; return term;
}, }
@observes("sortOrder") @observes("sortOrder")
triggerSearch() { triggerSearch() {
@ -214,7 +218,7 @@ export default Controller.extend({
this.set("page", 1); this.set("page", 1);
this._search(); this._search();
} }
}, }
@observes("search_type") @observes("search_type")
triggerSearchOnTypeChange() { triggerSearchOnTypeChange() {
@ -222,19 +226,19 @@ export default Controller.extend({
this.set("page", 1); this.set("page", 1);
this._search(); this._search();
} }
}, }
@observes("model") @observes("model")
modelChanged() { modelChanged() {
if (this.searchTerm !== this.q) { if (this.searchTerm !== this.q) {
this.setSearchTerm(this.q); this.setSearchTerm(this.q);
} }
}, }
@discourseComputed("q") @discourseComputed("q")
showLikeCount(q) { showLikeCount(q) {
return q?.includes("order:likes"); return q?.includes("order:likes");
}, }
@observes("q") @observes("q")
qChanged() { qChanged() {
@ -243,7 +247,7 @@ export default Controller.extend({
this.setSearchTerm(this.q); this.setSearchTerm(this.q);
this.send("search"); this.send("search");
} }
}, }
@discourseComputed("q") @discourseComputed("q")
isPrivateMessage(q) { isPrivateMessage(q) {
@ -256,13 +260,13 @@ export default Controller.extend({
`personal_messages:${this.currentUser.get("username_lower")}` `personal_messages:${this.currentUser.get("username_lower")}`
)) ))
); );
}, }
@discourseComputed("resultCount", "noSortQ") @discourseComputed("resultCount", "noSortQ")
resultCountLabel(count, term) { resultCountLabel(count, term) {
const plus = count % 50 === 0 ? "+" : ""; const plus = count % 50 === 0 ? "+" : "";
return I18n.t("search.result_count", { count, plus, term }); return I18n.t("search.result_count", { count, plus, term });
}, }
@observes("model.{posts,categories,tags,users}.length", "searchResultPosts") @observes("model.{posts,categories,tags,users}.length", "searchResultPosts")
resultCountChanged() { resultCountChanged() {
@ -277,14 +281,12 @@ export default Controller.extend({
this.model.tags.length + this.model.tags.length +
this.model.users.length this.model.users.length
); );
}, }
@discourseComputed("hasResults") @discourseComputed("hasResults")
canBulkSelect(hasResults) { canBulkSelect(hasResults) {
return this.currentUser && this.currentUser.staff && hasResults; return this.currentUser && this.currentUser.staff && hasResults;
}, }
hasSelection: gt("bulkSelectHelper.selected.length", 0),
@discourseComputed( @discourseComputed(
"bulkSelectHelper.selected.length", "bulkSelectHelper.selected.length",
@ -292,36 +294,36 @@ export default Controller.extend({
) )
hasUnselectedResults(selectionCount, postsCount) { hasUnselectedResults(selectionCount, postsCount) {
return selectionCount < postsCount; return selectionCount < postsCount;
}, }
@discourseComputed("model.grouped_search_result.can_create_topic") @discourseComputed("model.grouped_search_result.can_create_topic")
canCreateTopic(userCanCreateTopic) { canCreateTopic(userCanCreateTopic) {
return this.currentUser && userCanCreateTopic; return this.currentUser && userCanCreateTopic;
}, }
@discourseComputed("page") @discourseComputed("page")
isLastPage(page) { isLastPage(page) {
return page === PAGE_LIMIT; return page === PAGE_LIMIT;
}, }
@discourseComputed("search_type") @discourseComputed("search_type")
usingDefaultSearchType(searchType) { usingDefaultSearchType(searchType) {
return searchType === SEARCH_TYPE_DEFAULT; return searchType === SEARCH_TYPE_DEFAULT;
}, }
@discourseComputed("search_type") @discourseComputed("search_type")
customSearchType(searchType) { customSearchType(searchType) {
return customSearchTypes.find( return customSearchTypes.find(
(type) => searchType === type["searchTypeId"] (type) => searchType === type["searchTypeId"]
); );
}, }
@discourseComputed("bulkSelectEnabled") @discourseComputed("bulkSelectEnabled")
searchInfoClassNames(bulkSelectEnabled) { searchInfoClassNames(bulkSelectEnabled) {
return bulkSelectEnabled return bulkSelectEnabled
? "search-info bulk-select-visible" ? "search-info bulk-select-visible"
: "search-info"; : "search-info";
}, }
@discourseComputed("model.posts", "additionalSearchResults") @discourseComputed("model.posts", "additionalSearchResults")
searchResultPosts(posts, additionalSearchResults) { searchResultPosts(posts, additionalSearchResults) {
@ -333,9 +335,7 @@ export default Controller.extend({
} else { } else {
return posts; return posts;
} }
}, }
searchButtonDisabled: or("searching", "loading"),
@bind @bind
_search() { _search() {
@ -457,13 +457,13 @@ export default Controller.extend({
}); });
break; break;
} }
}, }
_afterTransition() { _afterTransition() {
if (Object.keys(this.model).length === 0) { if (Object.keys(this.model).length === 0) {
this.reset(); this.reset();
} }
}, }
reset() { reset() {
this.setProperties({ this.setProperties({
@ -472,12 +472,12 @@ export default Controller.extend({
resultCount: null, resultCount: null,
}); });
this.bulkSelectHelper.clear(); this.bulkSelectHelper.clear();
}, }
@action @action
afterBulkActionComplete() { afterBulkActionComplete() {
return Promise.resolve(this._search()); return Promise.resolve(this._search());
}, }
@action @action
createTopic(searchTerm, event) { createTopic(searchTerm, event) {
@ -494,7 +494,7 @@ export default Controller.extend({
draftKey: Composer.NEW_TOPIC_KEY, draftKey: Composer.NEW_TOPIC_KEY,
topicCategory, topicCategory,
}); });
}, }
@action @action
addSearchResults(list, identifier) { addSearchResults(list, identifier) {
@ -502,84 +502,88 @@ export default Controller.extend({
list, list,
identifier, identifier,
}); });
}, }
@action @action
setSortOrder(value) { setSortOrder(value) {
this.set("sortOrder", value); this.set("sortOrder", value);
this.searchPreferencesManager.sortOrder = value; this.searchPreferencesManager.sortOrder = value;
}, }
actions: { @action
selectAll() { selectAll() {
this.bulkSelectHelper.selected.addObjects( this.bulkSelectHelper.selected.addObjects(
this.get("searchResultPosts").mapBy("topic") this.get("searchResultPosts").mapBy("topic")
); );
// Doing this the proper way is a HUGE pain, // Doing this the proper way is a HUGE pain,
// we can hack this to work by observing each on the array // we can hack this to work by observing each on the array
// in the component, however, when we select ANYTHING, we would force // in the component, however, when we select ANYTHING, we would force
// 50 traversals of the list // 50 traversals of the list
// This hack is cheap and easy // This hack is cheap and easy
document
.querySelectorAll(".fps-result input[type=checkbox]")
.forEach((checkbox) => {
checkbox.checked = true;
});
}
@action
clearAll() {
this.bulkSelectHelper.selected.clear();
document
.querySelectorAll(".fps-result input[type=checkbox]")
.forEach((checkbox) => {
checkbox.checked = false;
});
}
@action
toggleBulkSelect() {
this.toggleProperty("bulkSelectEnabled");
this.bulkSelectHelper.selected.clear();
}
@action
search(options = {}) {
if (this.searching) {
return;
}
if (options.collapseFilters) {
document document
.querySelectorAll(".fps-result input[type=checkbox]") .querySelector("details.advanced-filters")
.forEach((checkbox) => { ?.removeAttribute("open");
checkbox.checked = true; }
}); this.set("page", 1);
},
clearAll() { this.appEvents.trigger("full-page-search:trigger-search");
this.bulkSelectHelper.selected.clear();
document this._search();
.querySelectorAll(".fps-result input[type=checkbox]") }
.forEach((checkbox) => {
checkbox.checked = false;
});
},
toggleBulkSelect() {
this.toggleProperty("bulkSelectEnabled");
this.bulkSelectHelper.selected.clear();
},
search(options = {}) {
if (this.searching) {
return;
}
if (options.collapseFilters) {
document
.querySelector("details.advanced-filters")
?.removeAttribute("open");
}
this.set("page", 1);
this.appEvents.trigger("full-page-search:trigger-search");
@action
loadMore() {
let page = this.page;
if (
this.get("model.grouped_search_result.more_full_page_results") &&
!this.loading &&
page < PAGE_LIMIT
) {
this.incrementProperty("page");
this._search(); this._search();
}, }
}
loadMore() { @action
let page = this.page; logClick(topicId) {
if ( if (this.get("model.grouped_search_result.search_log_id") && topicId) {
this.get("model.grouped_search_result.more_full_page_results") && logSearchLinkClick({
!this.loading && searchLogId: this.get("model.grouped_search_result.search_log_id"),
page < PAGE_LIMIT searchResultId: topicId,
) { searchResultType: "topic",
this.incrementProperty("page"); });
this._search(); }
} }
}, }
logClick(topicId) {
if (this.get("model.grouped_search_result.search_log_id") && topicId) {
logSearchLinkClick({
searchLogId: this.get("model.grouped_search_result.search_log_id"),
searchResultId: topicId,
searchResultType: "topic",
});
}
},
},
});