Skip to content

A platform for community discussion. Free, open, simple.

DEV: Convert core controllers to native class syntax (batch 3) (#28224)

David Taylor75d11bfeba8a
diff --git a/app/assets/javascripts/discourse/app/controllers/invites-show.js b/app/assets/javascripts/discourse/app/controllers/invites-show.js
index c0556074cee..653dad62a3d 100644
--- a/app/assets/javascripts/discourse/app/controllers/invites-show.js
+++ b/app/assets/javascripts/discourse/app/controllers/invites-show.js
@@ -16,368 +16,362 @@ import getUrl from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-export default Controller.extend(
+export default class InvitesShowController extends Controller.extend(
PasswordValidation,
UsernameValidation,
NameValidation,
- UserFieldsValidation,
- {
- queryParams: ["t"],
-
- invitedBy: readOnly("model.invited_by"),
- email: alias("model.email"),
- accountEmail: alias("email"),
- existingUserId: readOnly("model.existing_user_id"),
- existingUserCanRedeem: readOnly("model.existing_user_can_redeem"),
- existingUserCanRedeemError: readOnly(
- "model.existing_user_can_redeem_error"
- ),
- existingUserRedeeming: bool("existingUserId"),
- hiddenEmail: alias("model.hidden_email"),
- emailVerifiedByLink: alias("model.email_verified_by_link"),
- differentExternalEmail: alias("model.different_external_email"),
- accountUsername: alias("model.username"),
- passwordRequired: not("externalAuthsOnly"),
- successMessage: null,
- errorMessage: null,
- userFields: null,
- authOptions: null,
- inviteImageUrl: getUrl("/images/envelope.svg"),
- isInviteLink: readOnly("model.is_invite_link"),
- rejectedEmails: null,
- maskPassword: true,
-
- init() {
- this._super(...arguments);
-
- this.rejectedEmails = [];
- },
-
- authenticationComplete(options) {
- const props = {
- accountUsername: options.username,
- accountName: options.name,
- authOptions: EmberObject.create(options),
- };
-
- if (this.isInviteLink) {
- props.email = options.email;
- }
+ UserFieldsValidation
+) {
+ queryParams = ["t"];
+
+ @readOnly("model.invited_by") invitedBy;
+ @alias("model.email") email;
+ @alias("email") accountEmail;
+ @readOnly("model.existing_user_id") existingUserId;
+ @readOnly("model.existing_user_can_redeem") existingUserCanRedeem;
+ @readOnly("model.existing_user_can_redeem_error") existingUserCanRedeemError;
+ @bool("existingUserId") existingUserRedeeming;
+ @alias("model.hidden_email") hiddenEmail;
+ @alias("model.email_verified_by_link") emailVerifiedByLink;
+ @alias("model.different_external_email") differentExternalEmail;
+ @alias("model.username") accountUsername;
+ @not("externalAuthsOnly") passwordRequired;
+ @readOnly("model.is_invite_link") isInviteLink;
+
+ successMessage = null;
+ errorMessage = null;
+ userFields = null;
+ authOptions = null;
+ inviteImageUrl = getUrl("/images/envelope.svg");
+ rejectedEmails = [];
+ maskPassword = true;
+
+ authenticationComplete(options) {
+ const props = {
+ accountUsername: options.username,
+ accountName: options.name,
+ authOptions: EmberObject.create(options),
+ };
+
+ if (this.isInviteLink) {
+ props.email = options.email;
+ }
+
+ this.setProperties(props);
+ }
- this.setProperties(props);
- },
+ @discourseComputed
+ discourseConnectEnabled() {
+ return this.siteSettings.enable_discourse_connect;
+ }
- @discourseComputed
- discourseConnectEnabled() {
- return this.siteSettings.enable_discourse_connect;
- },
+ @discourseComputed
+ welcomeTitle() {
+ return I18n.t("invites.welcome_to", {
+ site_name: this.siteSettings.title,
+ });
+ }
- @discourseComputed
- welcomeTitle() {
- return I18n.t("invites.welcome_to", {
- site_name: this.siteSettings.title,
- });
- },
+ @discourseComputed("existingUserId")
+ subheaderMessage(existingUserId) {
+ if (existingUserId) {
+ return I18n.t("invites.existing_user_can_redeem");
+ } else {
+ return I18n.t("create_account.subheader_title");
+ }
+ }
- @discourseComputed("existingUserId")
- subheaderMessage(existingUserId) {
- if (existingUserId) {
- return I18n.t("invites.existing_user_can_redeem");
- } else {
- return I18n.t("create_account.subheader_title");
- }
- },
-
- @discourseComputed("email")
- yourEmailMessage(email) {
- return I18n.t("invites.your_email", { email });
- },
-
- @discourseComputed
- externalAuthsEnabled() {
- return findLoginMethods().length > 0;
- },
-
- @discourseComputed
- externalAuthsOnly() {
- return (
- !this.siteSettings.enable_local_logins &&
- this.externalAuthsEnabled &&
- !this.siteSettings.enable_discourse_connect
- );
- },
-
- @discourseComputed(
- "emailValidation.failed",
- "usernameValidation.failed",
- "passwordValidation.failed",
- "nameValidation.failed",
- "userFieldsValidation.failed",
- "existingUserRedeeming",
- "existingUserCanRedeem"
- )
- submitDisabled(
- emailValidationFailed,
- usernameValidationFailed,
- passwordValidationFailed,
- nameValidationFailed,
- userFieldsValidationFailed,
- existingUserRedeeming,
- existingUserCanRedeem
- ) {
- if (existingUserRedeeming) {
- return !existingUserCanRedeem;
- }
+ @discourseComputed("email")
+ yourEmailMessage(email) {
+ return I18n.t("invites.your_email", { email });
+ }
- return (
- emailValidationFailed ||
- usernameValidationFailed ||
- passwordValidationFailed ||
- nameValidationFailed ||
- userFieldsValidationFailed
- );
- },
-
- @discourseComputed(
- "externalAuthsEnabled",
- "externalAuthsOnly",
- "discourseConnectEnabled"
- )
- showSocialLoginAvailable(
- externalAuthsEnabled,
- externalAuthsOnly,
- discourseConnectEnabled
- ) {
- return (
- externalAuthsEnabled && !externalAuthsOnly && !discourseConnectEnabled
- );
- },
-
- @discourseComputed(
- "externalAuthsOnly",
- "authOptions",
- "emailValidation.failed",
- "existingUserRedeeming"
- )
- shouldDisplayForm(
- externalAuthsOnly,
- authOptions,
- emailValidationFailed,
- existingUserRedeeming
- ) {
- return (
- (this.siteSettings.enable_local_logins ||
- (externalAuthsOnly && authOptions && !emailValidationFailed)) &&
- !this.siteSettings.enable_discourse_connect &&
- !existingUserRedeeming
- );
- },
+ @discourseComputed
+ externalAuthsEnabled() {
+ return findLoginMethods().length > 0;
+ }
- @discourseComputed
- fullnameRequired() {
- return (
- this.siteSettings.full_name_required || this.siteSettings.enable_names
- );
- },
-
- @discourseComputed(
- "email",
- "rejectedEmails.[]",
- "authOptions.email",
- "authOptions.email_valid",
- "hiddenEmail",
- "emailVerifiedByLink",
- "differentExternalEmail"
- )
- emailValidation(
- email,
- rejectedEmails,
- externalAuthEmail,
- externalAuthEmailValid,
- hiddenEmail,
- emailVerifiedByLink,
- differentExternalEmail
- ) {
- if (hiddenEmail && !differentExternalEmail) {
- return EmberObject.create({
- ok: true,
- reason: I18n.t("user.email.ok"),
- });
- }
+ @discourseComputed
+ externalAuthsOnly() {
+ return (
+ !this.siteSettings.enable_local_logins &&
+ this.externalAuthsEnabled &&
+ !this.siteSettings.enable_discourse_connect
+ );
+ }
- // If blank, fail without a reason
- if (isEmpty(email)) {
- return EmberObject.create({
- failed: true,
- });
- }
+ @discourseComputed(
+ "emailValidation.failed",
+ "usernameValidation.failed",
+ "passwordValidation.failed",
+ "nameValidation.failed",
+ "userFieldsValidation.failed",
+ "existingUserRedeeming",
+ "existingUserCanRedeem"
+ )
+ submitDisabled(
+ emailValidationFailed,
+ usernameValidationFailed,
+ passwordValidationFailed,
+ nameValidationFailed,
+ userFieldsValidationFailed,
+ existingUserRedeeming,
+ existingUserCanRedeem
+ ) {
+ if (existingUserRedeeming) {
+ return !existingUserCanRedeem;
+ }
+
+ return (
+ emailValidationFailed ||
+ usernameValidationFailed ||
+ passwordValidationFailed ||
+ nameValidationFailed ||
+ userFieldsValidationFailed
+ );
+ }
- if (rejectedEmails.includes(email)) {
- return EmberObject.create({
- failed: true,
- reason: I18n.t("user.email.invalid"),
- });
- }
+ @discourseComputed(
+ "externalAuthsEnabled",
+ "externalAuthsOnly",
+ "discourseConnectEnabled"
+ )
+ showSocialLoginAvailable(
+ externalAuthsEnabled,
+ externalAuthsOnly,
+ discourseConnectEnabled
+ ) {
+ return (
+ externalAuthsEnabled && !externalAuthsOnly && !discourseConnectEnabled
+ );
+ }
- if (externalAuthEmail && externalAuthEmailValid) {
- const provider = this.authProviderDisplayName(
- this.get("authOptions.auth_provider")
- );
-
- if (externalAuthEmail === email) {
- return EmberObject.create({
- ok: true,
- reason: I18n.t("user.email.authenticated", {
- provider,
- }),
- });
- } else {
- return EmberObject.create({
- failed: true,
- reason: I18n.t("user.email.invite_auth_email_invalid", {
- provider,
- }),
- });
- }
- }
+ @discourseComputed(
+ "externalAuthsOnly",
+ "authOptions",
+ "emailValidation.failed",
+ "existingUserRedeeming"
+ )
+ shouldDisplayForm(
+ externalAuthsOnly,
+ authOptions,
+ emailValidationFailed,
+ existingUserRedeeming
+ ) {
+ return (
+ (this.siteSettings.enable_local_logins ||
+ (externalAuthsOnly && authOptions && !emailValidationFailed)) &&
+ !this.siteSettings.enable_discourse_connect &&
+ !existingUserRedeeming
+ );
+ }
+
+ @discourseComputed
+ fullnameRequired() {
+ return (
+ this.siteSettings.full_name_required || this.siteSettings.enable_names
+ );
+ }
- if (emailVerifiedByLink) {
+ @discourseComputed(
+ "email",
+ "rejectedEmails.[]",
+ "authOptions.email",
+ "authOptions.email_valid",
+ "hiddenEmail",
+ "emailVerifiedByLink",
+ "differentExternalEmail"
+ )
+ emailValidation(
+ email,
+ rejectedEmails,
+ externalAuthEmail,
+ externalAuthEmailValid,
+ hiddenEmail,
+ emailVerifiedByLink,
+ differentExternalEmail
+ ) {
+ if (hiddenEmail && !differentExternalEmail) {
+ return EmberObject.create({
+ ok: true,
+ reason: I18n.t("user.email.ok"),
+ });
+ }
+
+ // If blank, fail without a reason
+ if (isEmpty(email)) {
+ return EmberObject.create({
+ failed: true,
+ });
+ }
+
+ if (rejectedEmails.includes(email)) {
+ return EmberObject.create({
+ failed: true,
+ reason: I18n.t("user.email.invalid"),
+ });
+ }
+
+ if (externalAuthEmail && externalAuthEmailValid) {
+ const provider = this.authProviderDisplayName(
+ this.get("authOptions.auth_provider")
+ );
+
+ if (externalAuthEmail === email) {
return EmberObject.create({
ok: true,
- reason: I18n.t("user.email.authenticated_by_invite"),
+ reason: I18n.t("user.email.authenticated", {
+ provider,
+ }),
});
- }
-
- if (emailValid(email)) {
+ } else {
return EmberObject.create({
- ok: true,
- reason: I18n.t("user.email.ok"),
+ failed: true,
+ reason: I18n.t("user.email.invite_auth_email_invalid", {
+ provider,
+ }),
});
}
+ }
+ if (emailVerifiedByLink) {
return EmberObject.create({
- failed: true,
- reason: I18n.t("user.email.invalid"),
+ ok: true,
+ reason: I18n.t("user.email.authenticated_by_invite"),
});
- },
+ }
- authProviderDisplayName(providerName) {
- const matchingProvider = findLoginMethods().find((provider) => {
- return provider.name === providerName;
+ if (emailValid(email)) {
+ return EmberObject.create({
+ ok: true,
+ reason: I18n.t("user.email.ok"),
});
- return matchingProvider
- ? matchingProvider.get("prettyName")
- : providerName;
- },
-
- @discourseComputed
- wavingHandURL: () => wavingHandURL(),
-
- @discourseComputed
- ssoPath: () => getUrl("/session/sso"),
-
- @discourseComputed
- disclaimerHtml() {
- if (this.site.tos_url && this.site.privacy_policy_url) {
- return I18n.t("create_account.disclaimer", {
- tos_link: this.site.tos_url,
- privacy_link: this.site.privacy_policy_url,
- });
- }
- },
+ }
- @discourseComputed("authOptions.associate_url", "authOptions.auth_provider")
- associateHtml(url, provider) {
- if (!url) {
- return;
- }
- return I18n.t("create_account.associate", {
- associate_link: url,
- provider: I18n.t(`login.${provider}.name`),
+ return EmberObject.create({
+ failed: true,
+ reason: I18n.t("user.email.invalid"),
+ });
+ }
+
+ authProviderDisplayName(providerName) {
+ const matchingProvider = findLoginMethods().find((provider) => {
+ return provider.name === providerName;
+ });
+ return matchingProvider ? matchingProvider.get("prettyName") : providerName;
+ }
+
+ @discourseComputed
+ wavingHandURL() {
+ return wavingHandURL();
+ }
+
+ @discourseComputed
+ ssoPath() {
+ return getUrl("/session/sso");
+ }
+
+ @discourseComputed
+ disclaimerHtml() {
+ if (this.site.tos_url && this.site.privacy_policy_url) {
+ return I18n.t("create_account.disclaimer", {
+ tos_link: this.site.tos_url,
+ privacy_link: this.site.privacy_policy_url,
});
- },
-
- @action
- togglePasswordMask() {
- this.toggleProperty("maskPassword");
- },
-
- actions: {
- submit() {
- const userFields = this.userFields;
- let userCustomFields = {};
- if (!isEmpty(userFields)) {
- userFields.forEach(function (f) {
- userCustomFields[f.get("field.id")] = f.get("value");
- });
- }
+ }
+ }
- const data = {
- username: this.accountUsername,
- name: this.accountName,
- password: this.accountPassword,
- user_custom_fields: userCustomFields,
- timezone: moment.tz.guess(),
- };
+ @discourseComputed("authOptions.associate_url", "authOptions.auth_provider")
+ associateHtml(url, provider) {
+ if (!url) {
+ return;
+ }
+ return I18n.t("create_account.associate", {
+ associate_link: url,
+ provider: I18n.t(`login.${provider}.name`),
+ });
+ }
- if (this.isInviteLink) {
- data.email = this.email;
+ @action
+ togglePasswordMask() {
+ this.toggleProperty("maskPassword");
+ }
+
+ @action
+ submit() {
+ const userFields = this.userFields;
+ let userCustomFields = {};
+ if (!isEmpty(userFields)) {
+ userFields.forEach(function (f) {
+ userCustomFields[f.get("field.id")] = f.get("value");
+ });
+ }
+
+ const data = {
+ username: this.accountUsername,
+ name: this.accountName,
+ password: this.accountPassword,
+ user_custom_fields: userCustomFields,
+ timezone: moment.tz.guess(),
+ };
+
+ if (this.isInviteLink) {
+ data.email = this.email;
+ } else {
+ data.email_token = this.t;
+ }
+
+ ajax({
+ url: `/invites/show/${this.get("model.token")}.json`,
+ type: "PUT",
+ data,
+ })
+ .then((result) => {
+ if (result.success) {
+ this.set(
+ "successMessage",
+ result.message || I18n.t("invites.success")
+ );
+ if (result.redirect_to) {
+ DiscourseURL.redirectTo(result.redirect_to);
+ }
} else {
- data.email_token = this.t;
+ if (
+ result.errors &&
+ result.errors.email &&
+ result.errors.email.length > 0 &&
+ result.values
+ ) {
+ this.rejectedEmails.pushObject(result.values.email);
+ }
+ if (
+ result.errors &&
+ result.errors.password &&
+ result.errors.password.length > 0
+ ) {
+ this.rejectedPasswords.pushObject(this.accountPassword);
+ this.rejectedPasswordsMessages.set(
+ this.accountPassword,
+ result.errors.password[0]
+ );
+ }
+ if (result.message) {
+ this.set("errorMessage", result.message);
+ }
}
+ })
+ .catch((error) => {
+ this.set("errorMessage", extractError(error));
+ });
+ }
- ajax({
- url: `/invites/show/${this.get("model.token")}.json`,
- type: "PUT",
- data,
- })
- .then((result) => {
- if (result.success) {
- this.set(
- "successMessage",
- result.message || I18n.t("invites.success")
- );
- if (result.redirect_to) {
- DiscourseURL.redirectTo(result.redirect_to);
- }
- } else {
- if (
- result.errors &&
- result.errors.email &&
- result.errors.email.length > 0 &&
- result.values
- ) {
- this.rejectedEmails.pushObject(result.values.email);
- }
- if (
- result.errors &&
- result.errors.password &&
- result.errors.password.length > 0
- ) {
- this.rejectedPasswords.pushObject(this.accountPassword);
- this.rejectedPasswordsMessages.set(
- this.accountPassword,
- result.errors.password[0]
- );
- }
- if (result.message) {
- this.set("errorMessage", result.message);
- }
- }
- })
- .catch((error) => {
- this.set("errorMessage", extractError(error));
- });
- },
-
- externalLogin(provider) {
- provider.doLogin({
- signup: true,
- params: {
- origin: window.location.href,
- },
- });
+ @action
+ externalLogin(provider) {
+ provider.doLogin({
+ signup: true,
+ params: {
+ origin: window.location.href,
},
- },
+ });
}
-);
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/password-reset.js b/app/assets/javascripts/discourse/app/controllers/password-reset.js
index a02ae9a4c06..d8116ec76ef 100644
--- a/app/assets/javascripts/discourse/app/controllers/password-reset.js
+++ b/app/assets/javascripts/discourse/app/controllers/password-reset.js
@@ -11,23 +11,26 @@ import getURL from "discourse-common/lib/get-url";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-export default Controller.extend(PasswordValidation, {
- isDeveloper: alias("model.is_developer"),
- admin: alias("model.admin"),
- secondFactorRequired: alias("model.second_factor_required"),
- securityKeyRequired: alias("model.security_key_required"),
- backupEnabled: alias("model.backup_enabled"),
- securityKeyOrSecondFactorRequired: or(
- "model.second_factor_required",
- "model.security_key_required"
- ),
- otherMethodAllowed: readOnly("model.multiple_second_factor_methods"),
- passwordRequired: true,
- errorMessage: null,
- successMessage: null,
- requiresApproval: false,
- redirected: false,
- maskPassword: true,
+export default class PasswordResetController extends Controller.extend(
+ PasswordValidation
+) {
+ @alias("model.is_developer") isDeveloper;
+ @alias("model.admin") admin;
+ @alias("model.second_factor_required") secondFactorRequired;
+ @alias("model.security_key_required") securityKeyRequired;
+ @alias("model.backup_enabled") backupEnabled;
+ @or("model.second_factor_required", "model.security_key_required")
+ securityKeyOrSecondFactorRequired;
+ @readOnly("model.multiple_second_factor_methods") otherMethodAllowed;
+
+ passwordRequired = true;
+ errorMessage = null;
+ successMessage = null;
+ requiresApproval = false;
+ redirected = false;
+ maskPassword = true;
+
+ lockImageUrl = getURL("/images/lock.svg");
@discourseComputed("securityKeyRequired", "selectedSecondFactorMethod")
displaySecurityKeyForm(securityKeyRequired, selectedSecondFactorMethod) {
@@ -35,7 +38,7 @@ export default Controller.extend(PasswordValidation, {
securityKeyRequired &&
selectedSecondFactorMethod === SECOND_FACTOR_METHODS.SECURITY_KEY
);
- },
+ }
initSelectedSecondFactorMethod() {
if (this.model.security_key_required) {
@@ -48,21 +51,19 @@ export default Controller.extend(PasswordValidation, {
} else if (this.model.backup_enabled) {
this.set("selectedSecondFactorMethod", SECOND_FACTOR_METHODS.BACKUP_CODE);
}
- },
+ }
@discourseComputed()
continueButtonText() {
return I18n.t("password_reset.continue", {
site_name: this.siteSettings.title,
});
- },
+ }
@discourseComputed("redirectTo")
redirectHref(redirectTo) {
return getURL(redirectTo || "/");
- },
-
- lockImageUrl: getURL("/images/lock.svg"),
+ }
@action
done(event) {
@@ -73,12 +74,12 @@ export default Controller.extend(PasswordValidation, {
event.preventDefault();
this.set("redirected", true);
DiscourseURL.redirectTo(this.redirectTo || "/");
- },
+ }
@action
togglePasswordMask() {
this.toggleProperty("maskPassword");
- },
+ }
@action
async submit() {
@@ -138,7 +139,7 @@ export default Controller.extend(PasswordValidation, {
throw new Error(e);
}
}
- },
+ }
@action
authenticateSecurityKey() {
@@ -159,5 +160,5 @@ export default Controller.extend(PasswordValidation, {
});
}
);
- },
-});
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/preferences.js b/app/assets/javascripts/discourse/app/controllers/preferences.js
index fa4ba1ee7d2..ca9221d55ac 100644
--- a/app/assets/javascripts/discourse/app/controllers/preferences.js
+++ b/app/assets/javascripts/discourse/app/controllers/preferences.js
@@ -1,3 +1,3 @@
import Controller from "@ember/controller";
-export default Controller.extend({});
+export default class PreferencesController extends Controller {}
diff --git a/app/assets/javascripts/discourse/app/controllers/review-index.js b/app/assets/javascripts/discourse/app/controllers/review-index.js
index 99a256a104b..a3bfc340079 100644
--- a/app/assets/javascripts/discourse/app/controllers/review-index.js
+++ b/app/assets/javascripts/discourse/app/controllers/review-index.js
@@ -1,12 +1,13 @@
import Controller from "@ember/controller";
+import { action } from "@ember/object";
import { next } from "@ember/runloop";
import { underscore } from "@ember/string";
import { isPresent } from "@ember/utils";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-export default Controller.extend({
- queryParams: [
+export default class ReviewIndexController extends Controller {
+ queryParams = [
"priority",
"type",
"status",
@@ -18,26 +19,21 @@ export default Controller.extend({
"to_date",
"sort_order",
"additional_filters",
- ],
- type: null,
- status: "pending",
- priority: "low",
- category_id: null,
- reviewables: null,
- topic_id: null,
- filtersExpanded: false,
- username: "",
- reviewed_by: "",
- from_date: null,
- to_date: null,
- sort_order: null,
- additional_filters: null,
-
- init(...args) {
- this._super(...args);
- this.set("priority", this.siteSettings.reviewable_default_visibility);
- this.set("filtersExpanded", this.site.desktopView);
- },
+ ];
+
+ type = null;
+ status = "pending";
+ priority = this.siteSettings.reviewable_default_visibility;
+ category_id = null;
+ reviewables = null;
+ topic_id = null;
+ filtersExpanded = this.site.desktopView;
+ username = "";
+ reviewed_by = "";
+ from_date = null;
+ to_date = null;
+ sort_order = null;
+ additional_filters = null;
@discourseComputed("reviewableTypes")
allTypes() {
@@ -49,7 +45,7 @@ export default Controller.extend({
name: I18n.t(`review.types.${translationKey}.title`),
};
});
- },
+ }
@discourseComputed
priorities() {
@@ -59,7 +55,7 @@ export default Controller.extend({
name: I18n.t(`review.filters.priority.${priority}`),
};
});
- },
+ }
@discourseComputed
sortOrders() {
@@ -71,7 +67,7 @@ export default Controller.extend({
};
}
);
- },
+ }
@discourseComputed
statuses() {
@@ -86,110 +82,115 @@ export default Controller.extend({
].map((id) => {
return { id, name: I18n.t(`review.statuses.${id}.title`) };
});
- },
+ }
@discourseComputed("filtersExpanded")
toggleFiltersIcon(filtersExpanded) {
return filtersExpanded ? "chevron-up" : "chevron-down";
- },
+ }
setRange(range) {
this.setProperties(range);
- },
+ }
refreshModel() {
next(() => this.send("refreshRoute"));
- },
+ }
- actions: {
- remove(ids) {
- if (!ids) {
- return;
- }
-
- let newList = this.reviewables.reject((reviewable) => {
- return ids.includes(reviewable.id);
- });
-
- if (newList.length === 0) {
- this.refreshModel();
- } else {
- this.reviewables.setObjects(newList);
- }
- },
-
- resetTopic() {
- this.set("topic_id", null);
- this.refreshModel();
- },
-
- refresh() {
- const currentStatus = this.status;
- const nextStatus = this.filterStatus;
- const currentOrder = this.sort_order;
- let nextOrder = this.filterSortOrder;
-
- const createdAtStatuses = ["reviewed", "all"];
- const priorityStatuses = [
- "approved",
- "rejected",
- "deleted",
- "ignored",
- "pending",
- ];
-
- if (
- createdAtStatuses.includes(currentStatus) &&
- currentOrder === "created_at" &&
- priorityStatuses.includes(nextStatus) &&
- nextOrder === "created_at"
- ) {
- nextOrder = "score";
- }
+ @action
+ remove(ids) {
+ if (!ids) {
+ return;
+ }
- if (
- priorityStatuses.includes(currentStatus) &&
- currentOrder === "score" &&
- createdAtStatuses.includes(nextStatus) &&
- nextOrder === "score"
- ) {
- nextOrder = "created_at";
- }
-
- this.setProperties({
- type: this.filterType,
- priority: this.filterPriority,
- status: this.filterStatus,
- category_id: this.filterCategoryId,
- username: this.filterUsername,
- reviewed_by: this.filterReviewedBy,
- from_date: isPresent(this.filterFromDate)
- ? this.filterFromDate.toISOString(true).split("T")[0]
- : null,
- to_date: isPresent(this.filterToDate)
- ? this.filterToDate.toISOString(true).split("T")[0]
- : null,
- sort_order: nextOrder,
- additional_filters: JSON.stringify(this.additionalFilters),
- });
+ let newList = this.reviewables.reject((reviewable) => {
+ return ids.includes(reviewable.id);
+ });
+ if (newList.length === 0) {
this.refreshModel();
- },
-
- loadMore() {
- return this.reviewables.loadMore();
- },
-
- toggleFilters() {
- this.toggleProperty("filtersExpanded");
- },
-
- updateFilterReviewedBy(selected) {
- this.set("filterReviewedBy", selected.firstObject);
- },
+ } else {
+ this.reviewables.setObjects(newList);
+ }
+ }
+
+ @action
+ resetTopic() {
+ this.set("topic_id", null);
+ this.refreshModel();
+ }
+
+ @action
+ refresh() {
+ const currentStatus = this.status;
+ const nextStatus = this.filterStatus;
+ const currentOrder = this.sort_order;
+ let nextOrder = this.filterSortOrder;
+
+ const createdAtStatuses = ["reviewed", "all"];
+ const priorityStatuses = [
+ "approved",
+ "rejected",
+ "deleted",
+ "ignored",
+ "pending",
+ ];
+
+ if (
+ createdAtStatuses.includes(currentStatus) &&
+ currentOrder === "created_at" &&
+ priorityStatuses.includes(nextStatus) &&
+ nextOrder === "created_at"
+ ) {
+ nextOrder = "score";
+ }
+
+ if (
+ priorityStatuses.includes(currentStatus) &&
+ currentOrder === "score" &&
+ createdAtStatuses.includes(nextStatus) &&
+ nextOrder === "score"
+ ) {
+ nextOrder = "created_at";
+ }
+
+ this.setProperties({
+ type: this.filterType,
+ priority: this.filterPriority,
+ status: this.filterStatus,
+ category_id: this.filterCategoryId,
+ username: this.filterUsername,
+ reviewed_by: this.filterReviewedBy,
+ from_date: isPresent(this.filterFromDate)
+ ? this.filterFromDate.toISOString(true).split("T")[0]
+ : null,
+ to_date: isPresent(this.filterToDate)
+ ? this.filterToDate.toISOString(true).split("T")[0]
+ : null,
+ sort_order: nextOrder,
+ additional_filters: JSON.stringify(this.additionalFilters),
+ });
- updateFilterUsername(selected) {
- this.set("filterUsername", selected.firstObject);
- },
- },
-});
+ this.refreshModel();
+ }
+
+ @action
+ loadMore() {
+ return this.reviewables.loadMore();
+ }
+
+ @action
+ toggleFilters() {
+ this.toggleProperty("filtersExpanded");
+ }
+
+ @action
+ updateFilterReviewedBy(selected) {
+ this.set("filterReviewedBy", selected.firstObject);
+ }
+
+ @action
+ updateFilterUsername(selected) {
+ this.set("filterUsername", selected.firstObject);
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/review-settings.js b/app/assets/javascripts/discourse/app/controllers/review-settings.js
index 8071b79da04..6e3a9c61fae 100644
--- a/app/assets/javascripts/discourse/app/controllers/review-settings.js
+++ b/app/assets/javascripts/discourse/app/controllers/review-settings.js
@@ -1,32 +1,32 @@
import Controller from "@ember/controller";
+import { action } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-export default Controller.extend({
- saving: false,
- saved: false,
+export default class ReviewSettingsController extends Controller {
+ saving = false;
+ saved = false;
- actions: {
- save() {
- let priorities = {};
- this.scoreTypes.forEach((st) => {
- priorities[st.id] = parseFloat(st.reviewable_priority);
- });
+ @action
+ save() {
+ let priorities = {};
+ this.scoreTypes.forEach((st) => {
+ priorities[st.id] = parseFloat(st.reviewable_priority);
+ });
- this.set("saving", true);
- ajax("/review/settings", {
- type: "PUT",
- data: { reviewable_priorities: priorities },
+ this.set("saving", true);
+ ajax("/review/settings", {
+ type: "PUT",
+ data: { reviewable_priorities: priorities },
+ })
+ .then(() => {
+ this.set("saved", true);
})
- .then(() => {
- this.set("saved", true);
- })
- .catch(popupAjaxError)
- .finally(() => this.set("saving", false));
- },
- },
+ .catch(popupAjaxError)
+ .finally(() => this.set("saving", false));
+ }
@discourseComputed("settings.reviewable_score_types")
scoreTypes(types) {
@@ -36,5 +36,5 @@ export default Controller.extend({
...type,
title: type.title.replace("%{username}", username),
}));
- },
-});
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/second-factor-auth.js b/app/assets/javascripts/discourse/app/controllers/second-factor-auth.js
index 66813005552..e7f3f5f7098 100644
--- a/app/assets/javascripts/discourse/app/controllers/second-factor-auth.js
+++ b/app/assets/javascripts/discourse/app/controllers/second-factor-auth.js
@@ -10,45 +10,42 @@ import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
const { TOTP, BACKUP_CODE, SECURITY_KEY } = SECOND_FACTOR_METHODS;
-export default Controller.extend({
- TOTP,
- BACKUP_CODE,
- SECURITY_KEY,
-
- queryParams: ["nonce"],
-
- message: null,
- loadError: false,
- messageIsError: false,
- secondFactorToken: null,
- userSelectedMethod: null,
-
- totpEnabled: readOnly("model.totp_enabled"),
- backupCodesEnabled: readOnly("model.backup_enabled"),
- securityKeysEnabled: readOnly("model.security_keys_enabled"),
- allowedMethods: readOnly("model.allowed_methods"),
- customDescription: readOnly("model.description"),
-
- showTotpForm: equal("shownSecondFactorMethod", TOTP),
- showSecurityKeyForm: equal("shownSecondFactorMethod", SECURITY_KEY),
- showBackupCodesForm: equal("shownSecondFactorMethod", BACKUP_CODE),
+export default class SecondFactorAuthController extends Controller {
+ TOTP = TOTP;
+ BACKUP_CODE = BACKUP_CODE;
+ SECURITY_KEY = SECURITY_KEY;
+ queryParams = ["nonce"];
+ message = null;
+ loadError = false;
+ messageIsError = false;
+ secondFactorToken = null;
+ userSelectedMethod = null;
+
+ @readOnly("model.totp_enabled") totpEnabled;
+ @readOnly("model.backup_enabled") backupCodesEnabled;
+ @readOnly("model.security_keys_enabled") securityKeysEnabled;
+ @readOnly("model.allowed_methods") allowedMethods;
+ @readOnly("model.description") customDescription;
+ @equal("shownSecondFactorMethod", TOTP) showTotpForm;
+ @equal("shownSecondFactorMethod", SECURITY_KEY) showSecurityKeyForm;
+ @equal("shownSecondFactorMethod", BACKUP_CODE) showBackupCodesForm;
@discourseComputed("allowedMethods.[]", "totpEnabled")
totpAvailable() {
return this.totpEnabled && this.allowedMethods.includes(TOTP);
- },
+ }
@discourseComputed("allowedMethods.[]", "backupCodesEnabled")
backupCodesAvailable() {
return this.backupCodesEnabled && this.allowedMethods.includes(BACKUP_CODE);
- },
+ }
@discourseComputed("allowedMethods.[]", "securityKeysEnabled")
securityKeysAvailable() {
return (
this.securityKeysEnabled && this.allowedMethods.includes(SECURITY_KEY)
);
- },
+ }
@discourseComputed(
"userSelectedMethod",
@@ -75,7 +72,7 @@ export default Controller.extend({
throw new Error("unexpected state of user 2fa settings!");
}
}
- },
+ }
@discourseComputed(
"shownSecondFactorMethod",
@@ -115,7 +112,7 @@ export default Controller.extend({
}
return alts;
- },
+ }
@discourseComputed("shownSecondFactorMethod")
secondFactorTitle(shownSecondFactorMethod) {
@@ -127,7 +124,7 @@ export default Controller.extend({
case BACKUP_CODE:
return I18n.t("login.second_factor_backup_title");
}
- },
+ }
@discourseComputed("shownSecondFactorMethod")
secondFactorDescription(shownSecondFactorMethod) {
@@ -139,7 +136,7 @@ export default Controller.extend({
case BACKUP_CODE:
return I18n.t("login.second_factor_backup_description");
}
- },
+ }
@discourseComputed("messageIsError")
alertClass(messageIsError) {
@@ -148,7 +145,7 @@ export default Controller.extend({
} else {
return "alert-success";
}
- },
+ }
@discourseComputed("showTotpForm", "showBackupCodesForm")
inputFormClass(showTotpForm, showBackupCodesForm) {
@@ -157,7 +154,7 @@ export default Controller.extend({
} else if (showBackupCodesForm) {
return "backup-code-token";
}
- },
+ }
resetState() {
this.set("message", null);
@@ -165,17 +162,17 @@ export default Controller.extend({
this.set("secondFactorToken", null);
this.set("userSelectedMethod", null);
this.set("loadError", false);
- },
+ }
displayError(message) {
this.set("message", message);
this.set("messageIsError", true);
- },
+ }
displaySuccess(message) {
this.set("message", message);
this.set("messageIsError", false);
- },
+ }
verifySecondFactor(data) {
return ajax("/session/2fa", {
@@ -207,13 +204,13 @@ export default Controller.extend({
.catch((error) => {
this.displayError(extractError(error));
});
- },
+ }
@action
useAnotherMethod(newMethod, event) {
event?.preventDefault();
this.set("userSelectedMethod", newMethod);
- },
+ }
@action
authenticateSecurityKey() {
@@ -227,10 +224,10 @@ export default Controller.extend({
this.displayError(errorMessage);
}
);
- },
+ }
@action
authenticateToken() {
this.verifySecondFactor({ second_factor_token: this.secondFactorToken });
- },
-});
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/tag-groups-edit.js b/app/assets/javascripts/discourse/app/controllers/tag-groups-edit.js
index 175ca3cbcaa..a532c57d83b 100644
--- a/app/assets/javascripts/discourse/app/controllers/tag-groups-edit.js
+++ b/app/assets/javascripts/discourse/app/controllers/tag-groups-edit.js
@@ -1,16 +1,16 @@
import Controller, { inject as controller } from "@ember/controller";
+import { action } from "@ember/object";
import { service } from "@ember/service";
-export default Controller.extend({
- router: service(),
- tagGroups: controller(),
+export default class TagGroupsEditController extends Controller {
+ @service router;
+ @controller tagGroups;
- actions: {
- onDestroy() {
- const tagGroups = this.tagGroups.model;
- tagGroups.removeObject(this.model);
+ @action
+ onDestroy() {
+ const tagGroups = this.tagGroups.model;
+ tagGroups.removeObject(this.model);
- this.router.transitionTo("tagGroups.index");
- },
- },
-});
+ this.router.transitionTo("tagGroups.index");
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/tag-groups-new.js b/app/assets/javascripts/discourse/app/controllers/tag-groups-new.js
index 09dac6630ed..4c82f7979f6 100644
--- a/app/assets/javascripts/discourse/app/controllers/tag-groups-new.js
+++ b/app/assets/javascripts/discourse/app/controllers/tag-groups-new.js
@@ -1,16 +1,16 @@
import Controller, { inject as controller } from "@ember/controller";
+import { action } from "@ember/object";
import { service } from "@ember/service";
-export default Controller.extend({
- router: service(),
- tagGroups: controller(),
+export default class TagGroupsNewController extends Controller {
+ @service router;
+ @controller tagGroups;
- actions: {
- onSave() {
- const tagGroups = this.tagGroups.model;
- tagGroups.pushObject(this.model);
+ @action
+ onSave() {
+ const tagGroups = this.tagGroups.model;
+ tagGroups.pushObject(this.model);
- this.router.transitionTo("tagGroups.index");
- },
- },
-});
+ this.router.transitionTo("tagGroups.index");
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/tag-groups.js b/app/assets/javascripts/discourse/app/controllers/tag-groups.js
index 21acf7319d6..b06f9b84d3b 100644
--- a/app/assets/javascripts/discourse/app/controllers/tag-groups.js
+++ b/app/assets/javascripts/discourse/app/controllers/tag-groups.js
@@ -1,12 +1,12 @@
import Controller from "@ember/controller";
+import { action } from "@ember/object";
import { service } from "@ember/service";
-export default Controller.extend({
- router: service(),
+export default class TagGroupsController extends Controller {
+ @service router;
- actions: {
- newTagGroup() {
- this.router.transitionTo("tagGroups.new");
- },
- },
-});
+ @action
+ newTagGroup() {
+ this.router.transitionTo("tagGroups.new");
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/tags-index.js b/app/assets/javascripts/discourse/app/controllers/tags-index.js
index fa566f2f129..370c8f131c2 100644
--- a/app/assets/javascripts/discourse/app/controllers/tags-index.js
+++ b/app/assets/javascripts/discourse/app/controllers/tags-index.js
@@ -8,18 +8,20 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseComputed from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
-export default Controller.extend({
- dialog: service(),
- modal: service(),
- sortedByCount: true,
- sortedByName: false,
- sortAlphabetically: alias("siteSettings.tags_sort_alphabetically"),
- canAdminTags: alias("currentUser.staff"),
- groupedByCategory: notEmpty("model.extras.categories"),
- groupedByTagGroup: notEmpty("model.extras.tag_groups"),
+export default class TagsIndexController extends Controller {
+ @service dialog;
+ @service modal;
+
+ sortedByCount = true;
+ sortedByName = false;
+
+ @alias("siteSettings.tags_sort_alphabetically") sortAlphabetically;
+ @alias("currentUser.staff") canAdminTags;
+ @notEmpty("model.extras.categories") groupedByCategory;
+ @notEmpty("model.extras.tag_groups") groupedByTagGroup;
init() {
- this._super(...arguments);
+ super.init(...arguments);
const isAlphaSort = this.sortAlphabetically;
@@ -28,7 +30,7 @@ export default Controller.extend({
sortedByName: isAlphaSort ? true : false,
sortProperties: isAlphaSort ? ["id"] : ["totalCount:desc", "id"],
});
- },
+ }
@discourseComputed("groupedByCategory", "groupedByTagGroup")
otherTagsTitleKey(groupedByCategory, groupedByTagGroup) {
@@ -37,7 +39,7 @@ export default Controller.extend({
} else {
return "tagging.other_tags";
}
- },
+ }
@discourseComputed
actionsMapping() {
@@ -46,7 +48,7 @@ export default Controller.extend({
uploadTags: () => this.send("showUploader"),
deleteUnusedTags: () => this.send("deleteUnused"),
};
- },
+ }
@action
sortByCount(event) {
@@ -56,7 +58,7 @@ export default Controller.extend({
sortedByCount: true,
sortedByName: false,
});
- },
+ }
@action
sortById(event) {
@@ -66,53 +68,53 @@ export default Controller.extend({
sortedByCount: false,
sortedByName: true,
});
- },
-
- actions: {
- showUploader() {
- this.modal.show(TagUpload);
- },
-
- deleteUnused() {
- ajax("/tags/unused", { type: "GET" })
- .then((result) => {
- const displayN = 20;
- const tags = result["tags"];
-
- if (tags.length === 0) {
- this.dialog.alert(I18n.t("tagging.delete_no_unused_tags"));
- return;
- }
-
- const joinedTags = tags
- .slice(0, displayN)
- .join(I18n.t("tagging.tag_list_joiner"));
- const more = Math.max(0, tags.length - displayN);
-
- const tagsString =
- more === 0
- ? joinedTags
- : I18n.t("tagging.delete_unused_confirmation_more_tags", {
- count: more,
- tags: joinedTags,
- });
-
- const message = I18n.t("tagging.delete_unused_confirmation", {
- count: tags.length,
- tags: tagsString,
- });
-
- this.dialog.deleteConfirm({
- message,
- confirmButtonLabel: "tagging.delete_unused",
- didConfirm: () => {
- return ajax("/tags/unused", { type: "DELETE" })
- .then(() => this.send("triggerRefresh"))
- .catch(popupAjaxError);
- },
- });
- })
- .catch(popupAjaxError);
- },
- },
-});
+ }
+
+ @action
+ showUploader() {
+ this.modal.show(TagUpload);
+ }
+
+ @action
+ deleteUnused() {
+ ajax("/tags/unused", { type: "GET" })
+ .then((result) => {
+ const displayN = 20;
+ const tags = result["tags"];
+
+ if (tags.length === 0) {
+ this.dialog.alert(I18n.t("tagging.delete_no_unused_tags"));
+ return;
+ }
+
+ const joinedTags = tags
+ .slice(0, displayN)
+ .join(I18n.t("tagging.tag_list_joiner"));
+ const more = Math.max(0, tags.length - displayN);
+
+ const tagsString =
+ more === 0
+ ? joinedTags
+ : I18n.t("tagging.delete_unused_confirmation_more_tags", {
+ count: more,
+ tags: joinedTags,
+ });
+
+ const message = I18n.t("tagging.delete_unused_confirmation", {
+ count: tags.length,
+ tags: tagsString,
+ });
+
+ this.dialog.deleteConfirm({
+ message,
+ confirmButtonLabel: "tagging.delete_unused",
+ didConfirm: () => {
+ return ajax("/tags/unused", { type: "DELETE" })
+ .then(() => this.send("triggerRefresh"))
+ .catch(popupAjaxError);
+ },
+ });
+ })
+ .catch(popupAjaxError);
+ }
+}
diff --git a/app/assets/javascripts/discourse/app/controllers/topic.js b/app/assets/javascripts/discourse/app/controllers/topic.js
index 2414940e9a7..63e965acd58 100644
--- a/app/assets/javascripts/discourse/app/controllers/topic.js
+++ b/app/assets/javascripts/discourse/app/controllers/topic.js
@@ -4,6 +4,7 @@ import { alias, and, not, or } from "@ember/object/computed";
import { next, schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { isEmpty, isPresent } from "@ember/utils";
+import { observes } from "@ember-decorators/object";
import { Promise } from "rsvp";
import {
CLOSE_INITIATED_BY_BUTTON,
@@ -35,10 +36,7 @@ import Topic from "discourse/models/topic";
import TopicTimer from "discourse/models/topic-timer";
import discourseLater from "discourse-common/lib/later";
import { deepMerge } from "discourse-common/lib/object";
-import discourseComputed, {
- bind,
- observes,
-} from "discourse-common/utils/decorators";
+import discourseComputed, { bind } from "discourse-common/utils/decorators";
import I18n from "discourse-i18n";
let customPostMessageCallbacks = {};
@@ -57,69 +55,67 @@ export function registerCustomPostMessageCallback(type, callback) {
customPostMessageCallbacks[type] = callback;
}
-export default Controller.extend(bufferedProperty("model"), {
- composer: service(),
- dialog: service(),
- documentTitle: service(),
- screenTrack: service(),
- modal: service(),
- currentUser: service(),
- router: service(),
- siteSettings: service(),
- site: service(),
- appEvents: service(),
-
- multiSelect: false,
- selectedPostIds: null,
- editingTopic: false,
- queryParams: ["filter", "username_filters", "replies_to_post_number"],
- loadedAllPosts: or(
- "model.postStream.loadedAllPosts",
- "model.postStream.loadingLastPost"
- ),
- enteredAt: null,
- enteredIndex: null,
- retrying: false,
- userTriggeredProgress: null,
- _progressIndex: null,
- hasScrolled: null,
- username_filters: null,
- replies_to_post_number: null,
- filter: null,
- quoteState: null,
- currentPostId: null,
- userLastReadPostNumber: null,
- highestPostNumber: null,
+export default class TopicController extends Controller.extend(
+ bufferedProperty("model")
+) {
+ @service composer;
+ @service dialog;
+ @service documentTitle;
+ @service screenTrack;
+ @service modal;
+ @service currentUser;
+ @service router;
+ @service siteSettings;
+ @service site;
+ @service appEvents;
+
+ queryParams = ["filter", "username_filters", "replies_to_post_number"];
+
+ @and("canEditTopicFeaturedLink", "buffered.featured_link")
+ canRemoveTopicFeaturedLink;
+ @not("model.isPrivateMessage") showCategoryChooser;
+ @or("model.errorHtml", "model.errorMessage") hasError;
+ @not("hasError") noErrorYet;
+ @alias("site.categoriesList") categories;
+ @alias("selectedPostIds.length") selectedPostsCount;
+ @alias("selectedAllPosts") canDeselectAll;
+ @or("model.postStream.loadedAllPosts", "model.postStream.loadingLastPost")
+ loadedAllPosts;
+
+ multiSelect = false;
+ selectedPostIds = [];
+ editingTopic = false;
+ enteredAt = null;
+ enteredIndex = null;
+ retrying = false;
+ userTriggeredProgress = null;
+ hasScrolled = null;
+ username_filters = null;
+ replies_to_post_number = null;
+ filter = null;
+ quoteState = new QuoteState();
+ currentPostId = null;
+ userLastReadPostNumber = null;
+ highestPostNumber = null;
+ _progressIndex = null;
+ _retryInProgress = false;
+ _retryRateLimited = false;
+ _newPostsInStream = [];
init() {
- this._super(...arguments);
-
- this._retryInProgress = false;
- this._retryRateLimited = false;
- this._newPostsInStream = [];
+ super.init(...arguments);
this.appEvents.on("post:show-revision", this, "_showRevision");
this.appEvents.on("post:created", this, () => {
this._removeDeleteOnOwnerReplyBookmarks();
this.appEvents.trigger("post-stream:refresh", { force: true });
});
-
- this.setProperties({
- selectedPostIds: [],
- quoteState: new QuoteState(),
- });
- },
+ }
willDestroy() {
- this._super(...arguments);
-
+ super.willDestroy(...arguments);
this.appEvents.off("post:show-revision", this, "_showRevision");
- },
-
- canRemoveTopicFeaturedLink: and(
- "canEditTopicFeaturedLink",
- "buffered.featured_link"
- ),
+ }
updateQueryParams() {
const filters = this.get("model.postStream.streamFilters");
@@ -133,7 +129,7 @@ export default Controller.extend(bufferedProperty("model"), {
replies_to_post_number: null,
});
}
- },
+ }
@observes("model.title", "category")
_titleChanged() {
@@ -142,17 +138,17 @@ export default Controller.extend(bufferedProperty("model"), {
// force update lazily loaded titles
this.send("refreshTitle");
}
- },
+ }
@discourseComputed("model.postStream.loaded", "model.is_shared_draft")
showSharedDraftControls(loaded, isSharedDraft) {
return loaded && isSharedDraft;
- },
+ }
@discourseComputed("site.mobileView", "model.posts_count")
showSelectedPostsAtBottom(mobileView, postsCount) {
return mobileView && postsCount > 3;
- },
+ }
@discourseComputed(
"model.postStream.posts",
@@ -160,17 +156,17 @@ export default Controller.extend(bufferedProperty("model"), {
)
postsToRender(posts, postsWithPlaceholders) {
return this.capabilities.isAndroid ? posts : postsWithPlaceholders;
- },
+ }
@discourseComputed("model.postStream.loadingFilter")
androidLoading(loading) {
return this.capabilities.isAndroid && loading;
- },
+ }
@discourseComputed("model")
pmPath(topic) {
return this.currentUser && this.currentUser.pmPath(topic);
- },
+ }
_showRevision(postNumber, revision) {
const post = this.model.get("postStream").postForPostNumber(postNumber);
@@ -178,9 +174,7 @@ export default Controller.extend(bufferedProperty("model"), {
if (post && post.version > 1 && post.can_view_edit_history) {
schedule("afterRender", () => this.send("showHistory", post, revision));
}
- },
-
- showCategoryChooser: not("model.isPrivateMessage"),
+ }
gotoInbox(name) {
let url = userPath(`${this.get("currentUser.username_lower")}/messages`);
@@ -190,12 +184,12 @@ export default Controller.extend(bufferedProperty("model"), {
}
DiscourseURL.routeTo(url);
- },
+ }
@discourseComputed
selectedQuery() {
return (post) => this.postSelected(post);
- },
+ }
@discourseComputed("model.isPrivateMessage", "model.category.id")
canEditTopicFeaturedLink(isPrivateMessage, categoryId) {
@@ -215,12 +209,12 @@ export default Controller.extend(bufferedProperty("model"), {
!categoryIds.length ||
categoryIds.includes(categoryId)
);
- },
+ }
@discourseComputed("model")
featuredLinkDomain(topic) {
return extractLinkMeta(topic).domain;
- },
+ }
@discourseComputed("model.isPrivateMessage")
canEditTags(isPrivateMessage) {
@@ -228,22 +222,22 @@ export default Controller.extend(bufferedProperty("model"), {
this.site.get("can_tag_topics") &&
(!isPrivateMessage || this.site.get("can_tag_pms"))
);
- },
+ }
@discourseComputed("currentUser.can_send_private_messages")
canSendPms() {
return this.currentUser?.can_send_private_messages;
- },
+ }
@discourseComputed("buffered.category_id")
minimumRequiredTags(categoryId) {
return Category.findById(categoryId)?.minimumRequiredTags || 0;
- },
+ }
@discourseComputed("model.posts_count", "model.postStream.loadingFilter")
showBottomTopicMap(postsCount, loading) {
return !loading && postsCount > MIN_POSTS_COUNT;
- },
+ }
_removeDeleteOnOwnerReplyBookmarks() {
// the user has already navigated away from the topic. the PostCreator
@@ -278,11 +272,11 @@ export default Controller.extend(bufferedProperty("model"), {
) {
this.model.removeBookmark(forTopicBookmark.id);
}
- },
+ }
_forceRefreshPostStream() {
this.appEvents.trigger("post-stream:refresh", { force: true });
- },
+ }
_updateSelectedPostIds(postIds) {
const smallActionsPostIds = this._smallActionPostIds();
@@ -291,7 +285,7 @@ export default Controller.extend(bufferedProperty("model"), {
);
this.set("selectedPostIds", [...new Set(this.selectedPostIds)]);
this._forceRefreshPostStream();
- },
+ }
_smallActionPostIds() {
const smallActionsPostIds = new Set();
@@ -309,7 +303,7 @@ export default Controller.extend(bufferedProperty("model"), {
});
}
return smallActionsPostIds;
- },
+ }
_loadPostIds(post) {
if (this.loadingPostIds) {
@@ -334,7 +328,7 @@ export default Controller.extend(bufferedProperty("model"), {
.finally(() => {
this.set("loadingPostIds", false);
});
- },
+ }
@action
editTopic(event) {
@@ -342,7 +336,7 @@ export default Controller.extend(bufferedProperty("model"), {
if (this.get("model.details.can_edit")) {
this.set("editingTopic", true);
}
- },
+ }
@action
jumpTop(event) {
@@ -355,13 +349,13 @@ export default Controller.extend(bufferedProperty("model"), {
skipIfOnScreen: false,
keepFilter: true,
});
- },
+ }
@action
removeFeaturedLink(event) {
event?.preventDefault();
this.set("buffered.featured_link", null);
- },
+ }
@action
selectAll(event) {
@@ -373,845 +367,905 @@ export default Controller.extend(bufferedProperty("model"), {
),
]);
this._forceRefreshPostStream();
- },
+ }
@action
deselectAll(event) {
event?.preventDefault();
this.set("selectedPostIds", []);
this._forceRefreshPostStream();
- },
+ }
@action
toggleMultiSelect(event) {
event?.preventDefault();
this.toggleProperty("multiSelect");
this._forceRefreshPostStream();
- },
-
- actions: {
- topicCategoryChanged(categoryId) {
- this.set("buffered.category_id", categoryId);
- },
-
- topicTagsChanged(value) {
- this.set("buffered.tags", value);
- },
-
- deletePending(pending) {
- return ajax(`/review/${pending.id}`, { type: "DELETE" })
- .then(() => {
- this.get("model.pending_posts").removeObject(pending);
- })
- .catch(popupAjaxError);
- },
-
- showPostFlags(post) {
- return this.send("showFlags", post);
- },
-
- openFeatureTopic() {
- this.send("showFeatureTopic");
- },
-
- selectText() {
- const { postId, buffer, opts } = this.quoteState;
- const loadedPost = this.get("model.postStream").findLoadedPost(postId);
- const promise = loadedPost
- ? Promise.resolve(loadedPost)
- : this.get("model.postStream").loadPost(postId);
-
- return promise.then((post) => {
- const composer = this.composer;
- const viewOpen = composer.get("model.viewOpen");
-
- // If we can't create a post, delegate to reply as new topic
- if (!viewOpen && !this.get("model.details.can_create_post")) {
- this.send("replyAsNewTopic", post);
- return;
- }
+ }
- const composerOpts = {
- action: Composer.REPLY,
- draftSequence: post.get("topic.draft_sequence"),
- draftKey: post.get("topic.draft_key"),
- };
+ @action
+ topicCategoryChanged(categoryId) {
+ this.set("buffered.category_id", categoryId);
+ }
- if (post.get("post_number") === 1) {
- composerOpts.topic = post.get("topic");
- } else {
- composerOpts.post = post;
- }
+ @action
+ topicTagsChanged(value) {
+ this.set("buffered.tags", value);
+ }
- // If the composer is associated with a different post, we don't change it.
- const composerPost = composer.get("model.post");
- if (composerPost && composerPost.get("id") !== this.get("post.id")) {
- composerOpts.post = composerPost;
- }
+ @action
+ deletePending(pending) {
+ return ajax(`/review/${pending.id}`, { type: "DELETE" })
+ .then(() => {
+ this.get("model.pending_posts").removeObject(pending);
+ })
+ .catch(popupAjaxError);
+ }
- const quotedText = buildQuote(post, buffer, opts);
- composerOpts.quote = quotedText;
+ @action
+ showPostFlags(post) {
+ return this.send("showFlags", post);
+ }
- if (composer.get("model.viewOpen")) {
- this.appEvents.trigger("composer:insert-block", quotedText);
- } else if (composer.get("model.viewDraft")) {
- const model = composer.get("model");
- model.set("reply", model.get("reply") + "\n" + quotedText);
- composer.openIfDraft();
- } else {
- composer.open(composerOpts);
- }
- });
- },
+ @action
+ openFeatureTopic() {
+ this.send("showFeatureTopic");
+ }
- fillGapBefore(args) {
- return this.get("model.postStream").fillGapBefore(args.post, args.gap);
- },
+ @action
+ selectText() {
+ const { postId, buffer, opts } = this.quoteState;
+ const loadedPost = this.get("model.postStream").findLoadedPost(postId);
+ const promise = loadedPost
+ ? Promise.resolve(loadedPost)
+ : this.get("model.postStream").loadPost(postId);
- fillGapAfter(args) {
- return this.get("model.postStream").fillGapAfter(args.post, args.gap);
- },
+ return promise.then((post) => {
+ const composer = this.composer;
+ const viewOpen = composer.get("model.viewOpen");
- currentPostChanged(event) {
- const { post } = event;
- if (!post) {
+ // If we can't create a post, delegate to reply as new topic
+ if (!viewOpen && !this.get("model.details.can_create_post")) {
+ this.send("replyAsNewTopic", post);
return;
}
- this.set("currentPostId", post.id);
- const postNumber = post.get("post_number");
- const topic = this.model;
- topic.set("currentPost", postNumber);
- if (postNumber > (topic.get("last_read_post_number") || 0)) {
- topic.set("last_read_post_id", post.get("id"));
- topic.set("last_read_post_number", postNumber);
- }
+ const composerOpts = {
+ action: Composer.REPLY,
+ draftSequence: post.get("topic.draft_sequence"),
+ draftKey: post.get("topic.draft_key"),
+ };
- this.send("postChangedRoute", postNumber);
- this._progressIndex = topic.get("postStream").progressIndexOfPost(post);
+ if (post.get("post_number") === 1) {
+ composerOpts.topic = post.get("topic");
+ } else {
+ composerOpts.post = post;
+ }
- this.appEvents.trigger("topic:current-post-changed", { post });
- },
+ // If the composer is associated with a different post, we don't change it.
+ const composerPost = composer.get("model.post");
+ if (composerPost && composerPost.get("id") !== this.get("post.id")) {
+ composerOpts.post = composerPost;
+ }
- currentPostScrolled(event) {
- const total = this.get("model.postStream.filteredPostsCount");
- const percent =
- parseFloat(this._progressIndex + event.percent - 1) / total;
- this.appEvents.trigger("topic:current-post-scrolled", {
- postIndex: this._progressIndex,
- percent: Math.max(Math.min(percent, 1.0), 0.0),
- });
- },
+ const quotedText = buildQuote(post, buffer, opts);
+ composerOpts.quote = quotedText;
- // Called when the topmost visible post on the page changes.
- topVisibleChanged(event) {
- const { post, refresh } = event;
- if (!post) {
- return;
+ if (composer.get("model.viewOpen")) {
+ this.appEvents.trigger("composer:insert-block", quotedText);
+ } else if (composer.get("model.viewDraft")) {
+ const model = composer.get("model");
+ model.set("reply", model.get("reply") + "\n" + quotedText);
+ composer.openIfDraft();
+ } else {
+ composer.open(composerOpts);
}
+ });
+ }
- const postStream = this.get("model.postStream");
- const firstLoadedPost = postStream.get("posts.firstObject");
+ @action
+ fillGapBefore(args) {
+ return this.get("model.postStream").fillGapBefore(args.post, args.gap);
+ }
- if (post.get && post.get("post_number") === 1) {
- return;
- }
+ @action
+ fillGapAfter(args) {
+ return this.get("model.postStream").fillGapAfter(args.post, args.gap);
+ }
- if (firstLoadedPost && firstLoadedPost === post) {
- postStream.prependMore().then(() => refresh());
- }
- },
+ @action
+ currentPostChanged(event) {
+ const { post } = event;
+ if (!post) {
+ return;
+ }
- // Called the bottommost visible post on the page changes.
- bottomVisibleChanged(event) {
- const { post, refresh } = event;
+ this.set("currentPostId", post.id);
+ const postNumber = post.get("post_number");
+ const topic = this.model;
+ topic.set("currentPost", postNumber);
+ if (postNumber > (topic.get("last_read_post_number") || 0)) {
+ topic.set("last_read_post_id", post.get("id"));
+ topic.set("last_read_post_number", postNumber);
+ }
- const postStream = this.get("model.postStream");
- const lastLoadedPost = postStream.get("posts.lastObject");
+ this.send("postChangedRoute", postNumber);
+ this._progressIndex = topic.get("postStream").progressIndexOfPost(post);
- if (
- lastLoadedPost &&
- lastLoadedPost === post &&
- postStream.get("canAppendMore")
- ) {
- postStream.appendMore().then(() => refresh());
- // show loading stuff
- refresh();
- }
- },
+ this.appEvents.trigger("topic:current-post-changed", { post });
+ }
- showTopReplies() {
- return this.get("model.postStream")
- .showTopReplies()
- .then(() => {
- this.updateQueryParams();
- });
- },
+ @action
+ currentPostScrolled(event) {
+ const total = this.get("model.postStream.filteredPostsCount");
+ const percent = parseFloat(this._progressIndex + event.percent - 1) / total;
+ this.appEvents.trigger("topic:current-post-scrolled", {
+ postIndex: this._progressIndex,
+ percent: Math.max(Math.min(percent, 1.0), 0.0),
+ });
+ }
- cancelFilter(nearestPost = null) {
- const postStream = this.get("model.postStream");
+ // Called when the topmost visible post on the page changes.
+ @action
+ topVisibleChanged(event) {
+ const { post, refresh } = event;
+ if (!post) {
+ return;
+ }
- if (!nearestPost) {
- const loadedPost = postStream.findLoadedPost(this.currentPostId);
- if (loadedPost) {
- nearestPost = loadedPost.post_number;
- } else {
- postStream.findPostsByIds([this.currentPostId]).then((arr) => {
- nearestPost = arr[0].post_number;
- });
- }
- }
+ const postStream = this.get("model.postStream");
+ const firstLoadedPost = postStream.get("posts.firstObject");
- postStream.cancelFilter();
- postStream
- .refresh({
- nearPost: nearestPost,
- forceLoad: true,
- })
- .then(() => {
- DiscourseURL.routeTo(this.model.urlForPostNumber(nearestPost));
- this.updateQueryParams();
- });
- },
-
- removeAllowedUser(user) {
- return this.get("model.details")
- .removeAllowedUser(user)
- .then(() => {
- if (this.currentUser.id === user.id) {
- this.router.transitionTo("userPrivateMessages", user);
- }
- });
- },
+ if (post.get && post.get("post_number") === 1) {
+ return;
+ }
- removeAllowedGroup(group) {
- return this.get("model.details").removeAllowedGroup(group);
- },
+ if (firstLoadedPost && firstLoadedPost === post) {
+ postStream.prependMore().then(() => refresh());
+ }
+ }
- deleteTopic(opts = {}) {
- this.deleteTopic(opts);
- },
+ // Called the bottommost visible post on the page changes.
+ @action
+ bottomVisibleChanged(event) {
+ const { post, refresh } = event;
- // Archive a PM (as opposed to archiving a topic)
- toggleArchiveMessage() {
- const topic = this.model;
+ const postStream = this.get("model.postStream");
+ const lastLoadedPost = postStream.get("posts.lastObject");
- if (!topic || topic.get("archiving") || !topic.isPrivateMessage) {
- return;
- }
+ if (
+ lastLoadedPost &&
+ lastLoadedPost === post &&
+ postStream.get("canAppendMore")
+ ) {
+ postStream.appendMore().then(() => refresh());
+ // show loading stuff
+ refresh();
+ }
+ }
- const backToInbox = () => {
- resetCachedTopicList(this.session);
- this.gotoInbox(topic.get("inboxGroupName"));
- };
+ @action
+ showTopReplies() {
+ return this.get("model.postStream")
+ .showTopReplies()
+ .then(() => {
+ this.updateQueryParams();
+ });
+ }
- if (topic.get("message_archived")) {
- topic.moveToInbox().then(backToInbox);
+ @action
+ cancelFilter(nearestPost = null) {
+ const postStream = this.get("model.postStream");
+
+ if (!nearestPost) {
+ const loadedPost = postStream.findLoadedPost(this.currentPostId);
+ if (loadedPost) {
+ nearestPost = loadedPost.post_number;
} else {
- topic.archiveMessage().then(backToInbox);
+ postStream.findPostsByIds([this.currentPostId]).then((arr) => {
+ nearestPost = arr[0].post_number;
+ });
}
- },
+ }
- deferTopic() {
- const { screenTrack, currentUser } = this;
- const topic = this.model;
+ postStream.cancelFilter();
+ postStream
+ .refresh({
+ nearPost: nearestPost,
+ forceLoad: true,
+ })
+ .then(() => {
+ DiscourseURL.routeTo(this.model.urlForPostNumber(nearestPost));
+ this.updateQueryParams();
+ });
+ }
- screenTrack.reset();
- screenTrack.stop();
- const goToPath = topic.get("isPrivateMessage")
- ? currentUser.pmPath(topic)
- : "/";
- ajax("/t/" + topic.get("id") + "/timings.json?last=1", { type: "DELETE" })
- .then(() => {
- const highestSeenByTopic = this.session.get("highestSeenByTopic");
- highestSeenByTopic[topic.get("id")] = null;
- DiscourseURL.routeTo(goToPath);
- })
- .catch(popupAjaxError);
- },
-
- editFirstPost() {
- this.model
- .firstPost()
- .then((firstPost) => this.send("editPost", firstPost));
- },
-
- // Post related methods
- replyToPost(post) {
- const composerController = this.composer;
- const topic = post ? post.get("topic") : this.model;
- const quoteState = this.quoteState;
- const postStream = this.get("model.postStream");
-
- this.appEvents.trigger("page:compose-reply", topic);
-
- if (!postStream || !topic || !topic.get("details.can_create_post")) {
- return;
- }
+ @action
+ removeAllowedUser(user) {
+ return this.get("model.details")
+ .removeAllowedUser(user)
+ .then(() => {
+ if (this.currentUser.id === user.id) {
+ this.router.transitionTo("userPrivateMessages", user);
+ }
+ });
+ }
- const quotedPost = postStream.findLoadedPost(quoteState.postId);
- const quotedText = buildQuote(
- quotedPost,
- quoteState.buffer,
- quoteState.opts
- );
+ @action
+ removeAllowedGroup(group) {
+ return this.get("model.details").removeAllowedGroup(group);
+ }
- quoteState.clear();
+ // Archive a PM (as opposed to archiving a topic)
+ @action
+ toggleArchiveMessage() {
+ const topic = this.model;
- if (
- composerController.get("model.topic.id") === topic.get("id") &&
- composerController.get("model.action") === Composer.REPLY &&
- post?.get("post_number") !== 1
- ) {
- composerController.set("model.post", post);
- composerController.set("model.composeState", Composer.OPEN);
- this.appEvents.trigger("composer:insert-block", quotedText.trim());
- } else {
- const opts = {
- action: Composer.REPLY,
- draftKey: topic.get("draft_key"),
- draftSequence: topic.get("draft_sequence"),
- };
-
- if (quotedText) {
- opts.quote = quotedText;
- }
+ if (!topic || topic.get("archiving") || !topic.isPrivateMessage) {
+ return;
+ }
- if (post && post.get("post_number") !== 1) {
- opts.post = post;
- } else {
- opts.topic = topic;
- }
+ const backToInbox = () => {
+ resetCachedTopicList(this.session);
+ this.gotoInbox(topic.get("inboxGroupName"));
+ };
- composerController.open(opts);
- }
- return false;
- },
+ if (topic.get("message_archived")) {
+ topic.moveToInbox().then(backToInbox);
+ } else {
+ topic.archiveMessage().then(backToInbox);
+ }
+ }
- recoverPost(post) {
- post.get("post_number") === 1 ? this.recoverTopic() : post.recover();
- },
+ @action
+ deferTopic() {
+ const { screenTrack, currentUser } = this;
+ const topic = this.model;
- deletePost(post, opts) {
- if (post.get("post_number") === 1) {
- return this.deleteTopic(opts);
- } else if (
- (!opts?.force_destroy && !post.can_delete) ||
- (opts?.force_destroy && !post.can_permanently_delete)
- ) {
- return false;
+ screenTrack.reset();
+ screenTrack.stop();
+ const goToPath = topic.get("isPrivateMessage")
+ ? currentUser.pmPath(topic)
+ : "/";
+ ajax("/t/" + topic.get("id") + "/timings.json?last=1", { type: "DELETE" })
+ .then(() => {
+ const highestSeenByTopic = this.session.get("highestSeenByTopic");
+ highestSeenByTopic[topic.get("id")] = null;
+ DiscourseURL.routeTo(goToPath);
+ })
+ .catch(popupAjaxError);
+ }
+
+ @action
+ editFirstPost() {
+ this.model
+ .firstPost()
+ .then((firstPost) => this.send("editPost", firstPost));
+ }
+
+ // Post related methods
+ @action
+ replyToPost(post) {
+ const composerController = this.composer;
+ const topic = post ? post.get("topic") : this.model;
+ const quoteState = this.quoteState;
+ const postStream = this.get("model.postStream");
+
+ this.appEvents.trigger("page:compose-reply", topic);
+
+ if (!postStream || !topic || !topic.get("details.can_create_post")) {
+ return;
+ }
+
+ const quotedPost = postStream.findLoadedPost(quoteState.postId);
+ const quotedText = buildQuote(
+ quotedPost,
+ quoteState.buffer,
+ quoteState.opts
+ );
+
+ quoteState.clear();
+
+ if (
+ composerController.get("model.topic.id") === topic.get("id") &&
+ composerController.get("model.action") === Composer.REPLY &&
+ post?.get("post_number") !== 1
+ ) {
+ composerController.set("model.post", post);
+ composerController.set("model.composeState", Composer.OPEN);
+ this.appEvents.trigger("composer:insert-block", quotedText.trim());
+ } else {
+ const opts = {
+ action: Composer.REPLY,
+ draftKey: topic.get("draft_key"),
+ draftSequence: topic.get("draft_sequence"),
+ };
+
+ if (quotedText) {
+ opts.quote = quotedText;
}
- const user = this.currentUser;
- const refresh = () => this.appEvents.trigger("post-stream:refresh");
- const hasReplies = post.get("reply_count") > 0;
- const loadedPosts = this.get("model.postStream.posts");
+ if (post && post.get("post_number") !== 1) {
+ opts.post = post;
+ } else {
+ opts.topic = topic;
+ }
- if (user.get("staff") && hasReplies) {
- ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {
- if (replies.length === 0) {
- return post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
- }
+ composerController.open(opts);
+ }
+ return false;
+ }
+
+ @action
+ recoverPost(post) {
+ post.get("post_number") === 1 ? this.recoverTopic() : post.recover();
+ }
- const buttons = [];
+ @action
+ deletePost(post, opts) {
+ if (post.get("post_number") === 1) {
+ return this.deleteTopic(opts);
+ } else if (
+ (!opts?.force_destroy && !post.can_delete) ||
+ (opts?.force_destroy && !post.can_permanently_delete)
+ ) {
+ return false;
+ }
- const directReplyIds = replies
- .filter((r) => r.level === 1)
- .map((r) => r.id);
+ const user = this.currentUser;
+ const refresh = () => this.appEvents.trigger("post-stream:refresh");
+ const hasReplies = post.get("reply_count") > 0;
+ const loadedPosts = this.get("model.postStream.posts");
+ if (user.get("staff") && hasReplies) {
+ ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {
+ if (replies.length === 0) {
+ return post
+ .destroy(user, opts)
+ .then(refresh)
+ .catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
+ }
+
+ const buttons = [];
+
+ const directReplyIds = replies
+ .filter((r) => r.level === 1)
+ .map((r) => r.id);
+
+ buttons.push({
+ label: I18n.t("post.controls.delete_replies.direct_replies", {
+ count: directReplyIds.length,
+ }),
+ class: "btn-primary",
+ action: () => {
+ loadedPosts.forEach(
+ (p) =>
+ (p === post || directReplyIds.includes(p.id)) &&
+ p.setDeletedState(user)
+ );
+ Post.deleteMany([post.id, ...directReplyIds])
+ .then(refresh)
+ .catch(popupAjaxError);
+ },
+ });
+
+ if (replies.some((r) => r.level > 1)) {
buttons.push({
- label: I18n.t("post.controls.delete_replies.direct_replies", {
- count: directReplyIds.length,
+ label: I18n.t("post.controls.delete_replies.all_replies", {
+ count: replies.length,
}),
- class: "btn-primary",
action: () => {
loadedPosts.forEach(
(p) =>
- (p === post || directReplyIds.includes(p.id)) &&
+ (p === post || replies.some((r) => r.id === p.id)) &&
p.setDeletedState(user)
);
- Post.deleteMany([post.id, ...directReplyIds])
+ Post.deleteMany([post.id, ...replies.map((r) => r.id)])
.then(refresh)
.catch(popupAjaxError);
},
});
+ }
- if (replies.some((r) => r.level > 1)) {
- buttons.push({
- label: I18n.t("post.controls.delete_replies.all_replies", {
- count: replies.length,
- }),
- action: () => {
- loadedPosts.forEach(
- (p) =>
- (p === post || replies.some((r) => r.id === p.id)) &&
- p.setDeletedState(user)
- );
- Post.deleteMany([post.id, ...replies.map((r) => r.id)])
- .then(refresh)
- .catch(popupAjaxError);
- },
- });
- }
-
- buttons.push({
- label: I18n.t("post.controls.delete_replies.just_the_post"),
- action: () => {
- post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
- },
- });
-
- buttons.push({
- label: I18n.t("cancel"),
- class: "btn-flat",
- });
+ buttons.push({
+ label: I18n.t("post.controls.delete_replies.just_the_post"),
+ action: () => {
+ post
+ .destroy(user, opts)
+ .then(refresh)
+ .catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
+ },
+ });
- this.dialog.alert({
- title: I18n.t("post.controls.delete_replies.confirm"),
- buttons,
- });
+ buttons.push({
+ label: I18n.t("cancel"),
+ class: "btn-flat",
});
- } else {
- return post
- .destroy(user, opts)
- .then(refresh)
- .catch((error) => {
- popupAjaxError(error);
- post.undoDeleteState();
- });
- }
- },
- deletePostWithConfirmation(post, opts) {
- this.dialog.yesNoConfirm({
- message: I18n.t("post.confirm_delete"),
- didConfirm: () => this.send("deletePost", post, opts),
+ this.dialog.alert({
+ title: I18n.t("post.controls.delete_replies.confirm"),
+ buttons,
+ });
});
- },
+ } else {
+ return post
+ .destroy(user, opts)
+ .then(refresh)
+ .catch((error) => {
+ popupAjaxError(error);
+ post.undoDeleteState();
+ });
+ }
+ }
- permanentlyDeletePost(post) {
- return this.dialog.yesNoConfirm({
- message: I18n.t("post.controls.permanently_delete_confirmation"),
- didConfirm: () => {
- this.send("deletePost", post, { force_destroy: true });
- },
- });
- },
+ @action
+ deletePostWithConfirmation(post, opts) {
+ this.dialog.yesNoConfirm({
+ message: I18n.t("post.confirm_delete"),
+ didConfirm: () => this.send("deletePost", post, opts),
+ });
+ }
- editPost(post) {
- if (!this.currentUser) {
- return this.dialog.alert(I18n.t("post.controls.edit_anonymous"));
- } else if (!post.can_edit) {
- return false;
- }
+ @action
+ permanentlyDeletePost(post) {
+ return this.dialog.yesNoConfirm({
+ message: I18n.t("post.controls.permanently_delete_confirmation"),
+ didConfirm: () => {
+ this.send("deletePost", post, { force_destroy: true });
+ },
+ });
+ }
- const composer = this.composer;
- let topic = this.model;
- const composerModel = composer.get("model");
- let editingFirst =
- composerModel &&
- (post.get("firstPost") || composerModel.get("editingFirstPost"));
-
- let editingSharedDraft = false;
- let draftsCategoryId = this.get("site.shared_drafts_category_id");
- if (draftsCategoryId && draftsCategoryId === topic.get("category.id")) {
- editingSharedDraft = post.get("firstPost");
- }
+ @action
+ editPost(post) {
+ if (!this.currentUser) {
+ return this.dialog.alert(I18n.t("post.controls.edit_anonymous"));
+ } else if (!post.can_edit) {
+ return false;
+ }
- const opts = {
- post,
- action: editingSharedDraft ? Composer.EDIT_SHARED_DRAFT : Composer.EDIT,
- draftKey: post.get("topic.draft_key"),
- draftSequence: post.get("topic.draft_sequence"),
- };
+ const composer = this.composer;
+ let topic = this.model;
+ const composerModel = composer.get("model");
+ let editingFirst =
+ composerModel &&
+ (post.get("firstPost") || composerModel.get("editingFirstPost"));
+
+ let editingSharedDraft = false;
+ let draftsCategoryId = this.get("site.shared_drafts_category_id");
+ if (draftsCategoryId && draftsCategoryId === topic.get("category.id")) {
+ editingSharedDraft = post.get("firstPost");
+ }
- if (editingSharedDraft) {
- opts.destinationCategoryId = topic.get("destination_category_id");
- }
+ const opts = {
+ post,
+ action: editingSharedDraft ? Composer.EDIT_SHARED_DRAFT : Composer.EDIT,
+ draftKey: post.get("topic.draft_key"),
+ draftSequence: post.get("topic.draft_sequence"),
+ };
- // Reopen the composer if we're editing the same post
- const editingExisting =
- post.id === composerModel?.post?.id &&
- opts?.action === Composer.EDIT &&
- composerModel?.draftKey === opts.draftKey;
- if (editingExisting) {
- composer.unshrink();
- return;
- }
+ if (editingSharedDraft) {
+ opts.destinationCategoryId = topic.get("destination_category_id");
+ }
- // Cancel and reopen the composer for the first post
- if (editingFirst) {
- composer.cancelComposer(opts).then(() => composer.open(opts));
- } else {
- composer.open(opts);
- }
- },
-
- toggleBookmark(post) {
- if (!this.currentUser) {
- return this.dialog.alert(I18n.t("bookmarks.not_bookmarked"));
- } else if (post) {
- const bookmarkForPost = this.model.bookmarks.find(
- (bookmark) =>
- bookmark.bookmarkable_id === post.id &&
- bookmark.bookmarkable_type === "Post"
- );
- return this._modifyPostBookmark(
- bookmarkForPost ||
- Bookmark.createFor(this.currentUser, "Post", post.id),
- post
+ // Reopen the composer if we're editing the same post
+ const editingExisting =
+ post.id === composerModel?.post?.id &&
+ opts?.action === Composer.EDIT &&
+ composerModel?.draftKey === opts.draftKey;
+ if (editingExisting) {
+ composer.unshrink();
+ return;
+ }
+
+ // Cancel and reopen the composer for the first post
+ if (editingFirst) {
+ composer.cancelComposer(opts).then(() => composer.open(opts));
+ } else {
+ composer.open(opts);
+ }
+ }
+
+ @action
+ toggleBookmark(post) {
+ if (!this.currentUser) {
+ return this.dialog.alert(I18n.t("bookmarks.not_bookmarked"));
+ } else if (post) {
+ const bookmarkForPost = this.model.bookmarks.find(
+ (bookmark) =>
+ bookmark.bookmarkable_id === post.id &&
+ bookmark.bookmarkable_type === "Post"
+ );
+ return this._modifyPostBookmark(
+ bookmarkForPost ||
+ Bookmark.createFor(this.currentUser, "Post", post.id),
+ post
+ );
+ } else {
+ return this._toggleTopicLevelBookmark().then((changedIds) => {
+ if (!changedIds) {
+ return;
+ }
+ changedIds.forEach((id) =>
+ this.appEvents.trigger("post-stream:refresh", { id })
);
- } else {
- return this._toggleTopicLevelBookmark().then((changedIds) => {
- if (!changedIds) {
- return;
- }
- changedIds.forEach((id) =>
- this.appEvents.trigger("post-stream:refresh", { id })
- );
- });
- }
- },
+ });
+ }
+ }
- jumpToIndex(index) {
- this._jumpToIndex(index);
- },
+ @action
+ jumpToIndex(index) {
+ this._jumpToIndex(index);
+ }
- jumpToDate(date) {
- this._jumpToDate(date);
- },
+ @action
+ jumpToDate(date) {
+ this._jumpToDate(date);
+ }
- jumpToPostPrompt() {
- this.modal.show(JumpToPost, {
- model: {
- topic: this.model,
- jumpToIndex: (index) => this.send("jumpToIndex", index),
- jumpToDate: (date) => this.send("jumpToDate", date),
- },
- });
- },
+ @action
+ jumpToPostPrompt() {
+ this.modal.show(JumpToPost, {
+ model: {
+ topic: this.model,
+ jumpToIndex: (index) => this.send("jumpToIndex", index),
+ jumpToDate: (date) => this.send("jumpToDate", date),
+ },
+ });
+ }
- jumpToPost(postNumber) {
- this._jumpToPostNumber(postNumber);
- },
+ @action
+ jumpToPost(postNumber) {
+ this._jumpToPostNumber(postNumber);
+ }
- jumpBottom() {
- // When a topic only has one lengthy post
- const jumpEnd = this.model.highest_post_number === 1 ? true : false;
+ @action
+ jumpBottom() {
+ // When a topic only has one lengthy post
+ const jumpEnd = this.model.highest_post_number === 1 ? true : false;
- DiscourseURL.routeTo(this.get("model.lastPostUrl"), {
- skipIfOnScreen: false,
- jumpEnd,
- keepFilter: true,
- });
- },
+ DiscourseURL.routeTo(this.get("model.lastPostUrl"), {
+ skipIfOnScreen: false,
+ jumpEnd,
+ keepFilter: true,
+ });
+ }
- jumpEnd() {
- this.appEvents.trigger(
- "topic:jump-to-post",
- this.get("model.highest_post_number")
- );
- DiscourseURL.routeTo(this.get("model.lastPostUrl"), {
- jumpEnd: true,
- keepFilter: true,
- });
- },
+ @action
+ jumpEnd() {
+ this.appEvents.trigger(
+ "topic:jump-to-post",
+ this.get("model.highest_post_number")
+ );
+ DiscourseURL.routeTo(this.get("model.lastPostUrl"), {
+ jumpEnd: true,
+ keepFilter: true,
+ });
+ }
- jumpUnread() {
- this._jumpToPostId(this.get("model.last_read_post_id"));
- },
+ @action
+ jumpUnread() {
+ this._jumpToPostId(this.get("model.last_read_post_id"));
+ }
- jumpToPostId(postId) {
- this._jumpToPostId(postId);
- },
+ @action
+ jumpToPostId(postId) {
+ this._jumpToPostId(postId);
+ }
- togglePostSelection(post) {
- const selected = this.selectedPostIds;
- selected.includes(post.id)
- ? selected.removeObject(post.id)
- : selected.addObject(post.id);
- },
+ @action
+ togglePostSelection(post) {
+ const selected = this.selectedPostIds;
+ selected.includes(post.id)
+ ? selected.removeObject(post.id)
+ : selected.addObject(post.id);
+ }
- selectReplies(post) {
- ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {
- const replyIds = replies.map((r) => r.id);
- const postIds = [...this.selectedPostIds, post.id, ...replyIds];
- this.set("selectedPostIds", [...new Set(postIds)]);
- this._forceRefreshPostStream();
- });
- },
+ @action
+ selectReplies(post) {
+ ajax(`/posts/${post.id}/reply-ids.json`).then((replies) => {
+ const replyIds = replies.map((r) => r.id);
+ const postIds = [...this.selectedPostIds, post.id, ...replyIds];
+ this.set("selectedPostIds", [...new Set(postIds)]);
+ this._forceRefreshPostStream();
+ });
+ }
- selectBelow(post) {
- if (this.get("model.postStream.isMegaTopic")) {
- this._loadPostIds(post);
- } else {
- const stream = [...this.get("model.postStream.stream")];
- const below = stream.slice(stream.indexOf(post.id));
- this._updateSelectedPostIds(below);
- }
- },
+ @action
+ selectBelow(post) {
+ if (this.get("model.postStream.isMegaTopic")) {
+ this._loadPostIds(post);
+ } else {
+ const stream = [...this.get("model.postStream.stream")];
+ const below = stream.slice(stream.indexOf(post.id));
+ this._updateSelectedPostIds(below);
+ }
+ }
- deleteSelected() {
- const user = this.currentUser;
- this.dialog.yesNoConfirm({
- message: I18n.t("post.delete.confirm", {
- count: this.selectedPostsCount,
- }),
- didConfirm: () => {
- // If all posts are selected, it's the same thing as deleting the topic
- if (this.selectedAllPosts) {
- return this.deleteTopic();
- }
+ @action
+ deleteSelected() {
+ const user = this.currentUser;
+ this.dialog.yesNoConfirm({
+ message: I18n.t("post.delete.confirm", {
+ count: this.selectedPostsCount,
+ }),
+ didConfirm: () => {
+ // If all posts are selected, it's the same thing as deleting the topic
+ if (this.selectedAllPosts) {
+ return this.deleteTopic();
+ }
- Post.deleteMany(this.selectedPostIds);
- this.get("model.postStream.posts").forEach(
- (p) => this.postSelected(p) && p.setDeletedState(user)
- );
- this.send("toggleMultiSelect");
- },
- });
- },
+ Post.deleteMany(this.selectedPostIds);
+ this.get("model.postStream.posts").forEach(
+ (p) => this.postSelected(p) && p.setDeletedState(user)
+ );
+ this.send("toggleMultiSelect");
+ },
+ });
+ }
- mergePosts() {
- this.dialog.yesNoConfirm({
- message: I18n.t("post.merge.confirm", {
- count: this.selectedPostsCount,
- }),
- didConfirm: () => {
- Post.mergePosts(this.selectedPostIds);
- this.send("toggleMultiSelect");
- },
- });
- },
-
- changePostOwner(post) {
- this.set("selectedPostIds", [post.id]);
- this.send("changeOwner");
- },
-
- lockPost(post) {
- return post.updatePostField("locked", true);
- },
-
- unlockPost(post) {
- return post.updatePostField("locked", false);
- },
-
- grantBadge(post) {
- this.set("selectedPostIds", [post.id]);
- this.send("showGrantBadgeModal");
- },
-
- async changeNotice(post) {
- await this.modal.show(ChangePostNoticeModal, { model: { post } });
- },
-
- filterParticipant(user) {
- this.get("model.postStream")
- .filterParticipant(user.username)
- .then(() => this.updateQueryParams);
- },
-
- cancelEditingTopic() {
- this.set("editingTopic", false);
- this.rollbackBuffer();
- },
-
- finishedEditingTopic() {
- if (!this.editingTopic) {
- return;
- }
+ @action
+ mergePosts() {
+ this.dialog.yesNoConfirm({
+ message: I18n.t("post.merge.confirm", {
+ count: this.selectedPostsCount,
+ }),
+ didConfirm: () => {
+ Post.mergePosts(this.selectedPostIds);
+ this.send("toggleMultiSelect");
+ },
+ });
+ }
- // save the modifications
- const props = this.get("buffered.buffer");
+ @action
+ changePostOwner(post) {
+ this.set("selectedPostIds", [post.id]);
+ this.send("changeOwner");
+ }
- Topic.update(this.model, props, { fastEdit: true })
- .then(() => {
- // We roll back on success here because `update` saves the properties to the topic
- this.rollbackBuffer();
- this.set("editingTopic", false);
- })
- .catch(popupAjaxError);
- },
+ @action
+ lockPost(post) {
+ return post.updatePostField("locked", true);
+ }
- expandHidden(post) {
- return post.expandHidden();
- },
+ @action
+ unlockPost(post) {
+ return post.updatePostField("locked", false);
+ }
- toggleVisibility() {
- this.model.toggleStatus("visible");
- },
+ @action
+ grantBadge(post) {
+ this.set("selectedPostIds", [post.id]);
+ this.send("showGrantBadgeModal");
+ }
- toggleClosed() {
- const topic = this.model;
+ @action
+ async changeNotice(post) {
+ await this.modal.show(ChangePostNoticeModal, { model: { post } });
+ }
- this.model.toggleStatus("closed").then((result) => {
- topic.set("topic_status_update", result.topic_status_update);
- });
- },
-
- makeBanner() {
- this.model.makeBanner();
- },
-
- removeBanner() {
- this.model.removeBanner();
- },
-
- togglePinned() {
- const value = this.get("model.pinned_at") ? false : true,
- topic = this.model,
- until = this.get("model.pinnedInCategoryUntil");
-
- // optimistic update
- topic.setProperties({
- pinned_at: value ? moment() : null,
- pinned_globally: false,
- pinned_until: value ? until : null,
- });
+ @action
+ filterParticipant(user) {
+ this.get("model.postStream")
+ .filterParticipant(user.username)
+ .then(() => this.updateQueryParams);
+ }
- return topic.saveStatus("pinned", value, until);
- },
+ @action
+ cancelEditingTopic() {
+ this.set("editingTopic", false);
+ this.rollbackBuffer();
+ }
- pinGlobally() {
- const topic = this.model,
- until = this.get("model.pinnedGloballyUntil");
+ @action
+ finishedEditingTopic() {
+ if (!this.editingTopic) {
+ return;
+ }
- // optimistic update
- topic.setProperties({
- pinned_at: moment(),
- pinned_globally: true,
- pinned_until: until,
- });
+ // save the modifications
+ const props = this.get("buffered.buffer");
- return topic.saveStatus("pinned_globally", true, until);
- },
+ Topic.update(this.model, props, { fastEdit: true })
+ .then(() => {
+ // We roll back on success here because `update` saves the properties to the topic
+ this.rollbackBuffer();
+ this.set("editingTopic", false);
+ })
+ .catch(popupAjaxError);
+ }
- toggleArchived() {
- this.model.toggleStatus("archived");
- },
+ @action
+ expandHidden(post) {
+ return post.expandHidden();
+ }
- clearPin() {
- this.model.clearPin();
- },
+ @action
+ toggleVisibility() {
+ this.model.toggleStatus("visible");
+ }
- togglePinnedForUser() {
- if (this.get("model.pinned_at")) {
- const topic = this.model;
- if (topic.get("pinned")) {
- topic.clearPin();
- } else {
- topic.rePin();
- }
- }
- },
-
- replyAsNewTopic(post) {
- const composerController = this.composer;
- const { quoteState } = this;
- const quotedText = buildQuote(post, quoteState.buffer, quoteState.opts);
-
- quoteState.clear();
-
- let options;
- if (this.get("model.isPrivateMessage")) {
- let users = this.get("model.details.allowed_users");
- let groups = this.get("model.details.allowed_groups");
-
- let recipients = [];
- users.forEach((user) => recipients.push(user.username));
- groups.forEach((group) => recipients.push(group.name));
- recipients = recipients.join();
-
- options = {
- action: Composer.PRIVATE_MESSAGE,
- archetypeId: "private_message",
- draftKey: post.topic.draft_key,
- recipients,
- };
+ @action
+ toggleClosed() {
+ const topic = this.model;
+
+ this.model.toggleStatus("closed").then((result) => {
+ topic.set("topic_status_update", result.topic_status_update);
+ });
+ }
+
+ @action
+ makeBanner() {
+ this.model.makeBanner();
+ }
+
+ @action
+ removeBanner() {
+ this.model.removeBanner();
+ }
+
+ @action
+ togglePinned() {
+ const value = this.get("model.pinned_at") ? false : true,
+ topic = this.model,
+ until = this.get("model.pinnedInCategoryUntil");
+
+ // optimistic update
+ topic.setProperties({
+ pinned_at: value ? moment() : null,
+ pinned_globally: false,
+ pinned_until: value ? until : null,
+ });
+
+ return topic.saveStatus("pinned", value, until);
+ }
+
+ @action
+ pinGlobally() {
+ const topic = this.model,
+ until = this.get("model.pinnedGloballyUntil");
+
+ // optimistic update
+ topic.setProperties({
+ pinned_at: moment(),
+ pinned_globally: true,
+ pinned_until: until,
+ });
+
+ return topic.saveStatus("pinned_globally", true, until);
+ }
+
+ @action
+ toggleArchived() {
+ this.model.toggleStatus("archived");
+ }
+
+ @action
+ clearPin() {
+ this.model.clearPin();
+ }
+
+ @action
+ togglePinnedForUser() {
+ if (this.get("model.pinned_at")) {
+ const topic = this.model;
+ if (topic.get("pinned")) {
+ topic.clearPin();
} else {
- options = {
- action: Composer.CREATE_TOPIC,
- draftKey: post.topic.draft_key,
- topicCategoryId: this.get("model.category.id"),
- prioritizedCategoryId: this.get("model.category.id"),
- };
+ topic.rePin();
}
+ }
+ }
- composerController.open(options).then(() => {
- const title = escapeExpression(this.model.title);
- const postUrl = `${location.protocol}//${location.host}${post.url}`;
- const postLink = `[${title}](${postUrl})`;
- const text = `${I18n.t("post.continue_discussion", {
- postLink,
- })}\n\n${quotedText}`;
+ @action
+ replyAsNewTopic(post) {
+ const composerController = this.composer;
+ const { quoteState } = this;
+ const quotedText = buildQuote(post, quoteState.buffer, quoteState.opts);
+
+ quoteState.clear();
+
+ let options;
+ if (this.get("model.isPrivateMessage")) {
+ let users = this.get("model.details.allowed_users");
+ let groups = this.get("model.details.allowed_groups");
+
+ let recipients = [];
+ users.forEach((user) => recipients.push(user.username));
+ groups.forEach((group) => recipients.push(group.name));
+ recipients = recipients.join();
+
+ options = {
+ action: Composer.PRIVATE_MESSAGE,
+ archetypeId: "private_message",
+ draftKey: post.topic.draft_key,
+ recipients,
+ };
+ } else {
+ options = {
+ action: Composer.CREATE_TOPIC,
+ draftKey: post.topic.draft_key,
+ topicCategoryId: this.get("model.category.id"),
+ prioritizedCategoryId: this.get("model.category.id"),
+ };
+ }
- composerController.model.prependText(text, { new_line: true });
- });
- },
-
- retryLoading() {
- this.set("retrying", true);
- const rollback = () => this.set("retrying", false);
- this.get("model.postStream").refresh().then(rollback, rollback);
- },
-
- toggleWiki(post) {
- return post.updatePostField("wiki", !post.get("wiki"));
- },
-
- togglePostType(post) {
- const regular = this.site.get("post_types.regular");
- const moderator = this.site.get("post_types.moderator_action");
- return post.updatePostField(
- "post_type",
- post.get("post_type") === moderator ? regular : moderator
- );
- },
+ composerController.open(options).then(() => {
+ const title = escapeExpression(this.model.title);
+ const postUrl = `${location.protocol}//${location.host}${post.url}`;
+ const postLink = `[${title}](${postUrl})`;
+ const text = `${I18n.t("post.continue_discussion", {
+ postLink,
+ })}\n\n${quotedText}`;
- rebakePost(post) {
- return post.rebake();
- },
+ composerController.model.prependText(text, { new_line: true });
+ });
+ }
- unhidePost(post) {
- return post.unhide();
- },
+ @action
+ retryLoading() {
+ this.set("retrying", true);
+ const rollback = () => this.set("retrying", false);
+ this.get("model.postStream").refresh().then(rollback, rollback);
+ }
- convertToPublicTopic() {
- this.modal.show(ConvertToPublicTopicModal, {
- model: { topic: this.model },
- });
- },
-
- convertToPrivateMessage() {
- this.model
- .convertTopic("private")
- .then(() => window.location.reload())
- .catch(popupAjaxError);
- },
-
- resetBumpDate() {
- this.model.resetBumpDate();
- },
-
- removeTopicTimer(statusType, topicTimer) {
- TopicTimer.update(this.get("model.id"), null, null, statusType, null)
- .then(() => this.set(`model.${topicTimer}`, EmberObject.create({})))
- .catch((error) => popupAjaxError(error));
- },
- },
+ @action
+ toggleWiki(post) {
+ return post.updatePostField("wiki", !post.get("wiki"));
+ }
+
+ @action
+ togglePostType(post) {
+ const regular = this.site.get("post_types.regular");
+ const moderator = this.site.get("post_types.moderator_action");
+ return post.updatePostField(
+ "post_type",
+ post.get("post_type") === moderator ? regular : moderator
+ );
+ }
+
+ @action
+ rebakePost(post) {
+ return post.rebake();
+ }
+
+ @action
+ unhidePost(post) {
+ return post.unhide();
+ }
+
+ @action
+ convertToPublicTopic() {
+ this.modal.show(ConvertToPublicTopicModal, {
+ model: { topic: this.model },
+ });
+ }
+
+ @action
+ convertToPrivateMessage() {
+ this.model
+ .convertTopic("private")
+ .then(() => window.location.reload())
+ .catch(popupAjaxError);
+ }
+
+ @action
+ resetBumpDate() {
+ this.model.resetBumpDate();
+ }
+
+ @action
+ removeTopicTimer(statusType, topicTimer) {
+ TopicTimer.update(this.get("model.id"), null, null, statusType, null)
+ .then(() => this.set(`model.${topicTimer}`, EmberObject.create({})))
+ .catch((error) => popupAjaxError(error));
+ }
_jumpToIndex(index) {
const postStream = this.get("model.postStream");
@@ -1223,7 +1277,7 @@ export default Controller.extend(bufferedProperty("model"), {
const streamIndex = Math.max(1, Math.min(stream.length, index));
this._jumpToPostId(stream[streamIndex - 1]);
}
- },
+ }
_jumpToDate(date) {
const postStream = this.get("model.postStream");
@@ -1238,7 +1292,7 @@ export default Controller.extend(bufferedProperty("model"), {
.catch(() => {
this._jumpToIndex(postStream.get("topic.highest_post_number"));
});
- },
+ }
_jumpToPostNumber(postNumber) {
const postStream = this.get("model.postStream");
@@ -1253,7 +1307,7 @@ export default Controller.extend(bufferedProperty("model"), {
DiscourseURL.routeTo(this.model.urlForPostNumber(p.get("post_number")));
});
}
- },
+ }
_jumpToPostId(postId) {
if (!postId) {
@@ -1285,7 +1339,7 @@ export default Controller.extend(bufferedProperty("model"), {
);
});
}
- },
+ }
_modifyTopicBookmark(bookmark) {
this.modal.show(BookmarkModal, {
@@ -1307,7 +1361,7 @@ export default Controller.extend(bufferedProperty("model"), {
},
},
});
- },
+ }
_modifyPostBookmark(bookmark, post) {
this.modal
@@ -1342,7 +1396,7 @@ export default Controller.extend(bufferedProperty("model"), {
});
}
});
- },
+ }
_syncBookmarks(data) {
if (!this.model.bookmarks) {
@@ -1357,7 +1411,7 @@ export default Controller.extend(bufferedProperty("model"), {
bookmark.name = data.name;
bookmark.auto_delete_preference = data.auto_delete_preference;
}
- },
+ }
async _toggleTopicLevelBookmark() {
if (this.model.bookmarking) {
@@ -1387,7 +1441,7 @@ export default Controller.extend(bufferedProperty("model"), {
Bookmark.createFor(this.currentUser, "Topic", this.model.id)
);
}
- },
+ }
_maybeClearAllBookmarks() {
return new Promise((resolve) => {
@@ -1408,11 +1462,11 @@ export default Controller.extend(bufferedProperty("model"), {
},
});
});
- },
+ }
togglePinnedState() {
this.send("togglePinnedForUser");
- },
+ }
print() {
if (this.siteSettings.max_prints_per_hour_per_user > 0) {
@@ -1422,14 +1476,7 @@ export default Controller.extend(bufferedProperty("model"), {
"menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=600,height=315"
);
}
- },
-
- hasError: or("model.errorHtml", "model.errorMessage"),
- noErrorYet: not("hasError"),
-
- categories: alias("site.categoriesList"),
-
- selectedPostsCount: alias("selectedPostIds.length"),
+ }
@discourseComputed(
"selectedPostIds",
@@ -1441,7 +1488,7 @@ export default Controller.extend(bufferedProperty("model"), {
return selectedPostIds
.map((id) => loadedPosts.find((p) => p.id === id))
.filter((post) => post !== undefined);
- },
+ }
@discourseComputed("selectedPostsCount", "selectedPosts", "selectedPosts.[]")
selectedPostsUsername(selectedPostsCount, selectedPosts) {
@@ -1452,7 +1499,7 @@ export default Controller.extend(bufferedProperty("model"), {
return selectedPosts.every((p) => p.username === username)
? username
: undefined;
- },
+ }
@discourseComputed(
"selectedPostsCount",
@@ -1471,14 +1518,12 @@ export default Controller.extend(bufferedProperty("model"), {
} else {
return selectedPostsCount >= postsCount;
}
- },
+ }
@discourseComputed("selectedAllPosts", "model.postStream.isMegaTopic")
canSelectAll(selectedAllPosts, isMegaTopic) {
return isMegaTopic ? false : !selectedAllPosts;
- },
-
- canDeselectAll: alias("selectedAllPosts"),
+ }
@discourseComputed(
"currentUser.staff",
@@ -1498,12 +1543,12 @@ export default Controller.extend(bufferedProperty("model"), {
((selectedAllPosts && isStaff) ||
selectedPosts.every((p) => p.can_delete))
);
- },
+ }
@discourseComputed("model.details.can_move_posts", "selectedPostsCount")
canMergeTopic(canMovePosts, selectedPostsCount) {
return canMovePosts && selectedPostsCount > 0;
- },
+ }
@discourseComputed(
"currentUser.admin",
@@ -1524,7 +1569,7 @@ export default Controller.extend(bufferedProperty("model"), {
selectedPostsCount > 0 &&
selectedPostsUsername !== undefined
);
- },
+ }
@discourseComputed(
"selectedPostsCount",
@@ -1538,26 +1583,26 @@ export default Controller.extend(bufferedProperty("model"), {
selectedPostsUsername !== undefined &&
selectedPosts.every((p) => p.can_delete)
);
- },
+ }
@observes("multiSelect")
_multiSelectChanged() {
this.set("selectedPostIds", []);
- },
+ }
postSelected(post) {
return this.selectedAllPost || this.selectedPostIds.includes(post.id);
- },
+ }
@discourseComputed
loadingHTML() {
return spinnerHTML;
- },
+ }
@action
recoverTopic() {
this.model.recover();
- },
+ }
@action
buildQuoteMarkdown() {
@@ -1570,8 +1615,9 @@ export default Controller.extend(bufferedProperty("model"), {
return promise.then((post) => {
return buildQuote(post, buffer, opts);
});
- },
+ }
+ @action
deleteTopic(opts = {}) {
if (opts.force_destroy) {
return this.model.destroy(this.currentUser, opts);
@@ -1584,11 +1630,11 @@ export default Controller.extend(bufferedProperty("model"), {
} else {
this.model.destroy(this.currentUser, opts);
}
- },
+ }
deleteTopicModal() {
this.modal.show(DeleteTopicConfirmModal, { model: { topic: this.model } });
- },
+ }
retryOnRateLimit(times, promise, topicId) {
const currentTopicId = this.get("model.id");
@@ -1637,7 +1683,7 @@ export default Controller.extend(bufferedProperty("model"), {
.finally(() => {
this._retryInProgress = false;
});
- },
+ }
subscribe() {
this.unsubscribe();
@@ -1647,7 +1693,7 @@ export default Controller.extend(bufferedProperty("model"), {
this.onMessage,
this.get("model.message_bus_last_id")
);
- },
+ }
unsubscribe() {
// never unsubscribe when navigating from topic to topic
@@ -1656,7 +1702,7 @@ export default Controller.extend(bufferedProperty("model"), {
}
this.messageBus.unsubscribe("/topic/*", this.onMessage);
- },
+ }
@bind
onMessage(data) {
@@ -1794,11 +1840,11 @@ export default Controller.extend(bufferedProperty("model"), {
}
}
}
- },
+ }
reply() {
this.replyToPost();
- },
+ }
readPosts(topicId, postNumbers) {
const topic = this.model;
@@ -1824,5 +1870,5 @@ export default Controller.extend(bufferedProperty("model"), {
}
}
}
- },
-});
+ }
+}