Skip to content

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

DEV: Replace `discourseComputed` with `@computed` across the codebase (#36840)

Sérgio Saquetima2e64d4b458b
diff --git a/frontend/discourse/admin/components/admin-penalty-post-action.gjs b/frontend/discourse/admin/components/admin-penalty-post-action.gjs
index ed9e245e1aa..f4859f8321d 100644
--- a/frontend/discourse/admin/components/admin-penalty-post-action.gjs
+++ b/frontend/discourse/admin/components/admin-penalty-post-action.gjs
@@ -2,10 +2,10 @@
import { tracked } from "@glimmer/tracking";
import Component, { Input, Textarea } from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
-import discourseComputed, { afterRender } from "discourse/lib/decorators";
+import { afterRender } from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import I18n, { i18n } from "discourse-i18n";
@@ -21,8 +21,8 @@ export default class AdminPenaltyPostAction extends Component {
@equal("postAction", "edit") editing;
@equal("postAction", "delete_all") deletingAll;
- @discourseComputed
- penaltyActions() {
+ @computed
+ get penaltyActions() {
const allActions = ACTIONS.map((id) => ({
id,
name: i18n(`admin.user.penalty_post_${id}`),
diff --git a/frontend/discourse/admin/components/admin-penalty-reason.gjs b/frontend/discourse/admin/components/admin-penalty-reason.gjs
index eccdeb605af..e8aa223a23c 100644
--- a/frontend/discourse/admin/components/admin-penalty-reason.gjs
+++ b/frontend/discourse/admin/components/admin-penalty-reason.gjs
@@ -1,11 +1,10 @@
/* eslint-disable ember/no-classic-components */
import Component, { Textarea } from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import TextField from "discourse/components/text-field";
-import discourseComputed from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { eq } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -28,9 +27,9 @@ export default class AdminPenaltyReason extends Component {
@equal("selectedReason", CUSTOM_REASON_KEY) isCustomReason;
- @discourseComputed("reasonKeys")
- reasons(keys) {
- return keys.map((key) => {
+ @computed("reasonKeys")
+ get reasons() {
+ return this.reasonKeys.map((key) => {
return { id: key, name: i18n(`admin.user.suspend_reasons.${key}`) };
});
}
diff --git a/frontend/discourse/admin/components/admin-report-storage-stats.gjs b/frontend/discourse/admin/components/admin-report-storage-stats.gjs
index d63d7ba1cd7..65693406329 100644
--- a/frontend/discourse/admin/components/admin-report-storage-stats.gjs
+++ b/frontend/discourse/admin/components/admin-report-storage-stats.gjs
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
import formatDate from "discourse/helpers/format-date";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getUrl from "discourse/lib/get-url";
import I18n, { i18n } from "discourse-i18n";
@@ -18,34 +18,34 @@ export default class AdminReportStorageStats extends Component {
@alias("model.data.uploads") uploadStats;
- @discourseComputed("backupStats")
- showBackupStats(stats) {
- return stats && this.currentUser.admin;
+ @computed("backupStats")
+ get showBackupStats() {
+ return this.backupStats && this.currentUser.admin;
}
- @discourseComputed("backupLocation")
- backupLocationName(backupLocation) {
- return i18n(`admin.backups.location.${backupLocation}`);
+ @computed("backupLocation")
+ get backupLocationName() {
+ return i18n(`admin.backups.location.${this.backupLocation}`);
}
- @discourseComputed("backupStats.used_bytes")
- usedBackupSpace(bytes) {
- return I18n.toHumanSize(bytes);
+ @computed("backupStats.used_bytes")
+ get usedBackupSpace() {
+ return I18n.toHumanSize(this.backupStats?.used_bytes);
}
- @discourseComputed("backupStats.free_bytes")
- freeBackupSpace(bytes) {
- return I18n.toHumanSize(bytes);
+ @computed("backupStats.free_bytes")
+ get freeBackupSpace() {
+ return I18n.toHumanSize(this.backupStats?.free_bytes);
}
- @discourseComputed("uploadStats.used_bytes")
- usedUploadSpace(bytes) {
- return I18n.toHumanSize(bytes);
+ @computed("uploadStats.used_bytes")
+ get usedUploadSpace() {
+ return I18n.toHumanSize(this.uploadStats?.used_bytes);
}
- @discourseComputed("uploadStats.free_bytes")
- freeUploadSpace(bytes) {
- return I18n.toHumanSize(bytes);
+ @computed("uploadStats.free_bytes")
+ get freeUploadSpace() {
+ return I18n.toHumanSize(this.uploadStats?.free_bytes);
}
<template>
diff --git a/frontend/discourse/admin/components/admin-report-table-cell.gjs b/frontend/discourse/admin/components/admin-report-table-cell.gjs
index 38429e51d0d..be429b5e1a6 100644
--- a/frontend/discourse/admin/components/admin-report-table-cell.gjs
+++ b/frontend/discourse/admin/components/admin-report-table-cell.gjs
@@ -1,10 +1,10 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
@tagName("")
export default class AdminReportTableCell extends Component {
@@ -15,9 +15,9 @@ export default class AdminReportTableCell extends Component {
@alias("computedLabel.formattedValue") formattedValue;
@alias("computedLabel.value") value;
- @discourseComputed("label", "data", "options")
- computedLabel(label, data, options) {
- return label.compute(data, options || {});
+ @computed("label", "data", "options")
+ get computedLabel() {
+ return this.label.compute(this.data, this.options || {});
}
<template>
diff --git a/frontend/discourse/admin/components/admin-report-table.gjs b/frontend/discourse/admin/components/admin-report-table.gjs
index ad0b9cd9e6e..c999099edf2 100644
--- a/frontend/discourse/admin/components/admin-report-table.gjs
+++ b/frontend/discourse/admin/components/admin-report-table.gjs
@@ -1,14 +1,13 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { fn } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import AdminReportTableHeader from "discourse/admin/components/admin-report-table-header";
import AdminReportTableRow from "discourse/admin/components/admin-report-table-row";
import DButton from "discourse/components/d-button";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { makeArray } from "discourse/lib/helpers";
import { i18n } from "discourse-i18n";
@@ -23,82 +22,77 @@ export default class AdminReportTable extends Component {
page = 0;
- @discourseComputed("model.computedLabels.length")
- twoColumns(labelsLength) {
- return labelsLength === 2;
+ @computed("model.computedLabels.length")
+ get twoColumns() {
+ return this.model?.computedLabels?.length === 2;
}
- @discourseComputed(
- "totalsForSample",
- "options.total",
- "model.dates_filtering"
- )
- showTotalForSample(totalsForSample, total, datesFiltering) {
+ @computed("totalsForSample", "options.total", "model.dates_filtering")
+ get showTotalForSample() {
// check if we have at least one cell which contains a value
- const sum = totalsForSample
+ const sum = this.totalsForSample
.map((t) => t.value)
.filter((item) => item != null)
.reduce((s, v) => s + v, 0);
- return sum >= 1 && total && datesFiltering;
+ return sum >= 1 && this.options?.total && this.model?.dates_filtering;
}
- @discourseComputed("model.total", "options.total", "twoColumns")
- showTotal(reportTotal, total, twoColumns) {
- return reportTotal && total && twoColumns;
+ @computed("model.total", "options.total", "twoColumns")
+ get showTotal() {
+ return this.model?.total && this.options?.total && this.twoColumns;
}
- @discourseComputed(
- "model.{average,data}",
- "totalsForSample.1.value",
- "twoColumns"
- )
- showAverage(model, sampleTotalValue, hasTwoColumns) {
+ @computed("model.{average,data}", "totalsForSample.1.value", "twoColumns")
+ get showAverage() {
return (
- model.average &&
- model.data.length > 0 &&
- sampleTotalValue &&
- hasTwoColumns
+ this.model?.average &&
+ this.model?.data.length > 0 &&
+ this.totalsForSample?.[1]?.value &&
+ this.twoColumns
);
}
- @discourseComputed("totalsForSample.1.value", "model.data.length")
- averageForSample(totals, count) {
+ @computed("totalsForSample.1.value", "model.data.length")
+ get averageForSample() {
const averageLabel = this.model.computedLabels.at(-1);
- return averageLabel.compute({ y: (totals / count).toFixed(0) })
- .formattedValue;
+ return averageLabel.compute({
+ y: (this.totalsForSample?.[1]?.value / this.model?.data?.length).toFixed(
+ 0
+ ),
+ }).formattedValue;
}
- @discourseComputed("model.data.length")
- showSortingUI(dataLength) {
- return dataLength >= 5;
+ @computed("model.data.length")
+ get showSortingUI() {
+ return this.model?.data?.length >= 5;
}
- @discourseComputed("totalsForSampleRow", "model.computedLabels")
- totalsForSample(row, labels) {
- return labels.map((label) => {
- const computedLabel = label.compute(row);
+ @computed("totalsForSampleRow", "model.computedLabels")
+ get totalsForSample() {
+ return this.model?.computedLabels?.map((label) => {
+ const computedLabel = label.compute(this.totalsForSampleRow);
computedLabel.type = label.type;
computedLabel.property = label.mainProperty;
return computedLabel;
});
}
- @discourseComputed("model.total", "model.computedLabels")
- formattedTotal(total, labels) {
- const totalLabel = labels.at(-1);
- return totalLabel.compute({ y: total }).formattedValue;
+ @computed("model.total", "model.computedLabels")
+ get formattedTotal() {
+ const totalLabel = this.model?.computedLabels?.at(-1);
+ return totalLabel.compute({ y: this.model?.total }).formattedValue;
}
- @discourseComputed("model.data", "model.computedLabels")
- totalsForSampleRow(rows, labels) {
- if (!rows || !rows.length) {
+ @computed("model.data", "model.computedLabels")
+ get totalsForSampleRow() {
+ if (!this.model?.data || !this.model?.data?.length) {
return {};
}
let totalsRow = {};
- labels.forEach((label) => {
+ this.model?.computedLabels?.forEach((label) => {
const reducer = (sum, row) => {
const computedLabel = label.compute(row);
const value = computedLabel.value;
@@ -110,19 +104,21 @@ export default class AdminReportTable extends Component {
}
};
- const total = rows.reduce(reducer, 0);
+ const total = this.model?.data?.reduce(reducer, 0);
totalsRow[label.mainProperty] =
- label.type === "percent" ? Math.round(total / rows.length) : total;
+ label.type === "percent"
+ ? Math.round(total / this.model?.data?.length)
+ : total;
});
return totalsRow;
}
- @discourseComputed("sortLabel", "sortDirection", "model.data.[]")
- sortedData(sortLabel, sortDirection, data) {
- data = makeArray(data);
+ @computed("sortLabel", "sortDirection", "model.data.[]")
+ get sortedData() {
+ const data = makeArray(this.model?.data);
- if (sortLabel) {
+ if (this.sortLabel) {
const compare = (label, direction) => {
return (a, b) => {
const aValue = label.compute(a, { useSortProperty: true }).value;
@@ -132,30 +128,34 @@ export default class AdminReportTable extends Component {
};
};
- return data.sort(compare(sortLabel, sortDirection));
+ return data.sort(compare(this.sortLabel, this.sortDirection));
}
return data;
}
- @discourseComputed("sortedData.[]", "perPage", "page")
- paginatedData(data, perPage, page) {
- if (perPage < data.length) {
- const start = perPage * page;
- return data.slice(start, start + perPage);
+ @computed("sortedData.[]", "perPage", "page")
+ get paginatedData() {
+ if (this.perPage < this.sortedData?.length) {
+ const start = this.perPage * this.page;
+ return this.sortedData?.slice(start, start + this.perPage);
}
- return data;
+ return this.sortedData;
}
- @discourseComputed("model.data", "perPage", "page")
- pages(data, perPage, page) {
- if (!data || data.length <= perPage) {
+ @computed("model.data", "perPage", "page")
+ get pages() {
+ if (!this.model?.data || this.model?.data?.length <= this.perPage) {
return [];
}
const pagesIndexes = [];
- for (let i = 0; i < Math.ceil(data.length / perPage); i++) {
+ for (
+ let i = 0;
+ i < Math.ceil(this.model?.data?.length / this.perPage);
+ i++
+ ) {
pagesIndexes.push(i);
}
@@ -163,13 +163,13 @@ export default class AdminReportTable extends Component {
return {
page: v + 1,
index: v,
- class: v === page ? "is-current" : null,
+ class: v === this.page ? "is-current" : null,
};
});
if (pages.length > PAGES_LIMIT) {
- const before = Math.max(0, page - PAGES_LIMIT / 2);
- const after = Math.max(PAGES_LIMIT, page + PAGES_LIMIT / 2);
+ const before = Math.max(0, this.page - PAGES_LIMIT / 2);
+ const after = Math.max(PAGES_LIMIT, this.page + PAGES_LIMIT / 2);
pages = pages.slice(before, after);
}
diff --git a/frontend/discourse/admin/components/admin-theme-editor.gjs b/frontend/discourse/admin/components/admin-theme-editor.gjs
index 6d14ac9f13a..fe1834ceaab 100644
--- a/frontend/discourse/admin/components/admin-theme-editor.gjs
+++ b/frontend/discourse/admin/components/admin-theme-editor.gjs
@@ -12,7 +12,6 @@ import { tagName } from "@ember-decorators/component";
import AceEditor from "discourse/components/ace-editor";
import icon from "discourse/helpers/d-icon";
import { fmt } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { isDocumentRTL } from "discourse/lib/text-direction";
import { gt, lte } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -72,20 +71,20 @@ export default class AdminThemeEditor extends Component {
);
}
- @discourseComputed("currentTargetName", "fieldName")
- activeSectionMode(targetName, fieldName) {
- if (fieldName === "color_definitions") {
+ @computed("currentTargetName", "fieldName")
+ get activeSectionMode() {
+ if (this.fieldName === "color_definitions") {
return "scss";
}
- if (fieldName === "js") {
+ if (this.fieldName === "js") {
return "javascript";
}
- return fieldName && fieldName.includes("scss") ? "scss" : "html";
+ return this.fieldName && this.fieldName.includes("scss") ? "scss" : "html";
}
- @discourseComputed("currentTargetName", "fieldName")
- placeholder(targetName, fieldName) {
- if (fieldName && fieldName === "color_definitions") {
+ @computed("currentTargetName", "fieldName")
+ get placeholder() {
+ if (this.fieldName && this.fieldName === "color_definitions") {
const example =
":root {\n" +
" --mytheme-tertiary-or-highlight: #{dark-light-choose($tertiary, $highlight)};\n" +
@@ -117,18 +116,14 @@ export default class AdminThemeEditor extends Component {
this.theme.setField(this.currentTargetName, this.fieldName, value);
}
- @discourseComputed("maximized")
- maximizeIcon(maximized) {
- return maximized ? "discourse-compress" : "discourse-expand";
+ @computed("maximized")
+ get maximizeIcon() {
+ return this.maximized ? "discourse-compress" : "discourse-expand";
}
- @discourseComputed(
- "currentTargetName",
- "fieldName",
- )
- error(target, fieldName) {
- return this.theme.getError(target, fieldName);
+ @computed("currentTargetName", "fieldName", "[email protected]")
+ get error() {
+ return this.theme.getError(this.currentTargetName, this.fieldName);
}
@action
diff --git a/frontend/discourse/admin/components/edit-category-images.gjs b/frontend/discourse/admin/components/edit-category-images.gjs
index 82cead52d1f..ad341272006 100644
--- a/frontend/discourse/admin/components/edit-category-images.gjs
+++ b/frontend/discourse/admin/components/edit-category-images.gjs
@@ -1,30 +1,29 @@
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { buildCategoryPanel } from "discourse/admin/components/edit-category-panel";
import PluginOutlet from "discourse/components/plugin-outlet";
import UppyImageUploader from "discourse/components/uppy-image-uploader";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class EditCategoryImages extends buildCategoryPanel("images") {
- @discourseComputed("category.uploaded_background.url")
- backgroundImageUrl(uploadedBackgroundUrl) {
- return uploadedBackgroundUrl || "";
+ @computed("category.uploaded_background.url")
+ get backgroundImageUrl() {
+ return this.category?.uploaded_background?.url || "";
}
- @discourseComputed("category.uploaded_background_dark.url")
- backgroundDarkImageUrl(uploadedBackgroundDarkUrl) {
- return uploadedBackgroundDarkUrl || "";
+ @computed("category.uploaded_background_dark.url")
+ get backgroundDarkImageUrl() {
+ return this.category?.uploaded_background_dark?.url || "";
}
- @discourseComputed("category.uploaded_logo.url")
- logoImageUrl(uploadedLogoUrl) {
- return uploadedLogoUrl || "";
+ @computed("category.uploaded_logo.url")
+ get logoImageUrl() {
+ return this.category?.uploaded_logo?.url || "";
}
- @discourseComputed("category.uploaded_logo_dark.url")
- logoImageDarkUrl(uploadedLogoDarkUrl) {
- return uploadedLogoDarkUrl || "";
+ @computed("category.uploaded_logo_dark.url")
+ get logoImageDarkUrl() {
+ return this.category?.uploaded_logo_dark?.url || "";
}
@action
diff --git a/frontend/discourse/admin/components/edit-category-settings.gjs b/frontend/discourse/admin/components/edit-category-settings.gjs
index 7afd5877b03..71fee90a9ed 100644
--- a/frontend/discourse/admin/components/edit-category-settings.gjs
+++ b/frontend/discourse/admin/components/edit-category-settings.gjs
@@ -1,7 +1,7 @@
import { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { and, empty } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { buildCategoryPanel } from "discourse/admin/components/edit-category-panel";
@@ -13,7 +13,6 @@ import lazyHash from "discourse/helpers/lazy-hash";
import withEventValue from "discourse/helpers/with-event-value";
import { setting } from "discourse/lib/computed";
import { SEARCH_PRIORITIES } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import getUrl from "discourse/lib/get-url";
import { applyMutableValueTransformer } from "discourse/lib/transformer";
import ComboBox from "discourse/select-kit/components/combo-box";
@@ -30,17 +29,23 @@ export default class EditCategorySettings extends buildCategoryPanel(
showSubcategoryListStyle;
@empty("category.sort_order") isDefaultSortOrder;
- @discourseComputed(
+ @computed(
"category.isParent",
"category.parent_category_id",
"transientData.parent_category_id"
)
- isParentCategory(isParent, parentCategoryId, transientParentCategoryId) {
- return isParent || !(parentCategoryId || transientParentCategoryId);
+ get isParentCategory() {
+ return (
+ this.category?.isParent ||
+ !(
+ this.category?.parent_category_id ||
+ this.transientData?.parent_category_id
+ )
+ );
}
- @discourseComputed
- availableSubcategoryListStyles() {
+ @computed
+ get availableSubcategoryListStyles() {
return [
{ name: i18n("category.subcategory_list_styles.rows"), value: "rows" },
{
@@ -62,8 +67,8 @@ export default class EditCategorySettings extends buildCategoryPanel(
];
}
- @discourseComputed("category.id", "category.custom_fields")
- availableViews(categoryId, customFields) {
+ @computed("category.id", "category.custom_fields")
+ get availableViews() {
const views = [
{ name: i18n("filters.hot.title"), value: "hot" },
{ name: i18n("filters.latest.title"), value: "latest" },
@@ -71,8 +76,8 @@ export default class EditCategorySettings extends buildCategoryPanel(
];
const context = {
- categoryId,
- customFields,
+ categoryId: this.category?.id,
+ customFields: this.category?.custom_fields,
};
return applyMutableValueTransformer(
@@ -82,8 +87,8 @@ export default class EditCategorySettings extends buildCategoryPanel(
);
}
- @discourseComputed
- availableTopPeriods() {
+ @computed
+ get availableTopPeriods() {
return ["all", "yearly", "quarterly", "monthly", "weekly", "daily"].map(
(p) => {
return { name: i18n(`filters.top.${p}.title`), value: p };
@@ -91,15 +96,15 @@ export default class EditCategorySettings extends buildCategoryPanel(
);
}
- @discourseComputed
- availableListFilters() {
+ @computed
+ get availableListFilters() {
return ["all", "none"].map((p) => {
return { name: i18n(`category.list_filters.${p}`), value: p };
});
}
- @discourseComputed
- searchPrioritiesOptions() {
+ @computed
+ get searchPrioritiesOptions() {
const options = [];
Object.entries(SEARCH_PRIORITIES).forEach((entry) => {
@@ -114,8 +119,8 @@ export default class EditCategorySettings extends buildCategoryPanel(
return options;
}
- @discourseComputed
- availableSorts() {
+ @computed
+ get availableSorts() {
return applyMutableValueTransformer("category-sort-orders", [
"likes",
"op_likes",
@@ -130,27 +135,27 @@ export default class EditCategorySettings extends buildCategoryPanel(
.sort((a, b) => a.name.localeCompare(b.name));
}
- @discourseComputed("category.sort_ascending")
- sortAscendingOption(sortAscending) {
- if (sortAscending === "false") {
+ @computed("category.sort_ascending")
+ get sortAscendingOption() {
+ if (this.category?.sort_ascending === "false") {
return false;
}
- if (sortAscending === "true") {
+ if (this.category?.sort_ascending === "true") {
return true;
}
- return sortAscending;
+ return this.category?.sort_ascending;
}
- @discourseComputed
- sortAscendingOptions() {
+ @computed
+ get sortAscendingOptions() {
return [
{ name: i18n("category.sort_ascending"), value: true },
{ name: i18n("category.sort_descending"), value: false },
];
}
- @discourseComputed
- hiddenRelativeIntervals() {
+ @computed
+ get hiddenRelativeIntervals() {
return ["mins"];
}
diff --git a/frontend/discourse/admin/components/edit-category-tab.gjs b/frontend/discourse/admin/components/edit-category-tab.gjs
index 7154ed8b351..cd475015bb8 100644
--- a/frontend/discourse/admin/components/edit-category-tab.gjs
+++ b/frontend/discourse/admin/components/edit-category-tab.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { empty } from "@ember/object/computed";
import { scheduleOnce } from "@ember/runloop";
import { underscore } from "@ember/string";
@@ -9,7 +9,6 @@ import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
import { addUniqueValueToArray } from "discourse/lib/array-tools";
import { propertyEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import DiscourseURL from "discourse/lib/url";
import { i18n } from "discourse-i18n";
@@ -19,14 +18,14 @@ export default class EditCategoryTab extends Component {
@empty("params.slug") newCategory;
@propertyEqual("selectedTab", "tab") active;
- @discourseComputed("tab")
- tabClassName(tab) {
- return "edit-category-" + tab;
+ @computed("tab")
+ get tabClassName() {
+ return "edit-category-" + this.tab;
}
- @discourseComputed("tab", "tabTitle")
- title(tab, tabTitle) {
- return tabTitle ?? i18n(`category.${underscore(tab)}`);
+ @computed("tab", "tabTitle")
+ get title() {
+ return this.tabTitle ?? i18n(`category.${underscore(this.tab)}`);
}
didInsertElement() {
@@ -38,9 +37,12 @@ export default class EditCategoryTab extends Component {
addUniqueValueToArray(this.panels, this.tabClassName);
}
- @discourseComputed("params.slug", "params.parentSlug")
- fullSlug(slug, parentSlug) {
- const slugPart = parentSlug && slug ? `${parentSlug}/${slug}` : slug;
+ @computed("params.slug", "params.parentSlug")
+ get fullSlug() {
+ const slugPart =
+ this.params?.parentSlug && this.params?.slug
+ ? `${this.params?.parentSlug}/${this.params?.slug}`
+ : this.params?.slug;
return getURL(`/c/${slugPart}/edit/${this.tab}`);
}
diff --git a/frontend/discourse/admin/components/email-styles-editor.gjs b/frontend/discourse/admin/components/email-styles-editor.gjs
index 6457bf38a1f..c59aa21c71f 100644
--- a/frontend/discourse/admin/components/email-styles-editor.gjs
+++ b/frontend/discourse/admin/components/email-styles-editor.gjs
@@ -7,7 +7,6 @@ import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import AceEditor from "discourse/components/ace-editor";
import DButton from "discourse/components/d-button";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("")
@@ -16,16 +15,16 @@ export default class EmailStylesEditor extends Component {
@reads("fieldName") editorId;
- @discourseComputed("fieldName")
- currentEditorMode(fieldName) {
- return fieldName === "css" ? "scss" : fieldName;
+ @computed("fieldName")
+ get currentEditorMode() {
+ return this.fieldName === "css" ? "scss" : this.fieldName;
}
- @discourseComputed("fieldName", "styles.html", "styles.css")
- resetDisabled(fieldName) {
+ @computed("fieldName", "styles.html", "styles.css")
+ get resetDisabled() {
return (
- this.get(`styles.${fieldName}`) ===
- this.get(`styles.default_${fieldName}`)
+ this.get(`styles.${this.fieldName}`) ===
+ this.get(`styles.default_${this.fieldName}`)
);
}
diff --git a/frontend/discourse/admin/components/emoji-uploader.gjs b/frontend/discourse/admin/components/emoji-uploader.gjs
index 9fbb9300db4..6dba86ef765 100644
--- a/frontend/discourse/admin/components/emoji-uploader.gjs
+++ b/frontend/discourse/admin/components/emoji-uploader.gjs
@@ -2,7 +2,7 @@
import Component, { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { notEmpty } from "@ember/object/computed";
import { getOwner } from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
@@ -11,7 +11,6 @@ import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import withEventValue from "discourse/helpers/with-event-value";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import UppyUpload from "discourse/lib/uppy/uppy-upload";
import ComboBox from "discourse/select-kit/components/combo-box";
import { i18n } from "discourse-i18n";
@@ -81,18 +80,18 @@ export default class EmojiUploader extends Component {
this.uppyUpload.openPicker();
}
- @discourseComputed("uppyUpload.uploading", "uppyUpload.uploadProgress")
- buttonLabel(uploading, uploadProgress) {
- if (uploading) {
- return `${i18n("admin.emoji.uploading")} ${uploadProgress}%`;
+ @computed("uppyUpload.uploading", "uppyUpload.uploadProgress")
+ get buttonLabel() {
+ if (this.uppyUpload?.uploading) {
+ return `${i18n("admin.emoji.uploading")} ${this.uppyUpload?.uploadProgress}%`;
} else {
return i18n("admin.emoji.choose_files");
}
}
- @discourseComputed("uppyUpload.uploading")
- buttonIcon(uploading) {
- if (uploading) {
+ @computed("uppyUpload.uploading")
+ get buttonIcon() {
+ if (this.uppyUpload?.uploading) {
return "spinner";
} else {
return "plus";
diff --git a/frontend/discourse/admin/components/permalink-form.gjs b/frontend/discourse/admin/components/permalink-form.gjs
index 920520e77d8..ebaa8072eca 100644
--- a/frontend/discourse/admin/components/permalink-form.gjs
+++ b/frontend/discourse/admin/components/permalink-form.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { fn } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
@@ -9,7 +9,7 @@ import Permalink from "discourse/admin/models/permalink";
import DButton from "discourse/components/d-button";
import TextField from "discourse/components/text-field";
import { fmt } from "discourse/lib/computed";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { i18n } from "discourse-i18n";
@@ -25,8 +25,8 @@ export default class PermalinkForm extends Component {
action = null;
permalinkTypeValue = null;
- @discourseComputed
- permalinkTypes() {
+ @computed
+ get permalinkTypes() {
return [
{ id: "topic_id", name: i18n("admin.permalink.topic_id") },
{ id: "post_id", name: i18n("admin.permalink.post_id") },
diff --git a/frontend/discourse/admin/components/screened-ip-address-form.gjs b/frontend/discourse/admin/components/screened-ip-address-form.gjs
index 87558117d3b..75524423ab3 100644
--- a/frontend/discourse/admin/components/screened-ip-address-form.gjs
+++ b/frontend/discourse/admin/components/screened-ip-address-form.gjs
@@ -1,14 +1,13 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
import { fn } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { classNames, tagName } from "@ember-decorators/component";
import ScreenedIpAddress from "discourse/admin/models/screened-ip-address";
import DButton from "discourse/components/d-button";
import TextField from "discourse/components/text-field";
-import discourseComputed from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { i18n } from "discourse-i18n";
@@ -31,9 +30,9 @@ export default class ScreenedIpAddressForm extends Component {
formSubmitted = false;
actionName = "block";
- @discourseComputed("siteSettings.use_admin_ip_allowlist")
- actionNames(adminAllowlistEnabled) {
- if (adminAllowlistEnabled) {
+ @computed("siteSettings.use_admin_ip_allowlist")
+ get actionNames() {
+ if (this.siteSettings?.use_admin_ip_allowlist) {
return [
{ id: "block", name: i18n("admin.logs.screened_ips.actions.block") },
{
diff --git a/frontend/discourse/admin/components/site-settings/tag-group-list.gjs b/frontend/discourse/admin/components/site-settings/tag-group-list.gjs
index d36da5a703f..c3c0b33d2bd 100644
--- a/frontend/discourse/admin/components/site-settings/tag-group-list.gjs
+++ b/frontend/discourse/admin/components/site-settings/tag-group-list.gjs
@@ -1,16 +1,15 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import TagGroupChooser from "discourse/select-kit/components/tag-group-chooser";
@tagName("")
export default class TagGroupList extends Component {
- @discourseComputed("value")
- selectedTagGroups(value) {
- return value.split("|").filter(Boolean);
+ @computed("value")
+ get selectedTagGroups() {
+ return this.value.split("|").filter(Boolean);
}
@action
diff --git a/frontend/discourse/admin/components/site-settings/tag-list.gjs b/frontend/discourse/admin/components/site-settings/tag-list.gjs
index c87efe261c8..c53963b664b 100644
--- a/frontend/discourse/admin/components/site-settings/tag-list.gjs
+++ b/frontend/discourse/admin/components/site-settings/tag-list.gjs
@@ -1,16 +1,15 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import TagChooser from "discourse/select-kit/components/tag-chooser";
@tagName("")
export default class TagList extends Component {
- @discourseComputed("value")
- selectedTags(value) {
- return value.split("|").filter(Boolean);
+ @computed("value")
+ get selectedTags() {
+ return this.value.split("|").filter(Boolean);
}
@action
diff --git a/frontend/discourse/admin/components/value-list.gjs b/frontend/discourse/admin/components/value-list.gjs
index 848906558c5..eff272f64f9 100644
--- a/frontend/discourse/admin/components/value-list.gjs
+++ b/frontend/discourse/admin/components/value-list.gjs
@@ -2,7 +2,7 @@
import Component, { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { empty, reads } from "@ember/object/computed";
import { classNames } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
@@ -11,7 +11,6 @@ import {
removeValueFromArray,
uniqueItemsFromArray,
} from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { makeArray } from "discourse/lib/helpers";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import ComboBox from "discourse/select-kit/components/combo-box";
@@ -44,9 +43,9 @@ export default class ValueList extends Component {
);
}
- @discourseComputed("choices.[]", "collection.[]")
- filteredChoices(choices, collection) {
- return makeArray(choices).filter((i) => !collection.includes(i));
+ @computed("choices.[]", "collection.[]")
+ get filteredChoices() {
+ return makeArray(this.choices).filter((i) => !this.collection?.includes(i));
}
keyDown(event) {
@@ -143,9 +142,9 @@ export default class ValueList extends Component {
this.set("values", this.collection.join(this.inputDelimiter || "\n"));
}
- @discourseComputed("collection")
- showUpDownButtons(collection) {
- return collection.length - 1 ? true : false;
+ @computed("collection")
+ get showUpDownButtons() {
+ return this.collection.length - 1 ? true : false;
}
_splitValues(values, delimiter) {
diff --git a/frontend/discourse/admin/components/watched-word-form.gjs b/frontend/discourse/admin/components/watched-word-form.gjs
index d438ab79ed8..9142f815ca7 100644
--- a/frontend/discourse/admin/components/watched-word-form.gjs
+++ b/frontend/discourse/admin/components/watched-word-form.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/no-observers */
import Component, { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { empty, equal } from "@ember/object/computed";
import { isEmpty } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
@@ -10,7 +10,6 @@ import WatchedWord from "discourse/admin/models/watched-word";
import DButton from "discourse/components/d-button";
import TextField from "discourse/components/text-field";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import TagChooser from "discourse/select-kit/components/tag-chooser";
import WatchedWords from "discourse/select-kit/components/watched-words";
import { i18n } from "discourse-i18n";
@@ -30,9 +29,9 @@ export default class WatchedWordForm extends Component {
@equal("actionKey", "tag") canTag;
@equal("actionKey", "link") canLink;
- @discourseComputed("siteSettings.watched_words_regular_expressions")
- placeholderKey(watchedWordsRegularExpressions) {
- if (watchedWordsRegularExpressions) {
+ @computed("siteSettings.watched_words_regular_expressions")
+ get placeholderKey() {
+ if (this.siteSettings?.watched_words_regular_expressions) {
return "admin.watched_words.form.placeholder_regexp";
} else {
return "admin.watched_words.form.placeholder";
@@ -53,8 +52,8 @@ export default class WatchedWordForm extends Component {
});
}
- @discourseComputed("words.[]")
- isUniqueWord(words) {
+ @computed("words.[]")
+ get isUniqueWord() {
const existingWords = this.filteredContent || [];
const filtered = existingWords.filter(
(content) => content.action === this.actionKey
@@ -62,11 +61,11 @@ export default class WatchedWordForm extends Component {
const duplicate = filtered.find((content) => {
if (content.case_sensitive === true) {
- return words.includes(content.word);
+ return this.words?.includes(content.word);
} else {
- return words
- .map((w) => w.toLowerCase())
- .includes(content.word.toLowerCase());
+ return this.words
+ ?.map((w) => w.toLowerCase())
+ ?.includes(content.word.toLowerCase());
}
});
diff --git a/frontend/discourse/admin/controllers/admin-api-keys/new.js b/frontend/discourse/admin/controllers/admin-api-keys/new.js
index 426a5dfeca6..43611a9615c 100644
--- a/frontend/discourse/admin/controllers/admin-api-keys/new.js
+++ b/frontend/discourse/admin/controllers/admin-api-keys/new.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action, get } from "@ember/object";
+import { action, computed, get } from "@ember/object";
import { equal } from "@ember/object/computed";
import { service } from "@ember/service";
import { isBlank } from "@ember/utils";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import ApiKeyUrlsModal from "../../components/modal/api-key-urls";
@@ -32,12 +31,12 @@ export default class AdminApiKeysNewController extends Controller {
this._loadScopes();
}
- @discourseComputed("model.{description,username}", "showUserSelector")
- saveDisabled(model, showUserSelector) {
- if (isBlank(model.description)) {
+ @computed("model.{description,username}", "showUserSelector")
+ get saveDisabled() {
+ if (isBlank(this.model?.description)) {
return true;
}
- if (showUserSelector && isBlank(model.username)) {
+ if (this.showUserSelector && isBlank(this.model?.username)) {
return true;
}
return false;
diff --git a/frontend/discourse/admin/controllers/admin-customize-email-style/edit.js b/frontend/discourse/admin/controllers/admin-customize-email-style/edit.js
index 71d0764c394..94a8e8a69e1 100644
--- a/frontend/discourse/admin/controllers/admin-customize-email-style/edit.js
+++ b/frontend/discourse/admin/controllers/admin-customize-email-style/edit.js
@@ -1,20 +1,19 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminCustomizeEmailStyleEditController extends Controller {
@service dialog;
- @discourseComputed("model.isSaving")
- saveButtonText(isSaving) {
- return isSaving ? i18n("saving") : i18n("admin.customize.save");
+ @computed("model.isSaving")
+ get saveButtonText() {
+ return this.model?.isSaving ? i18n("saving") : i18n("admin.customize.save");
}
- @discourseComputed("model.changed", "model.isSaving")
- saveDisabled(changed, isSaving) {
- return !changed || isSaving;
+ @computed("model.changed", "model.isSaving")
+ get saveDisabled() {
+ return !this.model?.changed || this.model?.isSaving;
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-customize-themes.js b/frontend/discourse/admin/controllers/admin-customize-themes.js
index 881a41523d1..a93acc8ff39 100644
--- a/frontend/discourse/admin/controllers/admin-customize-themes.js
+++ b/frontend/discourse/admin/controllers/admin-customize-themes.js
@@ -1,22 +1,22 @@
import Controller from "@ember/controller";
+import { computed } from "@ember/object";
import { THEMES } from "discourse/admin/models/theme";
-import discourseComputed from "discourse/lib/decorators";
export default class AdminCustomizeThemesController extends Controller {
currentTab = THEMES;
- @discourseComputed("model", "[email protected]")
- fullThemes(themes) {
- return themes.filter((t) => !t.get("component"));
+ @computed("model", "[email protected]")
+ get fullThemes() {
+ return this.model.filter((t) => !t.get("component"));
}
- @discourseComputed("model", "[email protected]")
- childThemes(themes) {
- return themes.filter((t) => t.get("component"));
+ @computed("model", "[email protected]")
+ get childThemes() {
+ return this.model.filter((t) => t.get("component"));
}
- @discourseComputed("model.content")
- installedThemes(content) {
- return content || [];
+ @computed("model.content")
+ get installedThemes() {
+ return this.model?.content || [];
}
}
diff --git a/frontend/discourse/admin/controllers/admin-customize-themes/edit.js b/frontend/discourse/admin/controllers/admin-customize-themes/edit.js
index 7ebcc47f429..b38e83ba2bf 100644
--- a/frontend/discourse/admin/controllers/admin-customize-themes/edit.js
+++ b/frontend/discourse/admin/controllers/admin-customize-themes/edit.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { url } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminCustomizeThemesEditController extends Controller {
@@ -23,22 +22,22 @@ export default class AdminCustomizeThemesEditController extends Controller {
this.set("currentTarget", target && target.id);
}
- @discourseComputed("currentTarget")
- currentTargetName(id) {
+ @computed("currentTarget")
+ get currentTargetName() {
const target = this.get("model.targets").find(
- (t) => t.id === parseInt(id, 10)
+ (t) => t.id === parseInt(this.currentTarget, 10)
);
return target && target.name;
}
- @discourseComputed("model.isSaving")
- saveButtonText(isSaving) {
- return isSaving ? i18n("saving") : i18n("admin.customize.save");
+ @computed("model.isSaving")
+ get saveButtonText() {
+ return this.model?.isSaving ? i18n("saving") : i18n("admin.customize.save");
}
- @discourseComputed("model.changed", "model.isSaving")
- saveDisabled(changed, isSaving) {
- return !changed || isSaving;
+ @computed("model.changed", "model.isSaving")
+ get saveDisabled() {
+ return !this.model?.changed || this.model?.isSaving;
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-customize-themes/show.js b/frontend/discourse/admin/controllers/admin-customize-themes/show.js
index c67ba43963f..ed6392e759a 100644
--- a/frontend/discourse/admin/controllers/admin-customize-themes/show.js
+++ b/frontend/discourse/admin/controllers/admin-customize-themes/show.js
@@ -1,10 +1,9 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { match } from "@ember/object/computed";
import { service } from "@ember/service";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminCustomizeThemesShowController extends Controller {
@@ -13,28 +12,29 @@ export default class AdminCustomizeThemesShowController extends Controller {
@match("model.remote_theme.remote_url", /^http(s)?:\/\//) sourceIsHttp;
- @discourseComputed(
- "model.remote_theme.remote_url",
- "model.remote_theme.branch"
- )
- remoteThemeLink(remoteThemeUrl, remoteThemeBranch) {
- return remoteThemeBranch
- ? `${remoteThemeUrl.replace(/\.git$/, "")}/tree/${remoteThemeBranch}`
- : remoteThemeUrl;
+ @computed("model.remote_theme.remote_url", "model.remote_theme.branch")
+ get remoteThemeLink() {
+ return this.model?.remote_theme?.branch
+ ? `${this.model?.remote_theme?.remote_url?.replace(/\.git$/, "")}/tree/${this.model?.remote_theme?.branch}`
+ : this.model?.remote_theme?.remote_url;
}
- @discourseComputed("model.remoteError", "updatingRemote")
- showRemoteError(errorMessage, updating) {
- return errorMessage && !updating;
+ @computed("model.remoteError", "updatingRemote")
+ get showRemoteError() {
+ return this.model?.remoteError && !this.updatingRemote;
}
- @discourseComputed(
+ @computed(
"model.remote_theme.remote_url",
"model.remote_theme.local_version",
"model.remote_theme.commits_behind"
)
- finishInstall(remoteUrl, localVersion, commitsBehind) {
- return remoteUrl && !localVersion && !commitsBehind;
+ get finishInstall() {
+ return (
+ this.model?.remote_theme?.remote_url &&
+ !this.model?.remote_theme?.local_version &&
+ !this.model?.remote_theme?.commits_behind
+ );
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
index 398345efa48..32c06eaa62b 100644
--- a/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
+++ b/frontend/discourse/admin/controllers/admin-customize-themes/show/index.js
@@ -1,5 +1,5 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import {
empty,
filterBy,
@@ -16,7 +16,6 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
import { url } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { makeArray } from "discourse/lib/helpers";
import { i18n } from "discourse-i18n";
import ThemeUploadAddModal from "../../../components/theme-upload-add";
@@ -51,13 +50,13 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
@readOnly("model.settings") settings;
@readOnly("model.themeable_site_settings") themeSiteSettings;
- @discourseComputed("model.component", "model.remote_theme")
- showCheckboxes() {
+ @computed("model.component", "model.remote_theme")
+ get showCheckboxes() {
return !this.model.component || this.model.remote_theme;
}
- @discourseComputed("model.theme_fields.[]")
- extraFiles() {
+ @computed("model.theme_fields.[]")
+ get extraFiles() {
return this.model.theme_fields
?.filter(
({ target, type_id }) =>
@@ -67,8 +66,8 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
?.sort((a, b) => (a.file_path || "").localeCompare(b.file_path || ""));
}
- @discourseComputed("model.editedFields")
- editedFieldsFormatted() {
+ @computed("model.editedFields")
+ get editedFieldsFormatted() {
const descriptions = [];
["common", "desktop", "mobile"].forEach((target) => {
const fields = this.editedFieldsForTarget(target);
@@ -90,32 +89,37 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
return descriptions;
}
- @discourseComputed("colorSchemeId", "model.color_scheme_id")
- lightColorSchemeChanged(colorSchemeId, existingId) {
- colorSchemeId = colorSchemeId === null ? null : parseInt(colorSchemeId, 10);
+ @computed("colorSchemeId", "model.color_scheme_id")
+ get lightColorSchemeChanged() {
+ const colorSchemeId =
+ this.colorSchemeId === null ? null : parseInt(this.colorSchemeId, 10);
- return colorSchemeId !== existingId;
+ return colorSchemeId !== this.model?.color_scheme_id;
}
- @discourseComputed("darkColorSchemeId", "model.dark_color_scheme_id")
- darkColorSchemeChanged(darkColorSchemeId, existingId) {
- darkColorSchemeId =
- darkColorSchemeId === null ? null : parseInt(darkColorSchemeId, 10);
- return darkColorSchemeId !== existingId;
+ @computed("darkColorSchemeId", "model.dark_color_scheme_id")
+ get darkColorSchemeChanged() {
+ const darkColorSchemeId =
+ this.darkColorSchemeId === null
+ ? null
+ : parseInt(this.darkColorSchemeId, 10);
+ return darkColorSchemeId !== this.model?.dark_color_scheme_id;
}
- @discourseComputed("availableChildThemes", "model.childThemes.[]", "model")
- selectableChildThemes(available, childThemes) {
- if (available) {
- const themes = !childThemes
- ? available
- : available.filter((theme) => !childThemes.includes(theme));
+ @computed("availableChildThemes", "model.childThemes.[]", "model")
+ get selectableChildThemes() {
+ if (this.availableChildThemes) {
+ const themes = !this.model?.childThemes
+ ? this.availableChildThemes
+ : this.availableChildThemes.filter(
+ (theme) => !this.model?.childThemes.includes(theme)
+ );
return themes.length === 0 ? null : themes;
}
}
- @discourseComputed("model.parentThemes.[]")
- relativesSelectorSettingsForComponent() {
+ @computed("model.parentThemes.[]")
+ get relativesSelectorSettingsForComponent() {
return SiteSetting.create({
list_type: "compact",
type: "list",
@@ -132,8 +136,8 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
});
}
- @discourseComputed("model.childThemesNames.[]")
- relativesSelectorSettingsForTheme() {
+ @computed("model.childThemesNames.[]")
+ get relativesSelectorSettingsForTheme() {
return SiteSetting.create({
list_type: "compact",
type: "list",
@@ -150,47 +154,51 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
});
}
- @discourseComputed("allThemes", "model.component", "model")
- availableChildThemes(allThemes) {
+ @computed("allThemes", "model.component", "model")
+ get availableChildThemes() {
if (!this.get("model.component")) {
const themeId = this.get("model.id");
- return allThemes.filter(
+ return this.allThemes.filter(
(theme) => theme.get("id") !== themeId && theme.get("component")
);
}
}
- @discourseComputed("model.component")
- convertKey(component) {
- const type = component ? "component" : "theme";
+ @computed("model.component")
+ get convertKey() {
+ const type = this.model?.component ? "component" : "theme";
return `admin.customize.theme.convert_${type}`;
}
- @discourseComputed("model.component")
- convertTooltip(component) {
- const type = component ? "component" : "theme";
+ @computed("model.component")
+ get convertTooltip() {
+ const type = this.model?.component ? "component" : "theme";
return `admin.customize.theme.convert_${type}_tooltip`;
}
- @discourseComputed("model.translations")
- translations(translations) {
- return translations.map((setting) =>
+ @computed("model.translations")
+ get translations() {
+ return this.model?.translations?.map((setting) =>
ThemeSettings.create({ ...setting, textarea: true })
);
}
- @discourseComputed(
+ @computed(
"model.remote_theme.local_version",
"model.remote_theme.remote_version",
"model.remote_theme.commits_behind"
)
- hasOverwrittenHistory(localVersion, remoteVersion, commitsBehind) {
- return localVersion !== remoteVersion && commitsBehind === -1;
+ get hasOverwrittenHistory() {
+ return (
+ this.model?.remote_theme?.local_version !==
+ this.model?.remote_theme?.remote_version &&
+ this.model?.remote_theme?.commits_behind === -1
+ );
}
- @discourseComputed("model.remoteError", "updatingRemote")
- showRemoteError(errorMessage, updating) {
- return errorMessage && !updating;
+ @computed("model.remoteError", "updatingRemote")
+ get showRemoteError() {
+ return this.model?.remoteError && !this.updatingRemote;
}
editedFieldsForTarget(target) {
@@ -249,9 +257,9 @@ export default class AdminCustomizeThemesShowIndexController extends Controller
);
}
- @discourseComputed("model.user.id", "model.default")
- showConvert(userId, defaultTheme) {
- return userId > 0 && !defaultTheme;
+ @computed("model.user.id", "model.default")
+ get showConvert() {
+ return this.model?.user?.id > 0 && !this.model?.default;
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-email-templates/edit.js b/frontend/discourse/admin/controllers/admin-email-templates/edit.js
index 560e9aa8631..006a202e3a5 100644
--- a/frontend/discourse/admin/controllers/admin-email-templates/edit.js
+++ b/frontend/discourse/admin/controllers/admin-email-templates/edit.js
@@ -1,12 +1,11 @@
import { cached, tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { service } from "@ember/service";
import BufferedProxy from "ember-buffered-proxy/proxy";
import { interpolationKeysWithStatus as computeInterpolationKeysWithStatus } from "discourse/admin/lib/interpolation-keys";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { isObject } from "discourse/lib/object";
import { i18n } from "discourse-i18n";
@@ -28,28 +27,30 @@ export default class AdminEmailTemplatesEditController extends Controller {
});
}
- @discourseComputed("buffered.body", "buffered.subject")
- saveDisabled(body, subject) {
+ @computed("buffered.body", "buffered.subject")
+ get saveDisabled() {
+ // TODO (devxp) we need a buffered proxy that works with tracked properties
return (
- this.emailTemplate.body === body && this.emailTemplate.subject === subject
+ this.emailTemplate.body === this.get("buffered.body") &&
+ this.emailTemplate.subject === this.get("buffered.subject")
);
}
- @discourseComputed("buffered")
- hasMultipleSubjects(buffered) {
- if (buffered.getProperties("subject")["subject"]) {
+ @computed("buffered")
+ get hasMultipleSubjects() {
+ if (this.buffered.getProperties("subject")["subject"]) {
return false;
} else {
- return buffered.getProperties("id")["id"];
+ return this.buffered.getProperties("id")["id"];
}
}
- @discourseComputed("buffered")
- hasMultipleBodyTemplates(buffered) {
- if (!isObject(buffered.getProperties("body")["body"])) {
+ @computed("buffered")
+ get hasMultipleBodyTemplates() {
+ if (!isObject(this.buffered.getProperties("body")["body"])) {
return false;
} else {
- return buffered.getProperties("id")["id"];
+ return this.buffered.getProperties("id")["id"];
}
}
@@ -135,15 +136,15 @@ export default class AdminEmailTemplatesEditController extends Controller {
});
}
- @discourseComputed(
+ @computed(
"buffered.subject",
"buffered.body",
"emailTemplate.interpolation_keys"
)
- interpolationKeysWithStatus(subject, body, keys) {
+ get interpolationKeysWithStatus() {
return computeInterpolationKeysWithStatus(
- `${subject || ""} ${body || ""}`,
- keys
+ `${this.get("buffered.subject") || ""} ${this.get("buffered.body") || ""}`,
+ this.emailTemplate.interpolation_keys
);
}
}
diff --git a/frontend/discourse/admin/controllers/admin-logs/staff-action-logs.js b/frontend/discourse/admin/controllers/admin-logs/staff-action-logs.js
index 83884e24300..1ec2338ba74 100644
--- a/frontend/discourse/admin/controllers/admin-logs/staff-action-logs.js
+++ b/frontend/discourse/admin/controllers/admin-logs/staff-action-logs.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { exportEntity } from "discourse/lib/export-csv";
import { outputExportResult } from "discourse/lib/export-result";
import { i18n } from "discourse-i18n";
@@ -22,14 +21,16 @@ export default class AdminLogsStaffActionLogsController extends Controller {
/** @type {moment.Moment | null} */
endDate = null;
- @discourseComputed("filters.action_name")
- actionFilter(name) {
- return name ? i18n("admin.logs.staff_actions.actions." + name) : null;
+ @computed("filters.action_name")
+ get actionFilter() {
+ return this.filters?.action_name
+ ? i18n("admin.logs.staff_actions.actions." + this.filters?.action_name)
+ : null;
}
- @discourseComputed("filters")
- filtersExists(filters) {
- return filters && Object.keys(filters).length > 0;
+ @computed("filters")
+ get filtersExists() {
+ return this.filters && Object.keys(this.filters).length > 0;
}
_refresh() {
diff --git a/frontend/discourse/admin/controllers/admin-reports/show.js b/frontend/discourse/admin/controllers/admin-reports/show.js
index 003478152fc..8a2dcf8f95d 100644
--- a/frontend/discourse/admin/controllers/admin-reports/show.js
+++ b/frontend/discourse/admin/controllers/admin-reports/show.js
@@ -1,5 +1,5 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import { applyValueTransformer } from "discourse/lib/transformer";
export default class AdminReportsShowController extends Controller {
@@ -15,15 +15,15 @@ export default class AdminReportsShowController extends Controller {
filters = null;
chart_grouping = null;
- @discourseComputed("model.type")
- reportOptions(type) {
+ @computed("model.type")
+ get reportOptions() {
let options = { table: { perPage: 50, limit: 50 } };
- if (type === "top_referred_topics") {
+ if (this.model?.type === "top_referred_topics") {
options.table.limit = 10;
}
- if (type === "site_traffic") {
+ if (this.model?.type === "site_traffic") {
options.stackedChart = {
hiddenLabels: ["page_view_other", "page_view_crawler"],
};
diff --git a/frontend/discourse/admin/controllers/admin-site-text/edit.js b/frontend/discourse/admin/controllers/admin-site-text/edit.js
index 56af7fa9edd..d20d649fe40 100644
--- a/frontend/discourse/admin/controllers/admin-site-text/edit.js
+++ b/frontend/discourse/admin/controllers/admin-site-text/edit.js
@@ -1,12 +1,11 @@
import { cached, tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { service } from "@ember/service";
import BufferedProxy from "ember-buffered-proxy/proxy";
import { interpolationKeysWithStatus as computeInterpolationKeysWithStatus } from "discourse/admin/lib/interpolation-keys";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminSiteTextEdit extends Controller {
@@ -27,14 +26,14 @@ export default class AdminSiteTextEdit extends Controller {
});
}
- @discourseComputed("buffered.value", "siteText.value")
- saveDisabled(value) {
- return this.siteText.value === value;
+ @computed("buffered.value", "siteText.value")
+ get saveDisabled() {
+ return this.siteText.value === this.get("buffered.value"); // TODO (devxp) we need a buffered proxy that works with tracked properties
}
- @discourseComputed("siteText.status")
- isOutdated(status) {
- return status === "outdated";
+ @computed("siteText.status")
+ get isOutdated() {
+ return this.siteText?.status === "outdated";
}
@action
@@ -126,8 +125,11 @@ export default class AdminSiteTextEdit extends Controller {
.catch(popupAjaxError);
}
- @discourseComputed("buffered.value", "siteText.interpolation_keys")
- interpolationKeysWithStatus(value, keys) {
- return computeInterpolationKeysWithStatus(value, keys);
+ @computed("buffered.value", "siteText.interpolation_keys")
+ get interpolationKeysWithStatus() {
+ return computeInterpolationKeysWithStatus(
+ this.get("buffered.value"),
+ this.siteText.interpolation_keys
+ );
}
}
diff --git a/frontend/discourse/admin/controllers/admin-user/index.js b/frontend/discourse/admin/controllers/admin-user/index.js
index b2933f1948c..d6a7b7a9af1 100644
--- a/frontend/discourse/admin/controllers/admin-user/index.js
+++ b/frontend/discourse/admin/controllers/admin-user/index.js
@@ -9,7 +9,6 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { fmt, propertyNotEqual, setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import DiscourseURL, { userPath } from "discourse/lib/url";
import { i18n } from "discourse-i18n";
@@ -81,22 +80,20 @@ export default class AdminUserIndexController extends Controller {
?.join(", ");
}
- @discourseComputed("model.user_fields.[]")
- userFields(userFields) {
- return this.site.collectUserFields(userFields);
+ @computed("model.user_fields.[]")
+ get userFields() {
+ return this.site.collectUserFields(this.model?.user_fields);
}
- @discourseComputed(
- "model.can_delete_all_posts",
- "model.admin",
- "model.post_count"
- )
- deleteAllPostsExplanation(canDeleteAllPosts, admin, postCount) {
- if (canDeleteAllPosts) {
+ @computed("model.can_delete_all_posts", "model.admin", "model.post_count")
+ get deleteAllPostsExplanation() {
+ if (this.model?.can_delete_all_posts) {
return null;
- } else if (admin) {
+ } else if (this.model?.admin) {
return i18n("admin.user.delete_posts_forbidden_because_admin");
- } else if (postCount > this.siteSettings.delete_all_posts_max) {
+ } else if (
+ this.model?.post_count > this.siteSettings.delete_all_posts_max
+ ) {
return i18n("admin.user.cant_delete_all_too_many_posts", {
count: this.siteSettings.delete_all_posts_max,
});
@@ -107,11 +104,11 @@ export default class AdminUserIndexController extends Controller {
}
}
- @discourseComputed("model.canBeDeleted", "model.admin")
- deleteExplanation(canBeDeleted, admin) {
- if (canBeDeleted) {
+ @computed("model.canBeDeleted", "model.admin")
+ get deleteExplanation() {
+ if (this.model?.canBeDeleted) {
return null;
- } else if (admin) {
+ } else if (this.model?.admin) {
return i18n("admin.user.delete_forbidden_because_admin");
} else {
return i18n("admin.user.delete_forbidden", {
@@ -120,9 +117,9 @@ export default class AdminUserIndexController extends Controller {
}
}
- @discourseComputed("model.username")
- postEditsByEditorFilter(username) {
- return { editor: username };
+ @computed("model.username")
+ get postEditsByEditorFilter() {
+ return { editor: this.model?.username };
}
@computed("model.id", "currentUser.id")
@@ -160,9 +157,9 @@ export default class AdminUserIndexController extends Controller {
.catch(() => this.dialog.alert(i18n("generic_error")));
}
- @discourseComputed("ssoLastPayload")
- ssoPayload(lastPayload) {
- return lastPayload.split("&");
+ @computed("ssoLastPayload")
+ get ssoPayload() {
+ return this.ssoLastPayload.split("&");
}
@action
diff --git a/frontend/discourse/admin/controllers/admin-users-list/show.js b/frontend/discourse/admin/controllers/admin-users-list/show.js
index f44f4e4b040..5f5abb77a42 100644
--- a/frontend/discourse/admin/controllers/admin-users-list/show.js
+++ b/frontend/discourse/admin/controllers/admin-users-list/show.js
@@ -8,7 +8,7 @@ import AdminUser from "discourse/admin/models/admin-user";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { computedI18n, setting } from "discourse/lib/computed";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import { i18n } from "discourse-i18n";
@@ -42,16 +42,16 @@ export default class AdminUsersListShowController extends Controller {
return this._results.flat();
}
- @discourseComputed("query")
- title(query) {
- return i18n("admin.users.titles." + query);
+ @computed("query")
+ get title() {
+ return i18n("admin.users.titles." + this.query);
}
- @discourseComputed("showEmails")
- columnCount(showEmails) {
+ @computed("showEmails")
+ get columnCount() {
let colCount = 7; // note that the first column is hardcoded in the template
- if (showEmails) {
+ if (this.showEmails) {
colCount += 1;
}
diff --git a/frontend/discourse/admin/controllers/admin.js b/frontend/discourse/admin/controllers/admin.js
index aece8c720a6..c6dfb8b7876 100644
--- a/frontend/discourse/admin/controllers/admin.js
+++ b/frontend/discourse/admin/controllers/admin.js
@@ -1,27 +1,27 @@
import Controller from "@ember/controller";
+import { computed } from "@ember/object";
import { service } from "@ember/service";
import { dasherize } from "@ember/string";
-import discourseComputed from "discourse/lib/decorators";
export default class AdminController extends Controller {
@service router;
@service currentUser;
- @discourseComputed("siteSettings.enable_group_directory")
- showGroups(enableGroupDirectory) {
- return !enableGroupDirectory;
+ @computed("siteSettings.enable_group_directory")
+ get showGroups() {
+ return !this.siteSettings?.enable_group_directory;
}
- @discourseComputed("siteSettings.enable_badges")
- showBadges(enableBadges) {
- return this.currentUser.get("admin") && enableBadges;
+ @computed("siteSettings.enable_badges")
+ get showBadges() {
+ return this.currentUser.get("admin") && this.siteSettings?.enable_badges;
}
- @discourseComputed("router._router.currentPath")
- adminContentsClassName(currentPath) {
- let cssClasses = currentPath
- .split(".")
- .filter((segment) => {
+ @computed("router._router.currentPath")
+ get adminContentsClassName() {
+ let cssClasses = this.router?._router?.currentPath
+ ?.split(".")
+ ?.filter((segment) => {
return (
segment !== "index" &&
segment !== "loading" &&
@@ -29,8 +29,8 @@ export default class AdminController extends Controller {
segment !== "admin"
);
})
- .map(dasherize)
- .join(" ");
+ ?.map(dasherize)
+ ?.join(" ");
// this is done to avoid breaking css customizations
if (cssClasses.includes("dashboard")) {
diff --git a/frontend/discourse/admin/controllers/admin/backups/index.js b/frontend/discourse/admin/controllers/admin/backups/index.js
index 19342d540b2..a58cfb463df 100644
--- a/frontend/discourse/admin/controllers/admin/backups/index.js
+++ b/frontend/discourse/admin/controllers/admin/backups/index.js
@@ -1,11 +1,10 @@
import Controller, { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, equal } from "@ember/object/computed";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { computedI18n, setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { i18n } from "discourse-i18n";
@@ -22,11 +21,11 @@ export default class AdminBackupsIndexController extends Controller {
return getURL("/admin/backups/settings?filter=allow_restore");
}
- @discourseComputed("status.allowRestore", "status.isOperationRunning")
- restoreTitle(allowRestore, isOperationRunning) {
- if (!allowRestore) {
+ @computed("status.allowRestore", "status.isOperationRunning")
+ get restoreTitle() {
+ if (!this.status?.allowRestore) {
return "admin.backups.operations.restore.is_disabled_title";
- } else if (isOperationRunning) {
+ } else if (this.status?.isOperationRunning) {
return "admin.backups.operations.is_running";
} else {
return "admin.backups.operations.restore.title";
@@ -43,8 +42,8 @@ export default class AdminBackupsIndexController extends Controller {
}
}
- @discourseComputed("status.isOperationRunning")
- deleteTitle() {
+ @computed("status.isOperationRunning")
+ get deleteTitle() {
if (this.status.isOperationRunning) {
return "admin.backups.operations.is_running";
}
diff --git a/frontend/discourse/admin/controllers/admin/dashboard-moderation.js b/frontend/discourse/admin/controllers/admin/dashboard-moderation.js
index eb102191c1c..940abfe74ae 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard-moderation.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard-moderation.js
@@ -1,10 +1,9 @@
import { computed } from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
import AdminDashboardTabController from "../admin-dashboard-tab";
export default class AdminDashboardModerationController extends AdminDashboardTabController {
- @discourseComputed
- flagsStatusOptions() {
+ @computed
+ get flagsStatusOptions() {
return {
table: {
total: false,
@@ -21,8 +20,8 @@ export default class AdminDashboardModerationController extends AdminDashboardTa
.includes("moderators_activity");
}
- @discourseComputed
- userFlaggingRatioOptions() {
+ @computed
+ get userFlaggingRatioOptions() {
return {
table: {
total: false,
@@ -31,14 +30,14 @@ export default class AdminDashboardModerationController extends AdminDashboardTa
};
}
- @discourseComputed("endDate")
- lastWeekFilters(endDate) {
+ @computed("endDate")
+ get lastWeekFilters() {
const lastWeek = moment()
.locale("en")
.utc()
.endOf("day")
.subtract(1, "week");
- return { lastWeek, endDate };
+ return { lastWeek, endDate: this.endDate };
}
}
diff --git a/frontend/discourse/admin/controllers/admin/dashboard-reports.js b/frontend/discourse/admin/controllers/admin/dashboard-reports.js
index b22a38fe685..b332e992815 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard-reports.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard-reports.js
@@ -1,18 +1,15 @@
import Controller from "@ember/controller";
-import { action, get } from "@ember/object";
+import { action, computed, get } from "@ember/object";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
export default class AdminDashboardReportsController extends Controller {
filter = null;
- @discourseComputed(
- "model.[]",
- "filter",
- "siteSettings.dashboard_hidden_reports"
- )
- filteredReports(reports, filter) {
+ @computed("model.[]", "filter", "siteSettings.dashboard_hidden_reports")
+ get filteredReports() {
+ let reports = this.model;
+ let filter = this.filter;
if (filter) {
filter = filter.toLowerCase();
reports = reports.filter((report) => {
diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.js
index 4bf7574b47f..9e2bbd8b921 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard.js
@@ -5,7 +5,6 @@ import { service } from "@ember/service";
import AdminDashboard from "discourse/admin/models/admin-dashboard";
import VersionCheck from "discourse/admin/models/version-check";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
const PROBLEMS_CHECK_MINUTES = 1;
@@ -109,9 +108,9 @@ export default class AdminDashboardController extends Controller {
}
}
- @discourseComputed("problemsFetchedAt")
- problemsTimestamp(problemsFetchedAt) {
- return moment(problemsFetchedAt).format("LLL");
+ @computed("problemsFetchedAt")
+ get problemsTimestamp() {
+ return moment(this.problemsFetchedAt).format("LLL");
}
@action
diff --git a/frontend/discourse/admin/controllers/admin/dashboard/general.js b/frontend/discourse/admin/controllers/admin/dashboard/general.js
index f98cc47910e..75f22acd91f 100644
--- a/frontend/discourse/admin/controllers/admin/dashboard/general.js
+++ b/frontend/discourse/admin/controllers/admin/dashboard/general.js
@@ -5,7 +5,6 @@ import { REPORT_MODES } from "discourse/admin/lib/constants";
import AdminDashboard from "discourse/admin/models/admin-dashboard";
import Report from "discourse/admin/models/report";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { makeArray } from "discourse/lib/helpers";
import { i18n } from "discourse-i18n";
@@ -35,9 +34,11 @@ export default class AdminDashboardGeneralController extends AdminDashboardTabCo
return REPORT_MODES;
}
- @discourseComputed("siteSettings.dashboard_general_tab_activity_metrics")
- activityMetrics(metrics) {
- return (metrics || "").split("|").filter(Boolean);
+ @computed("siteSettings.dashboard_general_tab_activity_metrics")
+ get activityMetrics() {
+ return (this.siteSettings?.dashboard_general_tab_activity_metrics || "")
+ .split("|")
+ .filter(Boolean);
}
@computed("siteSettings.dashboard_hidden_reports")
@@ -76,13 +77,13 @@ export default class AdminDashboardGeneralController extends AdminDashboardTabCo
].some((report) => !this.hiddenReports.includes(report));
}
- @discourseComputed
- today() {
+ @computed
+ get today() {
return moment().locale("en").utc().endOf("day");
}
- @discourseComputed
- activityMetricsFilters() {
+ @computed
+ get activityMetricsFilters() {
const lastMonth = moment()
.locale("en")
.utc()
@@ -95,45 +96,45 @@ export default class AdminDashboardGeneralController extends AdminDashboardTabCo
};
}
- @discourseComputed
- topReferredTopicsOptions() {
+ @computed
+ get topReferredTopicsOptions() {
return {
table: { total: false, limit: 8 },
};
}
- @discourseComputed
- siteTrafficOptions() {
+ @computed
+ get siteTrafficOptions() {
return {
stackedChart: { hiddenLabels: ["page_view_other", "page_view_crawler"] },
};
}
- @discourseComputed
- topReferredTopicsFilters() {
+ @computed
+ get topReferredTopicsFilters() {
return {
startDate: moment().subtract(6, "days").startOf("day"),
endDate: this.today,
};
}
- @discourseComputed
- trendingSearchFilters() {
+ @computed
+ get trendingSearchFilters() {
return {
startDate: moment().subtract(1, "month").startOf("day"),
endDate: this.today,
};
}
- @discourseComputed
- trendingSearchOptions() {
+ @computed
+ get trendingSearchOptions() {
return {
table: { total: false, limit: 8 },
};
}
- @discourseComputed
- trendingSearchDisabledLabel() {
+ @computed
+ get trendingSearchDisabledLabel() {
return i18n("admin.dashboard.reports.trending_search.disabled", {
basePath: getURL(""),
});
diff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.js
index 5579c5d9869..d54ca2d0649 100644
--- a/frontend/discourse/admin/controllers/edit-category/tabs.js
+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js
@@ -1,12 +1,11 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action, getProperties } from "@ember/object";
+import { action, computed, getProperties } from "@ember/object";
import { and } from "@ember/object/computed";
import { next } from "@ember/runloop";
import { service } from "@ember/service";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import { registeredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
import getURL from "discourse/lib/get-url";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
@@ -115,23 +114,23 @@ export default class EditCategoryTabsController extends Controller {
return data;
}
- @discourseComputed("saving", "deleting")
- deleteDisabled(saving, deleting) {
- return deleting || saving || false;
+ @computed("saving", "deleting")
+ get deleteDisabled() {
+ return this.deleting || this.saving || false;
}
- @discourseComputed("name")
- categoryName(name) {
- name = name || "";
+ @computed("name")
+ get categoryName() {
+ const name = this.name || "";
return name.trim().length > 0 ? name : i18n("preview");
}
- @discourseComputed("saving", "model.id")
- saveLabel(saving, id) {
- if (saving) {
+ @computed("saving", "model.id")
+ get saveLabel() {
+ if (this.saving) {
return "saving";
}
- return id ? "category.save" : "category.create_category";
+ return this.model?.id ? "category.save" : "category.create_category";
}
get baseTitle() {
diff --git a/frontend/discourse/admin/models/admin-user.js b/frontend/discourse/admin/models/admin-user.js
index e3f15aa14a0..9c67dcae924 100644
--- a/frontend/discourse/admin/models/admin-user.js
+++ b/frontend/discourse/admin/models/admin-user.js
@@ -1,8 +1,8 @@
+import { computed } from "@ember/object";
import { gt, lt, not, or } from "@ember/object/computed";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { propertyNotEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { userPath } from "discourse/lib/url";
@@ -49,30 +49,30 @@ export default class AdminUser extends User {
return this.groups?.filter((g) => g.automatic) ?? [];
}
- @discourseComputed("bounce_score", "reset_bounce_score_after")
- bounceScore(bounce_score, reset_bounce_score_after) {
- if (bounce_score > 0) {
- return `${bounce_score} - ${moment(reset_bounce_score_after).format(
- "LL"
- )}`;
+ @computed("bounce_score", "reset_bounce_score_after")
+ get bounceScore() {
+ if (this.bounce_score > 0) {
+ return `${this.bounce_score} - ${moment(
+ this.reset_bounce_score_after
+ ).format("LL")}`;
} else {
- return bounce_score;
+ return this.bounce_score;
}
}
- @discourseComputed("bounce_score")
- bounceScoreExplanation(bounce_score) {
- if (bounce_score === 0) {
+ @computed("bounce_score")
+ get bounceScoreExplanation() {
+ if (this.bounce_score === 0) {
return i18n("admin.user.bounce_score_explanation.none");
- } else if (bounce_score < this.siteSettings.bounce_score_threshold) {
+ } else if (this.bounce_score < this.siteSettings.bounce_score_threshold) {
return i18n("admin.user.bounce_score_explanation.some");
} else {
return i18n("admin.user.bounce_score_explanation.threshold_reached");
}
}
- @discourseComputed
- bounceLink() {
+ @computed
+ get bounceLink() {
return getURL("/admin/email-logs/bounced");
}
@@ -228,10 +228,10 @@ export default class AdminUser extends User {
});
}
- @discourseComputed("suspended_till", "suspended_at")
- suspendDuration(suspendedTill, suspendedAt) {
- suspendedAt = moment(suspendedAt);
- suspendedTill = moment(suspendedTill);
+ @computed("suspended_till", "suspended_at")
+ get suspendDuration() {
+ const suspendedAt = moment(this.suspended_at);
+ const suspendedTill = moment(this.suspended_till);
return suspendedAt.format("L") + " - " + suspendedTill.format("L");
}
@@ -370,26 +370,26 @@ export default class AdminUser extends User {
return this;
}
- @discourseComputed("tl3_requirements")
- tl3Requirements(requirements) {
- if (requirements) {
- return this.store.createRecord("tl3Requirements", requirements);
+ @computed("tl3_requirements")
+ get tl3Requirements() {
+ if (this.tl3_requirements) {
+ return this.store.createRecord("tl3Requirements", this.tl3_requirements);
}
}
- @discourseComputed("suspended_by")
- suspendedBy(user) {
- return user ? AdminUser.create(user) : null;
+ @computed("suspended_by")
+ get suspendedBy() {
+ return this.suspended_by ? AdminUser.create(this.suspended_by) : null;
}
- @discourseComputed("silenced_by")
- silencedBy(user) {
- return user ? AdminUser.create(user) : null;
+ @computed("silenced_by")
+ get silencedBy() {
+ return this.silenced_by ? AdminUser.create(this.silenced_by) : null;
}
- @discourseComputed("approved_by")
- approvedBy(user) {
- return user ? AdminUser.create(user) : null;
+ @computed("approved_by")
+ get approvedBy() {
+ return this.approved_by ? AdminUser.create(this.approved_by) : null;
}
deleteSSORecord() {
diff --git a/frontend/discourse/admin/models/api-key.js b/frontend/discourse/admin/models/api-key.js
index 3e41acd039d..841f54ad118 100644
--- a/frontend/discourse/admin/models/api-key.js
+++ b/frontend/discourse/admin/models/api-key.js
@@ -2,7 +2,6 @@ import { computed } from "@ember/object";
import AdminUser from "discourse/admin/models/admin-user";
import { ajax } from "discourse/lib/ajax";
import { fmt } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import RestModel from "discourse/models/rest";
export default class ApiKey extends RestModel {
@@ -34,12 +33,12 @@ export default class ApiKey extends RestModel {
}
}
- @discourseComputed("description")
- shortDescription(description) {
- if (!description || description.length < 40) {
- return description;
+ @computed("description")
+ get shortDescription() {
+ if (!this.description || this.description.length < 40) {
+ return this.description;
}
- return `${description.substring(0, 40)}...`;
+ return `${this.description.substring(0, 40)}...`;
}
revoke() {
@@ -63,8 +62,8 @@ export default class ApiKey extends RestModel {
);
}
- @discourseComputed()
- basePath() {
+ @computed()
+ get basePath() {
return this.store
.adapterFor("api-key")
.pathFor(this.store, "api-key", this.id);
diff --git a/frontend/discourse/admin/models/backup-status.js b/frontend/discourse/admin/models/backup-status.js
index 175b2340cc2..60d8ef21853 100644
--- a/frontend/discourse/admin/models/backup-status.js
+++ b/frontend/discourse/admin/models/backup-status.js
@@ -1,12 +1,11 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { not } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
export default class BackupStatus extends EmberObject {
@not("restoreEnabled") restoreDisabled;
- @discourseComputed("allowRestore", "isOperationRunning")
- restoreEnabled(allowRestore, isOperationRunning) {
- return allowRestore && !isOperationRunning;
+ @computed("allowRestore", "isOperationRunning")
+ get restoreEnabled() {
+ return this.allowRestore && !this.isOperationRunning;
}
}
diff --git a/frontend/discourse/admin/models/color-scheme-color.js b/frontend/discourse/admin/models/color-scheme-color.js
index 02fe18604fc..c22d9e7a946 100644
--- a/frontend/discourse/admin/models/color-scheme-color.js
+++ b/frontend/discourse/admin/models/color-scheme-color.js
@@ -1,10 +1,9 @@
/* eslint-disable ember/no-observers */
import { tracked } from "@glimmer/tracking";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { observes, on } from "@ember-decorators/object";
import { isValidHex, normalizeHex } from "discourse/lib/color-transformations";
import { propertyNotEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ColorSchemeColor extends EmberObject {
@@ -35,24 +34,24 @@ export default class ColorSchemeColor extends EmberObject {
}
// Whether value has changed since it was last saved.
- @discourseComputed("hex")
- changed(hex) {
+ @computed("hex")
+ get changed() {
if (!this.originals) {
return false;
}
- if (hex !== this.originals.hex) {
+ if (this.hex !== this.originals.hex) {
return true;
}
return false;
}
// Whether the saved value is different than Discourse's default color scheme.
- @discourseComputed("default_hex", "hex")
- savedIsOverriden(defaultHex) {
- if (!defaultHex) {
+ @computed("default_hex", "hex")
+ get savedIsOverriden() {
+ if (!this.default_hex) {
return false;
}
- return this.originals.hex !== defaultHex;
+ return this.originals.hex !== this.default_hex;
}
revert() {
@@ -65,14 +64,16 @@ export default class ColorSchemeColor extends EmberObject {
}
}
- @discourseComputed("name")
- translatedName(name) {
- return i18n(`admin.customize.colors.${name}.name`, { defaultValue: name });
+ @computed("name")
+ get translatedName() {
+ return i18n(`admin.customize.colors.${this.name}.name`, {
+ defaultValue: this.name,
+ });
}
- @discourseComputed("name")
- description(name) {
- return i18n(`admin.customize.colors.${name}.description`, {
+ @computed("name")
+ get description() {
+ return i18n(`admin.customize.colors.${this.name}.description`, {
defaultValue: "",
});
}
@@ -83,8 +84,9 @@ export default class ColorSchemeColor extends EmberObject {
@property brightness
**/
- @discourseComputed("hex")
- brightness(hex) {
+ @computed("hex")
+ get brightness() {
+ let hex = this.hex;
if (hex.length === 6 || hex.length === 3) {
hex = normalizeHex(hex);
return Math.round(
@@ -103,8 +105,8 @@ export default class ColorSchemeColor extends EmberObject {
}
}
- @discourseComputed("hex")
- valid(hex) {
- return isValidHex(hex);
+ @computed("hex")
+ get valid() {
+ return isValidHex(this.hex);
}
}
diff --git a/frontend/discourse/admin/models/color-scheme.js b/frontend/discourse/admin/models/color-scheme.js
index e3a4f377b24..d453c9a98ec 100644
--- a/frontend/discourse/admin/models/color-scheme.js
+++ b/frontend/discourse/admin/models/color-scheme.js
@@ -1,9 +1,8 @@
import { tracked } from "@glimmer/tracking";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { not } from "@ember/object/computed";
import ColorSchemeColor from "discourse/admin/models/color-scheme-color";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import LegacyArrayLikeObject from "discourse/lib/legacy-array-like-object";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { i18n } from "discourse-i18n";
@@ -66,8 +65,8 @@ export default class ColorScheme extends EmberObject {
this.startTrackingChanges();
}
- @discourseComputed
- description() {
+ @computed
+ get description() {
return "" + this.name;
}
@@ -118,20 +117,15 @@ export default class ColorScheme extends EmberObject {
return newScheme;
}
- @discourseComputed(
- "name",
- "user_selectable",
- "saving"
- )
- changed(name, user_selectable) {
+ @computed("name", "user_selectable", "[email protected]", "saving")
+ get changed() {
if (!this.originals) {
return false;
}
- if (this.originals.name !== name) {
+ if (this.originals.name !== this.name) {
return true;
}
- if (this.originals.user_selectable !== user_selectable) {
+ if (this.originals.user_selectable !== this.user_selectable) {
return true;
}
if (this.colors.some((c) => c.get("changed"))) {
@@ -141,13 +135,15 @@ export default class ColorScheme extends EmberObject {
return false;
}
- @discourseComputed("changed")
- disableSave(changed) {
+ @computed("changed")
+ get disableSave() {
if (this.theme_id) {
return false;
}
- return !changed || this.saving || this.colors.some((c) => !c.get("valid"));
+ return (
+ !this.changed || this.saving || this.colors.some((c) => !c.get("valid"))
+ );
}
save(opts) {
diff --git a/frontend/discourse/admin/models/flag-type.js b/frontend/discourse/admin/models/flag-type.js
index 21278565162..bb2c018d521 100644
--- a/frontend/discourse/admin/models/flag-type.js
+++ b/frontend/discourse/admin/models/flag-type.js
@@ -1,10 +1,10 @@
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
export default class FlagType extends RestModel {
- @discourseComputed("id")
- name(id) {
- return i18n(`admin.flags.summary.action_type_${id}`, { count: 1 });
+ @computed("id")
+ get name() {
+ return i18n(`admin.flags.summary.action_type_${this.id}`, { count: 1 });
}
}
diff --git a/frontend/discourse/admin/models/permalink.js b/frontend/discourse/admin/models/permalink.js
index 3fb34c62fd8..e8b6cb751a1 100644
--- a/frontend/discourse/admin/models/permalink.js
+++ b/frontend/discourse/admin/models/permalink.js
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import DiscourseURL from "discourse/lib/url";
import Category from "discourse/models/category";
import RestModel from "discourse/models/rest";
@@ -10,18 +10,18 @@ export default class Permalink extends RestModel {
return data.map((p) => Permalink.create(p));
}
- @discourseComputed("category_id")
- category(category_id) {
- return Category.findById(category_id);
+ @computed("category_id")
+ get category() {
+ return Category.findById(this.category_id);
}
- @discourseComputed("external_url")
- linkIsExternal(external_url) {
- return !DiscourseURL.isInternal(external_url);
+ @computed("external_url")
+ get linkIsExternal() {
+ return !DiscourseURL.isInternal(this.external_url);
}
- @discourseComputed("url")
- key(url) {
- return url.replace("/", "_");
+ @computed("url")
+ get key() {
+ return this.url.replace("/", "_");
}
}
diff --git a/frontend/discourse/admin/models/report.js b/frontend/discourse/admin/models/report.js
index 0fc7f2d5298..3c9ce5c29ca 100644
--- a/frontend/discourse/admin/models/report.js
+++ b/frontend/discourse/admin/models/report.js
@@ -1,8 +1,7 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { isEmpty } from "@ember/utils";
import { renderAvatar } from "discourse/helpers/user-avatar";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { durationTiny, number } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
import { makeArray } from "discourse/lib/helpers";
@@ -205,14 +204,20 @@ export default class Report extends EmberObject {
description_link = null;
description = null;
- @discourseComputed("type", "start_date", "end_date")
- reportUrl(type, start_date, end_date) {
- start_date = moment.utc(start_date).locale("en").format("YYYY-MM-DD");
+ @computed("type", "start_date", "end_date")
+ get reportUrl() {
+ const start_date = moment
+ .utc(this.start_date)
+ .locale("en")
+ .format("YYYY-MM-DD");
- end_date = moment.utc(end_date).locale("en").format("YYYY-MM-DD");
+ const end_date = moment
+ .utc(this.end_date)
+ .locale("en")
+ .format("YYYY-MM-DD");
return getURL(
- `/admin/reports/${type}?start_date=${start_date}&end_date=${end_date}`
+ `/admin/reports/${this.type}?start_date=${start_date}&end_date=${end_date}`
);
}
@@ -251,33 +256,33 @@ export default class Report extends EmberObject {
}
}
- @discourseComputed("data", "average")
- todayCount() {
+ @computed("data", "average")
+ get todayCount() {
return this.valueAt(0);
}
- @discourseComputed("data", "average")
- yesterdayCount() {
+ @computed("data", "average")
+ get yesterdayCount() {
return this.valueAt(1);
}
- @discourseComputed("data", "average")
- sevenDaysAgoCount() {
+ @computed("data", "average")
+ get sevenDaysAgoCount() {
return this.valueAt(7);
}
- @discourseComputed("data", "average")
- thirtyDaysAgoCount() {
+ @computed("data", "average")
+ get thirtyDaysAgoCount() {
return this.valueAt(30);
}
- @discourseComputed("data", "average")
- lastSevenDaysCount() {
+ @computed("data", "average")
+ get lastSevenDaysCount() {
return this.averageCount(7, this.valueFor(1, 7));
}
- @discourseComputed("data", "average")
- lastThirtyDaysCount() {
+ @computed("data", "average")
+ get lastThirtyDaysCount() {
return this.averageCount(30, this.valueFor(1, 30));
}
@@ -285,85 +290,81 @@ export default class Report extends EmberObject {
return this.average ? value / count : value;
}
- @discourseComputed("yesterdayCount", "higher_is_better")
- yesterdayTrend(yesterdayCount, higherIsBetter) {
- return this._computeTrend(this.valueAt(2), yesterdayCount, higherIsBetter);
+ @computed("yesterdayCount", "higher_is_better")
+ get yesterdayTrend() {
+ return this._computeTrend(
+ this.valueAt(2),
+ this.yesterdayCount,
+ this.higher_is_better
+ );
}
- @discourseComputed("lastSevenDaysCount", "higher_is_better")
- sevenDaysTrend(lastSevenDaysCount, higherIsBetter) {
+ @computed("lastSevenDaysCount", "higher_is_better")
+ get sevenDaysTrend() {
return this._computeTrend(
this.valueFor(8, 14),
- lastSevenDaysCount,
- higherIsBetter
+ this.lastSevenDaysCount,
+ this.higher_is_better
);
}
- @discourseComputed("data")
- currentTotal(data) {
- return data.reduce((cur, pair) => cur + pair.y, 0);
+ @computed("data")
+ get currentTotal() {
+ return this.data.reduce((cur, pair) => cur + pair.y, 0);
}
- @discourseComputed("data", "currentTotal")
- currentAverage(data, total) {
- return makeArray(data).length === 0
+ @computed("data", "currentTotal")
+ get currentAverage() {
+ return makeArray(this.data).length === 0
? 0
- : parseFloat((total / parseFloat(data.length)).toFixed(1));
+ : parseFloat(
+ (this.currentTotal / parseFloat(this.data.length)).toFixed(1)
+ );
}
- @discourseComputed("trend", "higher_is_better")
- trendIcon(trend, higherIsBetter) {
- return this._iconForTrend(trend, higherIsBetter);
+ @computed("trend", "higher_is_better")
+ get trendIcon() {
+ return this._iconForTrend(this.trend, this.higher_is_better);
}
- @discourseComputed("sevenDaysTrend", "higher_is_better")
- sevenDaysTrendIcon(sevenDaysTrend, higherIsBetter) {
- return this._iconForTrend(sevenDaysTrend, higherIsBetter);
+ @computed("sevenDaysTrend", "higher_is_better")
+ get sevenDaysTrendIcon() {
+ return this._iconForTrend(this.sevenDaysTrend, this.higher_is_better);
}
- @discourseComputed("thirtyDaysTrend", "higher_is_better")
- thirtyDaysTrendIcon(thirtyDaysTrend, higherIsBetter) {
- return this._iconForTrend(thirtyDaysTrend, higherIsBetter);
+ @computed("thirtyDaysTrend", "higher_is_better")
+ get thirtyDaysTrendIcon() {
+ return this._iconForTrend(this.thirtyDaysTrend, this.higher_is_better);
}
- @discourseComputed("yesterdayTrend", "higher_is_better")
- yesterdayTrendIcon(yesterdayTrend, higherIsBetter) {
- return this._iconForTrend(yesterdayTrend, higherIsBetter);
+ @computed("yesterdayTrend", "higher_is_better")
+ get yesterdayTrendIcon() {
+ return this._iconForTrend(this.yesterdayTrend, this.higher_is_better);
}
- @discourseComputed(
- "prev_period",
- "currentTotal",
- "currentAverage",
- "higher_is_better"
- )
- trend(prev, currentTotal, currentAverage, higherIsBetter) {
- const total = this.average ? currentAverage : currentTotal;
- return this._computeTrend(prev, total, higherIsBetter);
+ @computed("prev_period", "currentTotal", "currentAverage", "higher_is_better")
+ get trend() {
+ const total = this.average ? this.currentAverage : this.currentTotal;
+ return this._computeTrend(this.prev_period, total, this.higher_is_better);
}
- @discourseComputed(
+ @computed(
"prev30Days",
"prev_period",
"lastThirtyDaysCount",
"higher_is_better"
)
- thirtyDaysTrend(
- prev30Days,
- prev_period,
- lastThirtyDaysCount,
- higherIsBetter
- ) {
+ get thirtyDaysTrend() {
return this._computeTrend(
- prev30Days ?? prev_period,
- lastThirtyDaysCount,
- higherIsBetter
+ this.prev30Days ?? this.prev_period,
+ this.lastThirtyDaysCount,
+ this.higher_is_better
);
}
- @discourseComputed("type")
- method(type) {
- if (type === "time_to_first_response") {
+ @computed("type")
+ get method() {
+ if (this.type === "time_to_first_response") {
return "average";
} else {
return "sum";
@@ -382,9 +383,10 @@ export default class Report extends EmberObject {
}
}
- @discourseComputed("prev_period", "currentTotal", "currentAverage")
- trendTitle(prev, currentTotal, currentAverage) {
- let current = this.average ? currentAverage : currentTotal;
+ @computed("prev_period", "currentTotal", "currentAverage")
+ get trendTitle() {
+ let prev = this.prev_period;
+ let current = this.average ? this.currentAverage : this.currentTotal;
let percent = this.percentChangeString(prev, current);
if (this.average) {
@@ -427,50 +429,50 @@ export default class Report extends EmberObject {
return title.join(" ");
}
- @discourseComputed("yesterdayCount")
- yesterdayCountTitle(yesterdayCount) {
- return this.changeTitle(this.valueAt(2), yesterdayCount, "yesterday");
+ @computed("yesterdayCount")
+ get yesterdayCountTitle() {
+ return this.changeTitle(this.valueAt(2), this.yesterdayCount, "yesterday");
}
- @discourseComputed("lastSevenDaysCount")
- sevenDaysCountTitle(lastSevenDaysCount) {
+ @computed("lastSevenDaysCount")
+ get sevenDaysCountTitle() {
return this.changeTitle(
this.valueFor(8, 14),
- lastSevenDaysCount,
+ this.lastSevenDaysCount,
"two_weeks_ago"
);
}
- @discourseComputed("prev30Days", "prev_period")
- canDisplayTrendIcon(prev30Days, prev_period) {
- return prev30Days ?? prev_period;
+ @computed("prev30Days", "prev_period")
+ get canDisplayTrendIcon() {
+ return this.prev30Days ?? this.prev_period;
}
- @discourseComputed("prev30Days", "prev_period", "lastThirtyDaysCount")
- thirtyDaysCountTitle(prev30Days, prev_period, lastThirtyDaysCount) {
+ @computed("prev30Days", "prev_period", "lastThirtyDaysCount")
+ get thirtyDaysCountTitle() {
return this.changeTitle(
- prev30Days ?? prev_period,
- lastThirtyDaysCount,
+ this.prev30Days ?? this.prev_period,
+ this.lastThirtyDaysCount,
"thirty_days_ago"
);
}
- @discourseComputed("data")
- sortedData(data) {
- return this.xAxisIsDate ? [...data].reverse() : [...data];
+ @computed("data")
+ get sortedData() {
+ return this.xAxisIsDate ? [...this.data].reverse() : [...this.data];
}
- @discourseComputed("data")
- xAxisIsDate() {
+ @computed("data")
+ get xAxisIsDate() {
if (!this.data[0]) {
return false;
}
return this.data && this.data[0].x.match(/\d{4}-\d{1,2}-\d{1,2}/);
}
- @discourseComputed("labels")
- computedLabels(labels) {
- return labels.map((label) => {
+ @computed("labels")
+ get computedLabels() {
+ return this.labels.map((label) => {
const type = label.type || "string";
let mainProperty;
diff --git a/frontend/discourse/admin/models/screened-email.js b/frontend/discourse/admin/models/screened-email.js
index a0e8680cce6..56622c3e284 100644
--- a/frontend/discourse/admin/models/screened-email.js
+++ b/frontend/discourse/admin/models/screened-email.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ScreenedEmail extends EmberObject {
@@ -14,9 +13,9 @@ export default class ScreenedEmail extends EmberObject {
);
}
- @discourseComputed("action")
- actionName(action) {
- return i18n("admin.logs.screened_actions." + action);
+ @computed("action")
+ get actionName() {
+ return i18n("admin.logs.screened_actions." + this.action);
}
clearBlock() {
diff --git a/frontend/discourse/admin/models/screened-ip-address.js b/frontend/discourse/admin/models/screened-ip-address.js
index 69a1fa901d0..1b639f54a77 100644
--- a/frontend/discourse/admin/models/screened-ip-address.js
+++ b/frontend/discourse/admin/models/screened-ip-address.js
@@ -1,7 +1,6 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ScreenedIpAddress extends EmberObject {
@@ -15,14 +14,14 @@ export default class ScreenedIpAddress extends EmberObject {
@equal("action_name", "block") isBlocked;
- @discourseComputed("action_name")
- actionName(actionName) {
- return i18n(`admin.logs.screened_ips.actions.${actionName}`);
+ @computed("action_name")
+ get actionName() {
+ return i18n(`admin.logs.screened_ips.actions.${this.action_name}`);
}
- @discourseComputed("ip_address")
- isRange(ipAddress) {
- return ipAddress.indexOf("/") > 0;
+ @computed("ip_address")
+ get isRange() {
+ return this.ip_address.indexOf("/") > 0;
}
save() {
diff --git a/frontend/discourse/admin/models/screened-url.js b/frontend/discourse/admin/models/screened-url.js
index 31e571938f3..64ce51b796c 100644
--- a/frontend/discourse/admin/models/screened-url.js
+++ b/frontend/discourse/admin/models/screened-url.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ScreenedUrl extends EmberObject {
@@ -14,8 +13,8 @@ export default class ScreenedUrl extends EmberObject {
);
}
- @discourseComputed("action")
- actionName(action) {
- return i18n("admin.logs.screened_actions." + action);
+ @computed("action")
+ get actionName() {
+ return i18n("admin.logs.screened_actions." + this.action);
}
}
diff --git a/frontend/discourse/admin/models/site-setting.js b/frontend/discourse/admin/models/site-setting.js
index 942411273d3..485696e9514 100644
--- a/frontend/discourse/admin/models/site-setting.js
+++ b/frontend/discourse/admin/models/site-setting.js
@@ -1,5 +1,5 @@
import { tracked } from "@glimmer/tracking";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import BufferedProxy from "ember-buffered-proxy/proxy";
import {
@@ -8,7 +8,7 @@ import {
} from "discourse/admin/lib/constants";
import SettingObjectHelper from "discourse/admin/lib/setting-object-helper";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
const AUTO_REFRESH_ON_SAVE = [
@@ -85,14 +85,14 @@ export default class SiteSetting extends EmberObject {
this.buffered = BufferedProxy.create({ content: this });
}
- @discourseComputed("setting")
- staffLogFilter(setting) {
- if (!setting) {
+ @computed("setting")
+ get staffLogFilter() {
+ if (!this.setting) {
return;
}
return {
- subject: setting,
+ subject: this.setting,
action_name: "change_site_setting",
};
}
diff --git a/frontend/discourse/admin/models/staff-action-log.js b/frontend/discourse/admin/models/staff-action-log.js
index d17532041f4..f675692679a 100644
--- a/frontend/discourse/admin/models/staff-action-log.js
+++ b/frontend/discourse/admin/models/staff-action-log.js
@@ -1,6 +1,6 @@
+import { computed } from "@ember/object";
import AdminUser from "discourse/admin/models/admin-user";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { escapeExpression } from "discourse/lib/utilities";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
@@ -37,12 +37,12 @@ export default class StaffActionLog extends RestModel {
showFullDetails = false;
- @discourseComputed("action_name")
- actionName(actionName) {
- return i18n(`admin.logs.staff_actions.actions.${actionName}`);
+ @computed("action_name")
+ get actionName() {
+ return i18n(`admin.logs.staff_actions.actions.${this.action_name}`);
}
- @discourseComputed(
+ @computed(
"email",
"ip_address",
"topic_id",
@@ -54,62 +54,53 @@ export default class StaffActionLog extends RestModel {
"useCustomModalForDetails",
"useModalForDetails"
)
- formattedDetails(
- email,
- ipAddress,
- topicId,
- postId,
- categoryId,
- newValue,
- previousValue,
- details,
- useCustomModalForDetails,
- useModalForDetails
- ) {
- const postLink = postId
- ? `<a href data-link-post-id="${postId}">${postId}</a>`
+ get formattedDetails() {
+ const postLink = this.post_id
+ ? `<a href data-link-post-id="${this.post_id}">${this.post_id}</a>`
: null;
- const topicLink = topicId
- ? `<a href data-link-topic-id="${topicId}">${topicId}</a>`
+ const topicLink = this.topic_id
+ ? `<a href data-link-topic-id="${this.topic_id}">${this.topic_id}</a>`
: null;
let lines = [
- format("email", email),
- format("admin.logs.ip_address", ipAddress),
+ format("email", this.email),
+ format("admin.logs.ip_address", this.ip_address),
format("admin.logs.topic_id", topicLink, false),
format("admin.logs.post_id", postLink, false),
- format("admin.logs.category_id", categoryId),
+ format("admin.logs.category_id", this.category_id),
];
- if (!useCustomModalForDetails) {
- lines.push(format("admin.logs.staff_actions.new_value", newValue));
+ if (!this.useCustomModalForDetails) {
+ lines.push(format("admin.logs.staff_actions.new_value", this.new_value));
lines.push(
- format("admin.logs.staff_actions.previous_value", previousValue)
+ format("admin.logs.staff_actions.previous_value", this.previous_value)
);
}
- if (!useModalForDetails && details) {
- lines = [...lines, ...escapeExpression(details).split("\n")];
+ if (!this.useModalForDetails && this.details) {
+ lines = [...lines, ...escapeExpression(this.details).split("\n")];
}
const formatted = lines.filter((l) => l.length > 0).join("<br/>");
return formatted.length > 0 ? formatted + "<br/>" : "";
}
- @discourseComputed("details")
- useModalForDetails(details) {
- return details && (details.length > 100 || details.includes("\n"));
+ @computed("details")
+ get useModalForDetails() {
+ return (
+ this.details && (this.details.length > 100 || this.details.includes("\n"))
+ );
}
- @discourseComputed("action_name")
- useCustomModalForDetails(actionName) {
+ @computed("action_name")
+ get useCustomModalForDetails() {
return [
"change_theme",
"delete_theme",
"tag_group_create",
"tag_group_destroy",
"tag_group_change",
- ].includes(actionName);
+ ].includes(this.action_name);
}
}
diff --git a/frontend/discourse/admin/models/theme.js b/frontend/discourse/admin/models/theme.js
index 4297d5ef034..ffaeeaea6f1 100644
--- a/frontend/discourse/admin/models/theme.js
+++ b/frontend/discourse/admin/models/theme.js
@@ -1,4 +1,4 @@
-import { get } from "@ember/object";
+import { computed, get } from "@ember/object";
import { gt, or } from "@ember/object/computed";
import { isBlank, isEmpty } from "@ember/utils";
import ThemeSettings from "discourse/admin/models/theme-settings";
@@ -8,7 +8,6 @@ import {
addUniqueValueToArray,
removeValueFromArray,
} from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
@@ -50,8 +49,8 @@ class Theme extends RestModel {
changed = false;
- @discourseComputed("theme_fields.[]")
- targets() {
+ @computed("theme_fields.[]")
+ get targets() {
return [
{ id: 0, name: "common" },
{ id: 1, name: "desktop", icon: "desktop" },
@@ -63,8 +62,8 @@ class Theme extends RestModel {
});
}
- @discourseComputed("theme_fields.[]")
- fieldNames() {
+ @computed("theme_fields.[]")
+ get fieldNames() {
const common = [
"scss",
"head_tag",
@@ -87,15 +86,11 @@ class Theme extends RestModel {
};
}
- @discourseComputed(
- "fieldNames",
- "theme_fields.[]",
- )
- fields(fieldNames) {
+ @computed("fieldNames", "theme_fields.[]", "[email protected]")
+ get fields() {
const hash = {};
- Object.keys(fieldNames).forEach((target) => {
- hash[target] = fieldNames[target].map((fieldName) => {
+ Object.keys(this.fieldNames).forEach((target) => {
+ hash[target] = this.fieldNames[target].map((fieldName) => {
const field = {
name: fieldName,
edited: this.hasEdited(target, fieldName),
@@ -115,15 +110,15 @@ class Theme extends RestModel {
return hash;
}
- @discourseComputed("theme_fields")
- themeFields(fields) {
- if (!fields) {
- this.set("theme_fields", []);
+ @computed("theme_fields")
+ get themeFields() {
+ if (!this.theme_fields) {
+ this.set("theme_fields", []); // eslint-disable-line ember/no-side-effects
return {};
}
let hash = {};
- fields.forEach((field) => {
+ this.theme_fields.forEach((field) => {
if (!field.type_id || FIELDS_IDS.includes(field.type_id)) {
hash[this.getKey(field)] = field;
}
@@ -131,34 +126,38 @@ class Theme extends RestModel {
return hash;
}
- @discourseComputed("theme_fields", "theme_fields.[]")
- uploads(fields) {
- if (!fields) {
+ @computed("theme_fields", "theme_fields.[]")
+ get uploads() {
+ if (!this.theme_fields) {
return [];
}
- return fields.filter(
+ return this.theme_fields.filter(
(f) => f.target === "common" && f.type_id === THEME_UPLOAD_VAR
);
}
- @discourseComputed("theme_fields", "[email protected]")
- isBroken(fields) {
+ @computed("theme_fields", "[email protected]")
+ get isBroken() {
return (
- fields && fields.some((field) => field.error && field.error.length > 0)
+ this.theme_fields &&
+ this.theme_fields.some((field) => field.error && field.error.length > 0)
);
}
- @discourseComputed("theme_fields.[]")
- editedFields(fields) {
- return fields.filter(
+ @computed("theme_fields.[]")
+ get editedFields() {
+ return this.theme_fields?.filter(
(field) => !isBlank(field.value) && field.type_id !== SETTINGS_TYPE_ID
);
}
- @discourseComputed("remote_theme.last_error_text")
- remoteError(errorText) {
- if (errorText && errorText.length > 0) {
- return errorText;
+ @computed("remote_theme.last_error_text")
+ get remoteError() {
+ if (
+ this.remote_theme?.last_error_text &&
+ this.remote_theme?.last_error_text?.length > 0
+ ) {
+ return this.remote_theme?.last_error_text;
}
}
@@ -257,16 +256,16 @@ class Theme extends RestModel {
}
}
- @discourseComputed("childThemes.[]")
- child_theme_ids(childThemes) {
- if (childThemes) {
- return childThemes.map((theme) => get(theme, "id"));
+ @computed("childThemes.[]")
+ get child_theme_ids() {
+ if (this.childThemes) {
+ return this.childThemes?.map((theme) => get(theme, "id"));
}
}
- @discourseComputed("recentlyInstalled", "component", "hasParents")
- warnUnassignedComponent(recent, component, hasParents) {
- return recent && component && !hasParents;
+ @computed("recentlyInstalled", "component", "hasParents")
+ get warnUnassignedComponent() {
+ return this.recentlyInstalled && this.component && !this.hasParents;
}
removeChildTheme(theme) {
diff --git a/frontend/discourse/admin/models/tl3-requirements.js b/frontend/discourse/admin/models/tl3-requirements.js
index ae2a918407b..bbf13f48d6a 100644
--- a/frontend/discourse/admin/models/tl3-requirements.js
+++ b/frontend/discourse/admin/models/tl3-requirements.js
@@ -1,23 +1,22 @@
-import EmberObject from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
+import EmberObject, { computed } from "@ember/object";
export default class Tl3Requirements extends EmberObject {
- @discourseComputed("days_visited", "time_period")
- days_visited_percent(daysVisited, timePeriod) {
- return Math.round((daysVisited * 100) / timePeriod);
+ @computed("days_visited", "time_period")
+ get days_visited_percent() {
+ return Math.round((this.days_visited * 100) / this.time_period);
}
- @discourseComputed("min_days_visited", "time_period")
- min_days_visited_percent(minDaysVisited, timePeriod) {
- return Math.round((minDaysVisited * 100) / timePeriod);
+ @computed("min_days_visited", "time_period")
+ get min_days_visited_percent() {
+ return Math.round((this.min_days_visited * 100) / this.time_period);
}
- @discourseComputed("num_topics_replied_to", "min_topics_replied_to")
- capped_topics_replied_to(numReplied, minReplied) {
- return numReplied > minReplied;
+ @computed("num_topics_replied_to", "min_topics_replied_to")
+ get capped_topics_replied_to() {
+ return this.num_topics_replied_to > this.min_topics_replied_to;
}
- @discourseComputed(
+ @computed(
"days_visited",
"min_days_visited",
"num_topics_replied_to",
@@ -38,8 +37,7 @@ export default class Tl3Requirements extends EmberObject {
"min_likes_given",
"num_likes_received",
"min_likes_received",
- "num_likes_received",
- "min_likes_received",
+
"num_likes_received_days",
"min_likes_received_days",
"num_likes_received_users",
@@ -48,7 +46,7 @@ export default class Tl3Requirements extends EmberObject {
"penalty_counts.silenced",
"penalty_counts.suspended"
)
- met() {
+ get met() {
return {
days_visited: this.days_visited >= this.min_days_visited,
topics_replied_to:
diff --git a/frontend/discourse/admin/models/version-check.js b/frontend/discourse/admin/models/version-check.js
index 43e8111cf41..cb7c655d794 100644
--- a/frontend/discourse/admin/models/version-check.js
+++ b/frontend/discourse/admin/models/version-check.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
export default class VersionCheck extends EmberObject {
static find() {
@@ -9,32 +8,34 @@ export default class VersionCheck extends EmberObject {
);
}
- @discourseComputed("updated_at")
- noCheckPerformed(updatedAt) {
- return updatedAt === null;
+ @computed("updated_at")
+ get noCheckPerformed() {
+ return this.updated_at === null;
}
- @discourseComputed("missing_versions_count")
- upToDate(missingVersionsCount) {
- return missingVersionsCount === 0 || missingVersionsCount === null;
+ @computed("missing_versions_count")
+ get upToDate() {
+ return (
+ this.missing_versions_count === 0 || this.missing_versions_count === null
+ );
}
- @discourseComputed("missing_versions_count")
- behindByOneVersion(missingVersionsCount) {
- return missingVersionsCount === 1;
+ @computed("missing_versions_count")
+ get behindByOneVersion() {
+ return this.missing_versions_count === 1;
}
- @discourseComputed("installed_sha")
- gitLink(installedSHA) {
- if (installedSHA) {
- return `https://github.com/discourse/discourse/commits/${installedSHA}`;
+ @computed("installed_sha")
+ get gitLink() {
+ if (this.installed_sha) {
+ return `https://github.com/discourse/discourse/commits/${this.installed_sha}`;
}
}
- @discourseComputed("installed_sha")
- shortSha(installedSHA) {
- if (installedSHA) {
- return installedSHA.slice(0, 10);
+ @computed("installed_sha")
+ get shortSha() {
+ if (this.installed_sha) {
+ return this.installed_sha.slice(0, 10);
}
}
}
diff --git a/frontend/discourse/admin/models/web-hook.js b/frontend/discourse/admin/models/web-hook.js
index 77da15a3383..d5268ac13c7 100644
--- a/frontend/discourse/admin/models/web-hook.js
+++ b/frontend/discourse/admin/models/web-hook.js
@@ -4,7 +4,6 @@ import { computed } from "@ember/object";
import { isEmpty } from "@ember/utils";
import { observes } from "@ember-decorators/object";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import Group from "discourse/models/group";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
@@ -92,16 +91,16 @@ export default class WebHook extends RestModel {
return Group.findAll({ term, ignore_automatic: false });
}
- @discourseComputed("wildcard_web_hook", "web_hook_event_types.[]")
- description(isWildcardWebHook, types) {
+ @computed("wildcard_web_hook", "web_hook_event_types.[]")
+ get description() {
let desc = "";
- types.forEach((type) => {
+ this.web_hook_event_types?.forEach((type) => {
const name = `${type.name.toLowerCase()}_event`;
desc += desc !== "" ? `, ${name}` : name;
});
- return isWildcardWebHook ? "*" : desc;
+ return this.wildcard_web_hook ? "*" : desc;
}
createProperties() {
diff --git a/frontend/discourse/app/components/avatar-uploader.gjs b/frontend/discourse/app/components/avatar-uploader.gjs
index 5598082638b..5874bbeae83 100644
--- a/frontend/discourse/app/components/avatar-uploader.gjs
+++ b/frontend/discourse/app/components/avatar-uploader.gjs
@@ -1,12 +1,11 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { getOwner } from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { isBlank } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
-import discourseComputed from "discourse/lib/decorators";
import UppyUpload from "discourse/lib/uppy/uppy-upload";
import { i18n } from "discourse-i18n";
@@ -34,13 +33,13 @@ export default class AvatarUploader extends Component {
imageIsNotASquare = false;
- @discourseComputed("uppyUpload.uploading", "uploadedAvatarId")
- customAvatarUploaded() {
+ @computed("uppyUpload.uploading", "uploadedAvatarId")
+ get customAvatarUploaded() {
return !this.uppyUpload.uploading && !isBlank(this.uploadedAvatarId);
}
- @discourseComputed("uppyUpload.uploading", "uppyUpload.uploadProgress")
- uploadLabel() {
+ @computed("uppyUpload.uploading", "uppyUpload.uploadProgress")
+ get uploadLabel() {
return this.uppyUpload.uploading
? `${i18n("uploading")} ${this.uppyUpload.uploadProgress}%`
: i18n("upload");
diff --git a/frontend/discourse/app/components/basic-topic-list.gjs b/frontend/discourse/app/components/basic-topic-list.gjs
index b93714a918d..8b5b132cd97 100644
--- a/frontend/discourse/app/components/basic-topic-list.gjs
+++ b/frontend/discourse/app/components/basic-topic-list.gjs
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components, ember/no-jquery, ember/no-observers, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias, not } from "@ember/object/computed";
import { service } from "@ember/service";
import { observes } from "@ember-decorators/object";
import $ from "jquery";
import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
import List from "discourse/components/topic-list/list";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class BasicTopicList extends Component {
@@ -24,8 +24,8 @@ export default class BasicTopicList extends Component {
}
}
- @discourseComputed("topicList.loaded")
- loaded() {
+ @computed("topicList.loaded")
+ get loaded() {
let topicList = this.topicList;
if (topicList) {
return topicList.get("loaded");
@@ -46,9 +46,9 @@ export default class BasicTopicList extends Component {
}
}
- @discourseComputed("topics")
- showUnreadIndicator(topics) {
- return topics.some(
+ @computed("topics")
+ get showUnreadIndicator() {
+ return this.topics.some(
(topic) => typeof topic.unread_by_group_member !== "undefined"
);
}
diff --git a/frontend/discourse/app/components/bookmark-actions-dropdown.js b/frontend/discourse/app/components/bookmark-actions-dropdown.js
index a3fd7da6544..169cc692c86 100644
--- a/frontend/discourse/app/components/bookmark-actions-dropdown.js
+++ b/frontend/discourse/app/components/bookmark-actions-dropdown.js
@@ -1,6 +1,5 @@
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import DropdownSelectBoxComponent from "discourse/select-kit/components/dropdown-select-box";
import {
pluginApiIdentifiers,
@@ -21,8 +20,8 @@ const ACTION_PIN = "pin";
})
@pluginApiIdentifiers("bookmark-actions-dropdown")
export default class BookmarkActionsDropdown extends DropdownSelectBoxComponent {
- @discourseComputed("bookmark")
- content(bookmark) {
+ @computed("bookmark")
+ get content() {
const actions = [];
actions.push({
@@ -39,7 +38,7 @@ export default class BookmarkActionsDropdown extends DropdownSelectBoxComponent
description: i18n("post.bookmarks.actions.edit_bookmark.description"),
});
- if (bookmark.reminder_at) {
+ if (this.bookmark.reminder_at) {
actions.push({
id: ACTION_CLEAR_REMINDER,
icon: "clock-rotate-left",
@@ -54,10 +53,10 @@ export default class BookmarkActionsDropdown extends DropdownSelectBoxComponent
id: ACTION_PIN,
icon: "thumbtack",
name: i18n(
- `post.bookmarks.actions.${bookmark.pinAction()}_bookmark.name`
+ `post.bookmarks.actions.${this.bookmark.pinAction()}_bookmark.name`
),
description: i18n(
- `post.bookmarks.actions.${bookmark.pinAction()}_bookmark.description`
+ `post.bookmarks.actions.${this.bookmark.pinAction()}_bookmark.description`
),
});
diff --git a/frontend/discourse/app/components/bread-crumbs.gjs b/frontend/discourse/app/components/bread-crumbs.gjs
index 0a4a4c5203b..c360438536c 100644
--- a/frontend/discourse/app/components/bread-crumbs.gjs
+++ b/frontend/discourse/app/components/bread-crumbs.gjs
@@ -1,6 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
+import { computed } from "@ember/object";
import { filter } from "@ember/object/computed";
import { compare } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
@@ -9,7 +10,6 @@ import PluginOutlet from "discourse/components/plugin-outlet";
import categoryVariables from "discourse/helpers/category-variables";
import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import CategoryDrop from "discourse/select-kit/components/category-drop";
import TagDrop from "discourse/select-kit/components/tag-drop";
@@ -38,9 +38,9 @@ export default class BreadCrumbs extends Component {
})
parentCategories;
- @discourseComputed("category", "categories", "noSubcategories")
- categoryBreadcrumbs(category, filteredCategories, noSubcategories) {
- const ancestors = category?.ancestors || [];
+ @computed("category", "categories", "noSubcategories")
+ get categoryBreadcrumbs() {
+ const ancestors = this.category?.ancestors || [];
const parentCategories = [undefined, ...ancestors];
const categories = [...ancestors, undefined];
@@ -49,7 +49,7 @@ export default class BreadCrumbs extends Component {
.map((record) => {
const [parentCategory, subCategory] = record;
- const options = filteredCategories.filter(
+ const options = this.categories.filter(
(c) =>
c.get("parentCategory.id") === (parentCategory && parentCategory.id)
);
@@ -59,80 +59,80 @@ export default class BreadCrumbs extends Component {
parentCategory,
options,
isSubcategory: !!parentCategory,
- noSubcategories: !subCategory && noSubcategories,
+ noSubcategories: !subCategory && this.noSubcategories,
hasOptions: !parentCategory || parentCategory.has_children,
};
});
}
- @discourseComputed("siteSettings.tagging_enabled", "editingCategory")
- showTagsSection(taggingEnabled, editingCategory) {
- return taggingEnabled && !editingCategory;
+ @computed("siteSettings.tagging_enabled", "editingCategory")
+ get showTagsSection() {
+ return this.siteSettings?.tagging_enabled && !this.editingCategory;
}
- @discourseComputed("category")
- parentCategory(category) {
+ @computed("category")
+ get parentCategory() {
deprecated(
"The parentCategory property of the bread-crumbs component is deprecated",
{ id: "discourse.breadcrumbs.parentCategory" }
);
- return category && category.parentCategory;
+ return this.category && this.category.parentCategory;
}
- @discourseComputed("parentCategories")
- parentCategoriesSorted(parentCategories) {
+ @computed("parentCategories")
+ get parentCategoriesSorted() {
deprecated(
"The parentCategoriesSorted property of the bread-crumbs component is deprecated",
{ id: "discourse.breadcrumbs.parentCategoriesSorted" }
);
if (this.siteSettings.fixed_category_positions) {
- return parentCategories;
+ return this.parentCategories;
}
- return parentCategories.sort(
+ return this.parentCategories.sort(
(a, b) => compare(b?.totalTopicCount, a?.totalTopicCount) // sort descending
);
}
- @discourseComputed("category")
- hidden(category) {
- return this.site.mobileView && !category;
+ @computed("category")
+ get hidden() {
+ return this.site.mobileView && !this.category;
}
- @discourseComputed("category", "parentCategory")
- firstCategory(category, parentCategory) {
+ @computed("category", "parentCategory")
+ get firstCategory() {
deprecated(
"The firstCategory property of the bread-crumbs component is deprecated",
{ id: "discourse.breadcrumbs.firstCategory" }
);
- return parentCategory || category;
+ return this.parentCategory || this.category;
}
- @discourseComputed("category", "parentCategory")
- secondCategory(category, parentCategory) {
+ @computed("category", "parentCategory")
+ get secondCategory() {
deprecated(
"The secondCategory property of the bread-crumbs component is deprecated",
{ id: "discourse.breadcrumbs.secondCategory" }
);
- return parentCategory && category;
+ return this.parentCategory && this.category;
}
- @discourseComputed("firstCategory", "hideSubcategories")
- childCategories(firstCategory, hideSubcategories) {
+ @computed("firstCategory", "hideSubcategories")
+ get childCategories() {
deprecated(
"The childCategories property of the bread-crumbs component is deprecated",
{ id: "discourse.breadcrumbs.childCategories" }
);
- if (hideSubcategories) {
+ if (this.hideSubcategories) {
return [];
}
- if (!firstCategory) {
+ if (!this.firstCategory) {
return [];
}
return this.categories.filter(
- (c) => c.get("parentCategory") === firstCategory
+ (c) => c.get("parentCategory") === this.firstCategory
);
}
diff --git a/frontend/discourse/app/components/categories-boxes-topic.gjs b/frontend/discourse/app/components/categories-boxes-topic.gjs
index f86e4521ef0..1bc39dec363 100644
--- a/frontend/discourse/app/components/categories-boxes-topic.gjs
+++ b/frontend/discourse/app/components/categories-boxes-topic.gjs
@@ -1,18 +1,18 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
@tagName("")
export default class CategoriesBoxesTopic extends Component {
- @discourseComputed("topic.pinned", "topic.closed", "topic.archived")
- topicStatusIcon(pinned, closed, archived) {
- if (pinned) {
+ @computed("topic.pinned", "topic.closed", "topic.archived")
+ get topicStatusIcon() {
+ if (this.topic?.pinned) {
return "thumbtack";
}
- if (closed || archived) {
+ if (this.topic?.closed || this.topic?.archived) {
return "category.restricted";
}
return "far-file-lines";
diff --git a/frontend/discourse/app/components/categories-only.gjs b/frontend/discourse/app/components/categories-only.gjs
index ef16402d9c7..172803d55ed 100644
--- a/frontend/discourse/app/components/categories-only.gjs
+++ b/frontend/discourse/app/components/categories-only.gjs
@@ -1,58 +1,57 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import ParentCategoryRow from "discourse/components/parent-category-row";
import PluginOutlet from "discourse/components/plugin-outlet";
import icon from "discourse/helpers/d-icon";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("")
export default class CategoriesOnly extends Component {
showMuted = false;
- @discourseComputed("showMutedCategories", "filteredCategories.length")
- mutedToggleIcon(showMutedCategories, filteredCategoriesLength) {
- if (filteredCategoriesLength === 0) {
+ @computed("showMutedCategories", "filteredCategories.length")
+ get mutedToggleIcon() {
+ if (this.filteredCategories?.length === 0) {
return;
}
- if (showMutedCategories) {
+ if (this.showMutedCategories) {
return "minus";
}
return "plus";
}
- @discourseComputed("showMuted", "filteredCategories.length")
- showMutedCategories(showMuted, filteredCategoriesLength) {
- return showMuted || filteredCategoriesLength === 0;
+ @computed("showMuted", "filteredCategories.length")
+ get showMutedCategories() {
+ return this.showMuted || this.filteredCategories?.length === 0;
}
- @discourseComputed("categories", "categories.length")
- filteredCategories(categories, categoriesLength) {
- if (!categories || categoriesLength === 0) {
+ @computed("categories", "categories.length")
+ get filteredCategories() {
+ if (!this.categories || this.categories?.length === 0) {
return [];
}
- return categories.filter((cat) => !cat.isHidden);
+ return this.categories.filter((cat) => !cat.isHidden);
}
- @discourseComputed("categories", "categories.length")
- mutedCategories(categories, categoriesLength) {
- if (!categories || categoriesLength === 0) {
+ @computed("categories", "categories.length")
+ get mutedCategories() {
+ if (!this.categories || this.categories?.length === 0) {
return [];
}
// hide in single category pages
- if (categories[0].parent_category_id) {
+ if (this.categories[0].parent_category_id) {
return [];
}
- return categories.filter((category) => category.hasMuted);
+ return this.categories.filter((category) => category.hasMuted);
}
@action
diff --git a/frontend/discourse/app/components/category-list-item.js b/frontend/discourse/app/components/category-list-item.js
index f606af180e0..fd0c0fc8e79 100644
--- a/frontend/discourse/app/components/category-list-item.js
+++ b/frontend/discourse/app/components/category-list-item.js
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { applyValueTransformer } from "discourse/lib/transformer";
const LIST_TYPE = {
@@ -14,19 +14,19 @@ export default class CategoryListItem extends Component {
category = null;
listType = LIST_TYPE.NORMAL;
- @discourseComputed("category.isHidden", "category.hasMuted", "listType")
- isHidden(isHiddenCategory, hasMuted, listType) {
+ @computed("category.isHidden", "category.hasMuted", "listType")
+ get isHidden() {
return (
- (isHiddenCategory && listType === LIST_TYPE.NORMAL) ||
- (!hasMuted && listType === LIST_TYPE.MUTED)
+ (this.category?.isHidden && this.listType === LIST_TYPE.NORMAL) ||
+ (!this.category?.hasMuted && this.listType === LIST_TYPE.MUTED)
);
}
- @discourseComputed("category.isMuted", "listType")
- isMuted(isMutedCategory, listType) {
+ @computed("category.isMuted", "listType")
+ get isMuted() {
return (
- (isMutedCategory && listType === LIST_TYPE.NORMAL) ||
- (!isMutedCategory && listType === LIST_TYPE.MUTED)
+ (this.category?.isMuted && this.listType === LIST_TYPE.NORMAL) ||
+ (!this.category?.isMuted && this.listType === LIST_TYPE.MUTED)
);
}
@@ -38,9 +38,9 @@ export default class CategoryListItem extends Component {
return this.category.newTopicsCount;
}
- @discourseComputed("category.path")
- slugPath(categoryPath) {
- return categoryPath.substring("/c/".length);
+ @computed("category.path")
+ get slugPath() {
+ return this.category?.path?.substring("/c/".length);
}
applyValueTransformer(name, value, context) {
diff --git a/frontend/discourse/app/components/color-picker-choice.js b/frontend/discourse/app/components/color-picker-choice.js
index 70fe300c16d..6884d2e54a4 100644
--- a/frontend/discourse/app/components/color-picker-choice.js
+++ b/frontend/discourse/app/components/color-picker-choice.js
@@ -1,31 +1,31 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import {
attributeBindings,
classNameBindings,
tagName,
} from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("button")
@attributeBindings("style", "title", "ariaLabel:aria-label")
@classNameBindings(":colorpicker", "isUsed:used-color:unused-color")
export default class ColorPickerChoice extends Component {
- @discourseComputed("color", "usedColors")
- isUsed(color, usedColors) {
- return (usedColors || []).includes(color.toUpperCase());
+ @computed("color", "usedColors")
+ get isUsed() {
+ return (this.usedColors || []).includes(this.color.toUpperCase());
}
- @discourseComputed("isUsed")
- title(isUsed) {
- return isUsed ? i18n("category.already_used") : null;
+ @computed("isUsed")
+ get title() {
+ return this.isUsed ? i18n("category.already_used") : null;
}
- @discourseComputed("color")
- style(color) {
- return htmlSafe(`background-color: #${color};`);
+ @computed("color")
+ get style() {
+ return htmlSafe(`background-color: #${this.color};`);
}
click(e) {
diff --git a/frontend/discourse/app/components/composer-action-title.gjs b/frontend/discourse/app/components/composer-action-title.gjs
index 5e4434daea3..b1b9a46b006 100644
--- a/frontend/discourse/app/components/composer-action-title.gjs
+++ b/frontend/discourse/app/components/composer-action-title.gjs
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import PostLanguageSelector from "discourse/components/post-language-selector";
-import discourseComputed from "discourse/lib/decorators";
import escape from "discourse/lib/escape";
import { iconHTML } from "discourse/lib/icon-library";
import {
@@ -39,44 +39,51 @@ export default class ComposerActionTitle extends Component {
// Note we update when some other attributes like tag/category change to allow
// text customizations to use those.
- @discourseComputed("options", "action", "model.tags", "model.category")
- actionTitle(opts, action) {
+ @computed("options", "action", "model.tags", "model.category")
+ get actionTitle() {
const result = this.model.customizationFor("actionTitle");
if (result) {
return result;
}
- if (TITLES[action]) {
- return i18n(TITLES[action]);
+ if (TITLES[this.action]) {
+ return i18n(TITLES[this.action]);
}
- if (action === REPLY) {
- if (opts.userAvatar && opts.userLink) {
- return this._formatReplyToUserPost(opts.userAvatar, opts.userLink);
- } else if (opts.topicLink) {
- return this._formatReplyToTopic(opts.topicLink);
+ if (this.action === REPLY) {
+ if (this.options.userAvatar && this.options.userLink) {
+ return this._formatReplyToUserPost(
+ this.options.userAvatar,
+ this.options.userLink
+ );
+ } else if (this.options.topicLink) {
+ return this._formatReplyToTopic(this.options.topicLink);
}
}
- if (action === EDIT) {
- if (opts.userAvatar && opts.userLink && opts.postLink) {
+ if (this.action === EDIT) {
+ if (
+ this.options.userAvatar &&
+ this.options.userLink &&
+ this.options.postLink
+ ) {
return this._formatEditUserPost(
- opts.userAvatar,
- opts.userLink,
- opts.postLink,
- opts.originalUser
+ this.options.userAvatar,
+ this.options.userLink,
+ this.options.postLink,
+ this.options.originalUser
);
}
}
}
- @discourseComputed("action")
- showPostLanguageSelector(action) {
+ @computed("action")
+ get showPostLanguageSelector() {
const allowedActions = [CREATE_TOPIC, EDIT, REPLY];
return (
this.currentUser &&
this.siteSettings.content_localization_enabled &&
- allowedActions.includes(action)
+ allowedActions.includes(this.action)
);
}
diff --git a/frontend/discourse/app/components/composer-body.js b/frontend/discourse/app/components/composer-body.js
index ab072d5d04d..e87ad93c972 100644
--- a/frontend/discourse/app/components/composer-body.js
+++ b/frontend/discourse/app/components/composer-body.js
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components, ember/no-observers, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { cancel, schedule } from "@ember/runloop";
import { service } from "@ember/service";
import { dasherize } from "@ember/string";
import { classNameBindings } from "@ember-decorators/component";
import { observes } from "@ember-decorators/object";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import discourseLater from "discourse/lib/later";
import Composer from "discourse/models/composer";
@@ -28,19 +28,24 @@ export default class ComposerBody extends Component {
elementId = "reply-control";
- @discourseComputed("composer.action")
- prefixedComposerAction(action) {
- return action ? `composer-action-${dasherize(action)}` : "";
+ @computed("composer.action")
+ get prefixedComposerAction() {
+ return this.composer?.action
+ ? `composer-action-${dasherize(this.composer?.action)}`
+ : "";
}
- @discourseComputed("currentUser.primary_group_name")
- currentUserPrimaryGroupClass(primaryGroupName) {
- return primaryGroupName && `group-${primaryGroupName}`;
+ @computed("currentUser.primary_group_name")
+ get currentUserPrimaryGroupClass() {
+ return (
+ this.currentUser?.primary_group_name &&
+ `group-${this.currentUser?.primary_group_name}`
+ );
}
- @discourseComputed("composer.composeState")
- composeState(composeState) {
- return composeState || Composer.CLOSED;
+ @computed("composer.composeState")
+ get composeState() {
+ return this.composer?.composeState || Composer.CLOSED;
}
keyUp() {
diff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjs
index 6fe5317f598..8a637b2a916 100644
--- a/frontend/discourse/app/components/composer-editor.gjs
+++ b/frontend/discourse/app/components/composer-editor.gjs
@@ -23,7 +23,7 @@ import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import { tinyAvatar } from "discourse/lib/avatar-utils";
import { setupComposerPosition } from "discourse/lib/composer/composer-position";
-import discourseComputed, { bind, debounce } from "discourse/lib/decorators";
+import { bind, debounce } from "discourse/lib/decorators";
import prepareFormTemplateData from "discourse/lib/form-template-validation";
import {
fetchUnseenHashtagsInContext,
@@ -133,14 +133,14 @@ export default class ComposerEditor extends Component {
return this.composer.get("model.topic");
}
- @discourseComputed(
+ @computed(
"composer.model.requiredCategoryMissing",
"currentUser.useRichEditor"
)
- replyPlaceholder(requiredCategoryMissing) {
+ get replyPlaceholder() {
let placeholder = "composer.reply_placeholder_choose_category";
- if (!requiredCategoryMissing) {
+ if (!this.composer?.model?.requiredCategoryMissing) {
const allowImages = authorizesOneOrMoreImageExtensions(
this.currentUser.staff,
this.siteSettings
@@ -165,8 +165,8 @@ export default class ComposerEditor extends Component {
);
}
- @discourseComputed
- showLink() {
+ @computed
+ get showLink() {
return this.currentUser && this.currentUser.link_posting_access !== "none";
}
@@ -177,8 +177,8 @@ export default class ComposerEditor extends Component {
}
}
- @discourseComputed
- markdownOptions() {
+ @computed
+ get markdownOptions() {
return {
previewing: true,
@@ -326,31 +326,25 @@ export default class ComposerEditor extends Component {
};
}
- @discourseComputed(
+ @computed(
"composer.model.reply",
"composer.model.replyLength",
"composer.model.missingReplyCharacters",
"composer.model.minimumPostLength",
"composer.lastValidatedAt"
)
- validation(
- reply,
- replyLength,
- missingReplyCharacters,
- minimumPostLength,
- lastValidatedAt
- ) {
+ get validation() {
const postType = this.get("composer.post.post_type");
if (postType === this.site.get("post_types.small_action")) {
return;
}
let reason;
- if (replyLength < 1) {
+ if (this.composer?.model?.replyLength < 1) {
reason = i18n("composer.error.post_missing");
- } else if (missingReplyCharacters > 0) {
+ } else if (this.composer?.model?.missingReplyCharacters > 0) {
reason = i18n("composer.error.post_length", {
- count: minimumPostLength,
+ count: this.composer?.model?.minimumPostLength,
});
const tl = this.get("currentUser.trust_level");
if ((tl === 0 || tl === 1) && !this._isNewTopic) {
@@ -368,7 +362,7 @@ export default class ComposerEditor extends Component {
return EmberObject.create({
failed: true,
reason,
- lastShownAt: lastValidatedAt,
+ lastShownAt: this.composer?.lastValidatedAt,
});
}
}
@@ -1075,17 +1069,21 @@ export default class ComposerEditor extends Component {
this.selectedFormTemplateId = formTemplateId;
}
- @discourseComputed(
+ @computed(
"composer.formTemplateIds",
"composer.model.replyingToTopic",
"composer.model.editingPost"
)
- showFormTemplateForm(formTemplateIds, replyingToTopic, editingPost) {
- return formTemplateIds?.length > 0 && !replyingToTopic && !editingPost;
+ get showFormTemplateForm() {
+ return (
+ this.composer?.formTemplateIds?.length > 0 &&
+ !this.composer?.model?.replyingToTopic &&
+ !this.composer?.model?.editingPost
+ );
}
- @discourseComputed("composer.model")
- forceEditorMode() {
+ @computed("composer.model")
+ get forceEditorMode() {
return applyValueTransformer("composer-force-editor-mode", null, {
model: this.composer.model,
});
diff --git a/frontend/discourse/app/components/composer-title.gjs b/frontend/discourse/app/components/composer-title.gjs
index 3821f9925f1..8402dfded65 100644
--- a/frontend/discourse/app/components/composer-title.gjs
+++ b/frontend/discourse/app/components/composer-title.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components, ember/no-observers, ember/require-tagless-components */
import Component from "@ember/component";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { alias, or } from "@ember/object/computed";
import { next, schedule } from "@ember/runloop";
import { classNames } from "@ember-decorators/component";
@@ -13,7 +13,6 @@ import TextField from "discourse/components/text-field";
import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import putCursorAtEnd from "discourse/lib/put-cursor-at-end";
import { i18n } from "discourse-i18n";
@@ -54,31 +53,27 @@ export default class ComposerTitle extends Component {
}
}
- @discourseComputed(
+ @computed(
"composer.titleLength",
"composer.missingTitleCharacters",
"composer.minimumTitleLength",
"lastValidatedAt",
"isTitleFocused"
)
- validation(
- titleLength,
- missingTitleChars,
- minimumTitleLength,
- lastValidatedAt,
- isTitleFocused
- ) {
+ get validation() {
let reason;
- if (isTitleFocused) {
+ if (this.isTitleFocused) {
return;
}
- if (titleLength < 1) {
+ if (this.composer?.titleLength < 1) {
reason = i18n("composer.error.title_missing");
- } else if (missingTitleChars > 0) {
+ } else if (this.composer?.missingTitleCharacters > 0) {
reason = i18n("composer.error.title_too_short", {
- count: minimumTitleLength,
+ count: this.composer?.minimumTitleLength,
});
- } else if (titleLength > this.siteSettings.max_topic_title_length) {
+ } else if (
+ this.composer?.titleLength > this.siteSettings.max_topic_title_length
+ ) {
reason = i18n("composer.error.title_too_long", {
count: this.siteSettings.max_topic_title_length,
});
@@ -88,16 +83,16 @@ export default class ComposerTitle extends Component {
return EmberObject.create({
failed: true,
reason,
- lastShownAt: lastValidatedAt,
+ lastShownAt: this.lastValidatedAt,
});
}
}
- @discourseComputed("watchForLink")
- titleMaxLength(watchForLink) {
+ @computed("watchForLink")
+ get titleMaxLength() {
// maxLength gets in the way of pasting long links, so don't use it if featured links are allowed.
// Validation will display a message if titles are too long.
- return watchForLink ? null : this.siteSettings.max_topic_title_length;
+ return this.watchForLink ? null : this.siteSettings.max_topic_title_length;
}
@observes("composer.titleLength", "watchForLink")
@@ -223,12 +218,12 @@ export default class ComposerTitle extends Component {
}
}
- @discourseComputed("composer.title", "composer.titleLength")
- isAbsoluteUrl(title, titleLength) {
+ @computed("composer.title", "composer.titleLength")
+ get isAbsoluteUrl() {
return (
- titleLength > 0 &&
- /^(https?:)?\/\/[\w\.\-]+/i.test(title) &&
- !/\s/.test(title)
+ this.composer?.titleLength > 0 &&
+ /^(https?:)?\/\/[\w\.\-]+/i.test(this.composer?.title) &&
+ !/\s/.test(this.composer?.title)
);
}
diff --git a/frontend/discourse/app/components/composer-user-selector.gjs b/frontend/discourse/app/components/composer-user-selector.gjs
index 39b51e7bf17..a1216221376 100644
--- a/frontend/discourse/app/components/composer-user-selector.gjs
+++ b/frontend/discourse/app/components/composer-user-selector.gjs
@@ -1,8 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
export default class ComposerUserSelector extends Component {
@@ -16,12 +15,12 @@ export default class ComposerUserSelector extends Component {
}
}
- @discourseComputed("recipients")
- splitRecipients(recipients) {
- if (Array.isArray(recipients)) {
- return recipients;
+ @computed("recipients")
+ get splitRecipients() {
+ if (Array.isArray(this.recipients)) {
+ return this.recipients;
}
- return recipients ? recipients.split(",").filter(Boolean) : [];
+ return this.recipients ? this.recipients.split(",").filter(Boolean) : [];
}
_updateGroups(selected, newGroups) {
diff --git a/frontend/discourse/app/components/create-invite-uploader.gjs b/frontend/discourse/app/components/create-invite-uploader.gjs
index e99a7fae081..aa13b82d3ad 100644
--- a/frontend/discourse/app/components/create-invite-uploader.gjs
+++ b/frontend/discourse/app/components/create-invite-uploader.gjs
@@ -1,10 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { getOwner } from "@ember/owner";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import UppyUpload from "discourse/lib/uppy/uppy-upload";
@tagName("")
@@ -24,9 +23,9 @@ export default class CreateInviteUploader extends Component {
},
});
- @discourseComputed("uppyUpload.filesAwaitingUpload", "uppyUpload.uploading")
- submitDisabled(filesAwaitingUpload, uploading) {
- return !filesAwaitingUpload || uploading;
+ @computed("uppyUpload.filesAwaitingUpload", "uppyUpload.uploading")
+ get submitDisabled() {
+ return !this.uppyUpload?.filesAwaitingUpload || this.uppyUpload?.uploading;
}
@action
diff --git a/frontend/discourse/app/components/d-editor.gjs b/frontend/discourse/app/components/d-editor.gjs
index 2d5caba6201..82cdc77657d 100644
--- a/frontend/discourse/app/components/d-editor.gjs
+++ b/frontend/discourse/app/components/d-editor.gjs
@@ -2,7 +2,7 @@
import { tracked } from "@glimmer/tracking";
import Component from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { getOwner } from "@ember/owner";
import { cancel, schedule, scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
@@ -29,7 +29,6 @@ import concatClass from "discourse/helpers/concat-class";
import Toolbar from "discourse/lib/composer/toolbar";
import { USER_OPTION_COMPOSITION_MODES } from "discourse/lib/constants";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { isTesting } from "discourse/lib/environment";
import { getRegister } from "discourse/lib/get-owner";
@@ -154,8 +153,8 @@ export default class DEditor extends Component {
});
}
- @discourseComputed("siteSettings.rich_editor", "forceEditorMode")
- showEditorModeToggle() {
+ @computed("siteSettings.rich_editor", "forceEditorMode")
+ get showEditorModeToggle() {
return this.siteSettings.rich_editor && isNone(this.forceEditorMode);
}
diff --git a/frontend/discourse/app/components/d-navigation.gjs b/frontend/discourse/app/components/d-navigation.gjs
index d8fb52a6d47..682b47234b4 100644
--- a/frontend/discourse/app/components/d-navigation.gjs
+++ b/frontend/discourse/app/components/d-navigation.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
@@ -17,7 +17,6 @@ import TagNotificationsTracking from "discourse/components/tag-notifications-tra
import TopicDismissButtons from "discourse/components/topic-dismiss-buttons";
import lazyHash from "discourse/helpers/lazy-hash";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { filterTypeForMode } from "discourse/lib/filter-mode";
import { NotificationLevels } from "discourse/lib/notification-levels";
import { applyValueTransformer } from "discourse/lib/transformer";
@@ -69,8 +68,8 @@ export default class DNavigation extends Component {
// Should be a `readOnly` instead but some themes/plugins still pass
// the `categories` property into this component
- @discourseComputed()
- categories() {
+ @computed()
+ get categories() {
let categories = this.site.categoriesList;
if (!this.siteSettings.allow_uncategorized_topics) {
@@ -89,13 +88,13 @@ export default class DNavigation extends Component {
return categories;
}
- @discourseComputed("category")
- showCategoryNotifications(category) {
- return category && this.currentUser;
+ @computed("category")
+ get showCategoryNotifications() {
+ return this.category && this.currentUser;
}
- @discourseComputed("category.notification_level")
- categoryNotificationLevel(notificationLevel) {
+ @computed("category.notification_level")
+ get categoryNotificationLevel() {
if (
this.currentUser?.indirectly_muted_category_ids?.includes(
this.category.id
@@ -103,37 +102,37 @@ export default class DNavigation extends Component {
) {
return NotificationLevels.MUTED;
} else {
- return notificationLevel;
+ return this.category?.notification_level;
}
}
// don't show tag notification menu on tag intersections
- @discourseComputed("tagNotification", "additionalTags")
- showTagNotifications(tagNotification, additionalTags) {
- return tagNotification && !additionalTags;
+ @computed("tagNotification", "additionalTags")
+ get showTagNotifications() {
+ return this.tagNotification && !this.additionalTags;
}
- @discourseComputed("category", "createTopicDisabled")
- categoryReadOnlyBanner(category, createTopicDisabled) {
- if (category && this.currentUser && createTopicDisabled) {
- return category.read_only_banner;
+ @computed("category", "createTopicDisabled")
+ get categoryReadOnlyBanner() {
+ if (this.category && this.currentUser && this.createTopicDisabled) {
+ return this.category.read_only_banner;
}
}
- @discourseComputed("category.can_edit")
- showCategoryEdit(canEdit) {
- return canEdit;
+ @computed("category.can_edit")
+ get showCategoryEdit() {
+ return this.category?.can_edit;
}
- @discourseComputed("additionalTags", "category", "tag.name")
- showToggleInfo(additionalTags, category, tagId) {
+ @computed("additionalTags", "category", "tag.name")
+ get showToggleInfo() {
if (this.siteSettings.experimental_tag_settings_page) {
return this.currentUser;
}
- return !additionalTags && !category && tagId !== "none";
+ return !this.additionalTags && !this.category && this.tag?.name !== "none";
}
- @discourseComputed(
+ @computed(
"filterType",
"category",
"noSubcategories",
@@ -141,27 +140,20 @@ export default class DNavigation extends Component {
"router.currentRoute.queryParams",
"skipCategoriesNavItem"
)
- navItems(
- filterType,
- category,
- noSubcategories,
- tag,
- currentRouteQueryParams,
- skipCategoriesNavItem
- ) {
- return NavItem.buildList(category, {
- filterType,
- noSubcategories,
- currentRouteQueryParams,
- tag,
+ get navItems() {
+ return NavItem.buildList(this.category, {
+ filterType: this.filterType,
+ noSubcategories: this.noSubcategories,
+ currentRouteQueryParams: this.router?.currentRoute?.queryParams,
+ tag: this.tag,
siteSettings: this.siteSettings,
- skipCategoriesNavItem,
+ skipCategoriesNavItem: this.skipCategoriesNavItem,
});
}
- @discourseComputed("filterType")
- notCategoriesRoute(filterType) {
- return filterType !== "categories";
+ @computed("filterType")
+ get notCategoriesRoute() {
+ return this.filterType !== "categories";
}
@action
diff --git a/frontend/discourse/app/components/date-input.gjs b/frontend/discourse/app/components/date-input.gjs
index e5b28485ce4..cad725af4af 100644
--- a/frontend/discourse/app/components/date-input.gjs
+++ b/frontend/discourse/app/components/date-input.gjs
@@ -7,7 +7,6 @@ import { waitForPromise } from "@ember/test-waiters";
import { classNames } from "@ember-decorators/component";
import { on as onEvent } from "@ember-decorators/object";
import { Promise } from "rsvp";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
function isInputDateSupported() {
@@ -24,8 +23,8 @@ export default class DateInput extends Component {
useNativePicker = isInputDateSupported();
_picker = null;
- @discourseComputed("site.mobileView")
- inputType() {
+ @computed("site.mobileView")
+ get inputType() {
return this.useNativePicker ? "date" : "text";
}
diff --git a/frontend/discourse/app/components/date-picker.gjs b/frontend/discourse/app/components/date-picker.gjs
index 56b36c41be4..a354e20dec0 100644
--- a/frontend/discourse/app/components/date-picker.gjs
+++ b/frontend/discourse/app/components/date-picker.gjs
@@ -5,7 +5,6 @@ import { schedule } from "@ember/runloop";
import { waitForPromise } from "@ember/test-waiters";
import { classNames } from "@ember-decorators/component";
import { on } from "@ember-decorators/object";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
const DATE_FORMAT = "YYYY-MM-DD";
@@ -17,9 +16,9 @@ export default class DatePicker extends Component {
maxDate = null;
_picker = null;
- @discourseComputed("site.mobileView")
- inputType(mobileView) {
- return mobileView ? "date" : "text";
+ @computed("site.mobileView")
+ get inputType() {
+ return this.site?.mobileView ? "date" : "text";
}
@on("didInsertElement")
diff --git a/frontend/discourse/app/components/discourse-linked-text.gjs b/frontend/discourse/app/components/discourse-linked-text.gjs
index 622dc4758b0..93fd74ccb99 100644
--- a/frontend/discourse/app/components/discourse-linked-text.gjs
+++ b/frontend/discourse/app/components/discourse-linked-text.gjs
@@ -1,16 +1,16 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("span")
export default class DiscourseLinkedText extends Component {
- @discourseComputed("text", "textParams")
- translatedText(text) {
- if (text) {
- return i18n(...arguments);
+ @computed("text", "textParams")
+ get translatedText() {
+ if (this.text) {
+ return i18n(this.text);
}
}
diff --git a/frontend/discourse/app/components/discourse-tag-bound.gjs b/frontend/discourse/app/components/discourse-tag-bound.gjs
index 65a218c73c1..c8bd9fb31f9 100644
--- a/frontend/discourse/app/components/discourse-tag-bound.gjs
+++ b/frontend/discourse/app/components/discourse-tag-bound.gjs
@@ -1,22 +1,22 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
@tagName("")
export default class DiscourseTagBound extends Component {
- @discourseComputed("tagRecord.name")
- tagClass(name) {
- return "tag-" + name;
+ @computed("tagRecord.name")
+ get tagClass() {
+ return "tag-" + this.tagRecord?.name;
}
- @discourseComputed("tagRecord.slug", "tagRecord.id")
- href(slug, id) {
- if (id) {
- const slugForUrl = slug || `${id}-tag`;
- return getURL(`/tag/${slugForUrl}/${id}`);
+ @computed("tagRecord.slug", "tagRecord.id")
+ get href() {
+ if (this.tagRecord?.id) {
+ const slugForUrl = this.tagRecord?.slug || `${this.tagRecord?.id}-tag`;
+ return getURL(`/tag/${slugForUrl}/${this.tagRecord?.id}`);
}
// fallback for tags without id
return getURL("/tag/" + this.tagRecord.name);
diff --git a/frontend/discourse/app/components/flag-action-type.gjs b/frontend/discourse/app/components/flag-action-type.gjs
index 98c7a03fd2b..e736448aaae 100644
--- a/frontend/discourse/app/components/flag-action-type.gjs
+++ b/frontend/discourse/app/components/flag-action-type.gjs
@@ -2,11 +2,11 @@
import Component, { Input, Textarea } from "@ember/component";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
+import { computed } from "@ember/object";
import { and, equal } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { applyValueTransformer } from "discourse/lib/transformer";
import { MAX_MESSAGE_LENGTH } from "discourse/models/post-action-type";
import { i18n } from "discourse-i18n";
@@ -23,57 +23,63 @@ export default class FlagActionType extends Component {
});
}
- @discourseComputed("flag.name_key")
- wrapperClassNames(nameKey) {
- return `flag-action-type ${nameKey}`;
+ @computed("flag.name_key")
+ get wrapperClassNames() {
+ return `flag-action-type ${this.flag?.name_key}`;
}
- @discourseComputed("flag.name_key")
- customPlaceholder(nameKey) {
+ @computed("flag.name_key")
+ get customPlaceholder() {
return applyValueTransformer(
"flag-custom-placeholder",
- i18n("flagging.custom_placeholder_" + nameKey, {
+ i18n("flagging.custom_placeholder_" + this.flag?.name_key, {
defaultValue: i18n("flagging.custom_placeholder_notify_moderators"),
}),
- { nameKey }
+ { nameKey: this.flag?.name_key }
);
}
- @discourseComputed("flag.name", "flag.name_key", "username")
- formattedName(name, nameKey, username) {
- if (["notify_user", "notify_moderators"].includes(nameKey)) {
- return name.replace(/{{username}}|%{username}/, username);
+ @computed("flag.name", "flag.name_key", "username")
+ get formattedName() {
+ if (["notify_user", "notify_moderators"].includes(this.flag?.name_key)) {
+ return this.flag?.name?.replace(
+ /{{username}}|%{username}/,
+ this.username
+ );
} else {
return applyValueTransformer(
"flag-formatted-name",
- i18n("flagging.formatted_name." + nameKey, {
- defaultValue: name,
+ i18n("flagging.formatted_name." + this.flag?.name_key, {
+ defaultValue: this.flag?.name,
}),
- { nameKey }
+ { nameKey: this.flag?.name_key }
);
}
}
- @discourseComputed("flag", "selectedFlag")
- selected(flag, selectedFlag) {
- return flag === selectedFlag;
+ @computed("flag", "selectedFlag")
+ get selected() {
+ return this.flag === this.selectedFlag;
}
- @discourseComputed("flag.description", "flag.short_description")
- description(long_description, short_description) {
- return this.site.mobileView ? short_description : long_description;
+ @computed("flag.description", "flag.short_description")
+ get description() {
+ return this.site.mobileView
+ ? this.flag?.short_description
+ : this.flag?.description;
}
- @discourseComputed("message.length")
- customMessageLengthClasses(messageLength) {
- return messageLength < this.siteSettings.min_personal_message_post_length
+ @computed("message.length")
+ get customMessageLengthClasses() {
+ return this.message?.length <
+ this.siteSettings.min_personal_message_post_length
? "too-short"
: "ok";
}
- @discourseComputed("message.length")
- customMessageLength(messageLength) {
- const len = messageLength || 0;
+ @computed("message.length")
+ get customMessageLength() {
+ const len = this.message?.length || 0;
const minLen = this.siteSettings.min_personal_message_post_length;
if (len === 0) {
return i18n("flagging.custom_message.at_least", { count: minLen });
diff --git a/frontend/discourse/app/components/future-date-input.gjs b/frontend/discourse/app/components/future-date-input.gjs
index da81ec19f45..00bf4137d21 100644
--- a/frontend/discourse/app/components/future-date-input.gjs
+++ b/frontend/discourse/app/components/future-date-input.gjs
@@ -2,13 +2,12 @@
import Component, { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { and, empty, equal } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import DatePickerFuture from "discourse/components/date-picker-future";
import icon from "discourse/helpers/d-icon";
import withEventValue from "discourse/helpers/with-event-value";
-import discourseComputed from "discourse/lib/decorators";
import {
extendedDefaultTimeShortcuts,
formatTime,
@@ -64,11 +63,11 @@ export default class FutureDateInput extends Component {
}
}
- @discourseComputed("customShortcuts")
- shortcuts(customShortcuts) {
+ @computed("customShortcuts")
+ get shortcuts() {
let shortcuts;
- if (customShortcuts && customShortcuts.length) {
- shortcuts = customShortcuts;
+ if (this.customShortcuts && this.customShortcuts.length) {
+ shortcuts = this.customShortcuts;
} else {
shortcuts = extendedDefaultTimeShortcuts(this.userTimezone);
}
diff --git a/frontend/discourse/app/components/google-search.gjs b/frontend/discourse/app/components/google-search.gjs
index 87af0411962..7ec4a2b9c30 100644
--- a/frontend/discourse/app/components/google-search.gjs
+++ b/frontend/discourse/app/components/google-search.gjs
@@ -1,11 +1,11 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import PluginOutlet from "discourse/components/plugin-outlet";
import concatClass from "discourse/helpers/concat-class";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { i18n } from "discourse-i18n";
@@ -13,8 +13,8 @@ import { i18n } from "discourse-i18n";
export default class GoogleSearch extends Component {
@alias("siteSettings.login_required") hidden;
- @discourseComputed
- siteUrl() {
+ @computed
+ get siteUrl() {
return `${location.protocol}//${location.host}${getURL("/")}`;
}
diff --git a/frontend/discourse/app/components/group-card-contents.gjs b/frontend/discourse/app/components/group-card-contents.gjs
index c6fd5501edf..7833dd0accc 100644
--- a/frontend/discourse/app/components/group-card-contents.gjs
+++ b/frontend/discourse/app/components/group-card-contents.gjs
@@ -1,5 +1,5 @@
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, gt } from "@ember/object/computed";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
@@ -12,7 +12,6 @@ import GroupMembershipButton from "discourse/components/group-membership-button"
import boundAvatar from "discourse/helpers/bound-avatar";
import routeAction from "discourse/helpers/route-action";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { wantsNewWindow } from "discourse/lib/intercept-click";
import { groupPath } from "discourse/lib/url";
import { i18n } from "discourse-i18n";
@@ -41,24 +40,24 @@ export default class GroupCardContents extends CardContentsBase {
group = null;
- @discourseComputed("group.members.[]")
- highlightedMembers(members) {
- return members.slice(0, maxMembersToDisplay);
+ @computed("group.members.[]")
+ get highlightedMembers() {
+ return this.group?.members.slice(0, maxMembersToDisplay);
}
- @discourseComputed("group.user_count", "group.members.[]")
- moreMembersCount(memberCount) {
- return Math.max(memberCount - maxMembersToDisplay, 0);
+ @computed("group.user_count", "group.members.[]")
+ get moreMembersCount() {
+ return Math.max(this.group?.user_count - maxMembersToDisplay, 0);
}
- @discourseComputed("group.name")
- groupClass(name) {
- return name ? `group-card-${name}` : "";
+ @computed("group.name")
+ get groupClass() {
+ return this.group?.name ? `group-card-${this.group?.name}` : "";
}
- @discourseComputed("group")
- groupPath(group) {
- return groupPath(group.name);
+ @computed("group")
+ get groupPath() {
+ return groupPath(this.group.name);
}
@onEvent("didInsertElement")
diff --git a/frontend/discourse/app/components/group-flair-inputs.gjs b/frontend/discourse/app/components/group-flair-inputs.gjs
index a37c088f028..462cba6ed2c 100644
--- a/frontend/discourse/app/components/group-flair-inputs.gjs
+++ b/frontend/discourse/app/components/group-flair-inputs.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/no-jquery, ember/no-observers */
import Component from "@ember/component";
import { fn, hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import { observes, on } from "@ember-decorators/object";
import $ from "jquery";
@@ -11,7 +11,6 @@ import TextField from "discourse/components/text-field";
import UppyImageUploader from "discourse/components/uppy-image-uploader";
import { ajax } from "discourse/lib/ajax";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { convertIconClass } from "discourse/lib/icon-library";
import IconPicker from "discourse/select-kit/components/icon-picker";
@@ -20,19 +19,21 @@ import { i18n } from "discourse-i18n";
@tagName("")
export default class GroupFlairInputs extends Component {
- @discourseComputed
- demoAvatarUrl() {
+ @computed
+ get demoAvatarUrl() {
return getURL("/images/avatar.png");
}
- @discourseComputed("model.flair_type")
- flairPreviewIcon(flairType) {
- return flairType && flairType === "icon";
+ @computed("model.flair_type")
+ get flairPreviewIcon() {
+ return this.model?.flair_type && this.model?.flair_type === "icon";
}
- @discourseComputed("model.flair_icon")
- flairPreviewIconUrl(flairIcon) {
- return flairIcon ? convertIconClass(flairIcon) : "";
+ @computed("model.flair_icon")
+ get flairPreviewIconUrl() {
+ return this.model?.flair_icon
+ ? convertIconClass(this.model?.flair_icon)
+ : "";
}
@on("didInsertElement")
@@ -70,19 +71,21 @@ export default class GroupFlairInputs extends Component {
}
}
- @discourseComputed("model.flair_type")
- flairPreviewImage(flairType) {
- return flairType && flairType === "image";
+ @computed("model.flair_type")
+ get flairPreviewImage() {
+ return this.model?.flair_type && this.model?.flair_type === "image";
}
- @discourseComputed("model.flair_url")
- flairImageUrl(flairUrl) {
- return flairUrl && flairUrl.includes("/") ? flairUrl : null;
+ @computed("model.flair_url")
+ get flairImageUrl() {
+ return this.model?.flair_url && this.model?.flair_url?.includes("/")
+ ? this.model?.flair_url
+ : null;
}
- @discourseComputed("flairPreviewImage")
- flairPreviewLabel(flairPreviewImage) {
- const key = flairPreviewImage ? "image" : "icon";
+ @computed("flairPreviewImage")
+ get flairPreviewLabel() {
+ const key = this.flairPreviewImage ? "image" : "icon";
return i18n(`groups.flair_preview_${key}`);
}
diff --git a/frontend/discourse/app/components/group-manage-email-settings.gjs b/frontend/discourse/app/components/group-manage-email-settings.gjs
index 5d065814fcb..487b72ebd19 100644
--- a/frontend/discourse/app/components/group-manage-email-settings.gjs
+++ b/frontend/discourse/app/components/group-manage-email-settings.gjs
@@ -1,14 +1,13 @@
/* eslint-disable ember/no-classic-components */
import Component, { Input } from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
import { on as onEvent } from "@ember-decorators/object";
import GroupManageSaveButton from "discourse/components/group-manage-save-button";
import GroupSmtpEmailSettings from "discourse/components/group-smtp-email-settings";
-import discourseComputed from "discourse/lib/decorators";
import { not } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -26,9 +25,9 @@ export default class GroupManageEmailSettings extends Component {
);
}
- @discourseComputed("smtpSettingsValid", "group.smtp_enabled")
- emailSettingsValid(smtpSettingsValid, smtpEnabled) {
- return !smtpEnabled || smtpSettingsValid;
+ @computed("smtpSettingsValid", "group.smtp_enabled")
+ get emailSettingsValid() {
+ return !this.group?.smtp_enabled || this.smtpSettingsValid;
}
_anySmtpFieldsFilled() {
diff --git a/frontend/discourse/app/components/group-manage-logs-filter.gjs b/frontend/discourse/app/components/group-manage-logs-filter.gjs
index 6690fcb0730..a994b6dd733 100644
--- a/frontend/discourse/app/components/group-manage-logs-filter.gjs
+++ b/frontend/discourse/app/components/group-manage-logs-filter.gjs
@@ -1,21 +1,23 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { concat, fn } from "@ember/helper";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("")
export default class GroupManageLogsFilter extends Component {
- @discourseComputed("type")
- label(type) {
- return i18n(`groups.manage.logs.${type}`);
+ @computed("type")
+ get label() {
+ return i18n(`groups.manage.logs.${this.type}`);
}
- @discourseComputed("value", "type")
- filterText(value, type) {
- return type === "action" ? i18n(`group_histories.actions.${value}`) : value;
+ @computed("value", "type")
+ get filterText() {
+ return this.type === "action"
+ ? i18n(`group_histories.actions.${this.value}`)
+ : this.value;
}
<template>
diff --git a/frontend/discourse/app/components/group-manage-save-button.gjs b/frontend/discourse/app/components/group-manage-save-button.gjs
index c646636423e..d116edd323e 100644
--- a/frontend/discourse/app/components/group-manage-save-button.gjs
+++ b/frontend/discourse/app/components/group-manage-save-button.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
@@ -8,7 +8,6 @@ import GroupFlairVisibilityWarning from "discourse/components/group-flair-visibi
import GroupDefaultNotificationsModal from "discourse/components/modal/group-default-notifications";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { GROUP_VISIBILITY_LEVELS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import { defaultHomepage } from "discourse/lib/utilities";
import { or } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -24,9 +23,9 @@ export default class GroupManageSaveButton extends Component {
saving = null;
disabled = false;
- @discourseComputed("saving")
- savingText(saving) {
- return saving ? i18n("saving") : i18n("save");
+ @computed("saving")
+ get savingText() {
+ return this.saving ? i18n("saving") : i18n("save");
}
_wouldLoseAccess() {
diff --git a/frontend/discourse/app/components/group-membership-button.gjs b/frontend/discourse/app/components/group-membership-button.gjs
index afb0c240452..a5c0c91a652 100644
--- a/frontend/discourse/app/components/group-membership-button.gjs
+++ b/frontend/discourse/app/components/group-membership-button.gjs
@@ -1,11 +1,10 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import RequestGroupMembershipForm from "./modal/request-group-membership-form";
@@ -16,24 +15,24 @@ export default class GroupMembershipButton extends Component {
@service dialog;
@service modal;
- @discourseComputed("model.public_admission", "userIsGroupUser")
- canJoinGroup(publicAdmission, userIsGroupUser) {
- return publicAdmission && !userIsGroupUser;
+ @computed("model.public_admission", "userIsGroupUser")
+ get canJoinGroup() {
+ return this.model?.public_admission && !this.userIsGroupUser;
}
- @discourseComputed("model.public_exit", "userIsGroupUser")
- canLeaveGroup(publicExit, userIsGroupUser) {
- return publicExit && userIsGroupUser;
+ @computed("model.public_exit", "userIsGroupUser")
+ get canLeaveGroup() {
+ return this.model?.public_exit && this.userIsGroupUser;
}
- @discourseComputed("model.allow_membership_requests", "userIsGroupUser")
- canRequestMembership(allowMembershipRequests, userIsGroupUser) {
- return allowMembershipRequests && !userIsGroupUser;
+ @computed("model.allow_membership_requests", "userIsGroupUser")
+ get canRequestMembership() {
+ return this.model?.allow_membership_requests && !this.userIsGroupUser;
}
- @discourseComputed("model.is_group_user")
- userIsGroupUser(isGroupUser) {
- return !!isGroupUser;
+ @computed("model.is_group_user")
+ get userIsGroupUser() {
+ return !!this.model?.is_group_user;
}
removeFromGroup() {
diff --git a/frontend/discourse/app/components/groups-form-interaction-fields.gjs b/frontend/discourse/app/components/groups-form-interaction-fields.gjs
index f4ce63bfcea..29e0864c7db 100644
--- a/frontend/discourse/app/components/groups-form-interaction-fields.gjs
+++ b/frontend/discourse/app/components/groups-form-interaction-fields.gjs
@@ -1,13 +1,13 @@
/* eslint-disable ember/no-classic-components */
import Component, { Input } from "@ember/component";
import { fn, hash } from "@ember/helper";
+import { computed } from "@ember/object";
import { or } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import PluginOutlet from "discourse/components/plugin-outlet";
import TextField from "discourse/components/text-field";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import { NotificationLevels } from "discourse/lib/notification-levels";
import ComboBox from "discourse/select-kit/components/combo-box";
import NotificationsButton from "discourse/select-kit/components/notifications-button";
@@ -63,42 +63,44 @@ export default class GroupsFormInteractionFields extends Component {
watchingNotificationLevel = NotificationLevels.WATCHING;
- @discourseComputed(
- "model.default_notification_level",
- "watchingNotificationLevel"
- )
- defaultNotificationLevel(
- defaultNotificationLevel,
- watchingNotificationLevel
- ) {
- if (Object.values(NotificationLevels).includes(defaultNotificationLevel)) {
- return defaultNotificationLevel;
+ @computed("model.default_notification_level", "watchingNotificationLevel")
+ get defaultNotificationLevel() {
+ if (
+ Object.values(NotificationLevels).includes(
+ this.model?.default_notification_level
+ )
+ ) {
+ return this.model?.default_notification_level;
}
- return watchingNotificationLevel;
+ return this.watchingNotificationLevel;
}
- @discourseComputed(
- "siteSettings.email_in",
- "model.automatic",
- "currentUser.admin"
- )
- showEmailSettings(emailIn, automatic, isAdmin) {
- return emailIn && isAdmin && !automatic;
+ @computed("siteSettings.email_in", "model.automatic", "currentUser.admin")
+ get showEmailSettings() {
+ return (
+ this.siteSettings?.email_in &&
+ this.currentUser?.admin &&
+ !this.model?.automatic
+ );
}
- @discourseComputed(
+ @computed(
"model.isCreated",
"model.can_admin_group",
"currentUser.can_create_group"
)
- canAdminGroup(isCreated, canAdmin, canCreate) {
- return (!isCreated && canCreate) || (isCreated && canAdmin);
+ get canAdminGroup() {
+ return (
+ (!this.model?.isCreated && this.currentUser?.can_create_group) ||
+ (this.model?.isCreated && this.model?.can_admin_group)
+ );
}
- @discourseComputed("membersVisibilityLevel")
- membersVisibilityPrivate(membersVisibilityLevel) {
+ @computed("membersVisibilityLevel")
+ get membersVisibilityPrivate() {
return (
- membersVisibilityLevel !== this.visibilityLevelOptions.firstObject.value
+ this.membersVisibilityLevel !==
+ this.visibilityLevelOptions.firstObject.value
);
}
diff --git a/frontend/discourse/app/components/groups-form-membership-fields.gjs b/frontend/discourse/app/components/groups-form-membership-fields.gjs
index 59da29210a4..920456b3abc 100644
--- a/frontend/discourse/app/components/groups-form-membership-fields.gjs
+++ b/frontend/discourse/app/components/groups-form-membership-fields.gjs
@@ -10,7 +10,6 @@ import GroupFlairInputs from "discourse/components/group-flair-inputs";
import PluginOutlet from "discourse/components/plugin-outlet";
import lazyHash from "discourse/helpers/lazy-hash";
import withEventValue from "discourse/helpers/with-event-value";
-import discourseComputed from "discourse/lib/decorators";
import AssociatedGroup from "discourse/models/associated-group";
import ComboBox from "discourse/select-kit/components/combo-box";
import ListSetting from "discourse/select-kit/components/list-setting";
@@ -51,36 +50,29 @@ export default class GroupsFormMembershipFields extends Component {
);
}
- @discourseComputed("model.visibility_level", "model.public_admission")
- disableMembershipRequestSetting(visibility_level, publicAdmission) {
- visibility_level = parseInt(visibility_level, 10);
- return publicAdmission || visibility_level > 1;
+ @computed("model.visibility_level", "model.public_admission")
+ get disableMembershipRequestSetting() {
+ const visibility_level = parseInt(this.model?.visibility_level, 10);
+ return this.model?.public_admission || visibility_level > 1;
}
- @discourseComputed(
- "model.visibility_level",
- "model.allow_membership_requests"
- )
- disablePublicSetting(visibility_level, allowMembershipRequests) {
- visibility_level = parseInt(visibility_level, 10);
- return allowMembershipRequests || visibility_level > 1;
+ @computed("model.visibility_level", "model.allow_membership_requests")
+ get disablePublicSetting() {
+ const visibility_level = parseInt(this.model?.visibility_level, 10);
+ return this.model?.allow_membership_requests || visibility_level > 1;
}
- @discourseComputed(
- "model.visibility_level",
- "model.primary_group",
- "hasFlair"
- )
- privateGroupNameNotice(visibilityLevel, isPrimaryGroup, hasFlair) {
- if (visibilityLevel === 0) {
+ @computed("model.visibility_level", "model.primary_group", "hasFlair")
+ get privateGroupNameNotice() {
+ if (this.model?.visibility_level === 0) {
return;
}
- if (isPrimaryGroup) {
+ if (this.model?.primary_group) {
return i18n("admin.groups.manage.alert.primary_group", {
group_name: this.model.name,
});
- } else if (hasFlair) {
+ } else if (this.hasFlair) {
return i18n("admin.groups.manage.alert.flair_group", {
group_name: this.model.name,
});
diff --git a/frontend/discourse/app/components/groups-form-profile-fields.gjs b/frontend/discourse/app/components/groups-form-profile-fields.gjs
index 41b86ed59cf..d791d51c06a 100644
--- a/frontend/discourse/app/components/groups-form-profile-fields.gjs
+++ b/frontend/discourse/app/components/groups-form-profile-fields.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components, ember/no-observers */
import Component from "@ember/component";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { not } from "@ember/object/computed";
import { isEmpty } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
@@ -13,7 +13,6 @@ import TextField from "discourse/components/text-field";
import lazyHash from "discourse/helpers/lazy-hash";
import { popupAjaxError } from "discourse/lib/ajax-error";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import Group from "discourse/models/group";
import { i18n } from "discourse-i18n";
@@ -35,9 +34,11 @@ export default class GroupsFormProfileFields extends Component {
}
}
- @discourseComputed("basicNameValidation", "uniqueNameValidation")
- nameValidation(basicNameValidation, uniqueNameValidation) {
- return uniqueNameValidation ? uniqueNameValidation : basicNameValidation;
+ @computed("basicNameValidation", "uniqueNameValidation")
+ get nameValidation() {
+ return this.uniqueNameValidation
+ ? this.uniqueNameValidation
+ : this.basicNameValidation;
}
@observes("nameInput")
diff --git a/frontend/discourse/app/components/invite-panel.gjs b/frontend/discourse/app/components/invite-panel.gjs
index e63aee29957..9af05897958 100644
--- a/frontend/discourse/app/components/invite-panel.gjs
+++ b/frontend/discourse/app/components/invite-panel.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component, { Textarea } from "@ember/component";
import { fn, hash } from "@ember/helper";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { alias, and, equal, readOnly } from "@ember/object/computed";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
@@ -12,7 +12,6 @@ import DiscourseLinkedText from "discourse/components/discourse-linked-text";
import GeneratedInviteLink from "discourse/components/generated-invite-link";
import TextField from "discourse/components/text-field";
import { computedI18n } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { getNativeContact } from "discourse/lib/pwa-utils";
import { emailValid } from "discourse/lib/utilities";
import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
@@ -62,7 +61,7 @@ export default class InvitePanel extends Component {
this.reset();
}
- @discourseComputed(
+ @computed(
"isAdmin",
"invitee",
"invitingToTopic",
@@ -71,45 +70,41 @@ export default class InvitePanel extends Component {
"inviteModel.saving",
"inviteModel.details.can_invite_to"
)
- disabled(
- isAdmin,
- invitee,
- invitingToTopic,
- isPrivateTopic,
- groupIds,
- saving,
- can_invite_to
- ) {
- if (saving) {
+ get disabled() {
+ if (this.inviteModel?.saving) {
return true;
}
- if (isEmpty(invitee)) {
+ if (isEmpty(this.invitee)) {
return true;
}
// when inviting to forum, email must be valid
- if (!invitingToTopic && !emailValid(invitee)) {
+ if (!this.invitingToTopic && !emailValid(this.invitee)) {
return true;
}
// normal users (not admin) can't invite users to private topic via email
- if (!isAdmin && isPrivateTopic && emailValid(invitee)) {
+ if (!this.isAdmin && this.isPrivateTopic && emailValid(this.invitee)) {
return true;
}
// when inviting to private topic via email, group name must be specified
- if (isPrivateTopic && isEmpty(groupIds) && emailValid(invitee)) {
+ if (
+ this.isPrivateTopic &&
+ isEmpty(this.groupIds) &&
+ emailValid(this.invitee)
+ ) {
return true;
}
- if (can_invite_to) {
+ if (this.inviteModel?.details?.can_invite_to) {
return false;
}
return false;
}
- @discourseComputed(
+ @computed(
"isAdmin",
"invitee",
"inviteModel.saving",
@@ -117,73 +112,76 @@ export default class InvitePanel extends Component {
"groupIds",
"hasCustomMessage"
)
- disabledCopyLink(
- isAdmin,
- invitee,
- saving,
- isPrivateTopic,
- groupIds,
- hasCustomMessage
- ) {
- if (hasCustomMessage) {
+ get disabledCopyLink() {
+ if (this.hasCustomMessage) {
return true;
}
- if (saving) {
+ if (this.inviteModel?.saving) {
return true;
}
- if (isEmpty(invitee)) {
+ if (isEmpty(this.invitee)) {
return true;
}
// email must be valid
- if (!emailValid(invitee)) {
+ if (!emailValid(this.invitee)) {
return true;
}
// normal users (not admin) can't invite users to private topic via email
- if (!isAdmin && isPrivateTopic && emailValid(invitee)) {
+ if (!this.isAdmin && this.isPrivateTopic && emailValid(this.invitee)) {
return true;
}
// when inviting to private topic via email, group name must be specified
- if (isPrivateTopic && isEmpty(groupIds) && emailValid(invitee)) {
+ if (
+ this.isPrivateTopic &&
+ isEmpty(this.groupIds) &&
+ emailValid(this.invitee)
+ ) {
return true;
}
return false;
}
- @discourseComputed("inviteModel.saving")
- buttonTitle(saving) {
- return saving ? "topic.inviting" : "topic.invite_reply.action";
+ @computed("inviteModel.saving")
+ get buttonTitle() {
+ return this.inviteModel?.saving
+ ? "topic.inviting"
+ : "topic.invite_reply.action";
}
// We are inviting to a topic if the topic isn't the current user.
// The current user would mean we are inviting to the forum in general.
- @discourseComputed("inviteModel")
- invitingToTopic(inviteModel) {
- return inviteModel !== this.currentUser;
+ @computed("inviteModel")
+ get invitingToTopic() {
+ return this.inviteModel !== this.currentUser;
}
- @discourseComputed("inviteModel", "inviteModel.details.can_invite_via_email")
- canInviteViaEmail(inviteModel, canInviteViaEmail) {
- return inviteModel === this.currentUser ? true : canInviteViaEmail;
+ @computed("inviteModel", "inviteModel.details.can_invite_via_email")
+ get canInviteViaEmail() {
+ return this.inviteModel === this.currentUser
+ ? true
+ : this.inviteModel?.details?.can_invite_via_email;
}
- @discourseComputed("isPM", "canInviteViaEmail")
- showCopyInviteButton(isPM, canInviteViaEmail) {
- return canInviteViaEmail && !isPM;
+ @computed("isPM", "canInviteViaEmail")
+ get showCopyInviteButton() {
+ return this.canInviteViaEmail && !this.isPM;
}
- @discourseComputed("isAdmin", "inviteModel.group_users")
- isGroupOwnerOrAdmin(isAdmin, groupUsers) {
+ @computed("isAdmin", "inviteModel.group_users")
+ get isGroupOwnerOrAdmin() {
return (
- isAdmin || (groupUsers && groupUsers.some((groupUser) => groupUser.owner))
+ this.isAdmin ||
+ (this.inviteModel?.group_users &&
+ this.inviteModel?.group_users?.some((groupUser) => groupUser.owner))
);
}
// Show Groups? (add invited user to private group)
- @discourseComputed(
+ @computed(
"isGroupOwnerOrAdmin",
"invitee",
"isPrivateTopic",
@@ -191,29 +189,22 @@ export default class InvitePanel extends Component {
"invitingToTopic",
"canInviteViaEmail"
)
- showGroups(
- isGroupOwnerOrAdmin,
- invitee,
- isPrivateTopic,
- isPM,
- invitingToTopic,
- canInviteViaEmail
- ) {
+ get showGroups() {
return (
- isGroupOwnerOrAdmin &&
- canInviteViaEmail &&
- !isPM &&
- (emailValid(invitee) || isPrivateTopic || !invitingToTopic)
+ this.isGroupOwnerOrAdmin &&
+ this.canInviteViaEmail &&
+ !this.isPM &&
+ (emailValid(this.invitee) || this.isPrivateTopic || !this.invitingToTopic)
);
}
- @discourseComputed("invitee")
- showCustomMessage(invitee) {
- return this.inviteModel === this.currentUser || emailValid(invitee);
+ @computed("invitee")
+ get showCustomMessage() {
+ return this.inviteModel === this.currentUser || emailValid(this.invitee);
}
// Instructional text for the modal.
- @discourseComputed(
+ @computed(
"isPM",
"invitingToTopic",
"invitee",
@@ -221,34 +212,27 @@ export default class InvitePanel extends Component {
"isAdmin",
"canInviteViaEmail"
)
- inviteInstructions(
- isPM,
- invitingToTopic,
- invitee,
- isPrivateTopic,
- isAdmin,
- canInviteViaEmail
- ) {
- if (!canInviteViaEmail) {
+ get inviteInstructions() {
+ if (!this.canInviteViaEmail) {
// can't invite via email, only existing users
return i18n("topic.invite_reply.discourse_connect_enabled");
- } else if (isPM) {
+ } else if (this.isPM) {
// inviting to a message
return i18n("topic.invite_private.email_or_username");
- } else if (invitingToTopic) {
+ } else if (this.invitingToTopic) {
// inviting to a private/public topic
- if (isPrivateTopic && !isAdmin) {
+ if (this.isPrivateTopic && !this.isAdmin) {
// inviting to a private topic and is not admin
return i18n("topic.invite_reply.to_username");
} else {
// when inviting to a topic, display instructions based on provided entity
- if (isEmpty(invitee)) {
+ if (isEmpty(this.invitee)) {
return i18n("topic.invite_reply.to_topic_blank");
- } else if (emailValid(invitee)) {
- this.set("inviteIcon", "envelope");
+ } else if (emailValid(this.invitee)) {
+ this.set("inviteIcon", "envelope"); // eslint-disable-line ember/no-side-effects
return i18n("topic.invite_reply.to_topic_email");
} else {
- this.set("inviteIcon", "hand-point-right");
+ this.set("inviteIcon", "hand-point-right"); // eslint-disable-line ember/no-side-effects
return i18n("topic.invite_reply.to_topic_username");
}
}
@@ -258,9 +242,9 @@ export default class InvitePanel extends Component {
}
}
- @discourseComputed("isPrivateTopic")
- showGroupsClass(isPrivateTopic) {
- return isPrivateTopic ? "required" : "optional";
+ @computed("isPrivateTopic")
+ get showGroupsClass() {
+ return this.isPrivateTopic ? "required" : "optional";
}
successMessage(invitee) {
@@ -279,19 +263,19 @@ export default class InvitePanel extends Component {
}
}
- @discourseComputed("isPM", "ajaxError")
- errorMessage(isPM, ajaxError) {
- if (ajaxError) {
- return ajaxError;
+ @computed("isPM", "ajaxError")
+ get errorMessage() {
+ if (this.ajaxError) {
+ return this.ajaxError;
}
- return isPM
+ return this.isPM
? i18n("topic.invite_private.error")
: i18n("topic.invite_reply.error");
}
- @discourseComputed("canInviteViaEmail")
- placeholderKey(canInviteViaEmail) {
- return canInviteViaEmail
+ @computed("canInviteViaEmail")
+ get placeholderKey() {
+ return this.canInviteViaEmail
? "topic.invite_private.email_or_username_placeholder"
: "topic.invite_reply.username_placeholder";
}
diff --git a/frontend/discourse/app/components/login-buttons.gjs b/frontend/discourse/app/components/login-buttons.gjs
index 37fc4c4b2b8..a40d39887c0 100644
--- a/frontend/discourse/app/components/login-buttons.gjs
+++ b/frontend/discourse/app/components/login-buttons.gjs
@@ -2,40 +2,40 @@
import Component from "@ember/component";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import GoogleIcon from "discourse/components/google-icon";
import PasskeyLoginButton from "discourse/components/passkey-login-button";
import PluginOutlet from "discourse/components/plugin-outlet";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
import { isWebauthnSupported } from "discourse/lib/webauthn";
import { findAll } from "discourse/models/login-method";
import { i18n } from "discourse-i18n";
@tagName("")
export default class LoginButtons extends Component {
- @discourseComputed(
- "buttons.length",
- "showLoginWithEmailLink",
- "showPasskeysButton"
- )
- hidden(buttonsCount, showLoginWithEmailLink, showPasskeysButton) {
- return buttonsCount === 0 && !showLoginWithEmailLink && !showPasskeysButton;
+ @computed("buttons.length", "showLoginWithEmailLink", "showPasskeysButton")
+ get hidden() {
+ return (
+ this.buttons?.length === 0 &&
+ !this.showLoginWithEmailLink &&
+ !this.showPasskeysButton
+ );
}
- @discourseComputed("buttons.length")
- multiple(buttonsCount) {
- return buttonsCount > 1;
+ @computed("buttons.length")
+ get multiple() {
+ return this.buttons?.length > 1;
}
- @discourseComputed
- buttons() {
+ @computed
+ get buttons() {
return findAll();
}
- @discourseComputed
- showPasskeysButton() {
+ @computed
+ get showPasskeysButton() {
return (
this.siteSettings.enable_local_logins &&
this.siteSettings.enable_passkeys &&
diff --git a/frontend/discourse/app/components/modal/share-topic.gjs b/frontend/discourse/app/components/modal/share-topic.gjs
index 2e37161a307..6179e10ba76 100644
--- a/frontend/discourse/app/components/modal/share-topic.gjs
+++ b/frontend/discourse/app/components/modal/share-topic.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components */
import Component, { Input } from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { readOnly } from "@ember/object/computed";
import { getOwner } from "@ember/owner";
import { service } from "@ember/service";
@@ -12,7 +12,7 @@ import CreateInvite from "discourse/components/modal/create-invite";
import PluginOutlet from "discourse/components/plugin-outlet";
import ShareSource from "discourse/components/share-source";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed, { afterRender } from "discourse/lib/decorators";
+import { afterRender } from "discourse/lib/decorators";
import { longDateNoYear } from "discourse/lib/formatter";
import { getAbsoluteURL } from "discourse/lib/get-url";
import Sharing from "discourse/lib/sharing";
@@ -63,30 +63,31 @@ export default class ShareTopicModal extends Component {
}
}
- @discourseComputed("post.shareUrl", "topic.shareUrl")
- url(postUrl, topicUrl) {
- if (postUrl) {
- return getAbsoluteURL(postUrl);
- } else if (topicUrl) {
- return getAbsoluteURL(topicUrl);
+ @computed("post.shareUrl", "topic.shareUrl")
+ get url() {
+ if (this.post?.shareUrl) {
+ return getAbsoluteURL(this.post?.shareUrl);
+ } else if (this.topic?.shareUrl) {
+ return getAbsoluteURL(this.topic?.shareUrl);
}
}
- @discourseComputed("post.created_at", "post.wiki", "post.last_wiki_edit")
- displayDate(createdAt, wiki, lastWikiEdit) {
- const date = wiki && lastWikiEdit ? lastWikiEdit : createdAt;
+ @computed("post.created_at", "post.wiki", "post.last_wiki_edit")
+ get displayDate() {
+ const date =
+ this.post?.wiki && this.post?.last_wiki_edit
+ ? this.post?.last_wiki_edit
+ : this.post?.created_at;
return longDateNoYear(new Date(date));
}
- @discourseComputed(
- "topic.{isPrivateMessage,invisible,category.read_restricted}"
- )
- sources(topic) {
+ @computed("topic.{isPrivateMessage,invisible,category.read_restricted}")
+ get sources() {
const privateContext =
this.siteSettings.login_required ||
- topic?.isPrivateMessage ||
- topic?.invisible ||
- topic?.category?.read_restricted;
+ this.topic?.isPrivateMessage ||
+ this.topic?.invisible ||
+ this.topic?.category?.read_restricted;
return Sharing.activeSources(this.siteSettings.share_links, privateContext);
}
diff --git a/frontend/discourse/app/components/navigation-item.gjs b/frontend/discourse/app/components/navigation-item.gjs
index ed87706c14c..4972168954e 100644
--- a/frontend/discourse/app/components/navigation-item.gjs
+++ b/frontend/discourse/app/components/navigation-item.gjs
@@ -1,9 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { filterTypeForMode } from "discourse/lib/filter-mode";
@tagName("")
@@ -18,23 +18,23 @@ export default class NavigationItem extends Component {
return filterTypeForMode(this.filterMode);
}
- @discourseComputed("content.filterType", "filterType", "content.active")
- active(contentFilterType, filterType, active) {
- if (active !== undefined) {
- return active;
+ @computed("content.filterType", "filterType", "content.active")
+ get active() {
+ if (this.content?.active !== undefined) {
+ return this.content?.active;
}
- return contentFilterType === filterType;
+ return this.content?.filterType === this.filterType;
}
- @discourseComputed("content.count", "content.name")
- isHidden(count, name) {
+ @computed("content.count", "content.name")
+ get isHidden() {
return (
!this.active &&
this.currentUser &&
!this.currentUser.new_new_view_enabled &&
this.currentUser.trust_level > 0 &&
- (name === "new" || name === "unread") &&
- count < 1
+ (this.content?.name === "new" || this.content?.name === "unread") &&
+ this.content?.count < 1
);
}
diff --git a/frontend/discourse/app/components/number-field.js b/frontend/discourse/app/components/number-field.js
index 34232629888..864ad79e7e4 100644
--- a/frontend/discourse/app/components/number-field.js
+++ b/frontend/discourse/app/components/number-field.js
@@ -1,7 +1,6 @@
import { computed } from "@ember/object";
import { classNameBindings } from "@ember-decorators/component";
import TextField from "discourse/components/text-field";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { allowOnlyNumericInput } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
@@ -57,8 +56,8 @@ export default class NumberField extends TextField {
}
}
- @discourseComputed("placeholderKey")
- placeholder(key) {
- return key ? i18n(key) : "";
+ @computed("placeholderKey")
+ get placeholder() {
+ return this.placeholderKey ? i18n(this.placeholderKey) : "";
}
}
diff --git a/frontend/discourse/app/components/pick-files-button.gjs b/frontend/discourse/app/components/pick-files-button.gjs
index 1a23ee4f874..05f0a876025 100644
--- a/frontend/discourse/app/components/pick-files-button.gjs
+++ b/frontend/discourse/app/components/pick-files-button.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
import { isBlank } from "@ember/utils";
@@ -8,7 +8,7 @@ import { classNames } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import concatClass from "discourse/helpers/concat-class";
import noop from "discourse/helpers/noop";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import {
authorizedExtensions,
authorizesAllExtensions,
@@ -59,16 +59,16 @@ export default class PickFilesButton extends Component {
this._filesPicked(files);
}
- @discourseComputed()
- acceptsAllFormats() {
+ @computed()
+ get acceptsAllFormats() {
return (
this.capabilities.isIOS ||
authorizesAllExtensions(this.currentUser.staff, this.siteSettings)
);
}
- @discourseComputed()
- acceptedFormats() {
+ @computed()
+ get acceptedFormats() {
// the acceptedFormatsOverride can be a list of extensions or mime types
if (!isBlank(this.acceptedFormatsOverride)) {
return this.acceptedFormatsOverride;
diff --git a/frontend/discourse/app/components/popup-input-tip.gjs b/frontend/discourse/app/components/popup-input-tip.gjs
index f1a71a9b17d..55e8f3af66c 100644
--- a/frontend/discourse/app/components/popup-input-tip.gjs
+++ b/frontend/discourse/app/components/popup-input-tip.gjs
@@ -1,5 +1,6 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { not, or, reads } from "@ember/object/computed";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
@@ -9,7 +10,6 @@ import {
tagName,
} from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
@tagName("a")
@classNameBindings(":popup-tip", "good", "bad", "lastShownAt::hide")
@@ -24,16 +24,16 @@ export default class PopupInputTip extends Component {
@reads("validation.failed") bad;
@not("bad") good;
- @discourseComputed("bad")
- role(bad) {
- if (bad) {
+ @computed("bad")
+ get role() {
+ if (this.bad) {
return "alert";
}
}
- @discourseComputed("validation.reason")
- ariaLabel(reason) {
- return reason?.replace(/(<([^>]+)>)/gi, "");
+ @computed("validation.reason")
+ get ariaLabel() {
+ return this.validation?.reason?.replace(/(<([^>]+)>)/gi, "");
}
dismiss() {
diff --git a/frontend/discourse/app/components/radio-button.js b/frontend/discourse/app/components/radio-button.js
index 3bc84a3be14..d39ecea1027 100644
--- a/frontend/discourse/app/components/radio-button.js
+++ b/frontend/discourse/app/components/radio-button.js
@@ -1,8 +1,8 @@
/* eslint-disable ember/no-classic-components, ember/no-jquery, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { attributeBindings, tagName } from "@ember-decorators/component";
import $ from "jquery";
-import discourseComputed from "discourse/lib/decorators";
@tagName("input")
@attributeBindings(
@@ -28,8 +28,8 @@ export default class RadioButton extends Component {
}
}
- @discourseComputed("value", "selection")
- checked(value, selection) {
- return value === selection;
+ @computed("value", "selection")
+ get checked() {
+ return this.value === this.selection;
}
}
diff --git a/frontend/discourse/app/components/reviewable-post-edits.gjs b/frontend/discourse/app/components/reviewable-post-edits.gjs
index 8fd8e3ecbeb..06274269478 100644
--- a/frontend/discourse/app/components/reviewable-post-edits.gjs
+++ b/frontend/discourse/app/components/reviewable-post-edits.gjs
@@ -1,13 +1,12 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { gt } from "@ember/object/computed";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import HistoryModal from "discourse/components/modal/history";
import { historyHeat } from "discourse/components/post/meta-data/edits-indicator";
-import discourseComputed from "discourse/lib/decorators";
import { longDate } from "discourse/lib/formatter";
import { i18n } from "discourse-i18n";
@@ -17,24 +16,29 @@ export default class ReviewablePostEdits extends Component {
@gt("reviewable.post_version", 1) hasEdits;
- @discourseComputed("reviewable.post_version")
- editCount(postVersion) {
- return postVersion - 1;
+ @computed("reviewable.post_version")
+ get editCount() {
+ return this.reviewable?.post_version - 1;
}
- @discourseComputed("reviewable.post_updated_at")
- historyClass(updatedAt) {
- return historyHeat(this.siteSettings, new Date(updatedAt));
+ @computed("reviewable.post_updated_at")
+ get historyClass() {
+ return historyHeat(
+ this.siteSettings,
+ new Date(this.reviewable?.post_updated_at)
+ );
}
- @discourseComputed("reviewable.post_updated_at")
- editedDate(updatedAt) {
- return longDate(updatedAt);
+ @computed("reviewable.post_updated_at")
+ get editedDate() {
+ return longDate(this.reviewable?.post_updated_at);
}
- @discourseComputed("reviewable.post_updated_at")
- editedTitle(updatedAt) {
- return i18n("post.last_edited_on", { dateTime: longDate(updatedAt) });
+ @computed("reviewable.post_updated_at")
+ get editedTitle() {
+ return i18n("post.last_edited_on", {
+ dateTime: longDate(this.reviewable?.post_updated_at),
+ });
}
@action
diff --git a/frontend/discourse/app/components/reviewable/item.gjs b/frontend/discourse/app/components/reviewable/item.gjs
index add0356a49a..edb044ff0b9 100644
--- a/frontend/discourse/app/components/reviewable/item.gjs
+++ b/frontend/discourse/app/components/reviewable/item.gjs
@@ -3,7 +3,7 @@ import { tracked } from "@glimmer/tracking";
import Component from "@ember/component";
import { concat, fn } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action, set } from "@ember/object";
+import { action, computed, set } from "@ember/object";
import { alias } from "@ember/object/computed";
import { getOwner } from "@ember/owner";
import { service } from "@ember/service";
@@ -30,7 +30,7 @@ import formatDate from "discourse/helpers/format-date";
import { newReviewableStatus } from "discourse/helpers/reviewable-status";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { getAbsoluteURL } from "discourse/lib/get-url";
import optionalService from "discourse/lib/optional-service";
import { showAlert } from "discourse/lib/post-action-feedback";
@@ -121,38 +121,35 @@ export default class ReviewableItem extends Component {
this.messageBus.unsubscribe("/reviewable_action", this._updateStatus);
}
- @discourseComputed(
+ @computed(
"reviewable.type",
"reviewable.last_performing_username",
"siteSettings.blur_tl0_flagged_posts_media",
"reviewable.target_created_by_trust_level",
"reviewable.deleted_at"
)
- customClasses(
- type,
- lastPerformingUsername,
- blurEnabled,
- trustLevel,
- deletedAt
- ) {
- let classes = dasherize(type);
-
- if (lastPerformingUsername) {
+ get customClasses() {
+ let classes = dasherize(this.reviewable?.type);
+
+ if (this.reviewable?.last_performing_username) {
classes = `${classes} reviewable-stale`;
}
- if (blurEnabled && trustLevel === 0) {
+ if (
+ this.siteSettings?.blur_tl0_flagged_posts_media &&
+ this.reviewable?.target_created_by_trust_level === 0
+ ) {
classes = `${classes} blur-images`;
}
- if (deletedAt) {
+ if (this.reviewable?.deleted_at) {
classes = `${classes} reviewable-deleted`;
}
return classes;
}
- @discourseComputed(
+ @computed(
"reviewable.created_from_flag",
"reviewable.status",
"claimOptional",
@@ -160,101 +157,105 @@ export default class ReviewableItem extends Component {
"reviewable.claimed_by",
"isAiReviewable"
)
- displayContextQuestion(
- createdFromFlag,
- status,
- claimOptional,
- claimRequired,
- claimedBy,
- isAiReviewable
- ) {
+ get displayContextQuestion() {
return (
- (createdFromFlag &&
- status === PENDING &&
- (claimOptional || (claimRequired && claimedBy !== null))) ||
- isAiReviewable
+ (this.reviewable?.created_from_flag &&
+ this.reviewable?.status === PENDING &&
+ (this.claimOptional ||
+ (this.claimRequired && this.reviewable?.claimed_by !== null))) ||
+ this.isAiReviewable
);
}
- @discourseComputed("reviewable.type")
- isAiReviewable(type) {
- return type === "ReviewableAiChatMessage" || type === "ReviewableAiPost";
+ @computed("reviewable.type")
+ get isAiReviewable() {
+ return (
+ this.reviewable?.type === "ReviewableAiChatMessage" ||
+ this.reviewable?.type === "ReviewableAiPost"
+ );
}
- @discourseComputed(
+ @computed(
"reviewable.topic",
"reviewable.topic_id",
"reviewable.removed_topic_id"
)
- topicId(topic, topicId, removedTopicId) {
- return (topic && topic.id) || topicId || removedTopicId;
+ get topicId() {
+ return (
+ (this.reviewable?.topic && this.reviewable?.topic?.id) ||
+ this.reviewable?.topic_id ||
+ this.reviewable?.removed_topic_id
+ );
}
- @discourseComputed(
+ @computed(
"siteSettings.reviewable_claiming",
"topicId",
"reviewable.claimed_by.automatic",
"reviewable.status"
)
- claimEnabled(claimMode, topicId, autoClaimed, status) {
+ get claimEnabled() {
return (
- (claimMode !== "disabled" || autoClaimed) &&
- !!topicId &&
- status === PENDING
+ (this.siteSettings?.reviewable_claiming !== "disabled" ||
+ this.reviewable?.claimed_by?.automatic) &&
+ !!this.topicId &&
+ this.reviewable?.status === PENDING
);
}
- @discourseComputed("siteSettings.reviewable_claiming", "claimEnabled")
- claimOptional(claimMode, claimEnabled) {
- return !claimEnabled || claimMode === "optional";
+ @computed("siteSettings.reviewable_claiming", "claimEnabled")
+ get claimOptional() {
+ return (
+ !this.claimEnabled ||
+ this.siteSettings?.reviewable_claiming === "optional"
+ );
}
- @discourseComputed("siteSettings.reviewable_claiming", "claimEnabled")
- claimRequired(claimMode, claimEnabled) {
- return claimEnabled && claimMode === "required";
+ @computed("siteSettings.reviewable_claiming", "claimEnabled")
+ get claimRequired() {
+ return (
+ this.claimEnabled && this.siteSettings?.reviewable_claiming === "required"
+ );
}
- @discourseComputed(
+ @computed(
"claimEnabled",
"siteSettings.reviewable_claiming",
"reviewable.claimed_by",
"reviewable.bundled_actions"
)
- canPerform(claimEnabled, claimMode, claimedBy, bundledActions) {
- if (bundledActions?.length === 0) {
+ get canPerform() {
+ if (this.reviewable?.bundled_actions?.length === 0) {
return false;
}
- if (!claimEnabled) {
+ if (!this.claimEnabled) {
return true;
}
- if (claimedBy) {
- return claimedBy.user.id === this.currentUser.id;
+ if (this.reviewable?.claimed_by) {
+ return this.reviewable?.claimed_by?.user.id === this.currentUser.id;
}
- return claimMode !== "required";
+ return this.siteSettings?.reviewable_claiming !== "required";
}
- @discourseComputed(
- "siteSettings.reviewable_claiming",
- "reviewable.claimed_by"
- )
- claimHelp(claimMode, claimedBy) {
- if (claimedBy) {
- if (claimedBy.user.id === this.currentUser.id) {
+ @computed("siteSettings.reviewable_claiming", "reviewable.claimed_by")
+ get claimHelp() {
+ if (this.reviewable?.claimed_by) {
+ if (this.reviewable?.claimed_by?.user.id === this.currentUser.id) {
return i18n("review.claim_help.claimed_by_you");
- } else if (claimedBy.automatic) {
+ } else if (this.reviewable?.claimed_by?.automatic) {
return i18n("review.claim_help.automatically_claimed_by", {
- username: claimedBy.user.username,
+ username: this.reviewable?.claimed_by?.user.username,
});
} else {
return i18n("review.claim_help.claimed_by_other", {
- username: claimedBy.user.username,
+ username: this.reviewable?.claimed_by?.user.username,
});
}
}
- return claimMode === "optional"
+ return this.siteSettings?.reviewable_claiming === "optional"
? i18n("review.claim_help.optional")
: i18n("review.claim_help.required");
}
@@ -262,14 +263,14 @@ export default class ReviewableItem extends Component {
// Find a component to render, if one exists. For example:
// `ReviewableUser` will return `reviewable/user` or `reviewable-user`.
// The former is the new reviewable component, so will only be returned if it exists.
- @discourseComputed("reviewable.type")
- reviewableComponent(type) {
- if (_components[type] !== undefined) {
- return _components[type];
+ @computed("reviewable.type")
+ get reviewableComponent() {
+ if (_components[this.reviewable?.type] !== undefined) {
+ return _components[this.reviewable?.type];
}
const owner = getOwner(this);
- const dasherized = dasherize(type);
+ const dasherized = dasherize(this.reviewable?.type);
const componentNames = [
dasherized.replace("reviewable-", "reviewable-refresh/"),
dasherized.replace("reviewable-", "reviewable/"),
@@ -281,62 +282,63 @@ export default class ReviewableItem extends Component {
owner.hasRegistration(`component:${componentName}`) ||
owner.hasRegistration(`template:components/${componentName}`);
if (componentExists) {
- _components[type] = componentName;
+ _components[this.reviewable?.type] = componentName;
break;
}
}
- return _components[type] || null;
+ return _components[this.reviewable?.type] || null;
}
- @discourseComputed("_updates.category_id", "reviewable.category.id")
- tagCategoryId(updatedCategoryId, categoryId) {
- return updatedCategoryId || categoryId;
+ @computed("_updates.category_id", "reviewable.category.id")
+ get tagCategoryId() {
+ return this._updates?.category_id || this.reviewable?.category?.id;
}
- @discourseComputed("reviewable.reviewable_scores")
- scoreSummary(scores) {
- const scoreData = scores.reduce((acc, score) => {
- if (!acc[score.score_type.type]) {
- acc[score.score_type.type] = {
- title: score.score_type.title,
- type: score.score_type.type,
- count: 0,
- };
- }
+ @computed("reviewable.reviewable_scores")
+ get scoreSummary() {
+ const scoreData = this.reviewable?.reviewable_scores?.reduce(
+ (acc, score) => {
+ if (!acc[score.score_type.type]) {
+ acc[score.score_type.type] = {
+ title: score.score_type.title,
+ type: score.score_type.type,
+ count: 0,
+ };
+ }
- acc[score.score_type.type].count += 1;
- return acc;
- }, {});
+ acc[score.score_type.type].count += 1;
+ return acc;
+ },
+ {}
+ );
return Object.values(scoreData);
}
- @discourseComputed(
- "reviewable.type",
- "reviewable.created_from_flag",
- "topicId"
- )
- reviewableTypeLabel(type, createdFromFlag, topicId) {
+ @computed("reviewable.type", "reviewable.created_from_flag", "topicId")
+ get reviewableTypeLabel() {
// handle plugin types
- if (reviewableTypeLabels[type]) {
- return reviewableTypeLabels[type];
+ if (reviewableTypeLabels[this.reviewable?.type]) {
+ return reviewableTypeLabels[this.reviewable?.type];
}
// core types
- if (type === "ReviewableUser") {
+ if (this.reviewable?.type === "ReviewableUser") {
return "review.user_label";
}
- if (type === "ReviewableQueuedPost") {
+ if (this.reviewable?.type === "ReviewableQueuedPost") {
// if topic_id is null it's a new topic
- return topicId ? "review.queued_post_label" : "review.queued_topic_label";
+ return this.topicId
+ ? "review.queued_post_label"
+ : "review.queued_topic_label";
}
- if (type === "ReviewableChatMessage") {
+ if (this.reviewable?.type === "ReviewableChatMessage") {
return "review.chat_flagged_as";
}
- if (createdFromFlag) {
+ if (this.reviewable?.created_from_flag) {
return "review.post_flagged_as";
}
diff --git a/frontend/discourse/app/components/reviewable/user.gjs b/frontend/discourse/app/components/reviewable/user.gjs
index b95a2b1b6e5..f4cc3252e95 100644
--- a/frontend/discourse/app/components/reviewable/user.gjs
+++ b/frontend/discourse/app/components/reviewable/user.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { concat } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import ScrubRejectedUserModal from "discourse/admin/components/modal/scrub-rejected-user";
@@ -9,7 +9,7 @@ import ReviewableField from "discourse/components/reviewable-field";
import rawDate from "discourse/helpers/raw-date";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import getUrl from "discourse/lib/get-url";
import { i18n } from "discourse-i18n";
@@ -18,14 +18,14 @@ export default class ReviewableUser extends Component {
@service modal;
@service store;
- @discourseComputed("reviewable.user_fields")
- userFields(fields) {
- return this.site.collectUserFields(fields);
+ @computed("reviewable.user_fields")
+ get userFields() {
+ return this.site.collectUserFields(this.reviewable?.user_fields);
}
- @discourseComputed("reviewable.payload")
- isScrubbed(payload) {
- return !!payload?.scrubbed_by;
+ @computed("reviewable.payload")
+ get isScrubbed() {
+ return !!this.reviewable?.payload?.scrubbed_by;
}
@action
diff --git a/frontend/discourse/app/components/save-controls.gjs b/frontend/discourse/app/components/save-controls.gjs
index 5d11239d84f..c0aa5579779 100644
--- a/frontend/discourse/app/components/save-controls.gjs
+++ b/frontend/discourse/app/components/save-controls.gjs
@@ -1,9 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { or } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@tagName("")
@@ -15,9 +15,9 @@ export default class SaveControls extends Component {
this.set("saved", false);
}
- @discourseComputed("model.isSaving")
- savingText(saving) {
- return saving ? "saving" : "save";
+ @computed("model.isSaving")
+ get savingText() {
+ return this.model?.isSaving ? "saving" : "save";
}
<template>
diff --git a/frontend/discourse/app/components/search-text-field.js b/frontend/discourse/app/components/search-text-field.js
index 134e06328b4..7849dc1a610 100644
--- a/frontend/discourse/app/components/search-text-field.js
+++ b/frontend/discourse/app/components/search-text-field.js
@@ -1,9 +1,9 @@
/* eslint-disable ember/no-jquery */
+import { computed } from "@ember/object";
import { getOwner } from "@ember/owner";
import { on } from "@ember-decorators/object";
import $ from "jquery";
import TextField from "discourse/components/text-field";
-import discourseComputed from "discourse/lib/decorators";
import { applySearchAutocomplete } from "discourse/lib/search";
import { i18n } from "discourse-i18n";
@@ -13,9 +13,11 @@ export default class SearchTextField extends TextField {
autocapitalize = "none";
autocorrect = "off";
- @discourseComputed("searchService.searchContextEnabled")
- placeholder(searchContextEnabled) {
- return searchContextEnabled ? "" : i18n("search.full_page_title");
+ @computed("searchService.searchContextEnabled")
+ get placeholder() {
+ return this.searchService?.searchContextEnabled
+ ? ""
+ : i18n("search.full_page_title");
}
@on("didInsertElement")
diff --git a/frontend/discourse/app/components/second-factor-form.gjs b/frontend/discourse/app/components/second-factor-form.gjs
index af0ba3cb0d8..702999855d8 100644
--- a/frontend/discourse/app/components/second-factor-form.gjs
+++ b/frontend/discourse/app/components/second-factor-form.gjs
@@ -1,18 +1,17 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { SECOND_FACTOR_METHODS } from "discourse/models/user";
import { i18n } from "discourse-i18n";
@tagName("")
export default class SecondFactorForm extends Component {
- @discourseComputed("secondFactorMethod")
- secondFactorTitle(secondFactorMethod) {
- switch (secondFactorMethod) {
+ @computed("secondFactorMethod")
+ get secondFactorTitle() {
+ switch (this.secondFactorMethod) {
case SECOND_FACTOR_METHODS.TOTP:
return i18n("login.second_factor_title");
case SECOND_FACTOR_METHODS.SECURITY_KEY:
@@ -22,9 +21,9 @@ export default class SecondFactorForm extends Component {
}
}
- @discourseComputed("secondFactorMethod")
- secondFactorDescription(secondFactorMethod) {
- switch (secondFactorMethod) {
+ @computed("secondFactorMethod")
+ get secondFactorDescription() {
+ switch (this.secondFactorMethod) {
case SECOND_FACTOR_METHODS.TOTP:
return i18n("login.second_factor_description");
case SECOND_FACTOR_METHODS.SECURITY_KEY:
@@ -34,25 +33,25 @@ export default class SecondFactorForm extends Component {
}
}
- @discourseComputed("secondFactorMethod", "isLogin")
- linkText(secondFactorMethod, isLogin) {
- if (isLogin) {
- return secondFactorMethod === SECOND_FACTOR_METHODS.TOTP
+ @computed("secondFactorMethod", "isLogin")
+ get linkText() {
+ if (this.isLogin) {
+ return this.secondFactorMethod === SECOND_FACTOR_METHODS.TOTP
? "login.second_factor_backup"
: "login.second_factor";
} else {
- return secondFactorMethod === SECOND_FACTOR_METHODS.TOTP
+ return this.secondFactorMethod === SECOND_FACTOR_METHODS.TOTP
? "user.second_factor_backup.use"
: "user.second_factor.use";
}
}
- @discourseComputed("backupEnabled", "totpEnabled", "secondFactorMethod")
- showToggleMethodLink(backupEnabled, totpEnabled, secondFactorMethod) {
+ @computed("backupEnabled", "totpEnabled", "secondFactorMethod")
+ get showToggleMethodLink() {
return (
- backupEnabled &&
- totpEnabled &&
- secondFactorMethod !== SECOND_FACTOR_METHODS.SECURITY_KEY
+ this.backupEnabled &&
+ this.totpEnabled &&
+ this.secondFactorMethod !== SECOND_FACTOR_METHODS.SECURITY_KEY
);
}
diff --git a/frontend/discourse/app/components/share-panel.gjs b/frontend/discourse/app/components/share-panel.gjs
index b9810e871f9..5f86fac2cd1 100644
--- a/frontend/discourse/app/components/share-panel.gjs
+++ b/frontend/discourse/app/components/share-panel.gjs
@@ -1,12 +1,11 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { isEmpty } from "@ember/utils";
import DTextarea from "discourse/components/d-textarea";
import ShareSource from "discourse/components/share-source";
-import discourseComputed from "discourse/lib/decorators";
import discourseLater from "discourse/lib/later";
import Sharing from "discourse/lib/sharing";
import { escapeExpression } from "discourse/lib/utilities";
@@ -19,25 +18,25 @@ export default class SharePanel extends Component {
@alias("panel.model.topic") topic;
@alias("panel.model.topic.category.read_restricted") privateCategory;
- @discourseComputed("topic.{isPrivateMessage,invisible,category}")
- sources(topic) {
+ @computed("topic.{isPrivateMessage,invisible,category}")
+ get sources() {
const privateContext =
this.siteSettings.login_required ||
- (topic && topic.isPrivateMessage) ||
- (topic && topic.invisible) ||
+ (this.topic && this.topic?.isPrivateMessage) ||
+ (this.topic && this.topic?.invisible) ||
this.privateCategory;
return Sharing.activeSources(this.siteSettings.share_links, privateContext);
}
- @discourseComputed("type", "topic.title")
- shareTitle(type, topicTitle) {
- topicTitle = escapeExpression(topicTitle);
+ @computed("type", "topic.title")
+ get shareTitle() {
+ const topicTitle = escapeExpression(this.topic?.title);
return i18n("share.topic_html", { topicTitle });
}
- @discourseComputed("panel.model.shareUrl", "topic.shareUrl")
- shareUrl(forcedShareUrl, shareUrl) {
- shareUrl = forcedShareUrl || shareUrl;
+ @computed("panel.model.shareUrl", "topic.shareUrl")
+ get shareUrl() {
+ let shareUrl = this.panel?.model?.shareUrl || this.topic?.shareUrl;
if (isEmpty(shareUrl)) {
return;
diff --git a/frontend/discourse/app/components/shared-draft-controls.gjs b/frontend/discourse/app/components/shared-draft-controls.gjs
index b8a13842e3e..9fdb07dda1d 100644
--- a/frontend/discourse/app/components/shared-draft-controls.gjs
+++ b/frontend/discourse/app/components/shared-draft-controls.gjs
@@ -1,10 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
-import discourseComputed from "discourse/lib/decorators";
import CategoryChooser from "discourse/select-kit/components/category-chooser";
import { i18n } from "discourse-i18n";
@@ -14,9 +13,13 @@ export default class SharedDraftControls extends Component {
publishing = false;
- @discourseComputed("topic.destination_category_id")
- validCategory(destCatId) {
- return destCatId && destCatId !== this.site.shared_drafts_category_id;
+ @computed("topic.destination_category_id")
+ get validCategory() {
+ return (
+ this.topic?.destination_category_id &&
+ this.topic?.destination_category_id !==
+ this.site.shared_drafts_category_id
+ );
}
@action
diff --git a/frontend/discourse/app/components/slow-mode-info.gjs b/frontend/discourse/app/components/slow-mode-info.gjs
index c2ebcece118..4fe069518db 100644
--- a/frontend/discourse/app/components/slow-mode-info.gjs
+++ b/frontend/discourse/app/components/slow-mode-info.gjs
@@ -1,25 +1,24 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import icon from "discourse/helpers/d-icon";
import { durationTextFromSeconds } from "discourse/helpers/slow-mode";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import Topic from "discourse/models/topic";
import { i18n } from "discourse-i18n";
@tagName("")
export default class SlowModeInfo extends Component {
- @discourseComputed("topic.slow_mode_seconds")
- durationText(seconds) {
- return durationTextFromSeconds(seconds);
+ @computed("topic.slow_mode_seconds")
+ get durationText() {
+ return durationTextFromSeconds(this.topic?.slow_mode_seconds);
}
- @discourseComputed("topic.slow_mode_seconds", "topic.closed")
- showSlowModeNotice(seconds, closed) {
- return seconds > 0 && !closed;
+ @computed("topic.slow_mode_seconds", "topic.closed")
+ get showSlowModeNotice() {
+ return this.topic?.slow_mode_seconds > 0 && !this.topic?.closed;
}
@action
diff --git a/frontend/discourse/app/components/tag-groups-form.gjs b/frontend/discourse/app/components/tag-groups-form.gjs
index fc1dda40935..deafff67468 100644
--- a/frontend/discourse/app/components/tag-groups-form.gjs
+++ b/frontend/discourse/app/components/tag-groups-form.gjs
@@ -2,7 +2,7 @@
import { cached } from "@glimmer/tracking";
import Component, { Input } from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
@@ -12,7 +12,6 @@ import DButton from "discourse/components/d-button";
import RadioButton from "discourse/components/radio-button";
import TextField from "discourse/components/text-field";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import PermissionType from "discourse/models/permission-type";
import GroupChooser from "discourse/select-kit/components/group-chooser";
import TagChooser from "discourse/select-kit/components/tag-chooser";
@@ -36,8 +35,9 @@ export default class TagGroupsForm extends Component {
});
}
- @discourseComputed("buffered.permissions")
- selectedGroupIds(permissions) {
+ @computed("buffered.permissions")
+ get selectedGroupIds() {
+ const permissions = this.get("buffered.permissions"); // TODO (devxp) we need a buffered proxy that works with tracked properties
if (!permissions) {
return [];
}
diff --git a/frontend/discourse/app/components/tag-info.gjs b/frontend/discourse/app/components/tag-info.gjs
index 9f628741ada..7c8cbeec5c0 100644
--- a/frontend/discourse/app/components/tag-info.gjs
+++ b/frontend/discourse/app/components/tag-info.gjs
@@ -3,7 +3,7 @@ import { tracked } from "@glimmer/tracking";
import Component, { Textarea } from "@ember/component";
import { array, fn } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { and, reads } from "@ember/object/computed";
import { LinkTo } from "@ember/routing";
@@ -24,7 +24,6 @@ import withEventValue from "discourse/helpers/with-event-value";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import TagChooser from "discourse/select-kit/components/tag-chooser";
import { i18n } from "discourse-i18n";
@@ -51,18 +50,18 @@ export default class TagInfo extends Component {
return this.siteSettings.experimental_tag_settings_page;
}
- @discourseComputed("tagInfo.tag_group_names")
- tagGroupsInfo(tagGroupNames) {
+ @computed("tagInfo.tag_group_names")
+ get tagGroupsInfo() {
return i18n("tagging.tag_groups_info", {
- count: tagGroupNames.length,
- tag_groups: tagGroupNames.join(", "),
+ count: this.tagInfo?.tag_group_names?.length,
+ tag_groups: this.tagInfo?.tag_group_names?.join(", "),
});
}
- @discourseComputed("tagInfo.categories")
- categoriesInfo(categories) {
+ @computed("tagInfo.categories")
+ get categoriesInfo() {
return i18n("tagging.category_restrictions", {
- count: categories.length,
+ count: this.tagInfo?.categories?.length,
});
}
@@ -78,19 +77,21 @@ export default class TagInfo extends Component {
return synonyms;
}
- @discourseComputed(
- "tagInfo.tag_group_names",
- "tagInfo.categories",
- "synonyms"
- )
- nothingToShow(tagGroupNames, categories, synonyms) {
- return isEmpty(tagGroupNames) && isEmpty(categories) && isEmpty(synonyms);
+ @computed("tagInfo.tag_group_names", "tagInfo.categories", "synonyms")
+ get nothingToShow() {
+ return (
+ isEmpty(this.tagInfo?.tag_group_names) &&
+ isEmpty(this.tagInfo?.categories) &&
+ isEmpty(this.synonyms)
+ );
}
- @discourseComputed("newTagName")
- updateDisabled(newTagName) {
+ @computed("newTagName")
+ get updateDisabled() {
const filterRegexp = new RegExp(this.site.tags_filter_regexp, "g");
- newTagName = newTagName ? newTagName.replace(filterRegexp, "").trim() : "";
+ const newTagName = this.newTagName
+ ? this.newTagName.replace(filterRegexp, "").trim()
+ : "";
return newTagName.length === 0;
}
diff --git a/frontend/discourse/app/components/tag-list.gjs b/frontend/discourse/app/components/tag-list.gjs
index ceb87255c91..49ddea5a8c1 100644
--- a/frontend/discourse/app/components/tag-list.gjs
+++ b/frontend/discourse/app/components/tag-list.gjs
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { sort } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import CategoryTitleLink from "discourse/components/category-title-link";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
import discourseTag from "discourse/helpers/discourse-tag";
-import discourseComputed from "discourse/lib/decorators";
import Category from "discourse/models/category";
import { i18n } from "discourse-i18n";
@@ -16,25 +16,25 @@ export default class TagList extends Component {
@sort("tags", "sortProperties") sortedTags;
- @discourseComputed("titleKey")
- title(titleKey) {
- return titleKey && i18n(titleKey);
+ @computed("titleKey")
+ get title() {
+ return this.titleKey && i18n(this.titleKey);
}
- @discourseComputed("categoryId")
- category(categoryId) {
- return categoryId && Category.findById(categoryId);
+ @computed("categoryId")
+ get category() {
+ return this.categoryId && Category.findById(this.categoryId);
}
- @discourseComputed("category.fullSlug")
- categoryClass(slug) {
- return slug && `tag-list-${slug}`;
+ @computed("category.fullSlug")
+ get categoryClass() {
+ return this.category?.fullSlug && `tag-list-${this.category?.fullSlug}`;
}
- @discourseComputed("tagGroupName")
- tagGroupNameClass(groupName) {
- if (groupName) {
- groupName = groupName
+ @computed("tagGroupName")
+ get tagGroupNameClass() {
+ if (this.tagGroupName) {
+ const groupName = this.tagGroupName
.replace(/\s+/g, "-")
.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, "")
.toLowerCase();
diff --git a/frontend/discourse/app/components/time-shortcut-picker.gjs b/frontend/discourse/app/components/time-shortcut-picker.gjs
index a26f620ac54..5fcded28c9b 100644
--- a/frontend/discourse/app/components/time-shortcut-picker.gjs
+++ b/frontend/discourse/app/components/time-shortcut-picker.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/no-observers */
import Component, { Input } from "@ember/component";
import { fn } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { and, equal } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import { observes, on } from "@ember-decorators/object";
@@ -10,7 +10,6 @@ import RelativeTimePicker from "discourse/components/relative-time-picker";
import TapTile from "discourse/components/tap-tile";
import TapTileGrid from "discourse/components/tap-tile-grid";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
import {
defaultTimeShortcuts,
formatTime,
@@ -165,24 +164,19 @@ export default class TimeShortcutPicker extends Component {
this.selectShortcut(TIME_SHORTCUT_TYPES.CUSTOM);
}
- @discourseComputed(
- "timeShortcuts",
- "hiddenOptions",
- "customLabels",
- "userTimezone"
- )
- options(timeShortcuts, hiddenOptions, customLabels, userTimezone) {
+ @computed("timeShortcuts", "hiddenOptions", "customLabels", "userTimezone")
+ get options() {
this._loadLastUsedCustomDatetime();
let options;
- if (timeShortcuts && timeShortcuts.length) {
- options = timeShortcuts;
+ if (this.timeShortcuts && this.timeShortcuts.length) {
+ options = this.timeShortcuts;
} else {
- options = defaultTimeShortcuts(userTimezone);
+ options = defaultTimeShortcuts(this.userTimezone);
}
options = hideDynamicTimeShortcuts(
options,
- userTimezone,
+ this.userTimezone,
this.siteSettings
);
@@ -197,15 +191,15 @@ export default class TimeShortcutPicker extends Component {
}
options = options.concat(specialOptions);
- if (hiddenOptions.length > 0) {
+ if (this.hiddenOptions.length > 0) {
options.forEach((opt) => {
- if (hiddenOptions.includes(opt.id)) {
+ if (this.hiddenOptions.includes(opt.id)) {
opt.hidden = true;
}
});
}
- this._applyCustomLabels(options, customLabels);
+ this._applyCustomLabels(options, this.customLabels);
options.forEach((o) => (o.timeFormatted = formatTime(o)));
return options;
}
diff --git a/frontend/discourse/app/components/topic-entrance.gjs b/frontend/discourse/app/components/topic-entrance.gjs
index 624d6356189..6363f1b97e1 100644
--- a/frontend/discourse/app/components/topic-entrance.gjs
+++ b/frontend/discourse/app/components/topic-entrance.gjs
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-classic-components, ember/no-jquery, ember/require-tagless-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
@@ -9,7 +9,7 @@ import { on } from "@ember-decorators/object";
import $ from "jquery";
import DButton from "discourse/components/d-button";
import icon from "discourse/helpers/d-icon";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import DiscourseURL from "discourse/lib/url";
import { i18n } from "discourse-i18n";
@@ -47,31 +47,32 @@ export default class TopicEntrance extends Component {
_originalActiveElement = null;
_activeButton = null;
- @discourseComputed("topic.created_at")
- createdDate(createdAt) {
- return new Date(createdAt);
+ @computed("topic.created_at")
+ get createdDate() {
+ return new Date(this.topic?.created_at);
}
- @discourseComputed("topic.bumped_at")
- bumpedDate(bumpedAt) {
- return new Date(bumpedAt);
+ @computed("topic.bumped_at")
+ get bumpedDate() {
+ return new Date(this.topic?.bumped_at);
}
- @discourseComputed("createdDate", "bumpedDate")
- showTime(createdDate, bumpedDate) {
+ @computed("createdDate", "bumpedDate")
+ get showTime() {
return (
- bumpedDate.getTime() - createdDate.getTime() < 1000 * 60 * 60 * 24 * 2
+ this.bumpedDate.getTime() - this.createdDate.getTime() <
+ 1000 * 60 * 60 * 24 * 2
);
}
- @discourseComputed("createdDate", "showTime")
- topDate(createdDate, showTime) {
- return entranceDate(createdDate, showTime);
+ @computed("createdDate", "showTime")
+ get topDate() {
+ return entranceDate(this.createdDate, this.showTime);
}
- @discourseComputed("bumpedDate", "showTime")
- bottomDate(bumpedDate, showTime) {
- return entranceDate(bumpedDate, showTime);
+ @computed("bumpedDate", "showTime")
+ get bottomDate() {
+ return entranceDate(this.bumpedDate, this.showTime);
}
@on("didInsertElement")
diff --git a/frontend/discourse/app/components/topic-footer-buttons.gjs b/frontend/discourse/app/components/topic-footer-buttons.gjs
index 8a94f22b736..0252c7b098d 100644
--- a/frontend/discourse/app/components/topic-footer-buttons.gjs
+++ b/frontend/discourse/app/components/topic-footer-buttons.gjs
@@ -17,7 +17,6 @@ import DMenu from "discourse/float-kit/components/d-menu";
import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import { NotificationLevels } from "discourse/lib/notification-levels";
import { getTopicFooterButtons } from "discourse/lib/register-topic-footer-button";
import { getTopicFooterDropdowns } from "discourse/lib/register-topic-footer-dropdown";
@@ -46,9 +45,9 @@ export default class TopicFooterButtons extends Component {
return getTopicFooterDropdowns(this);
}
- @discourseComputed("canSendPms", "topic.isPrivateMessage")
- canArchive(canSendPms, isPM) {
- return canSendPms && isPM;
+ @computed("canSendPms", "topic.isPrivateMessage")
+ get canArchive() {
+ return this.canSendPms && this.topic?.isPrivateMessage;
}
get inlineActionables() {
@@ -79,36 +78,40 @@ export default class TopicFooterButtons extends Component {
return this.dropdownButtons.length === 1 ? this.dropdownButtons[0] : null;
}
- @discourseComputed("topic.isPrivateMessage")
- showNotificationsButton(isPM) {
- return !isPM || this.canSendPms;
+ @computed("topic.isPrivateMessage")
+ get showNotificationsButton() {
+ return !this.topic?.isPrivateMessage || this.canSendPms;
}
- @discourseComputed("topic.details.notification_level")
- showNotificationUserTip(notificationLevel) {
- return notificationLevel >= NotificationLevels.TRACKING;
+ @computed("topic.details.notification_level")
+ get showNotificationUserTip() {
+ return (
+ this.topic?.details?.notification_level >= NotificationLevels.TRACKING
+ );
}
- @discourseComputed("topic.message_archived")
- archiveIcon(archived) {
- return archived ? "envelope" : "folder";
+ @computed("topic.message_archived")
+ get archiveIcon() {
+ return this.topic?.message_archived ? "envelope" : "folder";
}
- @discourseComputed("topic.message_archived")
- archiveTitle(archived) {
- return archived ? "topic.move_to_inbox.help" : "topic.archive_message.help";
+ @computed("topic.message_archived")
+ get archiveTitle() {
+ return this.topic?.message_archived
+ ? "topic.move_to_inbox.help"
+ : "topic.archive_message.help";
}
- @discourseComputed("topic.message_archived")
- archiveLabel(archived) {
- return archived
+ @computed("topic.message_archived")
+ get archiveLabel() {
+ return this.topic?.message_archived
? "topic.move_to_inbox.title"
: "topic.archive_message.title";
}
- @discourseComputed("topic.isPrivateMessage")
- showBookmarkLabel(isPM) {
- return !isPM;
+ @computed("topic.isPrivateMessage")
+ get showBookmarkLabel() {
+ return !this.topic?.isPrivateMessage;
}
<template>
diff --git a/frontend/discourse/app/components/topic-progress.gjs b/frontend/discourse/app/components/topic-progress.gjs
index 69c8148746e..bf578b737b6 100644
--- a/frontend/discourse/app/components/topic-progress.gjs
+++ b/frontend/discourse/app/components/topic-progress.gjs
@@ -1,13 +1,12 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { scheduleOnce } from "@ember/runloop";
import { htmlSafe } from "@ember/template";
import { classNameBindings } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import PluginOutlet from "discourse/components/plugin-outlet";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@classNameBindings("docked")
@@ -20,33 +19,37 @@ export default class TopicProgress extends Component {
_streamPercentage = null;
- @discourseComputed(
+ @computed(
"postStream.loaded",
"topic.currentPost",
"postStream.filteredPostsCount"
)
- hideProgress(loaded, currentPost, filteredPostsCount) {
- const hideOnShortStream = this.site.desktopView && filteredPostsCount < 2;
- return !loaded || !currentPost || hideOnShortStream;
+ get hideProgress() {
+ const hideOnShortStream =
+ this.site.desktopView && this.postStream?.filteredPostsCount < 2;
+ return (
+ !this.postStream?.loaded || !this.topic?.currentPost || hideOnShortStream
+ );
}
- @discourseComputed("postStream.filteredPostsCount")
- hugeNumberOfPosts(filteredPostsCount) {
+ @computed("postStream.filteredPostsCount")
+ get hugeNumberOfPosts() {
return (
- filteredPostsCount >= this.siteSettings.short_progress_text_threshold
+ this.postStream?.filteredPostsCount >=
+ this.siteSettings.short_progress_text_threshold
);
}
- @discourseComputed("progressPosition", "topic.last_read_post_id")
- showBackButton(position, lastReadId) {
- if (!lastReadId) {
+ @computed("progressPosition", "topic.last_read_post_id")
+ get showBackButton() {
+ if (!this.topic?.last_read_post_id) {
return;
}
const stream = this.get("postStream.stream");
- const readPos = stream.indexOf(lastReadId) || 0;
+ const readPos = stream.indexOf(this.topic?.last_read_post_id) || 0;
- return readPos < stream.length - 1 && readPos > position;
+ return readPos < stream.length - 1 && readPos > this.progressPosition;
}
_topicScrolled(event) {
@@ -63,9 +66,9 @@ export default class TopicProgress extends Component {
}
}
- @discourseComputed("_streamPercentage")
- progressStyle(_streamPercentage) {
- return `--progress-bg-width: ${_streamPercentage || 0}%`;
+ @computed("_streamPercentage")
+ get progressStyle() {
+ return `--progress-bg-width: ${this._streamPercentage || 0}%`;
}
didInsertElement() {
diff --git a/frontend/discourse/app/components/topic-timer-info.gjs b/frontend/discourse/app/components/topic-timer-info.gjs
index fa356f7d970..2adec2c725f 100644
--- a/frontend/discourse/app/components/topic-timer-info.gjs
+++ b/frontend/discourse/app/components/topic-timer-info.gjs
@@ -1,12 +1,12 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { cancel, next } from "@ember/runloop";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import { on } from "@ember-decorators/object";
import DButton from "discourse/components/d-button";
import { DELETE_REPLIES_TYPE } from "discourse/components/modal/edit-topic-timer";
-import discourseComputed from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import { iconHTML } from "discourse/lib/icon-library";
import discourseLater from "discourse/lib/later";
@@ -37,19 +37,19 @@ export default class TopicTimerInfo extends Component {
}
}
- @discourseComputed
- canModifyTimer() {
+ @computed
+ get canModifyTimer() {
return this.currentUser && this.currentUser.get("canManageTopic");
}
- @discourseComputed("canModifyTimer", "removeTopicTimer")
- showTrashCan(canModifyTimer, removeTopicTimer) {
- return canModifyTimer && removeTopicTimer;
+ @computed("canModifyTimer", "removeTopicTimer")
+ get showTrashCan() {
+ return this.canModifyTimer && this.removeTopicTimer;
}
- @discourseComputed("canModifyTimer", "showTopicTimerModal")
- showEdit(canModifyTimer, showTopicTimerModal) {
- return canModifyTimer && showTopicTimerModal;
+ @computed("canModifyTimer", "showTopicTimerModal")
+ get showEdit() {
+ return this.canModifyTimer && this.showTopicTimerModal;
}
additionalOpts() {
diff --git a/frontend/discourse/app/components/user-card-contents.gjs b/frontend/discourse/app/components/user-card-contents.gjs
index 739d7f10316..781d383c4e6 100644
--- a/frontend/discourse/app/components/user-card-contents.gjs
+++ b/frontend/discourse/app/components/user-card-contents.gjs
@@ -29,7 +29,6 @@ import replaceEmoji from "discourse/helpers/replace-emoji";
import userStatus from "discourse/helpers/user-status";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { durationTiny } from "discourse/lib/formatter";
import { getURLWithCDN } from "discourse/lib/get-url";
import { wantsNewWindow } from "discourse/lib/intercept-click";
@@ -114,61 +113,61 @@ export default class UserCardContents extends CardContentsBase {
).canCheckEmails;
}
- @discourseComputed("user")
- hasLocaleOrWebsite(user) {
- return user.location || user.website_name || this.userTimezone;
+ @computed("user")
+ get hasLocaleOrWebsite() {
+ return this.user.location || this.user.website_name || this.userTimezone;
}
- @discourseComputed("user.status")
- hasStatus() {
+ @computed("user.status")
+ get hasStatus() {
return this.siteSettings.enable_user_status && this.user.status;
}
- @discourseComputed("user.status.emoji")
- userStatusEmoji(emoji) {
- return emojiUnescape(escapeExpression(`:${emoji}:`));
+ @computed("user.status.emoji")
+ get userStatusEmoji() {
+ return emojiUnescape(escapeExpression(`:${this.user?.status?.emoji}:`));
}
- @discourseComputed("user.staff")
- staff(isStaff) {
- return isStaff ? "staff" : "";
+ @computed("user.staff")
+ get staff() {
+ return this.user?.staff ? "staff" : "";
}
- @discourseComputed("user.trust_level")
- newUser(trustLevel) {
- return trustLevel === 0 ? "new-user" : "";
+ @computed("user.trust_level")
+ get newUser() {
+ return this.user?.trust_level === 0 ? "new-user" : "";
}
- @discourseComputed("user.name")
- nameFirst(name) {
- return prioritizeNameInUx(name);
+ @computed("user.name")
+ get nameFirst() {
+ return prioritizeNameInUx(this.user?.name);
}
- @discourseComputed("user")
- userTimezone(user) {
+ @computed("user")
+ get userTimezone() {
if (!this.showUserLocalTime) {
return;
}
- return user.get("user_option.timezone");
+ return this.user.get("user_option.timezone");
}
- @discourseComputed("userTimezone")
- formattedUserLocalTime(timezone) {
- return moment.tz(timezone).format(i18n("dates.time"));
+ @computed("userTimezone")
+ get formattedUserLocalTime() {
+ return moment.tz(this.userTimezone).format(i18n("dates.time"));
}
- @discourseComputed("username")
- usernameClass(username) {
- return username ? `user-card-${username}` : "";
+ @computed("username")
+ get usernameClass() {
+ return this.username ? `user-card-${this.username}` : "";
}
- @discourseComputed("topicPostCount")
- filterPostsLabel(count) {
- return i18n("topic.filter_to", { count });
+ @computed("topicPostCount")
+ get filterPostsLabel() {
+ return i18n("topic.filter_to", { count: this.topicPostCount });
}
- @discourseComputed("[email protected]")
- publicUserFields() {
+ @computed("[email protected]")
+ get publicUserFields() {
const siteUserFields = this.site.get("user_fields");
if (!isEmpty(siteUserFields)) {
const userFields = this.get("user.user_fields");
@@ -184,36 +183,39 @@ export default class UserCardContents extends CardContentsBase {
}
}
- @discourseComputed("user.trust_level")
- removeNoFollow(trustLevel) {
- return trustLevel > 2 && !this.siteSettings.tl3_links_no_follow;
+ @computed("user.trust_level")
+ get removeNoFollow() {
+ return this.user?.trust_level > 2 && !this.siteSettings.tl3_links_no_follow;
}
- @discourseComputed("user.badge_count", "user.featured_user_badges.length")
- moreBadgesCount(badgeCount, badgeLength) {
- return badgeCount - badgeLength;
+ @computed("user.badge_count", "user.featured_user_badges.length")
+ get moreBadgesCount() {
+ return this.user?.badge_count - this.user?.featured_user_badges?.length;
}
- @discourseComputed("user.time_read", "user.recent_time_read")
- showRecentTimeRead(timeRead, recentTimeRead) {
- return timeRead !== recentTimeRead && recentTimeRead !== 0;
+ @computed("user.time_read", "user.recent_time_read")
+ get showRecentTimeRead() {
+ return (
+ this.user?.time_read !== this.user?.recent_time_read &&
+ this.user?.recent_time_read !== 0
+ );
}
- @discourseComputed("user.recent_time_read")
- recentTimeRead(recentTimeReadSeconds) {
- return durationTiny(recentTimeReadSeconds);
+ @computed("user.recent_time_read")
+ get recentTimeRead() {
+ return durationTiny(this.user?.recent_time_read);
}
- @discourseComputed("showRecentTimeRead", "user.time_read", "recentTimeRead")
- timeReadTooltip(showRecent, timeRead, recentTimeRead) {
- if (showRecent) {
+ @computed("showRecentTimeRead", "user.time_read", "recentTimeRead")
+ get timeReadTooltip() {
+ if (this.showRecentTimeRead) {
return i18n("time_read_recently_tooltip", {
- time_read: durationTiny(timeRead),
- recent_time_read: recentTimeRead,
+ time_read: durationTiny(this.user?.time_read),
+ recent_time_read: this.recentTimeRead,
});
} else {
return i18n("time_read_tooltip", {
- time_read: durationTiny(timeRead),
+ time_read: durationTiny(this.user?.time_read),
});
}
}
@@ -233,14 +235,14 @@ export default class UserCardContents extends CardContentsBase {
this.element.style.backgroundImage = bg;
}
- @discourseComputed("user.primary_group_name")
- primaryGroup(primaryGroup) {
- return `group-${primaryGroup}`;
+ @computed("user.primary_group_name")
+ get primaryGroup() {
+ return `group-${this.user?.primary_group_name}`;
}
- @discourseComputed("user.profile_hidden", "user.inactive")
- contentHidden(profileHidden, inactive) {
- return profileHidden || inactive;
+ @computed("user.profile_hidden", "user.inactive")
+ get contentHidden() {
+ return this.user?.profile_hidden || this.user?.inactive;
}
@onEvent("didInsertElement")
diff --git a/frontend/discourse/app/components/user-fields/base.js b/frontend/discourse/app/components/user-fields/base.js
index a27153fac4f..9090d72f3a9 100644
--- a/frontend/discourse/app/components/user-fields/base.js
+++ b/frontend/discourse/app/components/user-fields/base.js
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { classNameBindings } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
@classNameBindings(":user-field", "field.field_type", "customFieldClass")
export default class UserFieldBase extends Component {
@@ -15,15 +15,15 @@ export default class UserFieldBase extends Component {
this.field.element = element;
}
- @discourseComputed
- noneLabel() {
+ @computed
+ get noneLabel() {
return "user_fields.none";
}
- @discourseComputed("field.name")
- customFieldClass(fieldName) {
- if (fieldName) {
- fieldName = fieldName
+ @computed("field.name")
+ get customFieldClass() {
+ if (this.field?.name) {
+ const fieldName = this.field.name
.replace(/\s+/g, "-")
.replace(/[!\"#$%&'\(\)\*\+,\.\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g, "")
.toLowerCase();
diff --git a/frontend/discourse/app/components/user-info.gjs b/frontend/discourse/app/components/user-info.gjs
index c30734d7ad6..2bd327be7df 100644
--- a/frontend/discourse/app/components/user-info.gjs
+++ b/frontend/discourse/app/components/user-info.gjs
@@ -1,5 +1,6 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { tagName } from "@ember-decorators/component";
import PluginOutlet from "discourse/components/plugin-outlet";
@@ -9,7 +10,6 @@ import avatar from "discourse/helpers/avatar";
import concatClass from "discourse/helpers/concat-class";
import formatUsername from "discourse/helpers/format-username";
import lazyHash from "discourse/helpers/lazy-hash";
-import discourseComputed from "discourse/lib/decorators";
import { prioritizeNameInUx } from "discourse/lib/settings";
import { userPath } from "discourse/lib/url";
import { and } from "discourse/truth-helpers";
@@ -32,14 +32,14 @@ export default class UserInfo extends Component {
this.user?.statusManager?.stopTrackingStatus();
}
- @discourseComputed("user.username")
- userPath(username) {
- return userPath(username);
+ @computed("user.username")
+ get userPath() {
+ return userPath(this.user?.username);
}
- @discourseComputed("user.name")
- nameFirst(name) {
- return prioritizeNameInUx(name);
+ @computed("user.name")
+ get nameFirst() {
+ return prioritizeNameInUx(this.user?.name);
}
<template>
diff --git a/frontend/discourse/app/components/user-notification-schedule.gjs b/frontend/discourse/app/components/user-notification-schedule.gjs
index 207b49edc22..1a21dd26ed7 100644
--- a/frontend/discourse/app/components/user-notification-schedule.gjs
+++ b/frontend/discourse/app/components/user-notification-schedule.gjs
@@ -1,10 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import PreferenceCheckbox from "discourse/components/preference-checkbox";
import UserNotificationScheduleDay from "discourse/components/user-notification-schedule-day";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
const DAYS = [
@@ -32,25 +31,21 @@ class Day extends EmberObject {
this.set(`model.user_notification_schedule.day_${this.id}_end_time`, val);
}
- @discourseComputed(
- "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time"
- )
- startTimeValue(schedule) {
- return schedule[`day_${this.id}_start_time`];
+ @computed("model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time")
+ get startTimeValue() {
+ return this.model?.user_notification_schedule[`day_${this.id}_start_time`];
}
- @discourseComputed(
- "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time"
- )
- endTimeOptions(schedule) {
- return this.buildEndTimeOptionsFor(schedule[`day_${this.id}_start_time`]);
+ @computed("model.user_notification_schedule.day_{0,1,2,3,4,5,6}_start_time")
+ get endTimeOptions() {
+ return this.buildEndTimeOptionsFor(
+ this.model?.user_notification_schedule[`day_${this.id}_start_time`]
+ );
}
- @discourseComputed(
- "model.user_notification_schedule.day_{0,1,2,3,4,5,6}_end_time"
- )
- endTimeValue(schedule) {
- return schedule[`day_${this.id}_end_time`];
+ @computed("model.user_notification_schedule.day_{0,1,2,3,4,5,6}_end_time")
+ get endTimeValue() {
+ return this.model?.user_notification_schedule[`day_${this.id}_end_time`];
}
startingTimeChangedForDay(val) {
diff --git a/frontend/discourse/app/components/user-summary-category-search.gjs b/frontend/discourse/app/components/user-summary-category-search.gjs
index 73a86352c14..a3c169ad21b 100644
--- a/frontend/discourse/app/components/user-summary-category-search.gjs
+++ b/frontend/discourse/app/components/user-summary-category-search.gjs
@@ -1,14 +1,14 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
+import { computed } from "@ember/object";
import { LinkTo } from "@ember/routing";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
@tagName("")
export default class UserSummaryCategorySearch extends Component {
- @discourseComputed("user", "category")
- searchParams() {
+ @computed("user", "category")
+ get searchParams() {
let query = `@${this.get("user.username")} #${this.get("category.slug")}`;
if (this.searchOnlyFirstPosts) {
query += " in:first";
diff --git a/frontend/discourse/app/components/user-summary-topics-list.gjs b/frontend/discourse/app/components/user-summary-topics-list.gjs
index 3f26cbf853b..95a3cb32f22 100644
--- a/frontend/discourse/app/components/user-summary-topics-list.gjs
+++ b/frontend/discourse/app/components/user-summary-topics-list.gjs
@@ -1,9 +1,9 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { concat } from "@ember/helper";
+import { computed } from "@ember/object";
import { LinkTo } from "@ember/routing";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
// should be kept in sync with 'UserSummary::MAX_SUMMARY_RESULTS'
@@ -11,9 +11,9 @@ const MAX_SUMMARY_RESULTS = 6;
@tagName("")
export default class UserSummaryTopicsList extends Component {
- @discourseComputed("items.length")
- hasMore(length) {
- return length >= MAX_SUMMARY_RESULTS;
+ @computed("items.length")
+ get hasMore() {
+ return this.items?.length >= MAX_SUMMARY_RESULTS;
}
<template>
diff --git a/frontend/discourse/app/controllers/account-created/edit-email.js b/frontend/discourse/app/controllers/account-created/edit-email.js
index 0f248cabafa..24043a48572 100644
--- a/frontend/discourse/app/controllers/account-created/edit-email.js
+++ b/frontend/discourse/app/controllers/account-created/edit-email.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { changeEmail } from "discourse/lib/user-activation";
export default class AccountCreatedEditEmailController extends Controller {
@@ -11,9 +10,9 @@ export default class AccountCreatedEditEmailController extends Controller {
accountCreated;
newEmail;
- @discourseComputed("newEmail", "accountCreated.email")
- submitDisabled(newEmail, currentEmail) {
- return newEmail === currentEmail;
+ @computed("newEmail", "accountCreated.email")
+ get submitDisabled() {
+ return this.newEmail === this.accountCreated?.email;
}
@action
diff --git a/frontend/discourse/app/controllers/account-created/index.js b/frontend/discourse/app/controllers/account-created/index.js
index 07b7a6b5629..500b3da8cba 100644
--- a/frontend/discourse/app/controllers/account-created/index.js
+++ b/frontend/discourse/app/controllers/account-created/index.js
@@ -1,15 +1,14 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { resendActivationEmail } from "discourse/lib/user-activation";
import { i18n } from "discourse-i18n";
export default class AccountCreatedIndexController extends Controller {
@service router;
- @discourseComputed
- welcomeTitle() {
+ @computed
+ get welcomeTitle() {
return i18n("invites.welcome_to", {
site_name: this.siteSettings.title,
});
diff --git a/frontend/discourse/app/controllers/application.js b/frontend/discourse/app/controllers/application.js
index 8de1659c1c9..d368816714d 100644
--- a/frontend/discourse/app/controllers/application.js
+++ b/frontend/discourse/app/controllers/application.js
@@ -1,11 +1,10 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { dasherize } from "@ember/string";
import runAfterFramePaint from "discourse/lib/after-frame-paint";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import EmbedMode from "discourse/lib/embed-mode";
import { isTesting } from "discourse/lib/environment";
@@ -92,8 +91,8 @@ export default class ApplicationController extends Controller {
return this.showFooter && this.siteSettings.enable_powered_by_discourse;
}
- @discourseComputed
- canSignUp() {
+ @computed
+ get canSignUp() {
return (
!this.siteSettings.invite_only &&
this.siteSettings.allow_new_registrations &&
@@ -101,18 +100,18 @@ export default class ApplicationController extends Controller {
);
}
- @discourseComputed
- canDisplaySidebar() {
+ @computed
+ get canDisplaySidebar() {
return this.currentUser || !this.siteSettings.login_required;
}
- @discourseComputed
- loginRequired() {
+ @computed
+ get loginRequired() {
return this.siteSettings.login_required && !this.currentUser;
}
- @discourseComputed
- showFooterNav() {
+ @computed
+ get showFooterNav() {
return this.capabilities.isAppWebview || this.capabilities.isiOSPWA;
}
diff --git a/frontend/discourse/app/controllers/badges/index.js b/frontend/discourse/app/controllers/badges/index.js
index 7d0fac5d7ad..14a6e39ea73 100644
--- a/frontend/discourse/app/controllers/badges/index.js
+++ b/frontend/discourse/app/controllers/badges/index.js
@@ -1,5 +1,5 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
function badgeKey(badge) {
let pos = badge.get("badge_grouping.position");
@@ -9,9 +9,11 @@ function badgeKey(badge) {
}
export default class IndexController extends Controller {
- @discourseComputed("model")
- badgeGroups(model) {
- let sorted = model.sort((a, b) => badgeKey(a).localeCompare(badgeKey(b)));
+ @computed("model")
+ get badgeGroups() {
+ let sorted = this.model.sort((a, b) =>
+ badgeKey(a).localeCompare(badgeKey(b))
+ );
let grouped = [];
let group = [];
let groupId;
diff --git a/frontend/discourse/app/controllers/badges/show.js b/frontend/discourse/app/controllers/badges/show.js
index 2a7ba192698..61ac46b1557 100644
--- a/frontend/discourse/app/controllers/badges/show.js
+++ b/frontend/discourse/app/controllers/badges/show.js
@@ -1,8 +1,7 @@
import { tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import Badge from "discourse/models/badge";
import UserBadge from "discourse/models/user-badge";
@@ -20,25 +19,24 @@ export default class ShowController extends Controller {
queryParams = ["username"];
hiddenSetTitle = true;
- @discourseComputed("userBadgesAll")
- filteredList(userBadgesAll) {
- return userBadgesAll.filter((item) => item.badge.allow_title);
+ @computed("userBadgesAll")
+ get filteredList() {
+ return this.userBadgesAll.filter((item) => item.badge.allow_title);
}
- @discourseComputed("filteredList")
- selectableUserBadges(filteredList) {
+ get selectableUserBadges() {
return [
EmberObject.create({
id: 0,
badge: Badge.create({ name: i18n("badges.none") }),
}),
- ...uniqueItemsFromArray(filteredList, "badge.name"),
+ ...uniqueItemsFromArray(this.filteredList, "badge.name"),
];
}
- @discourseComputed("username")
- user(username) {
- if (username) {
+ @computed("username")
+ get user() {
+ if (this.username) {
return this.userBadges[0].get("user");
}
}
@@ -47,14 +45,18 @@ export default class ShowController extends Controller {
return this.username ? this.userBadgesGrantCount : this.model.grant_count;
}
- @discourseComputed("model.grant_count", "userBadgesGrantCount")
- othersCount(modelCount, userCount) {
- return modelCount - userCount;
+ @computed("model.grant_count", "userBadgesGrantCount")
+ get othersCount() {
+ return this.model?.grant_count - this.userBadgesGrantCount;
}
- @discourseComputed("model.allow_title", "model.has_badge", "model")
- canSelectTitle(hasTitleBadges, hasBadge) {
- return this.siteSettings.enable_badges && hasTitleBadges && hasBadge;
+ @computed("model.allow_title", "model.has_badge", "model")
+ get canSelectTitle() {
+ return (
+ this.siteSettings.enable_badges &&
+ this.model?.allow_title &&
+ this.model?.has_badge
+ );
}
get canLoadMore() {
@@ -64,9 +66,9 @@ export default class ShowController extends Controller {
return this.grantCount > (this.userBadges?.length || 0);
}
- @discourseComputed("user", "model.grant_count")
- canShowOthers(user, grantCount) {
- return !!user && grantCount > 1;
+ @computed("user", "model.grant_count")
+ get canShowOthers() {
+ return !!this.user && this.model?.grant_count > 1;
}
@action
diff --git a/frontend/discourse/app/controllers/discovery/categories.js b/frontend/discourse/app/controllers/discovery/categories.js
index a1cbe6426bd..8ae958250d6 100644
--- a/frontend/discourse/app/controllers/discovery/categories.js
+++ b/frontend/discourse/app/controllers/discovery/categories.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { reads } from "@ember/object/computed";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
export default class CategoriesController extends Controller {
@service router;
@@ -10,8 +9,8 @@ export default class CategoriesController extends Controller {
@reads("currentUser.staff") canEdit;
- @discourseComputed
- isCategoriesRoute() {
+ @computed
+ get isCategoriesRoute() {
return this.router.currentRouteName === "discovery.categories";
}
diff --git a/frontend/discourse/app/controllers/email-login.js b/frontend/discourse/app/controllers/email-login.js
index 3ccd7b6ba26..66748716e21 100644
--- a/frontend/discourse/app/controllers/email-login.js
+++ b/frontend/discourse/app/controllers/email-login.js
@@ -1,9 +1,8 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import DiscourseURL from "discourse/lib/url";
import { getWebauthnCredential } from "discourse/lib/webauthn";
@@ -16,9 +15,11 @@ export default class EmailLoginController extends Controller {
lockImageUrl = getURL("/images/lock.svg");
- @discourseComputed("model")
- secondFactorRequired(model) {
- return model.security_key_required || model.second_factor_required;
+ @computed("model")
+ get secondFactorRequired() {
+ return (
+ this.model.security_key_required || this.model.second_factor_required
+ );
}
@action
diff --git a/frontend/discourse/app/controllers/exception.js b/frontend/discourse/app/controllers/exception.js
index 71cba8c83ea..0f66260fdc3 100644
--- a/frontend/discourse/app/controllers/exception.js
+++ b/frontend/discourse/app/controllers/exception.js
@@ -1,9 +1,8 @@
import { cached } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, equal, gte, none } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
-import discourseComputed from "discourse/lib/decorators";
import DiscourseURL from "discourse/lib/url";
import { i18n } from "discourse-i18n";
@@ -45,34 +44,34 @@ export default class ExceptionController extends Controller {
@alias("thrown.requestedUrl") requestUrl;
- @discourseComputed("thrown")
- isNetwork(thrown) {
+ @computed("thrown")
+ get isNetwork() {
// never made it on the wire
- if (thrown && thrown.readyState === 0) {
+ if (this.thrown && this.thrown.readyState === 0) {
return true;
}
// timed out
- if (thrown && thrown.jqTextStatus === "timeout") {
+ if (this.thrown && this.thrown.jqTextStatus === "timeout") {
return true;
}
return false;
}
- @discourseComputed("isNetwork", "thrown.status", "thrown")
- reason(isNetwork, thrownStatus, thrown) {
- if (thrown.reason) {
- return thrown.reason;
- } else if (isNetwork) {
+ @computed("isNetwork", "thrown.status", "thrown")
+ get reason() {
+ if (this.thrown.reason) {
+ return this.thrown.reason;
+ } else if (this.isNetwork) {
return i18n("errors.reasons.network");
- } else if (thrownStatus >= 500) {
+ } else if (this.thrown?.status >= 500) {
return i18n("errors.reasons.server");
- } else if (thrownStatus === 404) {
+ } else if (this.thrown?.status === 404) {
return i18n("errors.reasons.not_found");
- } else if (thrownStatus === 403) {
+ } else if (this.thrown?.status === 403) {
return i18n("errors.reasons.forbidden");
- } else if (thrown === null) {
+ } else if (this.thrown === null) {
return i18n("errors.reasons.unknown");
} else {
// TODO
@@ -80,29 +79,29 @@ export default class ExceptionController extends Controller {
}
}
- @discourseComputed(
+ @computed(
"networkFixed",
"isNetwork",
"thrown.status",
"thrown.statusText",
"thrown"
)
- desc(networkFixed, isNetwork, thrownStatus, thrownStatusText, thrown) {
- if (thrown.desc) {
- return thrown.desc;
- } else if (networkFixed) {
+ get desc() {
+ if (this.thrown.desc) {
+ return this.thrown.desc;
+ } else if (this.networkFixed) {
return i18n("errors.desc.network_fixed");
- } else if (isNetwork) {
+ } else if (this.isNetwork) {
return i18n("errors.desc.network");
- } else if (thrownStatus === 404) {
+ } else if (this.thrown?.status === 404) {
return i18n("errors.desc.not_found");
- } else if (thrownStatus === 403) {
+ } else if (this.thrown?.status === 403) {
return i18n("errors.desc.forbidden");
- } else if (thrownStatus >= 500) {
+ } else if (this.thrown?.status >= 500) {
return i18n("errors.desc.server", {
- status: thrownStatus + " " + thrownStatusText,
+ status: this.thrown?.status + " " + this.thrown?.statusText,
});
- } else if (thrown === null) {
+ } else if (this.thrown === null) {
return i18n("errors.desc.unknown");
} else {
// TODO
@@ -137,13 +136,13 @@ export default class ExceptionController extends Controller {
};
}
- @discourseComputed("networkFixed", "isNetwork", "lastTransition")
- enabledButtons(networkFixed, isNetwork, lastTransition) {
- if (networkFixed) {
+ @computed("networkFixed", "isNetwork", "lastTransition")
+ get enabledButtons() {
+ if (this.networkFixed) {
return [this.buttons.ButtonLoadPage];
- } else if (isNetwork) {
+ } else if (this.isNetwork) {
return [this.buttons.ButtonBackDim, this.buttons.ButtonTryAgain];
- } else if (!lastTransition) {
+ } else if (!this.lastTransition) {
return [this.buttons.ButtonBackBright];
} else {
return [this.buttons.ButtonBackBright, this.buttons.ButtonTryAgain];
diff --git a/frontend/discourse/app/controllers/full-page-search.js b/frontend/discourse/app/controllers/full-page-search.js
index be7e7b94b01..0f799d3c641 100644
--- a/frontend/discourse/app/controllers/full-page-search.js
+++ b/frontend/discourse/app/controllers/full-page-search.js
@@ -9,7 +9,7 @@ import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { addUniqueValuesToArray } from "discourse/lib/array-tools";
import { search as searchCategoryTag } from "discourse/lib/category-tag-search";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { setTransient } from "discourse/lib/page-tracker";
import PostBulkSelectHelper from "discourse/lib/post-bulk-select-helper";
import { scrollTop } from "discourse/lib/scroll-top";
@@ -140,27 +140,27 @@ export default class FullPageSearchController extends Controller {
this.bulkSelectHelper = new PostBulkSelectHelper(this);
}
- @discourseComputed("resultCount")
- hasResults(resultCount) {
- return (resultCount || 0) > 0;
+ @computed("resultCount")
+ get hasResults() {
+ return (this.resultCount || 0) > 0;
}
- @discourseComputed("expanded")
- expandFilters(expanded) {
- return expanded === "true";
+ @computed("expanded")
+ get expandFilters() {
+ return this.expanded === "true";
}
- @discourseComputed("q")
- hasAutofocus(q) {
- return isEmpty(q);
+ @computed("q")
+ get hasAutofocus() {
+ return isEmpty(this.q);
}
- @discourseComputed("q")
- highlightQuery(q) {
- if (!q) {
+ @computed("q")
+ get highlightQuery() {
+ if (!this.q) {
return;
}
- return q
+ return this.q
.split(/\s+/)
.filter((t) => t !== "l")
.join(" ");
@@ -177,34 +177,34 @@ export default class FullPageSearchController extends Controller {
this.set("skip_context", !val);
}
- @discourseComputed("context", "context_id")
- searchContextDescription(context, id) {
- let name = id;
- if (context === "category") {
- let category = Category.findById(id);
+ @computed("context", "context_id")
+ get searchContextDescription() {
+ let name = this.context_id;
+ if (this.context === "category") {
+ let category = Category.findById(this.context_id);
if (!category) {
return;
}
name = category.get("name");
}
- return searchContextDescription(context, name);
+ return searchContextDescription(this.context, name);
}
- @discourseComputed("q")
- searchActive(q) {
- return isValidSearchTerm(q, this.siteSettings);
+ @computed("q")
+ get searchActive() {
+ return isValidSearchTerm(this.q, this.siteSettings);
}
- @discourseComputed("q")
- noSortQ(q) {
- q = this.cleanTerm(q);
+ @computed("q")
+ get noSortQ() {
+ const q = this.cleanTerm(this.q);
return escapeExpression(q);
}
- @discourseComputed("canCreateTopic", "siteSettings.login_required")
- showSuggestion(canCreateTopic, loginRequired) {
- return canCreateTopic || !loginRequired;
+ @computed("canCreateTopic", "siteSettings.login_required")
+ get showSuggestion() {
+ return this.canCreateTopic || !this.siteSettings?.login_required;
}
setSearchTerm(term) {
@@ -261,9 +261,9 @@ export default class FullPageSearchController extends Controller {
}
}
- @discourseComputed("q")
- showLikeCount(q) {
- return q?.includes("order:likes");
+ @computed("q")
+ get showLikeCount() {
+ return this.q?.includes("order:likes");
}
@observes("q")
@@ -275,29 +275,36 @@ export default class FullPageSearchController extends Controller {
}
}
- @discourseComputed("q")
- isPrivateMessage(q) {
+ @computed("q")
+ get isPrivateMessage() {
return (
- q &&
+ this.q &&
this.currentUser &&
- (q.includes("in:messages") ||
- q.includes("in:personal") ||
- q.includes(
+ (this.q.includes("in:messages") ||
+ this.q.includes("in:personal") ||
+ this.q.includes(
`personal_messages:${this.currentUser.get("username_lower")}`
))
);
}
- @discourseComputed("q")
- isPMOnly(q) {
+ @computed("q")
+ get isPMOnly() {
// Check if search is filtered to private messages only
- return q && /\bin:(personal|messages|personal-direct|all-pms)\b/i.test(q);
+ return (
+ this.q &&
+ /\bin:(personal|messages|personal-direct|all-pms)\b/i.test(this.q)
+ );
}
- @discourseComputed("resultCount", "noSortQ")
- resultCountLabel(count, term) {
- const plus = count % 50 === 0 ? "+" : "";
- return i18n("search.result_count", { count, plus, term });
+ @computed("resultCount", "noSortQ")
+ get resultCountLabel() {
+ const plus = this.resultCount % 50 === 0 ? "+" : "";
+ return i18n("search.result_count", {
+ count: this.resultCount,
+ plus,
+ term: this.noSortQ,
+ });
}
@observes("model.{posts,categories,tags,users}.length", "searchResultPosts")
@@ -315,57 +322,58 @@ export default class FullPageSearchController extends Controller {
);
}
- @discourseComputed("hasResults")
- canBulkSelect(hasResults) {
- return this.currentUser && this.currentUser.staff && hasResults;
+ @computed("hasResults")
+ get canBulkSelect() {
+ return this.currentUser && this.currentUser.staff && this.hasResults;
}
- @discourseComputed(
- "bulkSelectHelper.selected.length",
- "searchResultPosts.length"
- )
- hasUnselectedResults(selectionCount, postsCount) {
- return selectionCount < postsCount;
+ @computed("bulkSelectHelper.selected.length", "searchResultPosts.length")
+ get hasUnselectedResults() {
+ return (
+ this.bulkSelectHelper?.selected?.length < this.searchResultPosts?.length
+ );
}
- @discourseComputed("model.grouped_search_result.can_create_topic")
- canCreateTopic(userCanCreateTopic) {
- return this.currentUser && userCanCreateTopic;
+ @computed("model.grouped_search_result.can_create_topic")
+ get canCreateTopic() {
+ return (
+ this.currentUser && this.model?.grouped_search_result?.can_create_topic
+ );
}
- @discourseComputed("page")
- isLastPage(page) {
- return page === PAGE_LIMIT;
+ @computed("page")
+ get isLastPage() {
+ return this.page === PAGE_LIMIT;
}
- @discourseComputed("search_type")
- usingDefaultSearchType(searchType) {
- return searchType === SEARCH_TYPE_DEFAULT;
+ @computed("search_type")
+ get usingDefaultSearchType() {
+ return this.search_type === SEARCH_TYPE_DEFAULT;
}
- @discourseComputed("search_type")
- customSearchType(searchType) {
+ @computed("search_type")
+ get customSearchType() {
return customSearchTypes.find(
- (type) => searchType === type["searchTypeId"]
+ (type) => this.search_type === type["searchTypeId"]
);
}
- @discourseComputed("bulkSelectEnabled")
- searchInfoClassNames(bulkSelectEnabled) {
- return bulkSelectEnabled
+ @computed("bulkSelectEnabled")
+ get searchInfoClassNames() {
+ return this.bulkSelectEnabled
? "search-info bulk-select-visible"
: "search-info";
}
- @discourseComputed("model.posts", "additionalSearchResults")
- searchResultPosts(posts, additionalSearchResults) {
- if (additionalSearchResults?.list?.length > 0) {
+ @computed("model.posts", "additionalSearchResults")
+ get searchResultPosts() {
+ if (this.additionalSearchResults?.list?.length > 0) {
return reciprocallyRankedList(
- [posts, additionalSearchResults.list],
- ["topic_id", additionalSearchResults.identifier]
+ [this.model?.posts, this.additionalSearchResults.list],
+ ["topic_id", this.additionalSearchResults.identifier]
);
} else {
- return posts;
+ return this.model?.posts;
}
}
diff --git a/frontend/discourse/app/controllers/group.js b/frontend/discourse/app/controllers/group.js
index 5c7e284606d..3d8f01fe1b4 100644
--- a/frontend/discourse/app/controllers/group.js
+++ b/frontend/discourse/app/controllers/group.js
@@ -1,8 +1,7 @@
import Controller, { inject as controller } from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { service } from "@ember/service";
import GroupDeleteDialog from "discourse/components/dialog-messages/group-delete";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
class Tab extends EmberObject {
@@ -28,26 +27,20 @@ export default class GroupController extends Controller {
destroying = null;
showTooltip = false;
- @discourseComputed(
+ @computed(
"showMessages",
"model.user_count",
"model.request_count",
"canManageGroup",
"model.allow_membership_requests"
)
- tabs(
- showMessages,
- userCount,
- requestCount,
- canManageGroup,
- allowMembershipRequests
- ) {
+ get tabs() {
const membersTab = Tab.create({
name: "members",
route: "group.index",
icon: "users",
i18nKey: "members.title",
- count: userCount,
+ count: this.model?.user_count,
});
const defaultTabs = [
@@ -55,18 +48,18 @@ export default class GroupController extends Controller {
Tab.create({ name: "activity", icon: "bars-staggered" }),
];
- if (canManageGroup && allowMembershipRequests) {
+ if (this.canManageGroup && this.model?.allow_membership_requests) {
defaultTabs.push(
Tab.create({
name: "requests",
i18nKey: "requests.title",
icon: "user-plus",
- count: requestCount,
+ count: this.model?.request_count,
})
);
}
- if (showMessages) {
+ if (this.showMessages) {
defaultTabs.push(
Tab.create({
name: "messages",
@@ -76,7 +69,7 @@ export default class GroupController extends Controller {
);
}
- if (canManageGroup) {
+ if (this.canManageGroup) {
defaultTabs.push(
Tab.create({
name: "manage",
@@ -97,31 +90,33 @@ export default class GroupController extends Controller {
return defaultTabs;
}
- @discourseComputed(
+ @computed(
"model.has_messages",
"model.is_group_user",
"currentUser.can_send_private_messages"
)
- showMessages(hasMessages, isGroupUser) {
+ get showMessages() {
if (!this.currentUser?.can_send_private_messages) {
return false;
}
- if (!hasMessages) {
+ if (!this.model?.has_messages) {
return false;
}
- return isGroupUser || (this.currentUser && this.currentUser.admin);
+ return (
+ this.model?.is_group_user || (this.currentUser && this.currentUser.admin)
+ );
}
- @discourseComputed("model.messageable")
- displayGroupMessageButton(messageable) {
- return this.currentUser && messageable;
+ @computed("model.messageable")
+ get displayGroupMessageButton() {
+ return this.currentUser && this.model?.messageable;
}
- @discourseComputed("model", "model.automatic")
- canManageGroup(model) {
- return this.currentUser?.canManageGroup(model);
+ @computed("model", "model.automatic")
+ get canManageGroup() {
+ return this.currentUser?.canManageGroup(this.model);
}
@action
diff --git a/frontend/discourse/app/controllers/group/index.js b/frontend/discourse/app/controllers/group/index.js
index 67a10b6a04e..3ea5abb551d 100644
--- a/frontend/discourse/app/controllers/group/index.js
+++ b/frontend/discourse/app/controllers/group/index.js
@@ -1,13 +1,13 @@
/* eslint-disable ember/no-observers */
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { observes } from "@ember-decorators/object";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
import { GROUP_VISIBILITY_LEVELS } from "discourse/lib/constants";
-import discourseComputed, { debounce } from "discourse/lib/decorators";
+import { debounce } from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { i18n } from "discourse-i18n";
@@ -68,18 +68,20 @@ export default class GroupIndexController extends Controller {
});
}
- @discourseComputed("order", "asc", "filter")
- memberParams(order, asc, filter) {
- return { order, asc, filter };
+ @computed("order", "asc", "filter")
+ get memberParams() {
+ return { order: this.order, asc: this.asc, filter: this.filter };
}
- @discourseComputed("model")
- canManageGroup(model) {
- return this.currentUser?.canManageGroup(model) && !this.model.automatic;
+ @computed("model")
+ get canManageGroup() {
+ return (
+ this.currentUser?.canManageGroup(this.model) && !this.model.automatic
+ );
}
- @discourseComputed
- filterPlaceholder() {
+ @computed
+ get filterPlaceholder() {
if (this.currentUser && this.currentUser.admin) {
return "groups.members.filter_placeholder_admin";
} else {
@@ -87,11 +89,11 @@ export default class GroupIndexController extends Controller {
}
}
- @discourseComputed("filter", "members", "model.can_see_members")
- emptyMessageKey(filter, members, canSeeMembers) {
- if (!canSeeMembers) {
+ @computed("filter", "members", "model.can_see_members")
+ get emptyMessageKey() {
+ if (!this.model?.can_see_members) {
return "groups.members.forbidden";
- } else if (filter) {
+ } else if (this.filter) {
return "groups.members.no_filter_matches";
} else {
return "groups.empty.members";
diff --git a/frontend/discourse/app/controllers/group/manage.js b/frontend/discourse/app/controllers/group/manage.js
index 83d5e4ff35b..22bbf1e0334 100644
--- a/frontend/discourse/app/controllers/group/manage.js
+++ b/frontend/discourse/app/controllers/group/manage.js
@@ -1,9 +1,9 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
export default class GroupManageController extends Controller {
- @discourseComputed("model.automatic")
- tabs(automatic) {
+ @computed("model.automatic")
+ get tabs() {
const defaultTabs = [
{ route: "group.manage.profile", title: "groups.manage.profile.title" },
{
@@ -28,7 +28,7 @@ export default class GroupManageController extends Controller {
title: "groups.manage.logs.title",
});
- if (!automatic) {
+ if (!this.model?.automatic) {
if (this.siteSettings.enable_smtp) {
defaultTabs.splice(2, 0, {
route: "group.manage.email",
diff --git a/frontend/discourse/app/controllers/group/manage/categories.js b/frontend/discourse/app/controllers/group/manage/categories.js
index 89b90763fec..007804cbeb6 100644
--- a/frontend/discourse/app/controllers/group/manage/categories.js
+++ b/frontend/discourse/app/controllers/group/manage/categories.js
@@ -1,17 +1,23 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
export default class GroupManageCategoriesController extends Controller {
- @discourseComputed(
+ @computed(
"model.watchingCategories.[]",
"model.watchingFirstPostCategories.[]",
"model.trackingCategories.[]",
"model.regularCategories.[]",
"model.mutedCategories.[]"
)
- selectedCategories(watching, watchingFirst, tracking, regular, muted) {
+ get selectedCategories() {
return []
- .concat(watching, watchingFirst, tracking, regular, muted)
+ .concat(
+ this.model?.watchingCategories,
+ this.model?.watchingFirstPostCategories,
+ this.model?.trackingCategories,
+ this.model?.regularCategories,
+ this.model?.mutedCategories
+ )
.filter(Boolean);
}
}
diff --git a/frontend/discourse/app/controllers/group/manage/logs.js b/frontend/discourse/app/controllers/group/manage/logs.js
index 977a7c2a866..3e227f0e7ae 100644
--- a/frontend/discourse/app/controllers/group/manage/logs.js
+++ b/frontend/discourse/app/controllers/group/manage/logs.js
@@ -1,9 +1,8 @@
/* eslint-disable ember/no-observers */
import Controller, { inject as controller } from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { observes } from "@ember-decorators/object";
import { addUniqueValueToArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
export default class GroupManageLogsController extends Controller {
@controller group;
@@ -13,14 +12,19 @@ export default class GroupManageLogsController extends Controller {
offset = 0;
filters = EmberObject.create();
- @discourseComputed(
+ @computed(
"filters.action",
"filters.acting_user",
"filters.target_user",
"filters.subject"
)
- filterParams(filtersAction, acting_user, target_user, subject) {
- return { action: filtersAction, acting_user, target_user, subject };
+ get filterParams() {
+ return {
+ action: this.filters?.action,
+ acting_user: this.filters?.acting_user,
+ target_user: this.filters?.target_user,
+ subject: this.filters?.subject,
+ };
}
@observes(
diff --git a/frontend/discourse/app/controllers/group/manage/tags.js b/frontend/discourse/app/controllers/group/manage/tags.js
index 942e3920509..b0c453930df 100644
--- a/frontend/discourse/app/controllers/group/manage/tags.js
+++ b/frontend/discourse/app/controllers/group/manage/tags.js
@@ -1,17 +1,23 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
export default class GroupManageTagsController extends Controller {
- @discourseComputed(
+ @computed(
"model.watching_tags.[]",
"model.watching_first_post_tags.[]",
"model.tracking_tags.[]",
"model.regular_tags.[]",
"model.muted_tags.[]"
)
- selectedTags(watching, watchingFirst, tracking, regular, muted) {
+ get selectedTags() {
return []
- .concat(watching, watchingFirst, tracking, regular, muted)
+ .concat(
+ this.model?.watching_tags,
+ this.model?.watching_first_post_tags,
+ this.model?.tracking_tags,
+ this.model?.regular_tags,
+ this.model?.muted_tags
+ )
.filter((t) => t);
}
}
diff --git a/frontend/discourse/app/controllers/group/requests.js b/frontend/discourse/app/controllers/group/requests.js
index b8f238881b2..6a9ea92c324 100644
--- a/frontend/discourse/app/controllers/group/requests.js
+++ b/frontend/discourse/app/controllers/group/requests.js
@@ -1,10 +1,10 @@
/* eslint-disable ember/no-observers */
import Controller, { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { observes } from "@ember-decorators/object";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed, { debounce } from "discourse/lib/decorators";
+import { debounce } from "discourse/lib/decorators";
export default class GroupRequestsController extends Controller {
@controller application;
@@ -57,17 +57,17 @@ export default class GroupRequestsController extends Controller {
});
}
- @discourseComputed("order", "asc", "filter")
- memberParams(order, asc, filter) {
- return { order, asc, filter };
+ @computed("order", "asc", "filter")
+ get memberParams() {
+ return { order: this.order, asc: this.asc, filter: this.filter };
}
get hasRequesters() {
return this.model.requesters?.length > 0;
}
- @discourseComputed
- filterPlaceholder() {
+ @computed
+ get filterPlaceholder() {
if (this.currentUser && this.currentUser.admin) {
return "groups.members.filter_placeholder_admin";
} else {
diff --git a/frontend/discourse/app/controllers/groups/new.js b/frontend/discourse/app/controllers/groups/new.js
index cb7926b3da4..7498dbe1c4c 100644
--- a/frontend/discourse/app/controllers/groups/new.js
+++ b/frontend/discourse/app/controllers/groups/new.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
export default class GroupsNewController extends Controller {
@service router;
@@ -10,14 +9,18 @@ export default class GroupsNewController extends Controller {
saving = null;
- @discourseComputed("model.ownerUsernames")
- splitOwnerUsernames(owners) {
- return owners && owners.length ? owners.split(",") : [];
+ @computed("model.ownerUsernames")
+ get splitOwnerUsernames() {
+ return this.model?.ownerUsernames && this.model?.ownerUsernames?.length
+ ? this.model?.ownerUsernames?.split(",")
+ : [];
}
- @discourseComputed("model.usernames")
- splitUsernames(usernames) {
- return usernames && usernames.length ? usernames.split(",") : [];
+ @computed("model.usernames")
+ get splitUsernames() {
+ return this.model?.usernames && this.model?.usernames?.length
+ ? this.model?.usernames?.split(",")
+ : [];
}
@action
diff --git a/frontend/discourse/app/controllers/invites/show.js b/frontend/discourse/app/controllers/invites/show.js
index 5d441d76540..e23643fa1c4 100644
--- a/frontend/discourse/app/controllers/invites/show.js
+++ b/frontend/discourse/app/controllers/invites/show.js
@@ -1,12 +1,11 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { alias, bool, not, readOnly } from "@ember/object/computed";
import { isEmpty } from "@ember/utils";
import { ajax } from "discourse/lib/ajax";
import { extractError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import getUrl from "discourse/lib/get-url";
import NameValidationHelper from "discourse/lib/name-validation-helper";
import PasswordValidationHelper from "discourse/lib/password-validation-helper";
@@ -110,30 +109,30 @@ export default class InvitesShowController extends Controller {
this.setProperties(props);
}
- @discourseComputed
- discourseConnectEnabled() {
+ @computed
+ get discourseConnectEnabled() {
return this.siteSettings.enable_discourse_connect;
}
- @discourseComputed
- welcomeTitle() {
+ @computed
+ get welcomeTitle() {
return i18n("invites.welcome_to", {
site_name: this.siteSettings.title,
});
}
- @discourseComputed("email")
- yourEmailMessage(email) {
- return i18n("invites.your_email", { email });
+ @computed("email")
+ get yourEmailMessage() {
+ return i18n("invites.your_email", { email: this.email });
}
- @discourseComputed
- externalAuthsEnabled() {
+ @computed
+ get externalAuthsEnabled() {
return findLoginMethods().length > 0;
}
- @discourseComputed
- externalAuthsOnly() {
+ @computed
+ get externalAuthsOnly() {
return (
!this.siteSettings.enable_local_logins &&
!this.siteSettings.enable_discourse_connect &&
@@ -141,17 +140,17 @@ export default class InvitesShowController extends Controller {
);
}
- @discourseComputed("existingUserId")
- showWelcomeHeader(existingUserId) {
- return !existingUserId;
+ @computed("existingUserId")
+ get showWelcomeHeader() {
+ return !this.existingUserId;
}
- @discourseComputed("externalAuthsOnly", "discourseConnectEnabled")
- showSignupProgressBar(externalAuthsOnly, discourseConnectEnabled) {
- return !(externalAuthsOnly || discourseConnectEnabled);
+ @computed("externalAuthsOnly", "discourseConnectEnabled")
+ get showSignupProgressBar() {
+ return !(this.externalAuthsOnly || this.discourseConnectEnabled);
}
- @discourseComputed(
+ @computed(
"emailValidation.failed",
"usernameValidation.failed",
"passwordValidation.failed",
@@ -160,74 +159,61 @@ export default class InvitesShowController extends Controller {
"existingUserRedeeming",
"existingUserCanRedeem"
)
- submitDisabled(
- emailValidationFailed,
- usernameValidationFailed,
- passwordValidationFailed,
- nameValidationFailed,
- userFieldsValidationFailed,
- existingUserRedeeming,
- existingUserCanRedeem
- ) {
- if (existingUserRedeeming) {
- return !existingUserCanRedeem;
+ get submitDisabled() {
+ if (this.existingUserRedeeming) {
+ return !this.existingUserCanRedeem;
}
return (
- emailValidationFailed ||
- usernameValidationFailed ||
- passwordValidationFailed ||
- nameValidationFailed ||
- userFieldsValidationFailed
+ this.emailValidation?.failed ||
+ this.usernameValidation?.failed ||
+ this.passwordValidation?.failed ||
+ this.nameValidation?.failed ||
+ this.userFieldsValidation?.failed
);
}
- @discourseComputed(
+ @computed(
"externalAuthsEnabled",
"externalAuthsOnly",
"discourseConnectEnabled"
)
- showSocialLoginAvailable(
- externalAuthsEnabled,
- externalAuthsOnly,
- discourseConnectEnabled
- ) {
+ get showSocialLoginAvailable() {
return (
- externalAuthsEnabled && !externalAuthsOnly && !discourseConnectEnabled
+ this.externalAuthsEnabled &&
+ !this.externalAuthsOnly &&
+ !this.discourseConnectEnabled
);
}
- @discourseComputed(
+ @computed(
"externalAuthsOnly",
"authOptions",
"emailValidation.failed",
"existingUserRedeeming"
)
- shouldDisplayForm(
- externalAuthsOnly,
- authOptions,
- emailValidationFailed,
- existingUserRedeeming
- ) {
+ get shouldDisplayForm() {
return (
(this.siteSettings.enable_local_logins ||
- (externalAuthsOnly && authOptions && !emailValidationFailed)) &&
+ (this.externalAuthsOnly &&
+ this.authOptions &&
+ !this.emailValidation?.failed)) &&
!this.siteSettings.enable_discourse_connect &&
- !existingUserRedeeming
+ !this.existingUserRedeeming
);
}
- @discourseComputed
- showFullname() {
+ @computed
+ get showFullname() {
return this.site.full_name_visible_in_signup;
}
- @discourseComputed
- fullnameRequired() {
+ @computed
+ get fullnameRequired() {
return this.site.full_name_required_for_signup;
}
- @discourseComputed(
+ @computed(
"email",
"rejectedEmails.[]",
"authOptions.email",
@@ -236,16 +222,8 @@ export default class InvitesShowController extends Controller {
"emailVerifiedByLink",
"differentExternalEmail"
)
- emailValidation(
- email,
- rejectedEmails,
- externalAuthEmail,
- externalAuthEmailValid,
- hiddenEmail,
- emailVerifiedByLink,
- differentExternalEmail
- ) {
- if (hiddenEmail && !differentExternalEmail) {
+ get emailValidation() {
+ if (this.hiddenEmail && !this.differentExternalEmail) {
return EmberObject.create({
ok: true,
reason: i18n("user.email.ok"),
@@ -253,25 +231,25 @@ export default class InvitesShowController extends Controller {
}
// If blank, fail without a reason
- if (isEmpty(email)) {
+ if (isEmpty(this.email)) {
return EmberObject.create({
failed: true,
});
}
- if (rejectedEmails.includes(email)) {
+ if (this.rejectedEmails?.includes(this.email)) {
return EmberObject.create({
failed: true,
reason: i18n("user.email.invalid"),
});
}
- if (externalAuthEmail && externalAuthEmailValid) {
+ if (this.authOptions?.email && this.authOptions?.email_valid) {
const provider = this.authProviderDisplayName(
this.get("authOptions.auth_provider")
);
- if (externalAuthEmail === email) {
+ if (this.authOptions?.email === this.email) {
return EmberObject.create({
ok: true,
reason: i18n("user.email.authenticated", {
@@ -288,14 +266,14 @@ export default class InvitesShowController extends Controller {
}
}
- if (emailVerifiedByLink) {
+ if (this.emailVerifiedByLink) {
return EmberObject.create({
ok: true,
reason: i18n("user.email.authenticated_by_invite"),
});
}
- if (emailValid(email)) {
+ if (emailValid(this.email)) {
return EmberObject.create({
ok: true,
reason: i18n("user.email.ok"),
@@ -315,13 +293,13 @@ export default class InvitesShowController extends Controller {
return matchingProvider ? matchingProvider.get("prettyName") : providerName;
}
- @discourseComputed
- ssoPath() {
+ @computed
+ get ssoPath() {
return getUrl("/session/sso");
}
- @discourseComputed
- disclaimerHtml() {
+ @computed
+ get disclaimerHtml() {
if (this.site.tos_url && this.site.privacy_policy_url) {
return i18n("create_account.disclaimer", {
tos_link: this.site.tos_url,
@@ -330,14 +308,14 @@ export default class InvitesShowController extends Controller {
}
}
- @discourseComputed("authOptions.associate_url", "authOptions.auth_provider")
- associateHtml(url, provider) {
- if (!url) {
+ @computed("authOptions.associate_url", "authOptions.auth_provider")
+ get associateHtml() {
+ if (!this.authOptions?.associate_url) {
return;
}
return i18n("create_account.associate", {
- associate_link: url,
- provider: i18n(`login.${provider}.name`),
+ associate_link: this.authOptions?.associate_url,
+ provider: i18n(`login.${this.authOptions?.auth_provider}.name`),
});
}
diff --git a/frontend/discourse/app/controllers/password-reset.js b/frontend/discourse/app/controllers/password-reset.js
index d4ba25cdc52..1563c235c82 100644
--- a/frontend/discourse/app/controllers/password-reset.js
+++ b/frontend/discourse/app/controllers/password-reset.js
@@ -1,9 +1,8 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, or, readOnly } from "@ember/object/computed";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { wantsNewWindow } from "discourse/lib/intercept-click";
import PasswordValidationHelper from "discourse/lib/password-validation-helper";
@@ -34,11 +33,11 @@ export default class PasswordResetController extends Controller {
lockImageUrl = getURL("/images/lock.svg");
- @discourseComputed("securityKeyRequired", "selectedSecondFactorMethod")
- displaySecurityKeyForm(securityKeyRequired, selectedSecondFactorMethod) {
+ @computed("securityKeyRequired", "selectedSecondFactorMethod")
+ get displaySecurityKeyForm() {
return (
- securityKeyRequired &&
- selectedSecondFactorMethod === SECOND_FACTOR_METHODS.SECURITY_KEY
+ this.securityKeyRequired &&
+ this.selectedSecondFactorMethod === SECOND_FACTOR_METHODS.SECURITY_KEY
);
}
@@ -59,16 +58,16 @@ export default class PasswordResetController extends Controller {
return this.passwordValidationHelper.passwordValidation;
}
- @discourseComputed()
- continueButtonText() {
+ @computed()
+ get continueButtonText() {
return i18n("password_reset.continue", {
site_name: this.siteSettings.title,
});
}
- @discourseComputed("redirectTo")
- redirectHref(redirectTo) {
- return getURL(redirectTo || "/");
+ @computed("redirectTo")
+ get redirectHref() {
+ return getURL(this.redirectTo || "/");
}
get showPasswordValidation() {
diff --git a/frontend/discourse/app/controllers/preferences/account.js b/frontend/discourse/app/controllers/preferences/account.js
index 937b123c9d7..d8d299b3f2f 100644
--- a/frontend/discourse/app/controllers/preferences/account.js
+++ b/frontend/discourse/app/controllers/preferences/account.js
@@ -8,7 +8,6 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { propertyNotEqual, setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { exportUserArchive } from "discourse/lib/export-csv";
import getURL from "discourse/lib/get-url";
import { applyValueTransformer } from "discourse/lib/transformer";
@@ -65,8 +64,8 @@ export default class AccountController extends Controller {
).canCheckEmails;
}
- @discourseComputed()
- nameInstructions() {
+ @computed()
+ get nameInstructions() {
return i18n(
this.site.full_name_required_for_signup
? "user.name.instructions_required"
@@ -74,10 +73,10 @@ export default class AccountController extends Controller {
);
}
- @discourseComputed("model.filteredGroups")
- canSelectPrimaryGroup(primaryGroupOptions) {
+ @computed("model.filteredGroups")
+ get canSelectPrimaryGroup() {
return (
- primaryGroupOptions.length > 0 &&
+ this.model?.filteredGroups?.length > 0 &&
this.siteSettings.user_selected_primary_groups
);
}
@@ -97,32 +96,32 @@ export default class AccountController extends Controller {
.filter((value) => value.account || value.method.can_connect);
}
- @discourseComputed(
+ @computed(
"model.email",
"model.secondary_emails.[]",
"model.unconfirmed_emails.[]"
)
- emails(primaryEmail, secondaryEmails, unconfirmedEmails) {
+ get emails() {
const emails = [];
- if (primaryEmail) {
+ if (this.model?.email) {
emails.push(
EmberObject.create({
- email: primaryEmail,
+ email: this.model?.email,
primary: true,
confirmed: true,
})
);
}
- if (secondaryEmails) {
- secondaryEmails.forEach((email) => {
+ if (this.model?.secondary_emails) {
+ this.model?.secondary_emails.forEach((email) => {
emails.push(EmberObject.create({ email, confirmed: true }));
});
}
- if (unconfirmedEmails) {
- unconfirmedEmails.forEach((email) => {
+ if (this.model?.unconfirmed_emails) {
+ this.model?.unconfirmed_emails.forEach((email) => {
emails.push(EmberObject.create({ email }));
});
}
@@ -130,28 +129,28 @@ export default class AccountController extends Controller {
return emails.sort((a, b) => a.email.localeCompare(b.email));
}
- @discourseComputed(
+ @computed(
"model.second_factor_enabled",
"canCheckEmails",
"model.is_anonymous"
)
- canUpdateAssociatedAccounts(
- secondFactorEnabled,
- canCheckEmails,
- isAnonymous
- ) {
- if (secondFactorEnabled || !canCheckEmails || isAnonymous) {
+ get canUpdateAssociatedAccounts() {
+ if (
+ this.model?.second_factor_enabled ||
+ !this.canCheckEmails ||
+ this.model?.is_anonymous
+ ) {
return false;
}
return findAll().length > 0;
}
- @discourseComputed(
- "siteSettings.max_allowed_secondary_emails",
- "model.can_edit_email"
- )
- canAddEmail(maxAllowedSecondaryEmails, canEditEmail) {
- return maxAllowedSecondaryEmails > 0 && canEditEmail;
+ @computed("siteSettings.max_allowed_secondary_emails", "model.can_edit_email")
+ get canAddEmail() {
+ return (
+ this.siteSettings?.max_allowed_secondary_emails > 0 &&
+ this.model?.can_edit_email
+ );
}
@action
diff --git a/frontend/discourse/app/controllers/preferences/email.js b/frontend/discourse/app/controllers/preferences/email.js
index 58cd90e7f70..be4d85532ab 100644
--- a/frontend/discourse/app/controllers/preferences/email.js
+++ b/frontend/discourse/app/controllers/preferences/email.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { empty, or } from "@ember/object/computed";
import { propertyEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { emailValid } from "discourse/lib/utilities";
import { i18n } from "discourse-i18n";
@@ -23,30 +22,30 @@ export default class EmailController extends Controller {
@propertyEqual("newEmailLower", "oldEmail") unchanged;
- @discourseComputed("newEmail")
- newEmailLower(newEmail) {
- return newEmail.toLowerCase().trim();
+ @computed("newEmail")
+ get newEmailLower() {
+ return this.newEmail.toLowerCase().trim();
}
- @discourseComputed("saving", "new")
- saveButtonText(saving, isNew) {
- if (saving) {
+ @computed("saving", "new")
+ get saveButtonText() {
+ if (this.saving) {
return i18n("saving");
}
- if (isNew) {
+ if (this.new) {
return i18n("user.add_email.add");
}
return i18n("user.change");
}
- @discourseComputed("newEmail")
- invalidEmail(newEmail) {
- return !emailValid(newEmail);
+ @computed("newEmail")
+ get invalidEmail() {
+ return !emailValid(this.newEmail);
}
- @discourseComputed("invalidEmail", "oldEmail", "newEmail")
- emailValidation(invalidEmail, oldEmail, newEmail) {
- if (invalidEmail && (oldEmail || newEmail)) {
+ @computed("invalidEmail", "oldEmail", "newEmail")
+ get emailValidation() {
+ if (this.invalidEmail && (this.oldEmail || this.newEmail)) {
return EmberObject.create({
failed: true,
reason: i18n("user.email.invalid"),
diff --git a/frontend/discourse/app/controllers/preferences/emails.js b/frontend/discourse/app/controllers/preferences/emails.js
index 603803d1815..04ac8f30919 100644
--- a/frontend/discourse/app/controllers/preferences/emails.js
+++ b/frontend/discourse/app/controllers/preferences/emails.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { applyValueTransformer } from "discourse/lib/transformer";
import { i18n } from "discourse-i18n";
@@ -63,8 +62,8 @@ export default class EmailsController extends Controller {
);
}
- @discourseComputed()
- frequencyEstimate() {
+ @computed()
+ get frequencyEstimate() {
let estimate = this.get("model.mailing_list_posts_per_day");
if (!estimate || estimate < 2) {
return i18n("user.mailing_list_mode.few_per_day");
@@ -75,16 +74,16 @@ export default class EmailsController extends Controller {
}
}
- @discourseComputed()
- mailingListModeOptions() {
+ @computed()
+ get mailingListModeOptions() {
return [
{ name: this.frequencyEstimate, value: 1 },
{ name: i18n("user.mailing_list_mode.individual_no_echo"), value: 2 },
];
}
- @discourseComputed()
- emailFrequencyInstructions() {
+ @computed()
+ get emailFrequencyInstructions() {
return this.siteSettings.email_time_window_mins
? i18n("user.email.frequency", {
count: this.siteSettings.email_time_window_mins,
diff --git a/frontend/discourse/app/controllers/preferences/interface.js b/frontend/discourse/app/controllers/preferences/interface.js
index 7b3a435d417..7f389b53890 100644
--- a/frontend/discourse/app/controllers/preferences/interface.js
+++ b/frontend/discourse/app/controllers/preferences/interface.js
@@ -11,7 +11,6 @@ import {
} from "discourse/lib/color-scheme-picker";
import { propertyEqual } from "discourse/lib/computed";
import { INTERFACE_COLOR_MODES } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import {
currentThemeId,
listThemes,
@@ -52,8 +51,8 @@ export default class InterfaceController extends Controller {
@propertyEqual("model.id", "currentUser.id") isViewingOwnProfile;
subpageTitle = i18n("user.preferences_nav.interface");
- @discourseComputed("makeThemeDefault")
- saveAttrNames(makeThemeDefault) {
+ @computed("makeThemeDefault")
+ get saveAttrNames() {
let attrs = [
"locale",
"external_links_in_new_tab",
@@ -77,7 +76,7 @@ export default class InterfaceController extends Controller {
"enable_markdown_monospace_font",
];
- if (makeThemeDefault) {
+ if (this.makeThemeDefault) {
attrs.push("theme_ids");
}
@@ -86,19 +85,21 @@ export default class InterfaceController extends Controller {
});
}
- @discourseComputed()
- availableLocales() {
+ @computed()
+ get availableLocales() {
return this.siteSettings.available_locales;
}
- @discourseComputed("currentThemeId")
- defaultDarkSchemeId(themeId) {
- const theme = this.userSelectableThemes?.find((t) => t.id === themeId);
+ @computed("currentThemeId")
+ get defaultDarkSchemeId() {
+ const theme = this.userSelectableThemes?.find(
+ (t) => t.id === this.currentThemeId
+ );
return theme?.dark_color_scheme_id || -1;
}
- @discourseComputed
- textSizes() {
+ @computed
+ get textSizes() {
return TEXT_SIZES.map((value) => {
return { name: i18n(`user.text_size.${value}`), value };
});
@@ -112,15 +113,15 @@ export default class InterfaceController extends Controller {
);
}
- @discourseComputed
- titleCountModes() {
+ @computed
+ get titleCountModes() {
return TITLE_COUNT_MODES.map((value) => {
return { name: i18n(`user.title_count_mode.${value}`), value };
});
}
- @discourseComputed
- bookmarkAfterNotificationModes() {
+ @computed
+ get bookmarkAfterNotificationModes() {
return Object.keys(AUTO_DELETE_PREFERENCES).map((key) => {
return {
value: AUTO_DELETE_PREFERENCES[key],
@@ -129,71 +130,70 @@ export default class InterfaceController extends Controller {
});
}
- @discourseComputed
- userSelectableThemes() {
+ @computed
+ get userSelectableThemes() {
return listThemes(this.site);
}
- @discourseComputed("userSelectableThemes")
- showThemeSelector(themes) {
- return themes && themes.length > 1;
+ @computed("userSelectableThemes")
+ get showThemeSelector() {
+ return this.userSelectableThemes && this.userSelectableThemes.length > 1;
}
- @discourseComputed("themeId")
- themeIdChanged(themeId) {
+ @computed("themeId")
+ get themeIdChanged() {
if (!this.isViewingOwnProfile) {
return false;
}
if (this.currentThemeId === -1) {
- this.set("currentThemeId", themeId);
+ this.set("currentThemeId", this.themeId); // eslint-disable-line ember/no-side-effects
return false;
} else {
- return this.currentThemeId !== themeId;
+ return this.currentThemeId !== this.themeId;
}
}
- @discourseComputed
- userSelectableColorSchemes() {
+ @computed
+ get userSelectableColorSchemes() {
return listColorSchemes(this.site);
}
- @discourseComputed(
- "userSelectableThemes",
- "userSelectableColorSchemes",
- "themeId"
- )
- currentSchemeCanBeSelected(userThemes, userColorSchemes, themeId) {
- if (!userThemes || !themeId) {
+ @computed("userSelectableThemes", "userSelectableColorSchemes", "themeId")
+ get currentSchemeCanBeSelected() {
+ if (!this.userSelectableThemes || !this.themeId) {
return false;
}
- const theme = userThemes.find((t) => t.id === themeId);
+ const theme = this.userSelectableThemes.find((t) => t.id === this.themeId);
if (!theme) {
return false;
}
- return userColorSchemes.find(
+ return this.userSelectableColorSchemes.find(
(colorScheme) => colorScheme.id === theme.color_scheme_id
);
}
- @discourseComputed("model.user_option.theme_ids", "themeId")
- showThemeSetDefault(userOptionThemes, selectedTheme) {
+ @computed("model.user_option.theme_ids", "themeId")
+ get showThemeSetDefault() {
if (!this.isViewingOwnProfile) {
return false;
}
- return !userOptionThemes || userOptionThemes[0] !== selectedTheme;
+ return (
+ !this.model?.user_option?.theme_ids ||
+ this.model?.user_option?.theme_ids?.[0] !== this.themeId
+ );
}
- @discourseComputed("model.user_option.text_size", "textSize")
- showTextSetDefault(userOptionTextSize, selectedTextSize) {
+ @computed("model.user_option.text_size", "textSize")
+ get showTextSetDefault() {
if (!this.isViewingOwnProfile) {
return false;
}
- return userOptionTextSize !== selectedTextSize;
+ return this.model?.user_option?.text_size !== this.textSize;
}
get isInLightMode() {
@@ -254,8 +254,8 @@ export default class InterfaceController extends Controller {
setDefaultHomepage(userHome || siteHome);
}
- @discourseComputed()
- userSelectableHome() {
+ @computed()
+ get userSelectableHome() {
let homeValues = {};
Object.keys(USER_HOMES).forEach((newValue) => {
const newKey = USER_HOMES[newValue];
@@ -288,29 +288,28 @@ export default class InterfaceController extends Controller {
return result;
}
- @discourseComputed("selectedDarkColorSchemeId", "currentThemeId")
- showInterfaceColorModeSelector(selectedDarkColorSchemeId, themeId) {
- const theme = this.userSelectableThemes?.find((t) => t.id === themeId);
+ @computed("selectedDarkColorSchemeId", "currentThemeId")
+ get showInterfaceColorModeSelector() {
+ const theme = this.userSelectableThemes?.find(
+ (t) => t.id === this.currentThemeId
+ );
return (
(this.defaultDarkSchemeId > 0 &&
theme.color_scheme_id &&
theme.color_scheme_id !== theme.dark_color_scheme_id) ||
- selectedDarkColorSchemeId > 0
+ this.selectedDarkColorSchemeId > 0
);
}
- @discourseComputed
- userSelectableDarkColorSchemes() {
+ @computed
+ get userSelectableDarkColorSchemes() {
return listColorSchemes(this.site, {
darkOnly: true,
});
}
- @discourseComputed(
- "userSelectableColorSchemes",
- "userSelectableDarkColorSchemes"
- )
- showColorSchemeSelector() {
+ @computed("userSelectableColorSchemes", "userSelectableDarkColorSchemes")
+ get showColorSchemeSelector() {
return (
this.showLightColorSchemeSelector ||
this.showDarkColorSchemeSelector ||
@@ -318,14 +317,20 @@ export default class InterfaceController extends Controller {
);
}
- @discourseComputed("userSelectableColorSchemes")
- showLightColorSchemeSelector(lightSchemes) {
- return lightSchemes && lightSchemes.length > 1;
+ @computed("userSelectableColorSchemes")
+ get showLightColorSchemeSelector() {
+ return (
+ this.userSelectableColorSchemes &&
+ this.userSelectableColorSchemes.length > 1
+ );
}
- @discourseComputed("userSelectableDarkColorSchemes")
- showDarkColorSchemeSelector(darkSchemes) {
- return darkSchemes && darkSchemes.length > 1;
+ @computed("userSelectableDarkColorSchemes")
+ get showDarkColorSchemeSelector() {
+ return (
+ this.userSelectableDarkColorSchemes &&
+ this.userSelectableDarkColorSchemes.length > 1
+ );
}
get interfaceColorModes() {
diff --git a/frontend/discourse/app/controllers/preferences/profile.js b/frontend/discourse/app/controllers/preferences/profile.js
index 7d24a4e86f6..2368a18ab0b 100644
--- a/frontend/discourse/app/controllers/preferences/profile.js
+++ b/frontend/discourse/app/controllers/preferences/profile.js
@@ -1,12 +1,11 @@
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { readOnly } from "@ember/object/computed";
import { service } from "@ember/service";
import { compare, isEmpty } from "@ember/utils";
import FeatureTopicOnProfileModal from "discourse/components/modal/feature-topic-on-profile";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { applyValueTransformer } from "discourse/lib/transformer";
import { i18n } from "discourse-i18n";
@@ -48,8 +47,8 @@ export default class ProfileController extends Controller {
);
}
- @discourseComputed("[email protected]")
- userFields() {
+ @computed("[email protected]")
+ get userFields() {
let siteUserFields = this.site.user_fields;
if (isEmpty(siteUserFields)) {
return;
@@ -75,14 +74,14 @@ export default class ProfileController extends Controller {
});
}
- @discourseComputed("currentUser.needs_required_fields_check")
- showEnforcedRequiredFieldsNotice(needsRequiredFieldsCheck) {
- return needsRequiredFieldsCheck;
+ @computed("currentUser.needs_required_fields_check")
+ get showEnforcedRequiredFieldsNotice() {
+ return this.currentUser?.needs_required_fields_check;
}
- @discourseComputed("model.user_option.default_calendar")
- canChangeDefaultCalendar(defaultCalendar) {
- return defaultCalendar !== "none_selected";
+ @computed("model.user_option.default_calendar")
+ get canChangeDefaultCalendar() {
+ return this.model?.user_option?.default_calendar !== "none_selected";
}
@action
diff --git a/frontend/discourse/app/controllers/preferences/second-factor.js b/frontend/discourse/app/controllers/preferences/second-factor.js
index 54989b6ce27..fc896565999 100644
--- a/frontend/discourse/app/controllers/preferences/second-factor.js
+++ b/frontend/discourse/app/controllers/preferences/second-factor.js
@@ -1,5 +1,5 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { service } from "@ember/service";
import ConfirmSession from "discourse/components/dialog-messages/confirm-session";
@@ -10,7 +10,6 @@ import SecondFactorBackupEdit from "discourse/components/modal/second-factor-bac
import SecondFactorEdit from "discourse/components/modal/second-factor-edit";
import SecondFactorEditSecurityKey from "discourse/components/modal/second-factor-edit-security-key";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import DiscourseURL, { userPath } from "discourse/lib/url";
import { findAll } from "discourse/models/login-method";
import { SECOND_FACTOR_METHODS } from "discourse/models/user";
@@ -36,40 +35,40 @@ export default class SecondFactorController extends Controller {
return this.currentUser?.id === this.model.id;
}
- @discourseComputed
- hasOAuth() {
+ @computed
+ get hasOAuth() {
return findAll().length > 0;
}
- @discourseComputed
- displayOAuthWarning() {
+ @computed
+ get displayOAuthWarning() {
return (
this.hasOAuth && this.siteSettings.enforce_second_factor_on_external_auth
);
}
- @discourseComputed("currentUser")
- showEnforcedWithOAuthNotice(user) {
+ @computed("currentUser")
+ get showEnforcedWithOAuthNotice() {
return (
- user &&
- user.enforcedSecondFactor &&
+ this.currentUser &&
+ this.currentUser.enforcedSecondFactor &&
this.hasOAuth &&
!this.siteSettings.enforce_second_factor_on_external_auth
);
}
- @discourseComputed("currentUser")
- showEnforcedNotice(user) {
+ @computed("currentUser")
+ get showEnforcedNotice() {
return (
- user &&
- user.enforcedSecondFactor &&
+ this.currentUser &&
+ this.currentUser.enforcedSecondFactor &&
this.siteSettings.enforce_second_factor_on_external_auth
);
}
- @discourseComputed("totps", "security_keys")
- hasSecondFactors(totps, security_keys) {
- return totps.length > 0 || security_keys.length > 0;
+ @computed("totps", "security_keys")
+ get hasSecondFactors() {
+ return this.totps.length > 0 || this.security_keys.length > 0;
}
async createToTpModal() {
diff --git a/frontend/discourse/app/controllers/preferences/security.js b/frontend/discourse/app/controllers/preferences/security.js
index aa9a7e88623..298b277b3e3 100644
--- a/frontend/discourse/app/controllers/preferences/security.js
+++ b/frontend/discourse/app/controllers/preferences/security.js
@@ -8,7 +8,6 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import logout from "discourse/lib/logout";
import { userPath } from "discourse/lib/url";
import { isWebauthnSupported } from "discourse/lib/webauthn";
@@ -59,9 +58,9 @@ export default class SecurityController extends Controller {
);
}
- @discourseComputed("model.is_anonymous")
- canChangePassword(isAnonymous) {
- if (isAnonymous) {
+ @computed("model.is_anonymous")
+ get canChangePassword() {
+ if (this.model?.is_anonymous) {
return false;
} else {
return (
@@ -71,9 +70,9 @@ export default class SecurityController extends Controller {
}
}
- @discourseComputed("showAllAuthTokens", "model.user_auth_tokens")
- authTokens(showAllAuthTokens, tokens) {
- tokens.sort((a, b) => {
+ @computed("showAllAuthTokens", "model.user_auth_tokens")
+ get authTokens() {
+ this.model?.user_auth_tokens?.sort((a, b) => {
if (a.is_active) {
return -1;
} else if (b.is_active) {
@@ -83,9 +82,9 @@ export default class SecurityController extends Controller {
}
});
- return showAllAuthTokens
- ? tokens
- : tokens.slice(0, DEFAULT_AUTH_TOKENS_COUNT);
+ return this.showAllAuthTokens
+ ? this.model?.user_auth_tokens
+ : this.model?.user_auth_tokens?.slice(0, DEFAULT_AUTH_TOKENS_COUNT);
}
@action
@@ -112,7 +111,7 @@ export default class SecurityController extends Controller {
}
}
- @discourseComputed(
+ @computed(
"model.is_anonymous",
"model.no_password",
"siteSettings",
@@ -120,32 +119,25 @@ export default class SecurityController extends Controller {
"model.associated_accounts",
"model.can_remove_password"
)
- canRemovePassword(
- isAnonymous,
- noPassword,
- siteSettings,
- userPasskeys,
- associatedAccounts,
- canRemove
- ) {
+ get canRemovePassword() {
// Hint returned from staff-info controller that
// works even if staff hasn't revealed e-mails.
- if (canRemove) {
+ if (this.model?.can_remove_password) {
return true;
}
if (
- isAnonymous ||
- noPassword ||
- siteSettings.enable_discourse_connect ||
- !siteSettings.enable_local_logins
+ this.model?.is_anonymous ||
+ this.model?.no_password ||
+ this.siteSettings.enable_discourse_connect ||
+ !this.siteSettings.enable_local_logins
) {
return false;
}
return (
- associatedAccounts?.length > 0 ||
- (this.canUsePasskeys && userPasskeys?.length > 0)
+ this.model?.associated_accounts?.length > 0 ||
+ (this.canUsePasskeys && this.model?.user_passkeys?.length > 0)
);
}
diff --git a/frontend/discourse/app/controllers/preferences/tags.js b/frontend/discourse/app/controllers/preferences/tags.js
index 053a380ddbd..60e4f2a45d7 100644
--- a/frontend/discourse/app/controllers/preferences/tags.js
+++ b/frontend/discourse/app/controllers/preferences/tags.js
@@ -1,7 +1,6 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { applyValueTransformer } from "discourse/lib/transformer";
export default class TagsController extends Controller {
@@ -18,14 +17,21 @@ export default class TagsController extends Controller {
);
}
- @discourseComputed(
+ @computed(
"model.watched_tags.[]",
"model.watching_first_post_tags.[]",
"model.tracked_tags.[]",
"model.muted_tags.[]"
)
- selectedTags(watched, watchedFirst, tracked, muted) {
- return [].concat(watched, watchedFirst, tracked, muted).filter((t) => t);
+ get selectedTags() {
+ return []
+ .concat(
+ this.model?.watched_tags,
+ this.model?.watching_first_post_tags,
+ this.model?.tracked_tags,
+ this.model?.muted_tags
+ )
+ .filter((t) => t);
}
@action
diff --git a/frontend/discourse/app/controllers/preferences/users.js b/frontend/discourse/app/controllers/preferences/users.js
index 4aa5d3323f2..191fda913b5 100644
--- a/frontend/discourse/app/controllers/preferences/users.js
+++ b/frontend/discourse/app/controllers/preferences/users.js
@@ -3,7 +3,6 @@ import { action, computed } from "@ember/object";
import { and } from "@ember/object/computed";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { makeArray } from "discourse/lib/helpers";
import { applyValueTransformer } from "discourse/lib/transformer";
import { i18n } from "discourse-i18n";
@@ -68,9 +67,9 @@ export default class UsersController extends Controller {
);
}
- @discourseComputed("model.user_option.allow_private_messages")
- disableAllowPmUsersSetting(allowPrivateMessages) {
- return !allowPrivateMessages;
+ @computed("model.user_option.allow_private_messages")
+ get disableAllowPmUsersSetting() {
+ return !this.model?.user_option?.allow_private_messages;
}
@action
diff --git a/frontend/discourse/app/controllers/review/index.js b/frontend/discourse/app/controllers/review/index.js
index e984793ff69..40bfd421755 100644
--- a/frontend/discourse/app/controllers/review/index.js
+++ b/frontend/discourse/app/controllers/review/index.js
@@ -1,5 +1,5 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { next } from "@ember/runloop";
import { service } from "@ember/service";
import { underscore } from "@ember/string";
@@ -7,7 +7,6 @@ import { isPresent } from "@ember/utils";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { REVIEWABLE_UNKNOWN_TYPE_SOURCE } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ReviewIndexController extends Controller {
@@ -51,8 +50,8 @@ export default class ReviewIndexController extends Controller {
filterScoreType = null;
unknownTypeSource = REVIEWABLE_UNKNOWN_TYPE_SOURCE;
- @discourseComputed("reviewableTypes")
- allTypes() {
+ @computed("reviewableTypes")
+ get allTypes() {
return (this.reviewableTypes || []).map((type) => {
const translationKey = underscore(type).replace(/[^\w]+/g, "_");
@@ -63,13 +62,13 @@ export default class ReviewIndexController extends Controller {
});
}
- @discourseComputed("scoreTypes")
- allScoreTypes() {
+ @computed("scoreTypes")
+ get allScoreTypes() {
return this.scoreTypes || [];
}
- @discourseComputed
- priorities() {
+ @computed
+ get priorities() {
return ["any", "low", "medium", "high"].map((priority) => {
return {
id: priority,
@@ -78,8 +77,8 @@ export default class ReviewIndexController extends Controller {
});
}
- @discourseComputed
- sortOrders() {
+ @computed
+ get sortOrders() {
return ["score", "score_asc", "created_at", "created_at_asc"].map(
(order) => {
return {
@@ -90,8 +89,8 @@ export default class ReviewIndexController extends Controller {
);
}
- @discourseComputed
- statuses() {
+ @computed
+ get statuses() {
return [
"pending",
"approved",
@@ -105,9 +104,9 @@ export default class ReviewIndexController extends Controller {
});
}
- @discourseComputed("filtersExpanded")
- toggleFiltersIcon(filtersExpanded) {
- return filtersExpanded ? "chevron-up" : "chevron-down";
+ @computed("filtersExpanded")
+ get toggleFiltersIcon() {
+ return this.filtersExpanded ? "chevron-up" : "chevron-down";
}
setRange(range) {
@@ -118,9 +117,9 @@ export default class ReviewIndexController extends Controller {
next(() => this.send("refreshRoute"));
}
- @discourseComputed("unknownReviewableTypes")
- displayUnknownReviewableTypesWarning(unknownReviewableTypes) {
- return unknownReviewableTypes?.length > 0 && this.currentUser.admin;
+ @computed("unknownReviewableTypes")
+ get displayUnknownReviewableTypesWarning() {
+ return this.unknownReviewableTypes?.length > 0 && this.currentUser.admin;
}
@action
diff --git a/frontend/discourse/app/controllers/review/settings.js b/frontend/discourse/app/controllers/review/settings.js
index b7b918a210f..0bff287916c 100644
--- a/frontend/discourse/app/controllers/review/settings.js
+++ b/frontend/discourse/app/controllers/review/settings.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class ReviewSettingsController extends Controller {
@@ -28,11 +27,11 @@ export default class ReviewSettingsController extends Controller {
.finally(() => this.set("saving", false));
}
- @discourseComputed("settings.reviewable_score_types")
- scoreTypes(types) {
+ @computed("settings.reviewable_score_types")
+ get scoreTypes() {
const username = i18n("review.example_username");
- return types.map((type) => ({
+ return this.settings?.reviewable_score_types?.map((type) => ({
...type,
title: type.title.replace("%{username}", username),
}));
diff --git a/frontend/discourse/app/controllers/second-factor-auth.js b/frontend/discourse/app/controllers/second-factor-auth.js
index ec1d6512120..8f0e821b29c 100644
--- a/frontend/discourse/app/controllers/second-factor-auth.js
+++ b/frontend/discourse/app/controllers/second-factor-auth.js
@@ -1,9 +1,8 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal, readOnly } from "@ember/object/computed";
import { ajax } from "discourse/lib/ajax";
import { extractError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import DiscourseURL from "discourse/lib/url";
import { getWebauthnCredential } from "discourse/lib/webauthn";
import { SECOND_FACTOR_METHODS } from "discourse/models/user";
@@ -32,43 +31,38 @@ export default class SecondFactorAuthController extends Controller {
@equal("shownSecondFactorMethod", SECURITY_KEY) showSecurityKeyForm;
@equal("shownSecondFactorMethod", BACKUP_CODE) showBackupCodesForm;
- @discourseComputed("allowedMethods.[]", "totpEnabled")
- totpAvailable() {
+ @computed("allowedMethods.[]", "totpEnabled")
+ get totpAvailable() {
return this.totpEnabled && this.allowedMethods.includes(TOTP);
}
- @discourseComputed("allowedMethods.[]", "backupCodesEnabled")
- backupCodesAvailable() {
+ @computed("allowedMethods.[]", "backupCodesEnabled")
+ get backupCodesAvailable() {
return this.backupCodesEnabled && this.allowedMethods.includes(BACKUP_CODE);
}
- @discourseComputed("allowedMethods.[]", "securityKeysEnabled")
- securityKeysAvailable() {
+ @computed("allowedMethods.[]", "securityKeysEnabled")
+ get securityKeysAvailable() {
return (
this.securityKeysEnabled && this.allowedMethods.includes(SECURITY_KEY)
);
}
- @discourseComputed(
+ @computed(
"userSelectedMethod",
"securityKeysAvailable",
"totpAvailable",
"backupCodesAvailable"
)
- shownSecondFactorMethod(
- userSelectedMethod,
- securityKeysAvailable,
- totpAvailable,
- backupCodesAvailable
- ) {
- if (userSelectedMethod !== null) {
- return userSelectedMethod;
+ get shownSecondFactorMethod() {
+ if (this.userSelectedMethod !== null) {
+ return this.userSelectedMethod;
} else {
- if (securityKeysAvailable) {
+ if (this.securityKeysAvailable) {
return SECURITY_KEY;
- } else if (totpAvailable) {
+ } else if (this.totpAvailable) {
return TOTP;
- } else if (backupCodesAvailable) {
+ } else if (this.backupCodesAvailable) {
return BACKUP_CODE;
} else {
throw new Error("unexpected state of user 2fa settings!");
@@ -76,20 +70,18 @@ export default class SecondFactorAuthController extends Controller {
}
}
- @discourseComputed(
+ @computed(
"shownSecondFactorMethod",
"securityKeysAvailable",
"totpAvailable",
"backupCodesAvailable"
)
- alternativeMethods(
- shownSecondFactorMethod,
- securityKeysAvailable,
- totpAvailable,
- backupCodesAvailable
- ) {
+ get alternativeMethods() {
const alts = [];
- if (securityKeysAvailable && shownSecondFactorMethod !== SECURITY_KEY) {
+ if (
+ this.securityKeysAvailable &&
+ this.shownSecondFactorMethod !== SECURITY_KEY
+ ) {
alts.push({
id: SECURITY_KEY,
translationKey: "login.second_factor_toggle.security_key",
@@ -97,7 +89,7 @@ export default class SecondFactorAuthController extends Controller {
});
}
- if (totpAvailable && shownSecondFactorMethod !== TOTP) {
+ if (this.totpAvailable && this.shownSecondFactorMethod !== TOTP) {
alts.push({
id: TOTP,
translationKey: "login.second_factor_toggle.totp",
@@ -105,7 +97,10 @@ export default class SecondFactorAuthController extends Controller {
});
}
- if (backupCodesAvailable && shownSecondFactorMethod !== BACKUP_CODE) {
+ if (
+ this.backupCodesAvailable &&
+ this.shownSecondFactorMethod !== BACKUP_CODE
+ ) {
alts.push({
id: BACKUP_CODE,
translationKey: "login.second_factor_toggle.backup_code",
@@ -116,9 +111,9 @@ export default class SecondFactorAuthController extends Controller {
return alts;
}
- @discourseComputed("shownSecondFactorMethod")
- secondFactorTitle(shownSecondFactorMethod) {
- switch (shownSecondFactorMethod) {
+ @computed("shownSecondFactorMethod")
+ get secondFactorTitle() {
+ switch (this.shownSecondFactorMethod) {
case TOTP:
return i18n("login.second_factor_title");
case SECURITY_KEY:
@@ -128,9 +123,9 @@ export default class SecondFactorAuthController extends Controller {
}
}
- @discourseComputed("shownSecondFactorMethod")
- secondFactorDescription(shownSecondFactorMethod) {
- switch (shownSecondFactorMethod) {
+ @computed("shownSecondFactorMethod")
+ get secondFactorDescription() {
+ switch (this.shownSecondFactorMethod) {
case TOTP:
return i18n("login.second_factor_description");
case SECURITY_KEY:
@@ -140,20 +135,20 @@ export default class SecondFactorAuthController extends Controller {
}
}
- @discourseComputed("messageIsError")
- alertClass(messageIsError) {
- if (messageIsError) {
+ @computed("messageIsError")
+ get alertClass() {
+ if (this.messageIsError) {
return "alert-error";
} else {
return "alert-success";
}
}
- @discourseComputed("showTotpForm", "showBackupCodesForm")
- inputFormClass(showTotpForm, showBackupCodesForm) {
- if (showTotpForm) {
+ @computed("showTotpForm", "showBackupCodesForm")
+ get inputFormClass() {
+ if (this.showTotpForm) {
return "totp-token";
- } else if (showBackupCodesForm) {
+ } else if (this.showBackupCodesForm) {
return "backup-code-token";
}
}
@@ -229,9 +224,9 @@ export default class SecondFactorAuthController extends Controller {
);
}
- @discourseComputed("secondFactorToken")
- isSecondFactorTokenValid(secondFactorToken) {
- return secondFactorToken?.length > 0;
+ @computed("secondFactorToken")
+ get isSecondFactorTokenValid() {
+ return this.secondFactorToken?.length > 0;
}
@action
diff --git a/frontend/discourse/app/controllers/signup.js b/frontend/discourse/app/controllers/signup.js
index 81619cbaf24..dde0ffdaea9 100644
--- a/frontend/discourse/app/controllers/signup.js
+++ b/frontend/discourse/app/controllers/signup.js
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-observers */
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { notEmpty } from "@ember/object/computed";
import { service } from "@ember/service";
@@ -12,7 +12,7 @@ import { ajax } from "discourse/lib/ajax";
import { setting } from "discourse/lib/computed";
import { removeCookie } from "discourse/lib/cookie";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import NameValidationHelper from "discourse/lib/name-validation-helper";
import PasswordValidationHelper from "discourse/lib/password-validation-helper";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
@@ -125,28 +125,30 @@ export default class SignupPageController extends Controller {
}
}
- @discourseComputed("hasAuthOptions", "canCreateLocal", "skipConfirmation")
- showCreateForm(hasAuthOptions, canCreateLocal, skipConfirmation) {
- return (hasAuthOptions || canCreateLocal) && !skipConfirmation;
+ @computed("hasAuthOptions", "canCreateLocal", "skipConfirmation")
+ get showCreateForm() {
+ return (
+ (this.hasAuthOptions || this.canCreateLocal) && !this.skipConfirmation
+ );
}
- @discourseComputed("site.desktopView", "hasAuthOptions")
- showExternalLoginButtons(desktopView, hasAuthOptions) {
- return desktopView && !hasAuthOptions;
+ @computed("site.desktopView", "hasAuthOptions")
+ get showExternalLoginButtons() {
+ return this.site?.desktopView && !this.hasAuthOptions;
}
- @discourseComputed("formSubmitted")
- submitDisabled() {
+ @computed("formSubmitted")
+ get submitDisabled() {
return this.formSubmitted;
}
- @discourseComputed("userFields", "hasAtLeastOneLoginButton", "hasAuthOptions")
- bodyClasses(userFields, hasAtLeastOneLoginButton, hasAuthOptions) {
+ @computed("userFields", "hasAtLeastOneLoginButton", "hasAuthOptions")
+ get bodyClasses() {
const classes = [];
- if (userFields) {
+ if (this.userFields) {
classes.push("has-user-fields");
}
- if (hasAtLeastOneLoginButton && !hasAuthOptions) {
+ if (this.hasAtLeastOneLoginButton && !this.hasAuthOptions) {
classes.push("has-alt-auth");
}
if (!this.canCreateLocal) {
@@ -155,42 +157,40 @@ export default class SignupPageController extends Controller {
return classes.join(" ");
}
- @discourseComputed("authOptions", "authOptions.can_edit_username")
- usernameDisabled(authOptions, canEditUsername) {
- return authOptions && !canEditUsername;
+ @computed("authOptions", "authOptions.can_edit_username")
+ get usernameDisabled() {
+ return this.authOptions && !this.authOptions?.can_edit_username;
}
- @discourseComputed(
- "authOptions",
- "authOptions.can_edit_name",
- "authOptions.name"
- )
- nameDisabled(authOptions, canEditName, name) {
- return authOptions && !canEditName && name && name.length > 0;
+ @computed("authOptions", "authOptions.can_edit_name", "authOptions.name")
+ get nameDisabled() {
+ return (
+ this.authOptions &&
+ !this.authOptions?.can_edit_name &&
+ this.authOptions?.name &&
+ this.authOptions?.name?.length > 0
+ );
}
- @discourseComputed
- showFullname() {
+ @computed
+ get showFullname() {
return this.site.full_name_visible_in_signup;
}
- @discourseComputed
- fullnameRequired() {
+ @computed
+ get fullnameRequired() {
return this.site.full_name_required_for_signup;
}
- @discourseComputed(
+ @computed(
"emailValidation.ok",
"emailValidation.reason",
"emailValidationVisible"
)
- showEmailValidation(
- emailValidationOk,
- emailValidationReason,
- emailValidationVisible
- ) {
+ get showEmailValidation() {
return (
- emailValidationOk || (emailValidationReason && emailValidationVisible)
+ this.emailValidation?.ok ||
+ (this.emailValidation?.reason && this.emailValidationVisible)
);
}
@@ -209,8 +209,8 @@ export default class SignupPageController extends Controller {
return isEmpty(this.authOptions?.auth_provider);
}
- @discourseComputed
- disclaimerHtml() {
+ @computed
+ get disclaimerHtml() {
if (this.site.tos_url && this.site.privacy_policy_url) {
return i18n("create_account.disclaimer", {
tos_link: this.site.tos_url,
@@ -375,19 +375,19 @@ export default class SignupPageController extends Controller {
}
// Determines whether at least one login button is enabled
- @discourseComputed
- hasAtLeastOneLoginButton() {
+ @computed
+ get hasAtLeastOneLoginButton() {
return findAll().length > 0;
}
- @discourseComputed("authOptions", "hasAtLeastOneLoginButton")
- showRightSide(authOptions, hasAtLeastOneLoginButton) {
- return !authOptions && hasAtLeastOneLoginButton;
+ @computed("authOptions", "hasAtLeastOneLoginButton")
+ get showRightSide() {
+ return !this.authOptions && this.hasAtLeastOneLoginButton;
}
- @discourseComputed("authOptions")
- progressBarStep(authOptions) {
- return authOptions ? "activate" : "signup";
+ @computed("authOptions")
+ get progressBarStep() {
+ return this.authOptions ? "activate" : "signup";
}
fetchConfirmationValue() {
@@ -510,14 +510,14 @@ export default class SignupPageController extends Controller {
);
}
- @discourseComputed("authOptions.associate_url", "authOptions.auth_provider")
- associateHtml(url, provider) {
- if (!url) {
+ @computed("authOptions.associate_url", "authOptions.auth_provider")
+ get associateHtml() {
+ if (!this.authOptions?.associate_url) {
return;
}
return i18n("create_account.associate", {
- associate_link: url,
- provider: i18n(`login.${provider}.name`),
+ associate_link: this.authOptions?.associate_url,
+ provider: i18n(`login.${this.authOptions?.auth_provider}.name`),
});
}
diff --git a/frontend/discourse/app/controllers/tags/index.js b/frontend/discourse/app/controllers/tags/index.js
index 6fb84c307c5..f7705560d63 100644
--- a/frontend/discourse/app/controllers/tags/index.js
+++ b/frontend/discourse/app/controllers/tags/index.js
@@ -1,13 +1,12 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, notEmpty } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
import { service } from "@ember/service";
import autosize from "autosize";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { optionalRequire } from "discourse/lib/utilities";
export default class TagsIndexController extends Controller {
@@ -54,9 +53,9 @@ export default class TagsIndexController extends Controller {
);
}
- @discourseComputed("groupedByCategory", "groupedByTagGroup")
- otherTagsTitleKey(groupedByCategory, groupedByTagGroup) {
- if (!groupedByCategory && !groupedByTagGroup) {
+ @computed("groupedByCategory", "groupedByTagGroup")
+ get otherTagsTitleKey() {
+ if (!this.groupedByCategory && !this.groupedByTagGroup) {
return "tagging.all_tags";
} else {
return "tagging.other_tags";
diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.js
index e1c0728ce3f..eba22aabfc8 100644
--- a/frontend/discourse/app/controllers/topic.js
+++ b/frontend/discourse/app/controllers/topic.js
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-observers */
import { cached, tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { alias, and, not, or } from "@ember/object/computed";
import { next, schedule } from "@ember/runloop";
@@ -27,7 +27,7 @@ import {
} from "discourse/lib/array-tools";
import { BookmarkFormData } from "discourse/lib/bookmark-form-data";
import { resetCachedTopicList } from "discourse/lib/cached-topic-list";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import { wantsNewWindow } from "discourse/lib/intercept-click";
import discourseLater from "discourse/lib/later";
@@ -182,19 +182,19 @@ export default class TopicController extends Controller {
}
}
- @discourseComputed("model.postStream.loaded", "model.is_shared_draft")
- showSharedDraftControls(loaded, isSharedDraft) {
- return loaded && isSharedDraft;
+ @computed("model.postStream.loaded", "model.is_shared_draft")
+ get showSharedDraftControls() {
+ return this.model?.postStream?.loaded && this.model?.is_shared_draft;
}
- @discourseComputed("site.mobileView", "model.posts_count")
- showSelectedPostsAtBottom(mobileView, postsCount) {
- return mobileView && postsCount > 3;
+ @computed("site.mobileView", "model.posts_count")
+ get showSelectedPostsAtBottom() {
+ return this.site?.mobileView && this.model?.posts_count > 3;
}
- @discourseComputed("model")
- pmPath(topic) {
- return this.currentUser && this.currentUser.pmPath(topic);
+ @computed("model")
+ get pmPath() {
+ return this.currentUser && this.currentUser.pmPath(this.model);
}
_showRevision(postNumber, revision) {
@@ -215,18 +215,21 @@ export default class TopicController extends Controller {
DiscourseURL.routeTo(url);
}
- @discourseComputed
- selectedQuery() {
+ @computed
+ get selectedQuery() {
return (post) => this.postSelected(post);
}
- @discourseComputed("model.isPrivateMessage", "model.category.id")
- canEditTopicFeaturedLink(isPrivateMessage, categoryId) {
+ @computed("model.isPrivateMessage", "model.category.id")
+ get canEditTopicFeaturedLink() {
if (this.currentUser && this.currentUser.trust_level === 0) {
return false;
}
- if (!this.siteSettings.topic_featured_link_enabled || isPrivateMessage) {
+ if (
+ !this.siteSettings.topic_featured_link_enabled ||
+ this.model?.isPrivateMessage
+ ) {
return false;
}
@@ -236,50 +239,54 @@ export default class TopicController extends Controller {
return (
categoryIds === undefined ||
!categoryIds.length ||
- categoryIds.includes(categoryId)
+ categoryIds.includes(this.model?.category?.id)
);
}
- @discourseComputed("model")
- featuredLinkDomain(topic) {
- return extractLinkMeta(topic).domain;
+ @computed("model")
+ get featuredLinkDomain() {
+ return extractLinkMeta(this.model).domain;
}
- @discourseComputed("model.isPrivateMessage")
- canEditTags(isPrivateMessage) {
+ @computed("model.isPrivateMessage")
+ get canEditTags() {
return (
this.site.get("can_tag_topics") &&
- (!isPrivateMessage || this.site.get("can_tag_pms"))
+ (!this.model?.isPrivateMessage || this.site.get("can_tag_pms"))
);
}
- @discourseComputed("currentUser.can_send_private_messages")
- canSendPms() {
+ @computed("currentUser.can_send_private_messages")
+ get canSendPms() {
return this.currentUser?.can_send_private_messages;
}
- @discourseComputed("buffered.category_id")
- minimumRequiredTags(categoryId) {
- return Category.findById(categoryId)?.minimumRequiredTags || 0;
+ @computed("buffered.category_id")
+ get minimumRequiredTags() {
+ return (
+ Category.findById(this.get("buffered.category_id"))
+ ?.minimumRequiredTags || 0 // TODO (devxp) we need a buffered proxy that works with tracked properties
+ );
}
- @discourseComputed(
+ @computed(
"model.postStream.posts",
"model.word_count",
"model.postStream.loadingFilter"
)
- showBottomTopicMap(posts, wordCount, loading) {
+ get showBottomTopicMap() {
// filter out small posts, because they're short
const postsCount =
- posts?.filter((post) => post.post_type !== 3).length || 0;
+ this.model?.postStream?.posts?.filter((post) => post.post_type !== 3)
+ ?.length || 0;
const minWordCount = isTesting
? true
- : wordCount > MIN_BOTTOM_MAP_WORD_COUNT;
+ : this.model?.word_count > MIN_BOTTOM_MAP_WORD_COUNT;
return (
this.siteSettings.show_bottom_topic_map &&
- !loading &&
+ !this.model?.postStream?.loadingFilter &&
postsCount > MIN_POSTS_COUNT &&
minWordCount
);
@@ -1734,9 +1741,9 @@ export default class TopicController extends Controller {
}
}
- @discourseComputed("selectedAllPosts", "model.postStream.isMegaTopic")
- canSelectAll(selectedAllPosts, isMegaTopic) {
- return isMegaTopic ? false : !selectedAllPosts;
+ @computed("selectedAllPosts", "model.postStream.isMegaTopic")
+ get canSelectAll() {
+ return this.model?.postStream?.isMegaTopic ? false : !this.selectedAllPosts;
}
@dependentKeyCompat
@@ -1750,29 +1757,25 @@ export default class TopicController extends Controller {
);
}
- @discourseComputed("model.details.can_move_posts", "selectedPostsCount")
- canMergeTopic(canMovePosts, selectedPostsCount) {
- return canMovePosts && selectedPostsCount > 0;
+ @computed("model.details.can_move_posts", "selectedPostsCount")
+ get canMergeTopic() {
+ return this.model?.details?.can_move_posts && this.selectedPostsCount > 0;
}
- @discourseComputed(
+ @computed(
"currentUser.admin",
"currentUser.staff",
"siteSettings.moderators_change_post_ownership",
"selectedPostsCount",
"selectedPostsUsername"
)
- canChangeOwner(
- isAdmin,
- isStaff,
- modChangePostOwner,
- selectedPostsCount,
- selectedPostsUsername
- ) {
+ get canChangeOwner() {
return (
- (isAdmin || (modChangePostOwner && isStaff)) &&
- selectedPostsCount > 0 &&
- selectedPostsUsername !== undefined
+ (this.currentUser?.admin ||
+ (this.siteSettings?.moderators_change_post_ownership &&
+ this.currentUser?.staff)) &&
+ this.selectedPostsCount > 0 &&
+ this.selectedPostsUsername !== undefined
);
}
@@ -1795,8 +1798,8 @@ export default class TopicController extends Controller {
return this.selectedAllPost || this.selectedPostIds.includes(post.id);
}
- @discourseComputed
- loadingHTML() {
+ @computed
+ get loadingHTML() {
return spinnerHTML;
}
diff --git a/frontend/discourse/app/controllers/user-activity.js b/frontend/discourse/app/controllers/user-activity.js
index ef9b166094b..b2dc9365d5f 100644
--- a/frontend/discourse/app/controllers/user-activity.js
+++ b/frontend/discourse/app/controllers/user-activity.js
@@ -1,7 +1,7 @@
import { tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
+import { computed } from "@ember/object";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class UserActivityController extends Controller {
@@ -10,17 +10,21 @@ export default class UserActivityController extends Controller {
@tracked userActionType = null;
- @discourseComputed("currentUser.draft_count")
- draftLabel(count) {
- return count > 0
- ? i18n("drafts.label_with_count", { count })
+ @computed("currentUser.draft_count")
+ get draftLabel() {
+ return this.currentUser?.draft_count > 0
+ ? i18n("drafts.label_with_count", {
+ count: this.currentUser?.draft_count,
+ })
: i18n("drafts.label");
}
- @discourseComputed("model.pending_posts_count")
- pendingLabel(count) {
- return count > 0
- ? i18n("pending_posts.label_with_count", { count })
+ @computed("model.pending_posts_count")
+ get pendingLabel() {
+ return this.model?.pending_posts_count > 0
+ ? i18n("pending_posts.label_with_count", {
+ count: this.model?.pending_posts_count,
+ })
: i18n("pending_posts.label");
}
}
diff --git a/frontend/discourse/app/controllers/user-activity/bookmarks.js b/frontend/discourse/app/controllers/user-activity/bookmarks.js
index 00b9fb25b2f..62c2f876093 100644
--- a/frontend/discourse/app/controllers/user-activity/bookmarks.js
+++ b/frontend/discourse/app/controllers/user-activity/bookmarks.js
@@ -7,7 +7,6 @@ import { htmlSafe } from "@ember/template";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import BulkSelectHelper from "discourse/lib/bulk-select-helper";
-import discourseComputed from "discourse/lib/decorators";
import { iconHTML } from "discourse/lib/icon-library";
import Bookmark from "discourse/models/bookmark";
import { i18n } from "discourse-i18n";
@@ -42,8 +41,8 @@ export default class UserActivityBookmarksController extends Controller {
this._searchTerm = value;
}
- @discourseComputed()
- emptyStateBody() {
+ @computed()
+ get emptyStateBody() {
return htmlSafe(
i18n("user.no_bookmarks_body", {
icon: iconHTML("bookmark"),
@@ -51,14 +50,14 @@ export default class UserActivityBookmarksController extends Controller {
);
}
- @discourseComputed("inSearchMode", "noContent")
- userDoesNotHaveBookmarks(inSearchMode, noContent) {
- return !inSearchMode && noContent;
+ @computed("inSearchMode", "noContent")
+ get userDoesNotHaveBookmarks() {
+ return !this.inSearchMode && this.noContent;
}
- @discourseComputed("inSearchMode", "noContent")
- nothingFound(inSearchMode, noContent) {
- return inSearchMode && noContent;
+ @computed("inSearchMode", "noContent")
+ get nothingFound() {
+ return this.inSearchMode && this.noContent;
}
@action
diff --git a/frontend/discourse/app/controllers/user-invited.js b/frontend/discourse/app/controllers/user-invited.js
index 8f016f0512e..4a23e95d750 100644
--- a/frontend/discourse/app/controllers/user-invited.js
+++ b/frontend/discourse/app/controllers/user-invited.js
@@ -1,35 +1,35 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class UserInvitedController extends Controller {
- @discourseComputed("invitesCount.total", "invitesCount.pending")
- pendingLabel(invitesCountTotal, invitesCountPending) {
- if (invitesCountTotal > 0) {
+ @computed("invitesCount.total", "invitesCount.pending")
+ get pendingLabel() {
+ if (this.invitesCount?.total > 0) {
return i18n("user.invited.pending_tab_with_count", {
- count: invitesCountPending,
+ count: this.invitesCount?.pending,
});
} else {
return i18n("user.invited.pending_tab");
}
}
- @discourseComputed("invitesCount.total", "invitesCount.expired")
- expiredLabel(invitesCountTotal, invitesCountExpired) {
- if (invitesCountTotal > 0) {
+ @computed("invitesCount.total", "invitesCount.expired")
+ get expiredLabel() {
+ if (this.invitesCount?.total > 0) {
return i18n("user.invited.expired_tab_with_count", {
- count: invitesCountExpired,
+ count: this.invitesCount?.expired,
});
} else {
return i18n("user.invited.expired_tab");
}
}
- @discourseComputed("invitesCount.total", "invitesCount.redeemed")
- redeemedLabel(invitesCountTotal, invitesCountRedeemed) {
- if (invitesCountTotal > 0) {
+ @computed("invitesCount.total", "invitesCount.redeemed")
+ get redeemedLabel() {
+ if (this.invitesCount?.total > 0) {
return i18n("user.invited.redeemed_tab_with_count", {
- count: invitesCountRedeemed,
+ count: this.invitesCount?.redeemed,
});
} else {
return i18n("user.invited.redeemed_tab");
diff --git a/frontend/discourse/app/controllers/user-invited/show.js b/frontend/discourse/app/controllers/user-invited/show.js
index 85c0d5959eb..f663b1039cb 100644
--- a/frontend/discourse/app/controllers/user-invited/show.js
+++ b/frontend/discourse/app/controllers/user-invited/show.js
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-observers */
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal, reads } from "@ember/object/computed";
import { service } from "@ember/service";
import { observes } from "@ember-decorators/object";
@@ -9,7 +9,7 @@ import CreateInvite from "discourse/components/modal/create-invite";
import CreateInviteBulk from "discourse/components/modal/create-invite-bulk";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
-import discourseComputed, { debounce } from "discourse/lib/decorators";
+import { debounce } from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import Invite from "discourse/models/invite";
import { i18n } from "discourse-i18n";
@@ -38,9 +38,9 @@ export default class UserInvitedShowController extends Controller {
@equal("filter", "pending") invitePending;
@reads("currentUser.can_invite_to_forum") canInviteToForum;
- @discourseComputed("currentUser.admin", "siteSettings.allow_bulk_invite")
- canBulkInvite(isAdmin, allowBulkInvite) {
- return isAdmin && allowBulkInvite;
+ @computed("currentUser.admin", "siteSettings.allow_bulk_invite")
+ get canBulkInvite() {
+ return this.currentUser?.admin && this.siteSettings?.allow_bulk_invite;
}
@observes("searchTerm")
@@ -55,21 +55,21 @@ export default class UserInvitedShowController extends Controller {
);
}
- @discourseComputed("model")
- hasEmailInvites(model) {
- return model.invites.some((invite) => {
+ @computed("model")
+ get hasEmailInvites() {
+ return this.model.invites.some((invite) => {
return invite.email;
});
}
- @discourseComputed("model")
- showBulkActionButtons(model) {
- return model.invites.length > 0 && this.currentUser.staff;
+ @computed("model")
+ get showBulkActionButtons() {
+ return this.model.invites.length > 0 && this.currentUser.staff;
}
- @discourseComputed("invitesCount", "filter")
- showSearch(invitesCount, filter) {
- return invitesCount[filter] > 5;
+ @computed("invitesCount", "filter")
+ get showSearch() {
+ return this.invitesCount[this.filter] > 5;
}
@action
diff --git a/frontend/discourse/app/controllers/user-topics-list.js b/frontend/discourse/app/controllers/user-topics-list.js
index a6710a88675..68af1d52a35 100644
--- a/frontend/discourse/app/controllers/user-topics-list.js
+++ b/frontend/discourse/app/controllers/user-topics-list.js
@@ -1,12 +1,11 @@
import { tracked } from "@glimmer/tracking";
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { or } from "@ember/object/computed";
import { isNone } from "@ember/utils";
import { popupAjaxError } from "discourse/lib/ajax-error";
import BulkSelectHelper from "discourse/lib/bulk-select-helper";
-import discourseComputed from "discourse/lib/decorators";
import { defineTrackedProperty } from "discourse/lib/tracked-tools";
import Topic from "discourse/models/topic";
import {
@@ -52,19 +51,19 @@ export default class UserTopicsListController extends Controller {
return this.bulkSelectHelper.selected;
}
- @discourseComputed("model.topics.length", "incomingCount")
- noContent(topicsLength, incomingCount) {
- return topicsLength === 0 && incomingCount === 0;
+ @computed("model.topics.length", "incomingCount")
+ get noContent() {
+ return this.model?.topics?.length === 0 && this.incomingCount === 0;
}
- @discourseComputed("filter", "model.topics.length")
- showResetNew(filter, hasTopics) {
- return filter === NEW_FILTER && hasTopics;
+ @computed("filter", "model.topics.length")
+ get showResetNew() {
+ return this.filter === NEW_FILTER && this.model?.topics?.length;
}
- @discourseComputed("filter", "model.topics.length")
- showDismissRead(filter, hasTopics) {
- return filter === UNREAD_FILTER && hasTopics;
+ @computed("filter", "model.topics.length")
+ get showDismissRead() {
+ return this.filter === UNREAD_FILTER && this.model?.topics?.length;
}
subscribe() {
diff --git a/frontend/discourse/app/controllers/user.js b/frontend/discourse/app/controllers/user.js
index 9e4246c731c..d332b3cc939 100644
--- a/frontend/discourse/app/controllers/user.js
+++ b/frontend/discourse/app/controllers/user.js
@@ -6,7 +6,6 @@ import { dasherize } from "@ember/string";
import { compare, isEmpty } from "@ember/utils";
import CanCheckEmailsHelper from "discourse/lib/can-check-emails-helper";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import optionalService from "discourse/lib/optional-service";
import { prioritizeNameInUx } from "discourse/lib/settings";
@@ -52,32 +51,35 @@ export default class UserController extends Controller {
@and("model.can_be_deleted", "model.can_delete_all_posts") canDeleteUser;
@readOnly("router.currentRoute.parent.name") currentParentRoute;
- @discourseComputed("model.username")
- viewingSelf(username) {
- return this.currentUser && username === this.currentUser?.get("username");
+ @computed("model.username")
+ get viewingSelf() {
+ return (
+ this.currentUser &&
+ this.model?.username === this.currentUser?.get("username")
+ );
}
- @discourseComputed("viewingSelf", "model.profile_hidden")
- canExpandProfile(viewingSelf, profileHidden) {
- return !profileHidden && viewingSelf;
+ @computed("viewingSelf", "model.profile_hidden")
+ get canExpandProfile() {
+ return !this.model?.profile_hidden && this.viewingSelf;
}
- @discourseComputed("model.profileBackgroundUrl")
- hasProfileBackgroundUrl(background) {
- return !isEmpty(background.toString());
+ @computed("model.profileBackgroundUrl")
+ get hasProfileBackgroundUrl() {
+ return !isEmpty(this.model?.profileBackgroundUrl?.toString());
}
- @discourseComputed(
+ @computed(
"model.profile_hidden",
"isSummaryRoute",
"viewingSelf",
"forceExpand"
)
- collapsedInfo(profileHidden, isSummaryRoute, viewingSelf, forceExpand) {
- if (profileHidden) {
+ get collapsedInfo() {
+ if (this.model?.profile_hidden) {
return true;
}
- return (!isSummaryRoute || viewingSelf) && !forceExpand;
+ return (!this.isSummaryRoute || this.viewingSelf) && !this.forceExpand;
}
@computed("collapsedInfo")
@@ -93,69 +95,79 @@ export default class UserController extends Controller {
};
}
- @discourseComputed("model.suspended", "model.silenced", "currentUser.staff")
- isNotRestrictedOrIsStaff(suspended, silenced, isStaff) {
- return (!suspended && !silenced) || isStaff;
+ @computed("model.suspended", "model.silenced", "currentUser.staff")
+ get isNotRestrictedOrIsStaff() {
+ return (
+ (!this.model?.suspended && !this.model?.silenced) ||
+ this.currentUser?.staff
+ );
}
- @discourseComputed("model.trust_level")
- removeNoFollow(trustLevel) {
- return trustLevel > 2 && !this.siteSettings.tl3_links_no_follow;
+ @computed("model.trust_level")
+ get removeNoFollow() {
+ return (
+ this.model?.trust_level > 2 && !this.siteSettings.tl3_links_no_follow
+ );
}
- @discourseComputed("viewingSelf", "currentUser.admin")
- showBookmarks(viewingSelf, isAdmin) {
- return viewingSelf || isAdmin;
+ @computed("viewingSelf", "currentUser.admin")
+ get showBookmarks() {
+ return this.viewingSelf || this.currentUser?.admin;
}
- @discourseComputed("viewingSelf")
- showDrafts(viewingSelf) {
- return viewingSelf;
+ @computed("viewingSelf")
+ get showDrafts() {
+ return this.viewingSelf;
}
- @discourseComputed("viewingSelf")
- showRead(viewingSelf) {
- return viewingSelf;
+ @computed("viewingSelf")
+ get showRead() {
+ return this.viewingSelf;
}
- @discourseComputed(
+ @computed(
"viewingSelf",
"currentUser.admin",
"currentUser.can_send_private_messages"
)
- showPrivateMessages(viewingSelf, isAdmin) {
+ get showPrivateMessages() {
return (
- this.currentUser?.can_send_private_messages && (viewingSelf || isAdmin)
+ this.currentUser?.can_send_private_messages &&
+ (this.viewingSelf || this.currentUser?.admin)
);
}
- @discourseComputed("viewingSelf", "currentUser.admin")
- showActivityTab(viewingSelf, isAdmin) {
- return viewingSelf || isAdmin || !this.siteSettings.hide_user_activity_tab;
+ @computed("viewingSelf", "currentUser.admin")
+ get showActivityTab() {
+ return (
+ this.viewingSelf ||
+ this.currentUser?.admin ||
+ !this.siteSettings.hide_user_activity_tab
+ );
}
- @discourseComputed("viewingSelf", "currentUser.admin")
- showNotificationsTab(viewingSelf, isAdmin) {
- return viewingSelf || isAdmin;
+ @computed("viewingSelf", "currentUser.admin")
+ get showNotificationsTab() {
+ return this.viewingSelf || this.currentUser?.admin;
}
- @discourseComputed("model.name")
- nameFirst(name) {
- return prioritizeNameInUx(name);
+ @computed("model.name")
+ get nameFirst() {
+ return prioritizeNameInUx(this.model?.name);
}
- @discourseComputed("model.badge_count")
- showBadges(badgeCount) {
- return this.siteSettings.enable_badges && badgeCount > 0;
+ @computed("model.badge_count")
+ get showBadges() {
+ return this.siteSettings.enable_badges && this.model?.badge_count > 0;
}
- @discourseComputed()
- canInviteToForum() {
+ @computed()
+ get canInviteToForum() {
return this.currentUser?.get("can_invite_to_forum");
}
- @discourseComputed("[email protected]")
- publicUserFields() {
+ @computed("[email protected]")
+ get publicUserFields() {
const siteUserFields = this.site.get("user_fields");
if (!isEmpty(siteUserFields)) {
const userFields = this.get("model.user_fields");
@@ -173,10 +185,10 @@ export default class UserController extends Controller {
}
}
- @discourseComputed("model.primary_group_name")
- primaryGroup(group) {
- if (group) {
- return `group-${group}`;
+ @computed("model.primary_group_name")
+ get primaryGroup() {
+ if (this.model?.primary_group_name) {
+ return `group-${this.model?.primary_group_name}`;
}
}
diff --git a/frontend/discourse/app/controllers/user/badges.js b/frontend/discourse/app/controllers/user/badges.js
index f44195f9778..7dcb6125dca 100644
--- a/frontend/discourse/app/controllers/user/badges.js
+++ b/frontend/discourse/app/controllers/user/badges.js
@@ -1,7 +1,6 @@
import Controller, { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias, filterBy, sort } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
export default class UserBadgesController extends Controller {
@controller user;
@@ -12,9 +11,9 @@ export default class UserBadgesController extends Controller {
badgeSortOrder = ["grouping_position", "badge.badge_type_id", "badge.id"];
- @discourseComputed("favoriteBadges.length")
- canFavoriteMoreBadges(favoriteBadgesCount) {
- return favoriteBadgesCount < this.siteSettings.max_favorite_badges;
+ @computed("favoriteBadges.length")
+ get canFavoriteMoreBadges() {
+ return this.favoriteBadges?.length < this.siteSettings.max_favorite_badges;
}
@action
diff --git a/frontend/discourse/app/controllers/user/summary.js b/frontend/discourse/app/controllers/user/summary.js
index 8948133a791..cfe68f1bead 100644
--- a/frontend/discourse/app/controllers/user/summary.js
+++ b/frontend/discourse/app/controllers/user/summary.js
@@ -1,6 +1,6 @@
import Controller, { inject as controller } from "@ember/controller";
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
import { duration } from "discourse/lib/formatter";
// should be kept in sync with 'UserSummary::MAX_BADGES'
@@ -11,37 +11,40 @@ export default class UserSummaryController extends Controller {
@alias("userController.model") user;
- @discourseComputed("model.badges.length")
- moreBadges(badgesLength) {
- return badgesLength >= MAX_BADGES;
+ @computed("model.badges.length")
+ get moreBadges() {
+ return this.model?.badges?.length >= MAX_BADGES;
}
- @discourseComputed("model.time_read")
- timeRead(timeReadSeconds) {
- return duration(timeReadSeconds, { format: "tiny" });
+ @computed("model.time_read")
+ get timeRead() {
+ return duration(this.model?.time_read, { format: "tiny" });
}
- @discourseComputed("model.time_read")
- timeReadMedium(timeReadSeconds) {
- return duration(timeReadSeconds, { format: "medium" });
+ @computed("model.time_read")
+ get timeReadMedium() {
+ return duration(this.model?.time_read, { format: "medium" });
}
- @discourseComputed("model.time_read", "model.recent_time_read")
- showRecentTimeRead(timeRead, recentTimeRead) {
- return timeRead !== recentTimeRead && recentTimeRead !== 0;
+ @computed("model.time_read", "model.recent_time_read")
+ get showRecentTimeRead() {
+ return (
+ this.model?.time_read !== this.model?.recent_time_read &&
+ this.model?.recent_time_read !== 0
+ );
}
- @discourseComputed("model.recent_time_read")
- recentTimeRead(recentTimeReadSeconds) {
- return recentTimeReadSeconds > 0
- ? duration(recentTimeReadSeconds, { format: "tiny" })
+ @computed("model.recent_time_read")
+ get recentTimeRead() {
+ return this.model?.recent_time_read > 0
+ ? duration(this.model?.recent_time_read, { format: "tiny" })
: null;
}
- @discourseComputed("model.recent_time_read")
- recentTimeReadMedium(recentTimeReadSeconds) {
- return recentTimeReadSeconds > 0
- ? duration(recentTimeReadSeconds, { format: "medium" })
+ @computed("model.recent_time_read")
+ get recentTimeReadMedium() {
+ return this.model?.recent_time_read > 0
+ ? duration(this.model?.recent_time_read, { format: "medium" })
: null;
}
}
diff --git a/frontend/discourse/app/lib/computed.js b/frontend/discourse/app/lib/computed.js
index a8db2da5317..af371623a2a 100644
--- a/frontend/discourse/app/lib/computed.js
+++ b/frontend/discourse/app/lib/computed.js
@@ -35,7 +35,7 @@ function addonFmt(str, formats) {
@method propertyEqual
@params {String} p1 the first property
@params {String} p2 the second property
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function propertyEqual(p1, p2) {
@@ -50,7 +50,7 @@ export function propertyEqual(p1, p2) {
@method propertyNotEqual
@params {String} p1 the first property
@params {String} p2 the second property
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function propertyNotEqual(p1, p2) {
return computed(p1, p2, function () {
@@ -76,7 +76,7 @@ export function propertyLessThan(p1, p2) {
@method computedI18n
@params {String} properties* to format
@params {String} format the i18n format string
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function computedI18n(...args) {
const format = args.pop();
@@ -92,7 +92,7 @@ export { computedI18n as i18n };
@method htmlSafe
@params {String} properties* to htmlify
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function htmlSafe(...args) {
return computed(...args, {
@@ -110,7 +110,7 @@ export function htmlSafe(...args) {
@method fmt
@params {String} properties* to format
@params {String} format the format string
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function fmt(...args) {
const format = args.pop();
@@ -126,7 +126,7 @@ export function fmt(...args) {
@method url
@params {String} properties* to format
@params {String} format the format string for the URL
- @return {Function} discourseComputedProperty function returning a URL
+ @return {Function} computedProperty function returning a URL
**/
export function url(...args) {
const format = args.pop();
@@ -141,7 +141,7 @@ export function url(...args) {
@method endWith
@params {String} properties* to check
@params {String} substring the substring
- @return {Function} discourseComputedProperty function
+ @return {Function} computedProperty function
**/
export function endWith() {
const args = Array.prototype.slice.call(arguments, 0);
diff --git a/frontend/discourse/app/lib/decorator-alias.js b/frontend/discourse/app/lib/decorator-alias.js
index 36245d89f58..5c21a12ce28 100644
--- a/frontend/discourse/app/lib/decorator-alias.js
+++ b/frontend/discourse/app/lib/decorator-alias.js
@@ -2,7 +2,7 @@ import extractValue from "discourse/lib/extract-value";
export default function decoratorAlias(fn, errorMessage) {
return function (...params) {
- // determine if user called as @discourseComputed('blah', 'blah') or @discourseComputed
+ // determine if user called as @decorator('blah', 'blah') or @decorator
if (params.length === 0) {
throw new Error(errorMessage);
} else {
diff --git a/frontend/discourse/app/lib/decorators.js b/frontend/discourse/app/lib/decorators.js
index 57edbfe74db..f608b5ec37e 100644
--- a/frontend/discourse/app/lib/decorators.js
+++ b/frontend/discourse/app/lib/decorators.js
@@ -44,6 +44,60 @@ import handleDescriptor from "discourse/lib/handle-descriptor";
import isDescriptor from "discourse/lib/is-descriptor";
import macroAlias from "discourse/lib/macro-alias";
+/**
+ * A decorator that creates computed properties with dependent keys.
+ * This decorator allows you to define computed properties that automatically
+ * update when their dependent properties change.
+ *
+ * @deprecated Use `@tracked` properties with native getters or the standard `@computed`
+ * decorator from `@ember/object` instead.
+ *
+ * @param {...(string|PropertyDescriptor)} params - Either dependent property keys as strings,
+ * or a property descriptor when used without arguments
+ * @returns {PropertyDescriptor|Function} A property descriptor or decorator function
+ *
+ * @example
+ * // Usage with dependent keys
+ * class MyComponent {
+ * @discourseComputed('firstName', 'lastName')
+ * fullName(firstName, lastName) {
+ * return `${firstName} ${lastName}`;
+ * }
+ * }
+ *
+ * @example
+ * // Usage without arguments
+ * class MyComponent {
+ * @discourseComputed
+ * currentTime() {
+ * return new Date();
+ * }
+ * }
+ *
+ * @example
+ * // Recommended alternative with @computed from @ember/object
+ * import { computed } from '@ember/object';
+ *
+ * class MyComponent {
+ * @computed('firstName', 'lastName')
+ * get fullName() {
+ * return `${this.firstName} ${this.lastName}`;
+ * }
+ * }
+ *
+ * @example
+ * // Recommended alternative with @tracked properties
+ * import { tracked } from '@glimmer/tracking';
+ *
+ * class MyComponent {
+ * @tracked firstName;
+ * @tracked lastName;
+ *
+ * get fullName() {
+ * return `${this.firstName} ${this.lastName}`;
+ * }
+ * }
+ */
export default function discourseComputedDecorator(...params) {
// determine if user called as @discourseComputed('blah', 'blah') or @discourseComputed
if (isDescriptor(params[params.length - 1])) {
diff --git a/frontend/discourse/app/lib/register-topic-footer-button.js b/frontend/discourse/app/lib/register-topic-footer-button.js
index ee441b494df..c7819122d5e 100644
--- a/frontend/discourse/app/lib/register-topic-footer-button.js
+++ b/frontend/discourse/app/lib/register-topic-footer-button.js
@@ -38,7 +38,7 @@ export function registerTopicFooterButton(button) {
// css class appended to the button
classNames: [],
- // discourseComputed properties which should force a button state refresh
+ // computed properties which should force a button state refresh
// eg: ["topic.bookmarked", "topic.category_id"]
dependentKeys: [],
diff --git a/frontend/discourse/app/lib/register-topic-footer-dropdown.js b/frontend/discourse/app/lib/register-topic-footer-dropdown.js
index e6457435a0a..aa1ec598bb6 100644
--- a/frontend/discourse/app/lib/register-topic-footer-dropdown.js
+++ b/frontend/discourse/app/lib/register-topic-footer-dropdown.js
@@ -24,7 +24,7 @@ export function registerTopicFooterDropdown(dropdown) {
// css class appended to the button
classNames: [],
- // discourseComputed properties which should force a button state refresh
+ // computed properties which should force a button state refresh
// eg: ["topic.bookmarked", "topic.category_id"]
dependentKeys: [],
diff --git a/frontend/discourse/app/models/badge-grouping.js b/frontend/discourse/app/models/badge-grouping.js
index dfa6f596913..0a1f39f7945 100644
--- a/frontend/discourse/app/models/badge-grouping.js
+++ b/frontend/discourse/app/models/badge-grouping.js
@@ -1,15 +1,15 @@
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
export default class BadgeGrouping extends RestModel {
- @discourseComputed("name")
- i18nNameKey() {
+ @computed("name")
+ get i18nNameKey() {
return this.name.toLowerCase().replace(/\s/g, "_");
}
- @discourseComputed("name")
- displayName() {
+ @computed("name")
+ get displayName() {
const i18nKey = `badges.badge_grouping.${this.i18nNameKey}.name`;
return i18n(i18nKey, { defaultValue: this.name });
}
diff --git a/frontend/discourse/app/models/badge.js b/frontend/discourse/app/models/badge.js
index 09c5c827562..0f67fde3775 100644
--- a/frontend/discourse/app/models/badge.js
+++ b/frontend/discourse/app/models/badge.js
@@ -1,8 +1,7 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { alias, none } from "@ember/object/computed";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import BadgeGrouping from "discourse/models/badge-grouping";
import RestModel from "discourse/models/rest";
@@ -71,8 +70,8 @@ export default class Badge extends RestModel {
@alias("image_url") image;
- @discourseComputed
- url() {
+ @computed
+ get url() {
return getURL(`/badges/${this.id}/${this.slug}`);
}
@@ -89,9 +88,9 @@ export default class Badge extends RestModel {
}
}
- @discourseComputed("badge_type.name")
- badgeTypeClassName(type) {
- type = type || "";
+ @computed("badge_type.name")
+ get badgeTypeClassName() {
+ const type = this.badge_type?.name || "";
return `badge-type-${type.toLowerCase()}`;
}
diff --git a/frontend/discourse/app/models/bookmark.js b/frontend/discourse/app/models/bookmark.js
index 687361e5a67..8178e541c94 100644
--- a/frontend/discourse/app/models/bookmark.js
+++ b/frontend/discourse/app/models/bookmark.js
@@ -5,7 +5,6 @@ import { isEmpty } from "@ember/utils";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { formattedReminderTime } from "discourse/lib/bookmark";
-import discourseComputed from "discourse/lib/decorators";
import { longDate } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
import { applyModelTransformations } from "discourse/lib/model-transformers";
@@ -97,11 +96,11 @@ export default class Bookmark extends RestModel {
return this.pinned ? "unpin" : "pin";
}
- @discourseComputed("topic_id", "highest_post_number", "bookmarkable_url")
- lastPostUrl(topic_id, highest_post_number, bookmarkable_url) {
- return topic_id
- ? this.urlForPostNumber(highest_post_number)
- : bookmarkable_url;
+ @computed("topic_id", "highest_post_number", "bookmarkable_url")
+ get lastPostUrl() {
+ return this.topic_id
+ ? this.urlForPostNumber(this.highest_post_number)
+ : this.bookmarkable_url;
}
urlForPostNumber(postNumber) {
@@ -112,58 +111,58 @@ export default class Bookmark extends RestModel {
return url;
}
- @discourseComputed("bumped_at", "createdAt")
- bumpedAt(bumped_at, createdAt) {
- return bumped_at ? new Date(bumped_at) : createdAt;
+ @computed("bumped_at", "createdAt")
+ get bumpedAt() {
+ return this.bumped_at ? new Date(this.bumped_at) : this.createdAt;
}
- @discourseComputed("bumpedAt", "createdAt")
- bumpedAtTitle(bumpedAt, createdAt) {
+ @computed("bumpedAt", "createdAt")
+ get bumpedAtTitle() {
const BUMPED_FORMAT = "YYYY-MM-DDTHH:mm:ss";
- if (moment(bumpedAt).isValid() && moment(createdAt).isValid()) {
- const bumpedAtStr = moment(bumpedAt).format(BUMPED_FORMAT);
- const createdAtStr = moment(createdAt).format(BUMPED_FORMAT);
+ if (moment(this.bumpedAt).isValid() && moment(this.createdAt).isValid()) {
+ const bumpedAtStr = moment(this.bumpedAt).format(BUMPED_FORMAT);
+ const createdAtStr = moment(this.createdAt).format(BUMPED_FORMAT);
return bumpedAtStr !== createdAtStr
? `${i18n("topic.created_at", {
- date: longDate(createdAt),
- })}\n${i18n("topic.bumped_at", { date: longDate(bumpedAt) })}`
- : i18n("topic.created_at", { date: longDate(createdAt) });
+ date: longDate(this.createdAt),
+ })}\n${i18n("topic.bumped_at", { date: longDate(this.bumpedAt) })}`
+ : i18n("topic.created_at", { date: longDate(this.createdAt) });
}
}
- @discourseComputed("name", "reminder_at")
- reminderTitle(name, reminderAt) {
- if (!isEmpty(reminderAt)) {
+ @computed("name", "reminder_at")
+ get reminderTitle() {
+ if (!isEmpty(this.reminder_at)) {
return i18n("bookmarks.created_with_reminder_generic", {
date: formattedReminderTime(
- reminderAt,
+ this.reminder_at,
this.currentUser?.user_option?.timezone || moment.tz.guess()
),
- name: name || "",
+ name: this.name || "",
});
}
return i18n("bookmarks.created_generic", {
- name: name || "",
+ name: this.name || "",
});
}
- @discourseComputed("created_at")
- createdAt(created_at) {
- return new Date(created_at);
+ @computed("created_at")
+ get createdAt() {
+ return new Date(this.created_at);
}
- @discourseComputed("tags")
- visibleListTags(tags) {
- if (!tags || !this.siteSettings.suppress_overlapping_tags_in_list) {
- return tags;
+ @computed("tags")
+ get visibleListTags() {
+ if (!this.tags || !this.siteSettings.suppress_overlapping_tags_in_list) {
+ return this.tags;
}
const title = this.title;
const newTags = [];
- tags.forEach(function (tag) {
+ this.tags.forEach(function (tag) {
if (!title.toLowerCase().includes(tag)) {
newTags.push(tag);
}
@@ -177,23 +176,23 @@ export default class Bookmark extends RestModel {
return Category.findById(this.category_id);
}
- @discourseComputed("reminder_at", "currentUser")
- formattedReminder(bookmarkReminderAt, currentUser) {
+ @computed("reminder_at", "currentUser")
+ get formattedReminder() {
return capitalize(
formattedReminderTime(
- bookmarkReminderAt,
- currentUser?.user_option?.timezone || moment.tz.guess()
+ this.reminder_at,
+ this.currentUser?.user_option?.timezone || moment.tz.guess()
)
);
}
- @discourseComputed("reminder_at")
- reminderAtExpired(bookmarkReminderAt) {
- return moment(bookmarkReminderAt) < moment();
+ @computed("reminder_at")
+ get reminderAtExpired() {
+ return moment(this.reminder_at) < moment();
}
- @discourseComputed()
- topicForList() {
+ @computed()
+ get topicForList() {
// for topic level bookmarks we want to jump to the last unread post URL,
// which the topic-link helper does by default if no linked post number is
// provided
@@ -209,13 +208,13 @@ export default class Bookmark extends RestModel {
});
}
- @discourseComputed("bookmarkable_type")
- bookmarkableTopicAlike(bookmarkable_type) {
- return ["Topic", "Post"].includes(bookmarkable_type);
+ @computed("bookmarkable_type")
+ get bookmarkableTopicAlike() {
+ return ["Topic", "Post"].includes(this.bookmarkable_type);
}
- @discourseComputed("reminder_at", "name")
- hasMetadata() {
+ @computed("reminder_at", "name")
+ get hasMetadata() {
return this.reminder_at || this.name;
}
}
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.js
index d682ba27cfb..86a5a8b86df 100644
--- a/frontend/discourse/app/models/category.js
+++ b/frontend/discourse/app/models/category.js
@@ -11,7 +11,6 @@ import {
removeValueFromArray,
} from "discourse/lib/array-tools";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import getURL from "discourse/lib/get-url";
import { MultiCache } from "discourse/lib/multi-cache";
@@ -583,8 +582,8 @@ export default class Category extends RestModel {
}
}
- @discourseComputed
- availablePermissions() {
+ @computed
+ get availablePermissions() {
return [
PermissionType.create({ id: PermissionType.FULL }),
PermissionType.create({ id: PermissionType.CREATE_POST }),
@@ -592,25 +591,28 @@ export default class Category extends RestModel {
];
}
- @discourseComputed("id")
- searchContext(id) {
+ @computed("id")
+ get searchContext() {
return {
type: "category",
- id,
+ id: this.id,
/** @type Category */
category: this,
};
}
- @discourseComputed("parentCategory.ancestors")
- ancestors(parentAncestors) {
- return [...(parentAncestors || []), this];
+ @computed("parentCategory.ancestors")
+ get ancestors() {
+ return [...(this.parentCategory?.ancestors || []), this];
}
- @discourseComputed("parentCategory", "parentCategory.predecessors")
- predecessors(parentCategory, parentPredecessors) {
- if (parentCategory) {
- return [parentCategory, ...parentPredecessors];
+ @computed("parentCategory", "parentCategory.predecessors")
+ get predecessors() {
+ if (this.parentCategory) {
+ return [
+ this.parentCategory,
+ ...(this.parentCategory?.predecessors || []),
+ ];
} else {
return [];
}
@@ -626,134 +628,139 @@ export default class Category extends RestModel {
return descendants;
}
- @discourseComputed("parentCategory.level")
- level(parentLevel) {
- if (!parentLevel) {
- return parentLevel === 0 ? 1 : 0;
+ @computed("parentCategory.level")
+ get level() {
+ if (!this.parentCategory?.level) {
+ return this.parentCategory?.level === 0 ? 1 : 0;
} else {
- return parentLevel + 1;
+ return this.parentCategory?.level + 1;
}
}
- @discourseComputed("has_children", "subcategories")
- isParent(hasChildren, subcategories) {
- return hasChildren || (subcategories && subcategories.length > 0);
+ @computed("has_children", "subcategories")
+ get isParent() {
+ return (
+ this.has_children || (this.subcategories && this.subcategories.length > 0)
+ );
}
- @discourseComputed("subcategories")
- isGrandParent(subcategories) {
+ @computed("subcategories")
+ get isGrandParent() {
return (
- subcategories &&
- subcategories.some(
+ this.subcategories &&
+ this.subcategories.some(
(cat) => cat.subcategories && cat.subcategories.length > 0
)
);
}
- @discourseComputed("notification_level")
- isMuted(notificationLevel) {
- return notificationLevel === NotificationLevels.MUTED;
+ @computed("notification_level")
+ get isMuted() {
+ return this.notification_level === NotificationLevels.MUTED;
}
- @discourseComputed("isMuted", "subcategories")
- isHidden(isMuted, subcategories) {
- if (!isMuted) {
+ @computed("isMuted", "subcategories")
+ get isHidden() {
+ if (!this.isMuted) {
return false;
- } else if (!subcategories) {
+ } else if (!this.subcategories) {
return true;
}
- if (subcategories.some((cat) => !cat.isHidden)) {
+ if (this.subcategories.some((cat) => !cat.isHidden)) {
return false;
}
return true;
}
- @discourseComputed("isMuted", "subcategories")
- hasMuted(isMuted, subcategories) {
- if (isMuted) {
+ @computed("isMuted", "subcategories")
+ get hasMuted() {
+ if (this.isMuted) {
return true;
- } else if (!subcategories) {
+ } else if (!this.subcategories) {
return false;
}
- if (subcategories.some((cat) => cat.hasMuted)) {
+ if (this.subcategories.some((cat) => cat.hasMuted)) {
return true;
}
return false;
}
- @discourseComputed("notification_level")
- notificationLevelString(notificationLevel) {
+ @computed("notification_level")
+ get notificationLevelString() {
// Get the key from the value
const notificationLevelString = Object.keys(NotificationLevels).find(
- (key) => NotificationLevels[key] === notificationLevel
+ (key) => NotificationLevels[key] === this.notification_level
);
if (notificationLevelString) {
return notificationLevelString.toLowerCase();
}
}
- @discourseComputed("name")
- path() {
+ @computed("name")
+ get path() {
return `/c/${Category.slugFor(this)}/${this.id}`;
}
- @discourseComputed("path")
- url(path) {
- return getURL(path);
+ @computed("path")
+ get url() {
+ return getURL(this.path);
}
- @discourseComputed
- fullSlug() {
+ @computed
+ get fullSlug() {
return Category.slugFor(this).replace(/\//g, "-");
}
- @discourseComputed("name")
- nameLower(name) {
- return name.toLowerCase();
+ @computed("name")
+ get nameLower() {
+ return this.name.toLowerCase();
}
- @discourseComputed("url")
- unreadUrl(url) {
- return `${url}/l/unread`;
+ @computed("url")
+ get unreadUrl() {
+ return `${this.url}/l/unread`;
}
- @discourseComputed("url")
- newUrl(url) {
- return `${url}/l/new`;
+ @computed("url")
+ get newUrl() {
+ return `${this.url}/l/new`;
}
- @discourseComputed("color", "text_color")
- style(color, textColor) {
- return `background-color: #${color}; color: #${textColor}`;
+ @computed("color", "text_color")
+ get style() {
+ return `background-color: #${this.color}; color: #${this.text_color}`;
}
- @discourseComputed("topic_count")
- moreTopics(topicCount) {
- return topicCount > (this.num_featured_topics || 2);
+ @computed("topic_count")
+ get moreTopics() {
+ return this.topic_count > (this.num_featured_topics || 2);
}
- @discourseComputed("topic_count", "subcategories.[]")
- totalTopicCount(topicCount, subcategories) {
- if (subcategories) {
- subcategories.forEach((subcategory) => {
+ @computed("topic_count", "subcategories.[]")
+ get totalTopicCount() {
+ let topicCount = this.topic_count;
+ if (this.subcategories) {
+ this.subcategories.forEach((subcategory) => {
topicCount += subcategory.topic_count;
});
}
return topicCount;
}
- @discourseComputed("default_slow_mode_seconds")
- defaultSlowModeMinutes(seconds) {
- return seconds ? seconds / 60 : null;
+ @computed("default_slow_mode_seconds")
+ get defaultSlowModeMinutes() {
+ return this.default_slow_mode_seconds
+ ? this.default_slow_mode_seconds / 60
+ : null;
}
- @discourseComputed("notification_level")
- isTracked(notificationLevel) {
- return notificationLevel >= NotificationLevels.TRACKING;
+ @computed("notification_level")
+ get isTracked() {
+ return this.notification_level >= NotificationLevels.TRACKING;
}
get unreadTopicsCount() {
@@ -888,17 +895,17 @@ export default class Category extends RestModel {
});
}
- @discourseComputed("topics")
- latestTopic(topics) {
- if (topics && topics.length) {
- return topics[0];
+ @computed("topics")
+ get latestTopic() {
+ if (this.topics && this.topics.length) {
+ return this.topics[0];
}
}
- @discourseComputed("topics")
- featuredTopics(topics) {
- if (topics && topics.length) {
- return topics.slice(0, this.num_featured_topics || 2);
+ @computed("topics")
+ get featuredTopics() {
+ if (this.topics && this.topics.length) {
+ return this.topics.slice(0, this.num_featured_topics || 2);
}
}
@@ -925,9 +932,9 @@ export default class Category extends RestModel {
);
}
- @discourseComputed("id")
- isUncategorizedCategory(id) {
- return Category.isUncategorized(id);
+ @computed("id")
+ get isUncategorizedCategory() {
+ return Category.isUncategorized(this.id);
}
get canCreateTopic() {
diff --git a/frontend/discourse/app/models/composer.js b/frontend/discourse/app/models/composer.js
index 6d018c8cf09..ab47de357db 100644
--- a/frontend/discourse/app/models/composer.js
+++ b/frontend/discourse/app/models/composer.js
@@ -1,6 +1,6 @@
/* eslint-disable ember/no-observers */
import { tracked } from "@glimmer/tracking";
-import EmberObject, { set } from "@ember/object";
+import EmberObject, { computed, set } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { and, equal, not, or, reads } from "@ember/object/computed";
import { next, throttle } from "@ember/runloop";
@@ -11,7 +11,6 @@ import { observes, on } from "@ember-decorators/object";
import { Promise } from "rsvp";
import { extractError, throwAjaxError } from "discourse/lib/ajax-error";
import { tinyAvatar } from "discourse/lib/avatar-utils";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { QUOTE_REGEXP } from "discourse/lib/quote";
import { prioritizeNameFallback } from "discourse/lib/settings";
@@ -248,19 +247,19 @@ export default class Composer extends RestModel {
@tracked _categoryId = null;
- @discourseComputed("reply", "originalText")
- replyDirty(reply, original) {
- return (reply || "").trim() !== (original || "").trim();
+ @computed("reply", "originalText")
+ get replyDirty() {
+ return (this.reply || "").trim() !== (this.originalText || "").trim();
}
- @discourseComputed("title", "originalTitle")
- titleDirty(title, original) {
- return (title || "").trim() !== (original || "").trim();
+ @computed("title", "originalTitle")
+ get titleDirty() {
+ return (this.title || "").trim() !== (this.originalTitle || "").trim();
}
- @discourseComputed("replyDirty", "titleDirty", "hasMetaData")
- anyDirty(replyDirty, titleDirty, hasMetaData) {
- return replyDirty || titleDirty || hasMetaData;
+ @computed("replyDirty", "titleDirty", "hasMetaData")
+ get anyDirty() {
+ return this.replyDirty || this.titleDirty || this.hasMetaData;
}
@dependentKeyCompat
@@ -299,9 +298,9 @@ export default class Composer extends RestModel {
}
}
- @discourseComputed("categoryId")
- category(categoryId) {
- return categoryId ? Category.findById(categoryId) : null;
+ @computed("categoryId")
+ get category() {
+ return this.categoryId ? Category.findById(this.categoryId) : null;
}
@dependentKeyCompat
@@ -314,27 +313,30 @@ export default class Composer extends RestModel {
return isEdit(this.get("action"));
}
- @discourseComputed("category.minimumRequiredTags")
- minimumRequiredTags(minimumRequiredTags) {
- return minimumRequiredTags || 0;
+ @computed("category.minimumRequiredTags")
+ get minimumRequiredTags() {
+ return this.category?.minimumRequiredTags || 0;
}
- @discourseComputed("editingPost", "topic.details.can_edit")
- disableTitleInput(editingPost, canEditTopic) {
- return editingPost && !canEditTopic;
+ @computed("editingPost", "topic.details.can_edit")
+ get disableTitleInput() {
+ return this.editingPost && !this.topic?.details?.can_edit;
}
- @discourseComputed("privateMessage", "archetype.hasOptions")
- showCategoryChooser(isPrivateMessage, hasOptions) {
+ @computed("privateMessage", "archetype.hasOptions")
+ get showCategoryChooser() {
const manyCategories =
this.site.lazy_load_categories || this.site.categories.length > 1;
- return !isPrivateMessage && (hasOptions || manyCategories);
+ return (
+ !this.privateMessage && (this.archetype?.hasOptions || manyCategories)
+ );
}
- @discourseComputed("creatingPrivateMessage", "topic")
- privateMessage(creatingPrivateMessage, topic) {
+ @computed("creatingPrivateMessage", "topic")
+ get privateMessage() {
return (
- creatingPrivateMessage || (topic && topic.archetype === "private_message")
+ this.creatingPrivateMessage ||
+ (this.topic && this.topic.archetype === "private_message")
);
}
@@ -381,9 +383,11 @@ export default class Composer extends RestModel {
return 1;
}
- @discourseComputed("archetypeId")
- archetype(archetypeId) {
- return this.archetypes.find((archetype) => archetype.id === archetypeId);
+ @computed("archetypeId")
+ get archetype() {
+ return this.archetypes.find(
+ (archetype) => archetype.id === this.archetypeId
+ );
}
@observes("archetype")
@@ -404,33 +408,28 @@ export default class Composer extends RestModel {
);
}
- @discourseComputed(
+ @computed(
"canEditTitle",
"creatingPrivateMessage",
"categoryId",
"user.trust_level"
)
- canEditTopicFeaturedLink(
- canEditTitle,
- creatingPrivateMessage,
- categoryId,
- userTrustLevel
- ) {
- if (userTrustLevel === 0) {
+ get canEditTopicFeaturedLink() {
+ if (this.user?.trust_level === 0) {
return false;
}
if (
!this.siteSettings.topic_featured_link_enabled ||
- !canEditTitle ||
- creatingPrivateMessage
+ !this.canEditTitle ||
+ this.creatingPrivateMessage
) {
return false;
}
const categoryIds = this.site.topic_featured_link_allowed_category_ids;
if (
- !categoryId &&
+ !this.categoryId &&
categoryIds &&
(categoryIds.includes(this.site.uncategorized_category_id) ||
!this.siteSettings.allow_uncategorized_topics)
@@ -440,19 +439,19 @@ export default class Composer extends RestModel {
return (
categoryIds === undefined ||
!categoryIds.length ||
- categoryIds.includes(categoryId)
+ categoryIds.includes(this.categoryId)
);
}
- @discourseComputed("canEditTopicFeaturedLink")
- titlePlaceholder(canEditTopicFeaturedLink) {
- return canEditTopicFeaturedLink
+ @computed("canEditTopicFeaturedLink")
+ get titlePlaceholder() {
+ return this.canEditTopicFeaturedLink
? "composer.title_or_link_placeholder"
: "composer.title_placeholder";
}
- @discourseComputed("action", "post", "topic", "topic.title")
- replyOptions(action, post, topic, topicTitle) {
+ @computed("action", "post", "topic", "topic.title")
+ get replyOptions() {
const options = {
userLink: null,
topicLink: null,
@@ -461,26 +460,28 @@ export default class Composer extends RestModel {
originalUser: null,
};
- if (topic) {
+ if (this.topic) {
options.topicLink = {
- href: topic.url,
- anchor: topic.fancyTitle || escapeExpression(topicTitle),
+ href: this.topic.url,
+ anchor: this.topic.fancyTitle || escapeExpression(this.topic?.title),
};
}
- if (post) {
- options.label = i18n(`post.${action}`);
+ if (this.post) {
+ options.label = i18n(`post.${this.action}`);
const avatarTemplate = applyValueTransformer(
"composer-reply-options-user-avatar-template",
- post.avatar_template,
- { post }
+ this.post.avatar_template,
+ { post: this.post }
);
options.userAvatar = tinyAvatar(avatarTemplate);
if (this.site.desktopView) {
- const originalUserName = post.get("reply_to_user.username");
- const originalUserAvatar = post.get("reply_to_user.avatar_template");
- if (originalUserName && originalUserAvatar && isEdit(action)) {
+ const originalUserName = this.post.get("reply_to_user.username");
+ const originalUserAvatar = this.post.get(
+ "reply_to_user.avatar_template"
+ );
+ if (originalUserName && originalUserAvatar && isEdit(this.action)) {
options.originalUser = {
username: originalUserName,
avatar: tinyAvatar(originalUserAvatar),
@@ -489,23 +490,26 @@ export default class Composer extends RestModel {
}
}
- if (topic && post) {
- const postNumber = post.post_number;
+ if (this.topic && this.post) {
+ const postNumber = this.post.post_number;
options.postLink = {
- href: `${topic.url}/${postNumber}`,
+ href: `${this.topic.url}/${postNumber}`,
anchor: i18n("post.post_number", { number: postNumber }),
};
- const namePrioritized = prioritizeNameFallback(post.name, post.username);
+ const namePrioritized = prioritizeNameFallback(
+ this.post.name,
+ this.post.username
+ );
const name = applyValueTransformer(
"composer-reply-options-user-link-name",
namePrioritized,
- { post }
+ { post: this.post }
);
options.userLink = {
- href: `${topic.url}/${postNumber}`,
+ href: `${this.topic.url}/${postNumber}`,
anchor: name,
};
}
@@ -513,9 +517,11 @@ export default class Composer extends RestModel {
return options;
}
- @discourseComputed("targetRecipients")
- targetRecipientsArray(targetRecipients) {
- const recipients = targetRecipients ? targetRecipients.split(",") : [];
+ @computed("targetRecipients")
+ get targetRecipientsArray() {
+ const recipients = this.targetRecipients
+ ? this.targetRecipients.split(",")
+ : [];
const groups = new Set(this.site.groups.map((g) => g.name));
return recipients.map((item) => {
@@ -529,7 +535,7 @@ export default class Composer extends RestModel {
});
}
- @discourseComputed(
+ @computed(
"loading",
"canEditTitle",
"titleLength",
@@ -543,50 +549,37 @@ export default class Composer extends RestModel {
"minimumRequiredTags",
"user.staff"
)
- cantSubmitPost(
- loading,
- canEditTitle,
- titleLength,
- targetRecipients,
- targetRecipientsArray,
- replyLength,
- categoryId,
- missingReplyCharacters,
- tags,
- topicFirstPost,
- minimumRequiredTags,
- isStaffUser
- ) {
+ get cantSubmitPost() {
// can't submit while loading
- if (loading) {
+ if (this.loading) {
return true;
}
// title is required when
// - creating a new topic/private message
// - editing the 1st post
- if (canEditTitle && !this.titleLengthValid) {
+ if (this.canEditTitle && !this.titleLengthValid) {
return true;
}
// reply is always required
- if (missingReplyCharacters > 0) {
+ if (this.missingReplyCharacters > 0) {
return true;
}
if (
this.site.can_tag_topics &&
- !isStaffUser &&
- topicFirstPost &&
- minimumRequiredTags
+ !this.user?.staff &&
+ this.topicFirstPost &&
+ this.minimumRequiredTags
) {
- const tagsArray = tags || [];
- if (tagsArray.length < minimumRequiredTags) {
+ const tagsArray = this.tags || [];
+ if (tagsArray.length < this.minimumRequiredTags) {
return true;
}
}
- if (topicFirstPost) {
+ if (this.topicFirstPost) {
// user should modify topic template
const category = this.category;
if (category && category.topic_template) {
@@ -599,83 +592,71 @@ export default class Composer extends RestModel {
if (this.privateMessage) {
// need at least one user when sending a PM
- return targetRecipients && targetRecipientsArray.length === 0;
+ return this.targetRecipients && this.targetRecipientsArray.length === 0;
} else {
// has a category? (when needed)
return this.requiredCategoryMissing;
}
}
- @discourseComputed("canCategorize", "categoryId")
- requiredCategoryMissing(canCategorize, categoryId) {
+ @computed("canCategorize", "categoryId")
+ get requiredCategoryMissing() {
return (
- canCategorize &&
- !categoryId &&
+ this.canCategorize &&
+ !this.categoryId &&
!this.siteSettings.allow_uncategorized_topics &&
!!this._hasTopicTemplates
);
}
- @discourseComputed("minimumTitleLength", "titleLength", "post.static_doc")
- titleLengthValid(minTitleLength, titleLength, staticDoc) {
- if (this.user.admin && staticDoc && titleLength > 0) {
+ @computed("minimumTitleLength", "titleLength", "post.static_doc")
+ get titleLengthValid() {
+ if (this.user.admin && this.post?.static_doc && this.titleLength > 0) {
return true;
}
- if (titleLength < minTitleLength) {
+ if (this.titleLength < this.minimumTitleLength) {
return false;
}
- return titleLength <= this.siteSettings.max_topic_title_length;
+ return this.titleLength <= this.siteSettings.max_topic_title_length;
}
- @discourseComputed("metaData")
- hasMetaData(metaData) {
- return metaData ? isEmpty(Object.keys(metaData)) : false;
+ @computed("metaData")
+ get hasMetaData() {
+ return this.metaData ? isEmpty(Object.keys(this.metaData)) : false;
}
- @discourseComputed("minimumTitleLength", "titleLength")
- missingTitleCharacters(minimumTitleLength, titleLength) {
- return minimumTitleLength - titleLength;
+ @computed("minimumTitleLength", "titleLength")
+ get missingTitleCharacters() {
+ return this.minimumTitleLength - this.titleLength;
}
- @discourseComputed("privateMessage")
- minimumTitleLength(privateMessage) {
- if (privateMessage) {
+ @computed("privateMessage")
+ get minimumTitleLength() {
+ if (this.privateMessage) {
return this.siteSettings.min_personal_message_title_length;
} else {
return this.siteSettings.min_topic_title_length;
}
}
- @discourseComputed(
- "minimumPostLength",
- "replyLength",
- "canEditTopicFeaturedLink"
- )
- missingReplyCharacters(
- minimumPostLength,
- replyLength,
- canEditTopicFeaturedLink
- ) {
+ @computed("minimumPostLength", "replyLength", "canEditTopicFeaturedLink")
+ get missingReplyCharacters() {
if (
this.get("post.post_type") === this.site.get("post_types.small_action") ||
- (canEditTopicFeaturedLink && this.featuredLink)
+ (this.canEditTopicFeaturedLink && this.featuredLink)
) {
return 0;
}
- return minimumPostLength - replyLength;
+ return this.minimumPostLength - this.replyLength;
}
- @discourseComputed(
- "privateMessage",
- "topicFirstPost",
- "topic.pm_with_non_human_user"
- )
- minimumPostLength(privateMessage, topicFirstPost, pmWithNonHumanUser) {
- if (pmWithNonHumanUser) {
+ @computed("privateMessage", "topicFirstPost", "topic.pm_with_non_human_user")
+ get minimumPostLength() {
+ if (this.topic?.pm_with_non_human_user) {
return 1;
- } else if (privateMessage) {
+ } else if (this.privateMessage) {
return this.siteSettings.min_personal_message_post_length;
- } else if (topicFirstPost) {
+ } else if (this.topicFirstPost) {
// first post (topic body)
return this.siteSettings.min_first_post_length;
} else {
@@ -683,18 +664,18 @@ export default class Composer extends RestModel {
}
}
- @discourseComputed("title")
- titleLength(title) {
- title = title || "";
+ @computed("title")
+ get titleLength() {
+ const title = this.title || "";
if (isHTMLSafe(title)) {
return title.toString().length;
}
return title.replace(/\s+/gim, " ").trim().length;
}
- @discourseComputed("reply")
- replyLength(reply) {
- reply = reply || "";
+ @computed("reply")
+ get replyLength() {
+ let reply = this.reply || "";
if (reply.length > FAST_REPLY_LENGTH_THRESHOLD) {
return reply.length;
@@ -1324,7 +1305,7 @@ export default class Composer extends RestModel {
return "";
}
- @discourseComputed(
+ @computed(
"draftSaving",
"disableDrafts",
"canEditTitle",
@@ -1334,7 +1315,7 @@ export default class Composer extends RestModel {
"replyLength",
"minimumPostLength"
)
- canSaveDraft() {
+ get canSaveDraft() {
if (this.action === Composer.ADD_TRANSLATION) {
return false;
}
diff --git a/frontend/discourse/app/models/group-history.js b/frontend/discourse/app/models/group-history.js
index 9d05f66f8e6..154f5d47c49 100644
--- a/frontend/discourse/app/models/group-history.js
+++ b/frontend/discourse/app/models/group-history.js
@@ -1,10 +1,10 @@
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
export default class GroupHistory extends RestModel {
- @discourseComputed("action")
- actionTitle(action) {
- return i18n(`group_histories.actions.${action}`);
+ @computed("action")
+ get actionTitle() {
+ return i18n(`group_histories.actions.${this.action}`);
}
}
diff --git a/frontend/discourse/app/models/group.js b/frontend/discourse/app/models/group.js
index 725b7543adf..46ce47db027 100644
--- a/frontend/discourse/app/models/group.js
+++ b/frontend/discourse/app/models/group.js
@@ -1,12 +1,11 @@
/* eslint-disable ember/no-observers */
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { equal } from "@ember/object/computed";
import { isEmpty } from "@ember/utils";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { observes } from "@ember-decorators/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import Category from "discourse/models/category";
import GroupHistory from "discourse/models/group-history";
@@ -50,19 +49,21 @@ export default class Group extends RestModel {
@equal("mentionable_level", 99) canEveryoneMention;
- @discourseComputed("automatic_membership_email_domains")
- emailDomains(value) {
- return isEmpty(value) ? "" : value;
+ @computed("automatic_membership_email_domains")
+ get emailDomains() {
+ return isEmpty(this.automatic_membership_email_domains)
+ ? ""
+ : this.automatic_membership_email_domains;
}
- @discourseComputed("associated_group_ids")
- associatedGroupIds(value) {
- return isEmpty(value) ? [] : value;
+ @computed("associated_group_ids")
+ get associatedGroupIds() {
+ return isEmpty(this.associated_group_ids) ? [] : this.associated_group_ids;
}
- @discourseComputed("automatic")
- type(automatic) {
- return automatic ? "automatic" : "custom";
+ @computed("automatic")
+ get type() {
+ return this.automatic ? "automatic" : "custom";
}
async reloadMembers(params, refresh) {
@@ -184,28 +185,28 @@ export default class Group extends RestModel {
return this.reloadMembers({ filter: usernames.join(",") });
}
- @discourseComputed("display_name", "name")
- displayName(groupDisplayName, name) {
- return groupDisplayName || name;
+ @computed("display_name", "name")
+ get displayName() {
+ return this.display_name || this.name;
}
- @discourseComputed("flair_bg_color")
- flairBackgroundHexColor(flairBgColor) {
- return flairBgColor
- ? flairBgColor.replace(new RegExp("[^0-9a-fA-F]", "g"), "")
+ @computed("flair_bg_color")
+ get flairBackgroundHexColor() {
+ return this.flair_bg_color
+ ? this.flair_bg_color.replace(new RegExp("[^0-9a-fA-F]", "g"), "")
: null;
}
- @discourseComputed("flair_color")
- flairHexColor(flairColor) {
- return flairColor
- ? flairColor.replace(new RegExp("[^0-9a-fA-F]", "g"), "")
+ @computed("flair_color")
+ get flairHexColor() {
+ return this.flair_color
+ ? this.flair_color.replace(new RegExp("[^0-9a-fA-F]", "g"), "")
: null;
}
- @discourseComputed("visibility_level")
- isPrivate(visibilityLevel) {
- return visibilityLevel > 1;
+ @computed("visibility_level")
+ get isPrivate() {
+ return this.visibility_level > 1;
}
@observes("isPrivate", "canEveryoneMention")
diff --git a/frontend/discourse/app/models/invite.js b/frontend/discourse/app/models/invite.js
index ede732aa016..80615f95eda 100644
--- a/frontend/discourse/app/models/invite.js
+++ b/frontend/discourse/app/models/invite.js
@@ -1,10 +1,9 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { isNone } from "@ember/utils";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { userPath } from "discourse/lib/url";
import Topic from "discourse/models/topic";
import User from "discourse/models/user";
@@ -81,23 +80,25 @@ export default class Invite extends EmberObject {
.catch(popupAjaxError);
}
- @discourseComputed("invite_key")
- shortKey(key) {
- return key.slice(0, 4) + "...";
+ @computed("invite_key")
+ get shortKey() {
+ return this.invite_key.slice(0, 4) + "...";
}
- @discourseComputed("groups")
- groupIds(groups) {
- return groups ? groups.map((group) => group.id) : [];
+ @computed("groups")
+ get groupIds() {
+ return this.groups ? this.groups.map((group) => group.id) : [];
}
- @discourseComputed("topics.firstObject")
- topic(topicData) {
- return topicData ? Topic.create(topicData) : null;
+ @computed("topics.firstObject")
+ get topic() {
+ return this.topics?.firstObject
+ ? Topic.create(this.topics?.firstObject)
+ : null;
}
- @discourseComputed("email", "domain")
- emailOrDomain(email, domain) {
- return email || domain;
+ @computed("email", "domain")
+ get emailOrDomain() {
+ return this.email || this.domain;
}
}
diff --git a/frontend/discourse/app/models/login-method.js b/frontend/discourse/app/models/login-method.js
index 8412cbba008..07a4ed5375f 100644
--- a/frontend/discourse/app/models/login-method.js
+++ b/frontend/discourse/app/models/login-method.js
@@ -1,8 +1,7 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { Promise } from "rsvp";
import { updateCsrfToken } from "discourse/lib/ajax";
import cookie from "discourse/lib/cookie";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import Session from "discourse/models/session";
import Site from "discourse/models/site";
@@ -36,26 +35,26 @@ export default class LoginMethod extends EmberObject {
});
}
- @discourseComputed
- title() {
+ @computed
+ get title() {
return this.title_override || i18n(`login.${this.name}.title`);
}
- @discourseComputed
- icon() {
+ @computed
+ get icon() {
return this.icon_override || "user";
}
- @discourseComputed
- screenReaderTitle() {
+ @computed
+ get screenReaderTitle() {
return (
this.title_override ||
i18n(`login.${this.name}.sr_title`, { defaultValue: this.title })
);
}
- @discourseComputed
- prettyName() {
+ @computed
+ get prettyName() {
return this.pretty_name_override || i18n(`login.${this.name}.name`);
}
diff --git a/frontend/discourse/app/models/nav-item.js b/frontend/discourse/app/models/nav-item.js
index 50eddc77fff..ff884bb730d 100644
--- a/frontend/discourse/app/models/nav-item.js
+++ b/frontend/discourse/app/models/nav-item.js
@@ -1,9 +1,8 @@
import { tracked } from "@glimmer/tracking";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { dependentKeyCompat } from "@ember/object/compat";
import { reads } from "@ember/object/computed";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import getURL from "discourse/lib/get-url";
@@ -276,8 +275,8 @@ export default class NavItem extends EmberObject {
this._displayName = value;
}
- @discourseComputed("filterType", "category", "noSubcategories", "tag")
- href(filterType, category, noSubcategories, tag) {
+ @computed("filterType", "category", "noSubcategories", "tag")
+ get href() {
let customHref = null;
NavItem.customNavItemHrefs.forEach(function (cb) {
@@ -291,25 +290,29 @@ export default class NavItem extends EmberObject {
return getURL(customHref);
}
- const context = { category, noSubcategories, tag };
- return NavItem.pathFor(filterType, context);
+ const context = {
+ category: this.category,
+ noSubcategories: this.noSubcategories,
+ tag: this.tag,
+ };
+ return NavItem.pathFor(this.filterType, context);
}
- @discourseComputed("name", "category", "noSubcategories")
- filterMode(name, category, noSubcategories) {
+ @computed("name", "category", "noSubcategories")
+ get filterMode() {
let mode = "";
- if (category) {
+ if (this.category) {
mode += "c/";
- mode += Category.slugFor(category);
- if (noSubcategories) {
+ mode += Category.slugFor(this.category);
+ if (this.noSubcategories) {
mode += "/none";
}
mode += "/l/";
}
- return mode + name.replace(" ", "-");
+ return mode + this.name.replace(" ", "-");
}
- @discourseComputed(
+ @computed(
"name",
"category",
"tag",
@@ -317,13 +320,13 @@ export default class NavItem extends EmberObject {
"currentRouteQueryParams",
"topicTrackingState.messageCount"
)
- count(name, category, tag, noSubcategories, currentRouteQueryParams) {
+ get count() {
return this.topicTrackingState?.lookupCount({
- type: name,
- category,
- tagId: tag?.id,
- noSubcategories,
- customFilterFn: hasTrackedFilter(currentRouteQueryParams)
+ type: this.name,
+ category: this.category,
+ tagId: this.tag?.id,
+ noSubcategories: this.noSubcategories,
+ customFilterFn: hasTrackedFilter(this.currentRouteQueryParams)
? isTrackedTopic
: undefined,
});
diff --git a/frontend/discourse/app/models/pending-post.js b/frontend/discourse/app/models/pending-post.js
index 6ffd20b195b..cc9d65779f1 100644
--- a/frontend/discourse/app/models/pending-post.js
+++ b/frontend/discourse/app/models/pending-post.js
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { reads } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
import { cook } from "discourse/lib/text";
import { userPath } from "discourse/lib/url";
import RestModel from "discourse/models/rest";
@@ -19,13 +19,13 @@ export default class PendingPost extends RestModel {
});
}
- @discourseComputed("username")
- userUrl(username) {
- return userPath(username.toLowerCase());
+ @computed("username")
+ get userUrl() {
+ return userPath(this.username.toLowerCase());
}
- @discourseComputed("category_id")
- category() {
+ @computed("category_id")
+ get category() {
return Category.findById(this.category_id);
}
}
diff --git a/frontend/discourse/app/models/permission-type.js b/frontend/discourse/app/models/permission-type.js
index 4016f8e5042..c5917f46ad3 100644
--- a/frontend/discourse/app/models/permission-type.js
+++ b/frontend/discourse/app/models/permission-type.js
@@ -1,5 +1,4 @@
-import EmberObject from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
+import EmberObject, { computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export function buildPermissionDescription(id) {
@@ -16,8 +15,8 @@ export default class PermissionType extends EmberObject {
3: "readonly",
};
- @discourseComputed("id")
- description(id) {
- return buildPermissionDescription(id);
+ @computed("id")
+ get description() {
+ return buildPermissionDescription(this.id);
}
}
diff --git a/frontend/discourse/app/models/post-action-type.js b/frontend/discourse/app/models/post-action-type.js
index 26955f9d027..fc8788fec4f 100644
--- a/frontend/discourse/app/models/post-action-type.js
+++ b/frontend/discourse/app/models/post-action-type.js
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { equal } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
import RestModel from "discourse/models/rest";
import { i18n } from "discourse-i18n";
@@ -8,8 +8,8 @@ export const MAX_MESSAGE_LENGTH = 500;
export default class PostActionType extends RestModel {
@equal("name_key", "illegal") isIllegal;
- @discourseComputed()
- translatedDescription() {
+ @computed()
+ get translatedDescription() {
if (this.system) {
return i18n(`post.actions.by_you.${this.name_key}`);
}
diff --git a/frontend/discourse/app/models/post.js b/frontend/discourse/app/models/post.js
index ae3863b3af4..e1ff952b38c 100644
--- a/frontend/discourse/app/models/post.js
+++ b/frontend/discourse/app/models/post.js
@@ -1,5 +1,5 @@
import { cached, tracked } from "@glimmer/tracking";
-import EmberObject, { get } from "@ember/object";
+import EmberObject, { computed, get } from "@ember/object";
import { alias, and, equal, not, or } from "@ember/object/computed";
import { service } from "@ember/service";
import { isEmpty } from "@ember/utils";
@@ -8,7 +8,6 @@ import { resolveShareUrl } from "discourse/helpers/share-url";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { propertyEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { cook } from "discourse/lib/text";
import { fancyTitle } from "discourse/lib/topic-fancy-title";
import {
@@ -223,9 +222,13 @@ export default class Post extends RestModel {
return this.customShare || resolveShareUrl(this.url, this.currentUser);
}
- @discourseComputed("name", "username")
- showName(name, username) {
- return name && name !== username && this.siteSettings.display_name_on_posts;
+ @computed("name", "username")
+ get showName() {
+ return (
+ this.name &&
+ this.name !== this.username &&
+ this.siteSettings.display_name_on_posts
+ );
}
get deletedBy() {
@@ -236,24 +239,24 @@ export default class Post extends RestModel {
return this.firstPost ? this.topic?.deleted_at : this.deleted_at;
}
- @discourseComputed("post_number", "topic_id", "topic.slug")
- url(post_number, topic_id, topicSlug) {
+ @computed("post_number", "topic_id", "topic.slug")
+ get url() {
return postUrl(
- topicSlug || this.topic_slug,
- topic_id || this.get("topic.id"),
- post_number
+ this.topic?.slug || this.topic_slug,
+ this.topic_id || this.get("topic.id"),
+ this.post_number
);
}
// Don't drop the /1
- @discourseComputed("post_number", "url")
- urlWithNumber(postNumber, baseUrl) {
- return postNumber === 1 ? `${baseUrl}/1` : baseUrl;
+ @computed("post_number", "url")
+ get urlWithNumber() {
+ return this.post_number === 1 ? `${this.url}/1` : this.url;
}
- @discourseComputed("username")
- usernameUrl(username) {
- return userPath(username);
+ @computed("username")
+ get usernameUrl() {
+ return userPath(this.username);
}
updatePostField(field, value) {
@@ -276,8 +279,8 @@ export default class Post extends RestModel {
return this.link_counts.filter((link) => link.internal && link.title);
}
- @discourseComputed("[email protected]_act")
- flagsAvailable() {
+ @computed("[email protected]_act")
+ get flagsAvailable() {
// TODO: Investigate why `this.site` is sometimes null when running
// Search - Search with context
if (!this.site) {
@@ -289,17 +292,20 @@ export default class Post extends RestModel {
);
}
- @discourseComputed(
- "siteSettings.use_pg_headlines_for_excerpt",
- "topic_title_headline"
- )
- useTopicTitleHeadline(enabled, title) {
- return enabled && title;
+ @computed("siteSettings.use_pg_headlines_for_excerpt", "topic_title_headline")
+ get useTopicTitleHeadline() {
+ return (
+ this.siteSettings?.use_pg_headlines_for_excerpt &&
+ this.topic_title_headline
+ );
}
- @discourseComputed("topic_title_headline")
- topicTitleHeadline(title) {
- return fancyTitle(title, this.siteSettings.support_mixed_text_direction);
+ @computed("topic_title_headline")
+ get topicTitleHeadline() {
+ return fancyTitle(
+ this.topic_title_headline,
+ this.siteSettings.support_mixed_text_direction
+ );
}
get canBookmark() {
diff --git a/frontend/discourse/app/models/reviewable.js b/frontend/discourse/app/models/reviewable.js
index a58fe941b70..8f09cd1bdd6 100644
--- a/frontend/discourse/app/models/reviewable.js
+++ b/frontend/discourse/app/models/reviewable.js
@@ -1,8 +1,8 @@
+import { computed } from "@ember/object";
import { dasherize, underscore } from "@ember/string";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { uniqueItemsFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import RestModel from "discourse/models/rest";
import I18n, { i18n } from "discourse-i18n";
import Category from "./category";
@@ -20,37 +20,37 @@ export default class Reviewable extends RestModel {
return json;
}
- @discourseComputed("type", "topic")
- resolvedType(type, topic) {
+ @computed("type", "topic")
+ get resolvedType() {
// Display "Queued Topic" if the post will create a topic
- if (type === "ReviewableQueuedPost" && !topic) {
+ if (this.type === "ReviewableQueuedPost" && !this.topic) {
return "ReviewableQueuedTopic";
}
- return type;
+ return this.type;
}
- @discourseComputed("resolvedType")
- humanType(resolvedType) {
- return i18n(`review.types.${underscore(resolvedType)}.title`, {
+ @computed("resolvedType")
+ get humanType() {
+ return i18n(`review.types.${underscore(this.resolvedType)}.title`, {
defaultValue: "",
});
}
- @discourseComputed("humanType")
- humanTypeCssClass(humanType) {
- return "-" + dasherize(humanType);
+ @computed("humanType")
+ get humanTypeCssClass() {
+ return "-" + dasherize(this.humanType);
}
- @discourseComputed("resolvedType")
- humanNoun(resolvedType) {
- return i18n(`review.types.${underscore(resolvedType)}.noun`, {
+ @computed("resolvedType")
+ get humanNoun() {
+ return i18n(`review.types.${underscore(this.resolvedType)}.noun`, {
defaultValue: "reviewable",
});
}
- @discourseComputed("humanNoun")
- flaggedReviewableContextQuestion(humanNoun) {
+ @computed("humanNoun")
+ get flaggedReviewableContextQuestion() {
const uniqueReviewableScores = uniqueItemsFromArray(
this.reviewable_scores,
"score_type.type"
@@ -59,7 +59,7 @@ export default class Reviewable extends RestModel {
if (uniqueReviewableScores.length === 1) {
if (uniqueReviewableScores[0].score_type.type === "notify_moderators") {
return i18n("review.context_question.something_else_wrong", {
- reviewable_type: humanNoun,
+ reviewable_type: this.humanNoun,
});
}
}
@@ -75,14 +75,14 @@ export default class Reviewable extends RestModel {
return i18n("review.context_question.is_this_post", {
reviewable_human_score_types: listOfQuestions,
- reviewable_type: humanNoun,
+ reviewable_type: this.humanNoun,
});
}
- @discourseComputed("resolvedType", "reviewable_scores")
- userReviewableContextQuestion(resolvedType, scores) {
- if (resolvedType === "ReviewableUser") {
- const isSuspectUser = scores?.some(
+ @computed("resolvedType", "reviewable_scores")
+ get userReviewableContextQuestion() {
+ if (this.resolvedType === "ReviewableUser") {
+ const isSuspectUser = this.reviewable_scores?.some(
(score) => score.reason_type === "suspect_user"
);
if (isSuspectUser) {
@@ -90,20 +90,20 @@ export default class Reviewable extends RestModel {
}
return i18n("review.context_question.approve_user");
}
- if (resolvedType === "ReviewableQueuedPost") {
+ if (this.resolvedType === "ReviewableQueuedPost") {
return i18n("review.context_question.approve_post");
}
- if (resolvedType === "ReviewableQueuedTopic") {
+ if (this.resolvedType === "ReviewableQueuedTopic") {
return i18n("review.context_question.approve_topic");
}
- if (resolvedType === "ReviewablePost") {
+ if (this.resolvedType === "ReviewablePost") {
return i18n("review.context_question.approve_post");
}
return null;
}
- @discourseComputed("category_id")
- category() {
+ @computed("category_id")
+ get category() {
return Category.findById(this.category_id);
}
diff --git a/frontend/discourse/app/models/site.js b/frontend/discourse/app/models/site.js
index 0c622b47a23..3fa64cd6682 100644
--- a/frontend/discourse/app/models/site.js
+++ b/frontend/discourse/app/models/site.js
@@ -8,7 +8,6 @@ import { isEmpty } from "@ember/utils";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
import { removeValueFromArray } from "discourse/lib/array-tools";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";
import { isRailsTesting, isTesting } from "discourse/lib/environment";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
@@ -186,17 +185,17 @@ export default class Site extends RestModel {
return map;
}
- @discourseComputed("notification_types")
- notificationLookup(notificationTypes) {
+ @computed("notification_types")
+ get notificationLookup() {
const result = [];
- Object.keys(notificationTypes).forEach(
- (k) => (result[notificationTypes[k]] = k)
+ Object.keys(this.notification_types).forEach(
+ (k) => (result[this.notification_types[k]] = k)
);
return result;
}
- @discourseComputed("post_action_types.[]")
- flagTypes() {
+ @computed("post_action_types.[]")
+ get flagTypes() {
const postActionTypes = this.post_action_types;
if (!postActionTypes) {
return [];
@@ -226,18 +225,18 @@ export default class Site extends RestModel {
}
// Returns it in the correct order, by setting
- @discourseComputed("categories.[]")
- categoriesList(categories) {
+ @computed("categories.[]")
+ get categoriesList() {
return this.siteSettings.fixed_category_positions
- ? categories
+ ? this.categories
: this.sortedCategories;
}
- @discourseComputed("categories.[]", "[email protected]_level")
- trackedCategoriesList(categories) {
+ @computed("categories.[]", "[email protected]_level")
+ get trackedCategoriesList() {
const trackedCategories = [];
- for (const category of categories) {
+ for (const category of this.categories) {
if (category.isTracked) {
if (
this.siteSettings.allow_uncategorized_topics ||
diff --git a/frontend/discourse/app/models/tag-group.js b/frontend/discourse/app/models/tag-group.js
index 8b0c8e37c13..a4b34b4479a 100644
--- a/frontend/discourse/app/models/tag-group.js
+++ b/frontend/discourse/app/models/tag-group.js
@@ -1,17 +1,17 @@
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import PermissionType from "discourse/models/permission-type";
import RestModel from "discourse/models/rest";
export default class TagGroup extends RestModel {
- @discourseComputed("permissions")
- permissionName(permissions) {
- if (!permissions) {
+ @computed("permissions")
+ get permissionName() {
+ if (!this.permissions) {
return "public";
}
- if (permissions[0] === PermissionType.FULL) {
+ if (this.permissions[0] === PermissionType.FULL) {
return "public";
- } else if (permissions[0] === PermissionType.READONLY) {
+ } else if (this.permissions[0] === PermissionType.READONLY) {
return "visible";
} else {
return "private";
diff --git a/frontend/discourse/app/models/tag.js b/frontend/discourse/app/models/tag.js
index 1ac1522080a..0e0d6e04c96 100644
--- a/frontend/discourse/app/models/tag.js
+++ b/frontend/discourse/app/models/tag.js
@@ -1,34 +1,34 @@
+import { computed } from "@ember/object";
import { readOnly } from "@ember/object/computed";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import RestModel from "discourse/models/rest";
export default class Tag extends RestModel {
@readOnly("pm_only") pmOnly;
- @discourseComputed("slug", "id")
- url(slug, id) {
- if (id) {
- const slugForUrl = slug || `${id}-tag`;
- return getURL(`/tag/${slugForUrl}/${id}`);
+ @computed("slug", "id")
+ get url() {
+ if (this.id) {
+ const slugForUrl = this.slug || `${this.id}-tag`;
+ return getURL(`/tag/${slugForUrl}/${this.id}`);
}
// fallback for tags without id (legacy)
return getURL(`/tag/${this.name}`);
}
- @discourseComputed("count", "pm_count")
- totalCount(count, pmCount) {
- return pmCount ? count + pmCount : count;
+ @computed("count", "pm_count")
+ get totalCount() {
+ return this.pm_count ? this.count + this.pm_count : this.count;
}
- @discourseComputed("id", "name")
- searchContext(id, name) {
+ @computed("id", "name")
+ get searchContext() {
return {
type: "tag",
- id,
+ id: this.id,
/** @type Tag */
tag: this,
- name,
+ name: this.name,
};
}
}
diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.js
index 12a1a0117ed..04f0da2ff52 100644
--- a/frontend/discourse/app/models/topic.js
+++ b/frontend/discourse/app/models/topic.js
@@ -10,7 +10,6 @@ import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValuesFromArray } from "discourse/lib/array-tools";
import { fmt, propertyEqual } from "discourse/lib/computed";
import { TOPIC_VISIBILITY_REASONS } from "discourse/lib/constants";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { longDate } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
@@ -368,32 +367,38 @@ export default class Topic extends RestModel {
});
}
- @discourseComputed("last_read_post_number", "highest_post_number")
- visited(lastReadPostNumber, highestPostNumber) {
+ @computed("last_read_post_number", "highest_post_number")
+ get visited() {
// >= to handle case where there are deleted posts at the end of the topic
- return lastReadPostNumber >= highestPostNumber;
+ return this.last_read_post_number >= this.highest_post_number;
}
- @discourseComputed("posters.firstObject")
- creator(poster) {
- return poster && poster.user;
+ @computed("posters.firstObject")
+ get creator() {
+ return this.posters?.firstObject && this.posters?.firstObject?.user;
}
- @discourseComputed("posters.[]")
- lastPoster(posters) {
- if (posters && posters.length > 0) {
- const latest = posters.filter((p) => p.extras?.includes("latest"))[0];
- return latest || posters.firstObject;
+ @computed("posters.[]")
+ get lastPoster() {
+ if (this.posters && this.posters?.length > 0) {
+ const latest = this.posters?.filter((p) =>
+ p.extras?.includes("latest")
+ )[0];
+ return latest || this.posters?.firstObject;
}
}
- @discourseComputed("posters.[]", "participants.[]", "allowed_user_count")
- featuredUsers(posters, participants, allowedUserCount) {
- let users = posters;
+ @computed("posters.[]", "participants.[]", "allowed_user_count")
+ get featuredUsers() {
+ let users = this.posters;
const maxUserCount = 5;
const posterCount = users.length;
- if (this.isPrivateMessage && participants && posterCount < maxUserCount) {
+ if (
+ this.isPrivateMessage &&
+ this.participants &&
+ posterCount < maxUserCount
+ ) {
let pushOffset = 0;
if (posterCount > 1) {
const lastUser = users[posterCount - 1];
@@ -402,10 +407,10 @@ export default class Topic extends RestModel {
}
}
- const poster_ids = posters
- .map((p) => p.user && p.user.id)
- .filter((id) => id);
- participants.some((p) => {
+ const poster_ids = this.posters
+ ?.map((p) => p.user && p.user.id)
+ ?.filter((id) => id);
+ this.participants?.some((p) => {
if (!poster_ids.includes(p.user_id)) {
users.splice(users.length - pushOffset, 0, p);
if (users.length === maxUserCount) {
@@ -416,69 +421,72 @@ export default class Topic extends RestModel {
});
}
- if (this.isPrivateMessage && allowedUserCount > maxUserCount) {
+ if (this.isPrivateMessage && this.allowed_user_count > maxUserCount) {
users.splice(maxUserCount - 2, 1); // remove second-last avatar
users.push({
- moreCount: `+${allowedUserCount - maxUserCount + 1}`,
+ moreCount: `+${this.allowed_user_count - maxUserCount + 1}`,
});
}
return users;
}
- @discourseComputed("fancy_title")
- fancyTitle(title) {
- return fancyTitle(title, this.siteSettings.support_mixed_text_direction);
+ @computed("fancy_title")
+ get fancyTitle() {
+ return fancyTitle(
+ this.fancy_title,
+ this.siteSettings.support_mixed_text_direction
+ );
}
// returns createdAt if there's no bumped date
- @discourseComputed("bumped_at", "createdAt")
- bumpedAt(bumped_at, createdAt) {
- if (bumped_at) {
- return new Date(bumped_at);
+ @computed("bumped_at", "createdAt")
+ get bumpedAt() {
+ if (this.bumped_at) {
+ return new Date(this.bumped_at);
} else {
- return createdAt;
+ return this.createdAt;
}
}
- @discourseComputed("bumpedAt", "createdAt")
- bumpedAtTitle(bumpedAt, createdAt) {
+ @computed("bumpedAt", "createdAt")
+ get bumpedAtTitle() {
const BUMPED_FORMAT = "YYYY-MM-DDTHH:mm:ss";
- if (moment(bumpedAt).isValid() && moment(createdAt).isValid()) {
- const bumpedAtStr = moment(bumpedAt).format(BUMPED_FORMAT);
- const createdAtStr = moment(createdAt).format(BUMPED_FORMAT);
+ if (moment(this.bumpedAt).isValid() && moment(this.createdAt).isValid()) {
+ const bumpedAtStr = moment(this.bumpedAt).format(BUMPED_FORMAT);
+ const createdAtStr = moment(this.createdAt).format(BUMPED_FORMAT);
return bumpedAtStr !== createdAtStr
? `${i18n("topic.created_at", {
- date: longDate(createdAt),
- })}\n${i18n("topic.bumped_at", { date: longDate(bumpedAt) })}`
- : i18n("topic.created_at", { date: longDate(createdAt) });
+ date: longDate(this.createdAt),
+ })}\n${i18n("topic.bumped_at", { date: longDate(this.bumpedAt) })}`
+ : i18n("topic.created_at", { date: longDate(this.createdAt) });
}
}
- @discourseComputed("created_at")
- createdAt(created_at) {
- return new Date(created_at);
+ @computed("created_at")
+ get createdAt() {
+ return new Date(this.created_at);
}
- @discourseComputed
- postStream() {
+ @computed
+ get postStream() {
return this.store.createRecord("postStream", {
id: this.id,
topic: this,
});
}
- @discourseComputed("tags")
- visibleListTags(tags) {
- if (!tags || !this.siteSettings.suppress_overlapping_tags_in_list) {
- return tags;
+ @computed("tags")
+ get visibleListTags() {
+ if (!this.tags || !this.siteSettings.suppress_overlapping_tags_in_list) {
+ return this.tags;
}
const title = this.title.toLowerCase();
const newTags = [];
- tags.forEach(function (tag) {
+ this.tags.forEach(function (tag) {
const tagName = typeof tag === "string" ? tag : tag.name;
if (!title.includes(tagName.toLowerCase())) {
newTags.push(tag);
@@ -500,9 +508,9 @@ export default class Topic extends RestModel {
return this.get("suggested_topics")?.map((data) => Topic.create(data));
}
- @discourseComputed("posts_count")
- replyCount(postsCount) {
- return postsCount - 1;
+ @computed("posts_count")
+ get replyCount() {
+ return this.posts_count - 1;
}
get details() {
@@ -519,13 +527,13 @@ export default class Topic extends RestModel {
this._details = this.store.createRecord("topicDetails", value);
}
- @discourseComputed("visible")
- invisible(visible) {
- return visible !== undefined ? !visible : undefined;
+ @computed("visible")
+ get invisible() {
+ return this.visible !== undefined ? !this.visible : undefined;
}
- @discourseComputed("visibility_reason_id")
- visibilityReasonTranslated() {
+ @computed("visibility_reason_id")
+ get visibilityReasonTranslated() {
if (
this.visibility_reason_id &&
this.visibility_reason_id !== TOPIC_VISIBILITY_REASONS.unknown
@@ -539,9 +547,9 @@ export default class Topic extends RestModel {
return "";
}
- @discourseComputed("id")
- searchContext(id) {
- return { type: "topic", id };
+ @computed("id")
+ get searchContext() {
+ return { type: "topic", id: this.id };
}
@computed("category_id", "site.categoriesById.[]")
@@ -553,18 +561,18 @@ export default class Topic extends RestModel {
this.set("category_id", newCategory?.id);
}
- @discourseComputed("url")
- shareUrl(url) {
- return resolveShareUrl(url, this.currentUser);
+ @computed("url")
+ get shareUrl() {
+ return resolveShareUrl(this.url, this.currentUser);
}
- @discourseComputed("id", "slug")
- url(id, slug) {
- slug = slug || "";
+ @computed("id", "slug")
+ get url() {
+ let slug = this.slug || "";
if (slug.trim().length === 0) {
slug = "topic";
}
- return `${getURL("/t/")}${slug}/${id}`;
+ return `${getURL("/t/")}${slug}/${this.id}`;
}
// Helper to build a Url with a post number
@@ -576,30 +584,30 @@ export default class Topic extends RestModel {
return url;
}
- @discourseComputed("unread_posts", "new_posts")
- totalUnread(unreadPosts, newPosts) {
+ @computed("unread_posts", "new_posts")
+ get totalUnread() {
deprecated("The totalUnread property of the topic model is deprecated", {
id: "discourse.topic.totalUnread",
});
- return unreadPosts || newPosts;
+ return this.unread_posts || this.new_posts;
}
- @discourseComputed("unread_posts", "new_posts")
- displayNewPosts(unreadPosts, newPosts) {
+ @computed("unread_posts", "new_posts")
+ get displayNewPosts() {
deprecated(
"The displayNewPosts property of the topic model is deprecated",
{ id: "discourse.topic.totalUnread" }
);
- return unreadPosts || newPosts;
+ return this.unread_posts || this.new_posts;
}
- @discourseComputed("last_read_post_number", "url")
- lastReadUrl(lastReadPostNumber) {
- return this.urlForPostNumber(lastReadPostNumber);
+ @computed("last_read_post_number", "url")
+ get lastReadUrl() {
+ return this.urlForPostNumber(this.last_read_post_number);
}
- @discourseComputed("last_read_post_number", "highest_post_number", "url")
- lastUnreadUrl(lastReadPostNumber, highestPostNumber) {
+ @computed("last_read_post_number", "highest_post_number", "url")
+ get lastUnreadUrl() {
let customUrl = null;
_customLastUnreadUrlCallbacks.some((cb) => {
const result = cb(this);
@@ -614,58 +622,60 @@ export default class Topic extends RestModel {
}
if (
- lastReadPostNumber >= highestPostNumber &&
+ this.last_read_post_number >= this.highest_post_number &&
this.get("category.navigate_to_first_post_after_read")
) {
return this.urlForPostNumber(1);
}
- let postNumber = lastReadPostNumber + 1;
- if (postNumber > highestPostNumber) {
- postNumber = highestPostNumber;
+ let postNumber = this.last_read_post_number + 1;
+ if (postNumber > this.highest_post_number) {
+ postNumber = this.highest_post_number;
}
return this.urlForPostNumber(postNumber);
}
- @discourseComputed("highest_post_number", "url")
- lastPostUrl(highestPostNumber) {
- return this.urlForPostNumber(highestPostNumber);
+ @computed("highest_post_number", "url")
+ get lastPostUrl() {
+ return this.urlForPostNumber(this.highest_post_number);
}
- @discourseComputed("url")
- firstPostUrl() {
+ @computed("url")
+ get firstPostUrl() {
return this.urlForPostNumber(1);
}
- @discourseComputed("url")
- summaryUrl() {
+ @computed("url")
+ get summaryUrl() {
const summaryQueryString = this.has_summary ? "?filter=summary" : "";
return `${this.urlForPostNumber(1)}${summaryQueryString}`;
}
- @discourseComputed("last_poster.username")
- lastPosterUrl(username) {
- return userPath(username);
+ @computed("last_poster.username")
+ get lastPosterUrl() {
+ return userPath(this.last_poster?.username);
}
- @discourseComputed("views")
- viewsHeat(v) {
- if (v >= this.siteSettings.topic_views_heat_high) {
+ @computed("views")
+ get viewsHeat() {
+ if (this.views >= this.siteSettings.topic_views_heat_high) {
return "heatmap-high";
}
- if (v >= this.siteSettings.topic_views_heat_medium) {
+ if (this.views >= this.siteSettings.topic_views_heat_medium) {
return "heatmap-med";
}
- if (v >= this.siteSettings.topic_views_heat_low) {
+ if (this.views >= this.siteSettings.topic_views_heat_low) {
return "heatmap-low";
}
return null;
}
- @discourseComputed("archetype")
- archetypeObject(archetype) {
- return Site.currentProp("archetypes").find((item) => item.id === archetype);
+ @computed("archetype")
+ get archetypeObject() {
+ return Site.currentProp("archetypes").find(
+ (item) => item.id === this.archetype
+ );
}
toggleStatus(property) {
@@ -904,14 +914,14 @@ export default class Topic extends RestModel {
});
}
- @discourseComputed("excerpt")
- escapedExcerpt(excerpt) {
- return emojiUnescape(excerpt);
+ @computed("excerpt")
+ get escapedExcerpt() {
+ return emojiUnescape(this.excerpt);
}
- @discourseComputed("excerpt")
- excerptTruncated(excerpt) {
- return excerpt && excerpt.slice(-8) === "&hellip;";
+ @computed("excerpt")
+ get excerptTruncated() {
+ return this.excerpt && this.excerpt.slice(-8) === "&hellip;";
}
archiveMessage() {
diff --git a/frontend/discourse/app/models/user-action-stat.js b/frontend/discourse/app/models/user-action-stat.js
index c9e23b4e179..4e4a6458c28 100644
--- a/frontend/discourse/app/models/user-action-stat.js
+++ b/frontend/discourse/app/models/user-action-stat.js
@@ -1,24 +1,24 @@
+import { computed } from "@ember/object";
import { i18n } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import RestModel from "discourse/models/rest";
import UserAction from "discourse/models/user-action";
export default class UserActionStat extends RestModel {
@i18n("action_type", "user_action_groups.%@") description;
- @discourseComputed("action_type")
- isPM(actionType) {
+ @computed("action_type")
+ get isPM() {
return (
- actionType === UserAction.TYPES.messages_sent ||
- actionType === UserAction.TYPES.messages_received
+ this.action_type === UserAction.TYPES.messages_sent ||
+ this.action_type === UserAction.TYPES.messages_received
);
}
- @discourseComputed("action_type")
- isResponse(actionType) {
+ @computed("action_type")
+ get isResponse() {
return (
- actionType === UserAction.TYPES.replies ||
- actionType === UserAction.TYPES.quotes
+ this.action_type === UserAction.TYPES.replies ||
+ this.action_type === UserAction.TYPES.quotes
);
}
}
diff --git a/frontend/discourse/app/models/user-action.js b/frontend/discourse/app/models/user-action.js
index a14497ba9c4..a25f71d35c7 100644
--- a/frontend/discourse/app/models/user-action.js
+++ b/frontend/discourse/app/models/user-action.js
@@ -1,6 +1,6 @@
+import { computed } from "@ember/object";
import { equal, or } from "@ember/object/computed";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { emojiUnescape } from "discourse/lib/text";
import { userPath } from "discourse/lib/url";
import { escapeExpression, postUrl } from "discourse/lib/utilities";
@@ -98,14 +98,17 @@ export default class UserAction extends RestModel {
@or("messageSentType", "messageReceivedType") isPM;
@or("postType", "replyType") postReplyType;
- @discourseComputed("category_id")
- category() {
+ @computed("category_id")
+ get category() {
return Category.findById(this.category_id);
}
- @discourseComputed("action_type")
- descriptionKey(action) {
- if (action === null || UserAction.TO_SHOW.includes(action)) {
+ @computed("action_type")
+ get descriptionKey() {
+ if (
+ this.action_type === null ||
+ UserAction.TO_SHOW.includes(this.action_type)
+ ) {
if (this.isPM) {
return this.sameUser ? "sent_by_you" : "sent_by_user";
} else {
@@ -134,44 +137,44 @@ export default class UserAction extends RestModel {
}
}
- @discourseComputed("username")
- sameUser(username) {
- return username === this.currentUser?.get("username");
+ @computed("username")
+ get sameUser() {
+ return this.username === this.currentUser?.get("username");
}
- @discourseComputed("target_username")
- targetUser(targetUsername) {
- return targetUsername === this.currentUser?.get("username");
+ @computed("target_username")
+ get targetUser() {
+ return this.target_username === this.currentUser?.get("username");
}
- @discourseComputed("target_username")
- targetUserUrl(username) {
- return userPath(username);
+ @computed("target_username")
+ get targetUserUrl() {
+ return userPath(this.target_username);
}
- @discourseComputed("username")
- usernameLower(username) {
- return username.toLowerCase();
+ @computed("username")
+ get usernameLower() {
+ return this.username.toLowerCase();
}
- @discourseComputed("usernameLower")
- userUrl(usernameLower) {
- return userPath(usernameLower);
+ @computed("usernameLower")
+ get userUrl() {
+ return userPath(this.usernameLower);
}
- @discourseComputed()
- postUrl() {
+ @computed()
+ get postUrl() {
return postUrl(this.slug, this.topic_id, this.post_number);
}
- @discourseComputed()
- replyUrl() {
+ @computed()
+ get replyUrl() {
return postUrl(this.slug, this.topic_id, this.reply_to_post_number);
}
- @discourseComputed("title")
- titleHtml(title) {
- return title && emojiUnescape(escapeExpression(title));
+ @computed("title")
+ get titleHtml() {
+ return this.title && emojiUnescape(escapeExpression(this.title));
}
addChild(action) {
@@ -203,7 +206,7 @@ export default class UserAction extends RestModel {
}
}
- @discourseComputed(
+ @computed(
"childGroups",
"childGroups.likes.items",
"childGroups.likes.items.[]",
@@ -214,7 +217,7 @@ export default class UserAction extends RestModel {
"childGroups.bookmarks.items",
"childGroups.bookmarks.items.[]"
)
- children() {
+ get children() {
const g = this.childGroups;
let rval = [];
if (g) {
diff --git a/frontend/discourse/app/models/user-badge.js b/frontend/discourse/app/models/user-badge.js
index 8076169a937..5b8152b6cf8 100644
--- a/frontend/discourse/app/models/user-badge.js
+++ b/frontend/discourse/app/models/user-badge.js
@@ -1,8 +1,7 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import Badge from "discourse/models/badge";
import Topic from "discourse/models/topic";
import User from "discourse/models/user";
@@ -143,8 +142,8 @@ export default class UserBadge extends EmberObject {
});
}
- @discourseComputed
- postUrl() {
+ @computed
+ get postUrl() {
if (this.topic_title) {
return "/t/-/" + this.topic_id + "/" + this.post_number;
}
diff --git a/frontend/discourse/app/models/user-draft.js b/frontend/discourse/app/models/user-draft.js
index a441677f3ac..dd0d96b3e4f 100644
--- a/frontend/discourse/app/models/user-draft.js
+++ b/frontend/discourse/app/models/user-draft.js
@@ -1,6 +1,6 @@
+import { computed } from "@ember/object";
import { service } from "@ember/service";
import replaceEmoji from "discourse/helpers/replace-emoji";
-import discourseComputed from "discourse/lib/decorators";
import { userPath } from "discourse/lib/url";
import { postUrl } from "discourse/lib/utilities";
import {
@@ -18,32 +18,32 @@ export default class UserDraft extends RestModel {
return replaceEmoji(this.get("title"));
}
- @discourseComputed("draft_username")
- editableDraft(draftUsername) {
- return draftUsername === this.currentUser?.get("username");
+ @computed("draft_username")
+ get editableDraft() {
+ return this.draft_username === this.currentUser?.get("username");
}
- @discourseComputed("username_lower")
- userUrl(usernameLower) {
- return userPath(usernameLower);
+ @computed("username_lower")
+ get userUrl() {
+ return userPath(this.username_lower);
}
- @discourseComputed("topic_id")
- postUrl(topicId) {
- if (!topicId) {
+ @computed("topic_id")
+ get postUrl() {
+ if (!this.topic_id) {
return;
}
return postUrl(this.slug, this.topic_id, this.post_number);
}
- @discourseComputed("draft_key")
- draftType(draftKey) {
- if (draftKey.startsWith(NEW_TOPIC_KEY)) {
+ @computed("draft_key")
+ get draftType() {
+ if (this.draft_key.startsWith(NEW_TOPIC_KEY)) {
return i18n("drafts.new_topic");
- } else if (draftKey.startsWith(NEW_PRIVATE_MESSAGE_KEY)) {
+ } else if (this.draft_key.startsWith(NEW_PRIVATE_MESSAGE_KEY)) {
return i18n("drafts.new_private_message");
- } else if (draftKey.startsWith(EDIT_TOPIC_KEY)) {
+ } else if (this.draft_key.startsWith(EDIT_TOPIC_KEY)) {
return i18n("drafts.edit_topic");
}
return false;
diff --git a/frontend/discourse/app/models/user-drafts-stream.js b/frontend/discourse/app/models/user-drafts-stream.js
index d2357f1ca73..73bc770dd2e 100644
--- a/frontend/discourse/app/models/user-drafts-stream.js
+++ b/frontend/discourse/app/models/user-drafts-stream.js
@@ -1,6 +1,6 @@
+import { computed } from "@ember/object";
import { Promise } from "rsvp";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { cook, excerpt } from "discourse/lib/text";
import Category from "discourse/models/category";
import {
@@ -30,9 +30,9 @@ export default class UserDraftsStream extends RestModel {
});
}
- @discourseComputed("content.length", "loading")
- noContent(contentLength, loading) {
- return contentLength === 0 && !loading;
+ @computed("content.length", "loading")
+ get noContent() {
+ return this.content?.length === 0 && !this.loading;
}
remove(draft) {
diff --git a/frontend/discourse/app/models/user-stream.js b/frontend/discourse/app/models/user-stream.js
index 79509619336..da75c9103dd 100644
--- a/frontend/discourse/app/models/user-stream.js
+++ b/frontend/discourse/app/models/user-stream.js
@@ -1,8 +1,8 @@
import { tracked } from "@glimmer/tracking";
+import { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
import { removeValueFromArray } from "discourse/lib/array-tools";
import { url } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
import RestModel from "discourse/models/rest";
import Site from "discourse/models/site";
@@ -23,17 +23,17 @@ export default class UserStream extends RestModel {
)
baseUrl;
- @discourseComputed("filter")
- filterParam(filter) {
- if (filter === UserAction.TYPES.replies) {
+ @computed("filter")
+ get filterParam() {
+ if (this.filter === UserAction.TYPES.replies) {
return [UserAction.TYPES.replies, UserAction.TYPES.quotes].join(",");
}
- if (!filter) {
+ if (!this.filter) {
return [UserAction.TYPES.topics, UserAction.TYPES.posts].join(",");
}
- return filter;
+ return this.filter;
}
async filterBy(opts) {
@@ -47,8 +47,8 @@ export default class UserStream extends RestModel {
return this.findItems();
}
- @discourseComputed("baseUrl", "filterParam", "actingUsername")
- nextFindUrl() {
+ @computed("baseUrl", "filterParam", "actingUsername")
+ get nextFindUrl() {
let findUrl = this.baseUrl;
if (this.filterParam) {
findUrl += `&filter=${this.filterParam}`;
@@ -61,13 +61,13 @@ export default class UserStream extends RestModel {
return findUrl;
}
- @discourseComputed("loaded", "content.[]")
- noContent(loaded, content) {
- return loaded && content.length === 0;
+ @computed("loaded", "content.[]")
+ get noContent() {
+ return this.loaded && this.content?.length === 0;
}
- @discourseComputed("nextFindUrl", "lastLoadedUrl")
- canLoadMore() {
+ @computed("nextFindUrl", "lastLoadedUrl")
+ get canLoadMore() {
return this.nextFindUrl !== this.lastLoadedUrl;
}
diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.js
index 97dd45a4dab..7a77b2a4ee3 100644
--- a/frontend/discourse/app/models/user.js
+++ b/frontend/discourse/app/models/user.js
@@ -25,7 +25,6 @@ import {
USER_OPTION_COMPOSITION_MODES,
} from "discourse/lib/constants";
import cookie, { removeCookie } from "discourse/lib/cookie";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { isTesting } from "discourse/lib/environment";
import { longDate } from "discourse/lib/formatter";
@@ -274,34 +273,36 @@ export default class User extends RestModel.extend(Evented) {
statusManager = new UserStatusManager(this);
- @discourseComputed("user_option.composition_mode")
- useRichEditor(compositionMode) {
- return compositionMode === USER_OPTION_COMPOSITION_MODES.rich;
+ @computed("user_option.composition_mode")
+ get useRichEditor() {
+ return (
+ this.user_option?.composition_mode === USER_OPTION_COMPOSITION_MODES.rich
+ );
}
- @discourseComputed("can_be_deleted", "post_count")
- canBeDeleted(canBeDeleted, postCount) {
+ @computed("can_be_deleted", "post_count")
+ get canBeDeleted() {
const maxPostCount = this.siteSettings.delete_all_posts_max;
- return canBeDeleted && postCount <= maxPostCount;
+ return this.can_be_deleted && this.post_count <= maxPostCount;
}
- @discourseComputed()
- stream() {
+ @computed()
+ get stream() {
return UserStream.create({ user: this });
}
- @discourseComputed()
- bookmarks() {
+ @computed()
+ get bookmarks() {
return Bookmark.create({ user: this });
}
- @discourseComputed()
- postsStream() {
+ @computed()
+ get postsStream() {
return UserPostsStream.create({ user: this });
}
- @discourseComputed()
- userDraftsStream() {
+ @computed()
+ get userDraftsStream() {
return UserDraftsStream.create({ user: this });
}
@@ -327,40 +328,47 @@ export default class User extends RestModel.extend(Evented) {
return ajax(`/session/${this.username}`, { type: "DELETE" });
}
- @discourseComputed("username_lower")
- searchContext(username) {
+ @computed("username_lower")
+ get searchContext() {
return {
type: "user",
- id: username,
+ id: this.username_lower,
/** @type User */
user: this,
};
}
- @discourseComputed("username", "name")
- displayName(username, name) {
- if (this.siteSettings.enable_names && !isEmpty(name)) {
- return name;
+ @computed("username", "name")
+ get displayName() {
+ if (this.siteSettings.enable_names && !isEmpty(this.name)) {
+ return this.name;
}
- return username;
+ return this.username;
}
- @discourseComputed("profile_background_upload_url")
- profileBackgroundUrl(bgUrl) {
- if (isEmpty(bgUrl) || !this.siteSettings.allow_profile_backgrounds) {
+ @computed("profile_background_upload_url")
+ get profileBackgroundUrl() {
+ if (
+ isEmpty(this.profile_background_upload_url) ||
+ !this.siteSettings.allow_profile_backgrounds
+ ) {
return htmlSafe("");
}
- return htmlSafe("background-image: url(" + getURLWithCDN(bgUrl) + ")");
+ return htmlSafe(
+ "background-image: url(" +
+ getURLWithCDN(this.profile_background_upload_url) +
+ ")"
+ );
}
- @discourseComputed()
- path() {
+ @computed()
+ get path() {
// no need to observe, requires a hard refresh to update
return userPath(this.username_lower);
}
- @discourseComputed()
- userApiKeys() {
+ @computed()
+ get userApiKeys() {
const keys = this.user_api_keys;
if (keys) {
return keys.map((raw) => {
@@ -417,81 +425,81 @@ export default class User extends RestModel.extend(Evented) {
}
}
- @discourseComputed()
- mutedTopicsPath() {
+ @computed()
+ get mutedTopicsPath() {
return defaultHomepage() === "latest"
? getURL("/?state=muted")
: getURL("/latest?state=muted");
}
- @discourseComputed()
- watchingTopicsPath() {
+ @computed()
+ get watchingTopicsPath() {
return defaultHomepage() === "latest"
? getURL("/?state=watching")
: getURL("/latest?state=watching");
}
- @discourseComputed()
- trackingTopicsPath() {
+ @computed()
+ get trackingTopicsPath() {
return defaultHomepage() === "latest"
? getURL("/?state=tracking")
: getURL("/latest?state=tracking");
}
- @discourseComputed("username")
- username_lower(username) {
- return username.toLowerCase();
+ @computed("username")
+ get username_lower() {
+ return this.username.toLowerCase();
}
- @discourseComputed("trust_level")
- trustLevel(trustLevel) {
+ @computed("trust_level")
+ get trustLevel() {
return Site.currentProp("trustLevels").find(
- (l) => l.id === parseInt(trustLevel, 10)
+ (l) => l.id === parseInt(this.trust_level, 10)
);
}
- @discourseComputed("previous_visit_at")
- previousVisitAt(previous_visit_at) {
- return new Date(previous_visit_at);
+ @computed("previous_visit_at")
+ get previousVisitAt() {
+ return new Date(this.previous_visit_at);
}
- @discourseComputed("suspended_till")
- suspended(suspendedTill) {
- return suspendedTill && moment(suspendedTill).isAfter();
+ @computed("suspended_till")
+ get suspended() {
+ return this.suspended_till && moment(this.suspended_till).isAfter();
}
- @discourseComputed("suspended_till")
- suspendedForever(suspendedTill) {
- return isForever(suspendedTill);
+ @computed("suspended_till")
+ get suspendedForever() {
+ return isForever(this.suspended_till);
}
- @discourseComputed("silenced_till")
- silenced(silencedTill) {
- return silencedTill && moment(silencedTill).isAfter();
+ @computed("silenced_till")
+ get silenced() {
+ return this.silenced_till && moment(this.silenced_till).isAfter();
}
- @discourseComputed("silenced_till")
- silencedForever(silencedTill) {
- return isForever(silencedTill);
+ @computed("silenced_till")
+ get silencedForever() {
+ return isForever(this.silenced_till);
}
- @discourseComputed("suspended_till")
- suspendedTillDate(suspendedTill) {
- return longDate(suspendedTill);
+ @computed("suspended_till")
+ get suspendedTillDate() {
+ return longDate(this.suspended_till);
}
- @discourseComputed("silenced_till")
- silencedTillDate(silencedTill) {
- return longDate(silencedTill);
+ @computed("silenced_till")
+ get silencedTillDate() {
+ return longDate(this.silenced_till);
}
- @discourseComputed("sidebar_tags.[]")
- sidebarTags(sidebarTags) {
- if (!sidebarTags || sidebarTags.length === 0) {
+ @computed("sidebar_tags.[]")
+ get sidebarTags() {
+ if (!this.sidebar_tags || this.sidebar_tags?.length === 0) {
return [];
}
- return sidebarTags.sort((a, b) => {
+ return this.sidebar_tags?.sort((a, b) => {
return a.name.localeCompare(b.name);
});
}
@@ -787,8 +795,8 @@ export default class User extends RestModel.extend(Evented) {
);
}
- @discourseComputed("groups.[]")
- filteredGroups() {
+ @computed("groups.[]")
+ get filteredGroups() {
const groups = this.groups || [];
return groups.filter((group) => {
@@ -796,15 +804,15 @@ export default class User extends RestModel.extend(Evented) {
});
}
- @discourseComputed("filteredGroups", "numGroupsToDisplay")
- displayGroups(filteredGroups, numGroupsToDisplay) {
- const groups = filteredGroups.slice(0, numGroupsToDisplay);
+ @computed("filteredGroups", "numGroupsToDisplay")
+ get displayGroups() {
+ const groups = this.filteredGroups.slice(0, this.numGroupsToDisplay);
return groups.length === 0 ? null : groups;
}
// The user's stat count, excluding PMs.
- @discourseComputed("[email protected]")
- statsCountNonPM() {
+ @computed("[email protected]")
+ get statsCountNonPM() {
if (isEmpty(this.statsExcludingPms)) {
return 0;
}
@@ -818,8 +826,8 @@ export default class User extends RestModel.extend(Evented) {
}
// The user's stats, excluding PMs.
- @discourseComputed("[email protected]")
- statsExcludingPms() {
+ @computed("[email protected]")
+ get statsExcludingPms() {
if (isEmpty(this.stats)) {
return [];
}
@@ -1051,9 +1059,11 @@ export default class User extends RestModel.extend(Evented) {
);
}
- @discourseComputed("can_delete_account")
- canDeleteAccount(canDeleteAccount) {
- return !this.siteSettings.enable_discourse_connect && canDeleteAccount;
+ @computed("can_delete_account")
+ get canDeleteAccount() {
+ return (
+ !this.siteSettings.enable_discourse_connect && this.can_delete_account
+ );
}
@dependentKeyCompat
@@ -1174,8 +1184,8 @@ export default class User extends RestModel.extend(Evented) {
return group.get("can_admin_group") || group.get("is_group_owner");
}
- @discourseComputed("[email protected]", "badges.[]")
- availableTitles() {
+ @computed("[email protected]", "badges.[]")
+ get availableTitles() {
const titles = [];
(this.groups || []).forEach((group) => {
@@ -1200,8 +1210,8 @@ export default class User extends RestModel.extend(Evented) {
});
}
- @discourseComputed("groups.[]")
- availableFlairs() {
+ @computed("groups.[]")
+ get availableFlairs() {
const flairs = [];
if (this.groups) {
@@ -1221,15 +1231,15 @@ export default class User extends RestModel.extend(Evented) {
return flairs;
}
- @discourseComputed("user_option.text_size_seq", "user_option.text_size")
- currentTextSize(serverSeq, serverSize) {
+ @computed("user_option.text_size_seq", "user_option.text_size")
+ get currentTextSize() {
if (cookie(TEXT_SIZE_COOKIE_NAME)) {
const [cookieSize, cookieSeq] = cookie(TEXT_SIZE_COOKIE_NAME).split("|");
- if (cookieSeq >= serverSeq) {
+ if (cookieSeq >= this.user_option?.text_size_seq) {
return cookieSize;
}
}
- return serverSize;
+ return this.user_option?.text_size;
}
updateTextSizeCookie(newSize) {
@@ -1244,12 +1254,12 @@ export default class User extends RestModel.extend(Evented) {
}
}
- @discourseComputed("second_factor_enabled", "staff")
- enforcedSecondFactor(secondFactorEnabled, staff) {
+ @computed("second_factor_enabled", "staff")
+ get enforcedSecondFactor() {
const enforce = this.siteSettings.enforce_second_factor;
return (
- !secondFactorEnabled &&
- (enforce === "all" || (enforce === "staff" && staff))
+ !this.second_factor_enabled &&
+ (enforce === "all" || (enforce === "staff" && this.staff))
);
}
@@ -1325,13 +1335,13 @@ export default class User extends RestModel.extend(Evented) {
return getOwner(this).lookup("service:notifications").isInDoNotDisturb;
}
- @discourseComputed(
- "tracked_tags.[]",
- "watched_tags.[]",
- "watching_first_post_tags.[]"
- )
- trackedTags(trackedTags, watchedTags, watchingFirstPostTags) {
- return [...trackedTags, ...watchedTags, ...watchingFirstPostTags];
+ @computed("tracked_tags.[]", "watched_tags.[]", "watching_first_post_tags.[]")
+ get trackedTags() {
+ return [
+ ...(this.tracked_tags || []),
+ ...(this.watched_tags || []),
+ ...(this.watching_first_post_tags || []),
+ ];
}
get prefersLightColor() {
diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.js
index fda8ace574f..1be5acdc9d7 100644
--- a/frontend/discourse/app/services/composer.js
+++ b/frontend/discourse/app/services/composer.js
@@ -20,7 +20,6 @@ import {
import { popupAjaxError } from "discourse/lib/ajax-error";
import { customPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import deprecated from "discourse/lib/deprecated";
import { isRailsTesting } from "discourse/lib/environment";
import prepareFormTemplateData, {
@@ -251,9 +250,9 @@ export default class ComposerService extends Service {
this.selectedFormTemplate = formTemplate;
}
- @discourseComputed("showPreview")
- toggleText(showPreview) {
- return showPreview
+ @computed("showPreview")
+ get toggleText() {
+ return this.showPreview
? i18n("composer.hide_preview")
: i18n("composer.show_preview");
}
@@ -268,27 +267,27 @@ export default class ComposerService extends Service {
}
}
- @discourseComputed(
+ @computed(
"model.replyingToTopic",
"model.creatingPrivateMessage",
"model.targetRecipients",
"model.composeState"
)
- focusTarget(replyingToTopic, creatingPM, usernames, composeState) {
+ get focusTarget() {
// Focus on usernames if it's blank or if it's just you
- usernames = usernames || "";
+ const usernames = this.model?.targetRecipients || "";
if (
- (creatingPM && usernames.length === 0) ||
+ (this.model?.creatingPrivateMessage && usernames.length === 0) ||
usernames === this.currentUser.username
) {
return "usernames";
}
- if (replyingToTopic) {
+ if (this.model?.replyingToTopic) {
return "reply";
}
- if (composeState === Composer.FULLSCREEN) {
+ if (this.model?.composeState === Composer.FULLSCREEN) {
return "editor";
}
@@ -316,54 +315,56 @@ export default class ComposerService extends Service {
});
}
- @discourseComputed("model.canEditTitle", "model.creatingPrivateMessage")
- canEditTags(canEditTitle, creatingPrivateMessage) {
+ @computed("model.canEditTitle", "model.creatingPrivateMessage")
+ get canEditTags() {
const isPrivateMessage =
- creatingPrivateMessage || this.get("model.topic.isPrivateMessage");
+ this.model?.creatingPrivateMessage ||
+ this.get("model.topic.isPrivateMessage");
return (
- canEditTitle &&
+ this.model?.canEditTitle &&
this.site.can_tag_topics &&
(!isPrivateMessage || this.site.can_tag_pms)
);
}
- @discourseComputed("model.editingPost", "model.topic.details.can_edit")
- disableCategoryChooser(editingPost, canEditTopic) {
- return editingPost && !canEditTopic;
+ @computed("model.editingPost", "model.topic.details.can_edit")
+ get disableCategoryChooser() {
+ return this.model?.editingPost && !this.model?.topic?.details?.can_edit;
}
- @discourseComputed("model.editingPost", "model.topic.canEditTags")
- disableTagsChooser(editingPost, canEditTags) {
- return editingPost && !canEditTags;
+ @computed("model.editingPost", "model.topic.canEditTags")
+ get disableTagsChooser() {
+ return this.model?.editingPost && !this.model?.topic?.canEditTags;
}
- @discourseComputed("canWhisper", "replyingToWhisper")
- showWhisperToggle(canWhisper, replyingToWhisper) {
- return canWhisper && !replyingToWhisper;
+ @computed("canWhisper", "replyingToWhisper")
+ get showWhisperToggle() {
+ return this.canWhisper && !this.replyingToWhisper;
}
- @discourseComputed("model.post")
- replyingToWhisper(repliedToPost) {
+ @computed("model.post")
+ get replyingToWhisper() {
return (
- repliedToPost && repliedToPost.post_type === this.site.post_types.whisper
+ this.model?.post &&
+ this.model?.post?.post_type === this.site.post_types.whisper
);
}
- @discourseComputed("model.action", "isWhispering", "model.privateMessage")
- saveIcon(modelAction, isWhispering, privateMessage) {
- if (isWhispering) {
+ @computed("model.action", "isWhispering", "model.privateMessage")
+ get saveIcon() {
+ if (this.isWhispering) {
return "far-eye-slash";
}
- if (privateMessage && modelAction === Composer.REPLY) {
+ if (this.model?.privateMessage && this.model?.action === Composer.REPLY) {
return "envelope";
}
- return SAVE_ICONS[modelAction];
+ return SAVE_ICONS[this.model?.action];
}
// Note we update when some other attributes like tag/category change to allow
// text customizations to use those.
- @discourseComputed(
+ @computed(
"model.action",
"isWhispering",
"model.editConflict",
@@ -371,26 +372,29 @@ export default class ComposerService extends Service {
"model.tags",
"model.category"
)
- saveLabel(modelAction, isWhispering, editConflict, privateMessage) {
+ get saveLabel() {
let result = this.model.customizationFor("saveLabel");
if (result) {
return result;
}
- if (editConflict) {
+ if (this.model?.editConflict) {
return "composer.overwrite_edit";
- } else if (isWhispering) {
+ } else if (this.isWhispering) {
return "composer.create_whisper";
- } else if (privateMessage && modelAction === Composer.REPLY) {
+ } else if (
+ this.model?.privateMessage &&
+ this.model?.action === Composer.REPLY
+ ) {
return "composer.create_pm";
}
- return SAVE_LABELS[modelAction];
+ return SAVE_LABELS[this.model?.action];
}
- @discourseComputed("whisperer", "model.action")
- canWhisper(whisperer, modelAction) {
- return whisperer && modelAction === Composer.REPLY;
+ @computed("whisperer", "model.action")
+ get canWhisper() {
+ return this.whisperer && this.model?.action === Composer.REPLY;
}
_setupPopupMenuOption(option) {
@@ -419,14 +423,17 @@ export default class ComposerService extends Service {
return option;
}
- @discourseComputed("model.requiredCategoryMissing", "model.replyLength")
- disableTextarea(requiredCategoryMissing, replyLength) {
- return requiredCategoryMissing && replyLength === 0;
+ @computed("model.requiredCategoryMissing", "model.replyLength")
+ get disableTextarea() {
+ return this.model?.requiredCategoryMissing && this.model?.replyLength === 0;
}
- @discourseComputed("model.composeState", "model.creatingTopic", "model.post")
- popupMenuOptions(composeState) {
- if (composeState === "open" || composeState === "fullscreen") {
+ @computed("model.composeState", "model.creatingTopic", "model.post")
+ get popupMenuOptions() {
+ if (
+ this.model?.composeState === "open" ||
+ this.model?.composeState === "fullscreen"
+ ) {
const options = [];
options.push(
@@ -498,13 +505,13 @@ export default class ComposerService extends Service {
}
}
- @discourseComputed(
+ @computed(
"model.creatingPrivateMessage",
"model.targetRecipients",
"model.warningsDisabled"
)
- showWarning(creatingPrivateMessage, usernames, warningsDisabled) {
- if (!this.get("currentUser.staff") || warningsDisabled) {
+ get showWarning() {
+ if (!this.get("currentUser.staff") || this.model?.warningsDisabled) {
return false;
}
@@ -512,42 +519,42 @@ export default class ComposerService extends Service {
// We need exactly one user to issue a warning
if (
- isEmpty(usernames) ||
- usernames.split(",").length !== 1 ||
+ isEmpty(this.model?.targetRecipients) ||
+ this.model?.targetRecipients?.split(",")?.length !== 1 ||
hasTargetGroups
) {
return false;
}
- return creatingPrivateMessage;
+ return this.model?.creatingPrivateMessage;
}
- @discourseComputed("model.topic.title")
- draftTitle(topicTitle) {
- return emojiUnescape(escapeExpression(topicTitle));
+ @computed("model.topic.title")
+ get draftTitle() {
+ return emojiUnescape(escapeExpression(this.model?.topic?.title));
}
- @discourseComputed
- allowUpload() {
+ @computed
+ get allowUpload() {
return authorizesOneOrMoreExtensions(
this.currentUser.staff,
this.siteSettings
);
}
- @discourseComputed()
- uploadIcon() {
+ @computed()
+ get uploadIcon() {
return uploadIcon(this.currentUser.staff, this.siteSettings);
}
- @discourseComputed(
+ @computed(
"model.action",
"isWhispering",
"model.privateMessage",
"model.post.username"
)
- ariaLabel(modelAction, isWhispering, privateMessage, postUsername) {
- switch (modelAction) {
+ get ariaLabel() {
+ switch (this.model?.action) {
case "createSharedDraft":
return i18n("composer.create_shared_draft");
case "editSharedDraft":
@@ -559,17 +566,17 @@ export default class ComposerService extends Service {
case "edit":
return i18n("composer.composer_actions.edit");
case "reply":
- if (isWhispering) {
+ if (this.isWhispering) {
return `${i18n("composer.create_whisper")} ${this.site.get(
"whispers_allowed_groups_names"
)}`;
}
- if (privateMessage) {
+ if (this.model?.privateMessage) {
return i18n("composer.create_pm");
}
- if (postUsername) {
+ if (this.model?.post?.username) {
return i18n("composer.composer_actions.reply_to_post.label", {
- postUsername,
+ postUsername: this.model?.post?.username,
});
} else {
return i18n("composer.composer_actions.reply_to_topic.label");
@@ -1828,29 +1835,36 @@ export default class ComposerService extends Service {
}
}
- @discourseComputed("model.categoryId", "lastValidatedAt")
- categoryValidation(categoryId, lastValidatedAt) {
- if (!this.siteSettings.allow_uncategorized_topics && !categoryId) {
+ @computed("model.categoryId", "lastValidatedAt")
+ get categoryValidation() {
+ if (
+ !this.siteSettings.allow_uncategorized_topics &&
+ !this.model?.categoryId
+ ) {
return EmberObject.create({
failed: true,
reason: i18n("composer.error.category_missing"),
- lastShownAt: lastValidatedAt,
+ lastShownAt: this.lastValidatedAt,
});
}
}
- @discourseComputed("model.category", "model.tags", "lastValidatedAt")
- tagValidation(category, tags, lastValidatedAt) {
- const tagsArray = tags || [];
- if (this.site.can_tag_topics && !this.currentUser.staff && category) {
+ @computed("model.category", "model.tags", "lastValidatedAt")
+ get tagValidation() {
+ const tagsArray = this.model?.tags || [];
+ if (
+ this.site.can_tag_topics &&
+ !this.currentUser.staff &&
+ this.model?.category
+ ) {
// category.minimumRequiredTags incorporates both minimum_required_tags, and required_tag_groups
- if (category.minimumRequiredTags > tagsArray.length) {
+ if (this.model?.category?.minimumRequiredTags > tagsArray.length) {
return EmberObject.create({
failed: true,
reason: i18n("composer.error.tags_missing", {
- count: category.minimumRequiredTags,
+ count: this.model?.category?.minimumRequiredTags,
}),
- lastShownAt: lastValidatedAt,
+ lastShownAt: this.lastValidatedAt,
});
}
}
@@ -1875,9 +1889,13 @@ export default class ComposerService extends Service {
}
}
- @discourseComputed("model.viewFullscreen", "model.showFullScreenExitPrompt")
- showFullScreenPrompt(isFullscreen, showExitPrompt) {
- return isFullscreen && showExitPrompt && !this.capabilities.touch;
+ @computed("model.viewFullscreen", "model.showFullScreenExitPrompt")
+ get showFullScreenPrompt() {
+ return (
+ this.model?.viewFullscreen &&
+ this.model?.showFullScreenExitPrompt &&
+ !this.capabilities.touch
+ );
}
close() {
@@ -1897,14 +1915,14 @@ export default class ComposerService extends Service {
this.set("formTemplateInitialValues", undefined);
}
- @discourseComputed("model.action")
- canEdit(modelAction) {
- return modelAction === "edit" && this.currentUser.can_edit;
+ @computed("model.action")
+ get canEdit() {
+ return this.model?.action === "edit" && this.currentUser.can_edit;
}
- @discourseComputed("model.composeState")
- visible(state) {
- return state && state !== "closed";
+ @computed("model.composeState")
+ get visible() {
+ return this.model?.composeState && this.model?.composeState !== "closed";
}
clearLastValidatedAt() {
diff --git a/frontend/discourse/app/services/logs-notice.js b/frontend/discourse/app/services/logs-notice.js
index c1d2eb5e64c..723d5a91978 100644
--- a/frontend/discourse/app/services/logs-notice.js
+++ b/frontend/discourse/app/services/logs-notice.js
@@ -1,10 +1,11 @@
/* eslint-disable ember/no-observers */
+import { computed } from "@ember/object";
import { readOnly } from "@ember/object/computed";
import Service, { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { isEmpty } from "@ember/utils";
import { observes } from "@ember-decorators/object";
-import discourseComputed, { bind } from "discourse/lib/decorators";
+import { bind } from "discourse/lib/decorators";
import { autoUpdatingRelativeAge } from "discourse/lib/formatter";
import getURL from "discourse/lib/get-url";
import I18n from "discourse-i18n";
@@ -73,19 +74,19 @@ export default class LogsNoticeService extends Service {
);
}
- @discourseComputed("text")
- isEmpty(text) {
- return isEmpty(text);
+ @computed("text")
+ get isEmpty() {
+ return isEmpty(this.text);
}
- @discourseComputed("text")
- message(text) {
- return htmlSafe(text);
+ @computed("text")
+ get message() {
+ return htmlSafe(this.text);
}
- @discourseComputed("isEmpty", "isAdmin")
- hidden(thisIsEmpty, isAdmin) {
- return !isAdmin || thisIsEmpty;
+ @computed("isEmpty", "isAdmin")
+ get hidden() {
+ return !this.isAdmin || this.isEmpty;
}
@observes("text")
diff --git a/frontend/discourse/select-kit/components/category-drop/category-drop-header.gjs b/frontend/discourse/select-kit/components/category-drop/category-drop-header.gjs
index fdaf55c4bf3..484319bbc0b 100644
--- a/frontend/discourse/select-kit/components/category-drop/category-drop-header.gjs
+++ b/frontend/discourse/select-kit/components/category-drop/category-drop-header.gjs
@@ -1,19 +1,19 @@
+import { computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
import ComboBoxSelectBoxHeaderComponent from "discourse/select-kit/components/combo-box/combo-box-header";
import { resolveComponent } from "discourse/select-kit/components/select-kit";
@classNames("category-drop-header")
export default class CategoryDropHeader extends ComboBoxSelectBoxHeaderComponent {
- @discourseComputed("selectedContent.color")
- categoryBackgroundColor(categoryColor) {
- return categoryColor || "#e9e9e9";
+ @computed("selectedContent.color")
+ get categoryBackgroundColor() {
+ return this.selectedContent?.color || "#e9e9e9";
}
- @discourseComputed("selectedContent.text_color")
- categoryTextColor(categoryTextColor) {
- return categoryTextColor || "#333";
+ @computed("selectedContent.text_color")
+ get categoryTextColor() {
+ return this.selectedContent?.text_color || "#333";
}
<template>
diff --git a/frontend/discourse/select-kit/components/composer-actions.js b/frontend/discourse/select-kit/components/composer-actions.js
index d47a880a85c..c110b7864be 100644
--- a/frontend/discourse/select-kit/components/composer-actions.js
+++ b/frontend/discourse/select-kit/components/composer-actions.js
@@ -1,10 +1,9 @@
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal, gt } from "@ember/object/computed";
import { service } from "@ember/service";
import { camelize } from "@ember/string";
import { isEmpty } from "@ember/utils";
import { classNames } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { escapeExpression } from "discourse/lib/utilities";
import {
CREATE_SHARED_DRAFT,
@@ -48,27 +47,21 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
@equal("action", EDIT) isEditing;
@gt("topic.slow_mode_seconds", 0) isInSlowMode;
- @discourseComputed("isEditing", "action", "whisper", "noBump", "isInSlowMode")
- iconForComposerAction(
- isEditing,
- composerAction,
- whisper,
- noBump,
- isInSlowMode
- ) {
- if (composerAction === CREATE_TOPIC) {
+ @computed("isEditing", "action", "whisper", "noBump", "isInSlowMode")
+ get iconForComposerAction() {
+ if (this.action === CREATE_TOPIC) {
return "plus";
- } else if (composerAction === PRIVATE_MESSAGE) {
+ } else if (this.action === PRIVATE_MESSAGE) {
return "envelope";
- } else if (composerAction === CREATE_SHARED_DRAFT) {
+ } else if (this.action === CREATE_SHARED_DRAFT) {
return "far-clipboard";
- } else if (whisper) {
+ } else if (this.whisper) {
return "far-eye-slash";
- } else if (noBump) {
+ } else if (this.noBump) {
return "anchor";
- } else if (isInSlowMode) {
+ } else if (this.isInSlowMode) {
return "hourglass-start";
- } else if (isEditing) {
+ } else if (this.isEditing) {
return "pencil";
} else {
return "share";
@@ -115,8 +108,8 @@ export default class ComposerActions extends DropdownSelectBoxComponent {
return {};
}
- @discourseComputed("seq")
- content() {
+ @computed("seq")
+ get content() {
let items = [];
if (
diff --git a/frontend/discourse/select-kit/components/multi-select/multi-select-filter.gjs b/frontend/discourse/select-kit/components/multi-select/multi-select-filter.gjs
index e922209dfda..f792476ae33 100644
--- a/frontend/discourse/select-kit/components/multi-select/multi-select-filter.gjs
+++ b/frontend/discourse/select-kit/components/multi-select/multi-select-filter.gjs
@@ -1,21 +1,20 @@
import { Input } from "@ember/component";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { isEmpty } from "@ember/utils";
import { classNames } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
import SelectKitFilterComponent from "discourse/select-kit/components/select-kit/select-kit-filter";
@classNames("multi-select-filter")
export default class MultiSelectFilter extends SelectKitFilterComponent {
- @discourseComputed("placeholder", "selectKit.hasSelection")
- computedPlaceholder(placeholder, hasSelection) {
- if (this.hidePlaceholderWithSelection && hasSelection) {
+ @computed("placeholder", "selectKit.hasSelection")
+ get computedPlaceholder() {
+ if (this.hidePlaceholderWithSelection && this.selectKit?.hasSelection) {
return "";
}
- return isEmpty(placeholder) ? "" : placeholder;
+ return isEmpty(this.placeholder) ? "" : this.placeholder;
}
@action
diff --git a/frontend/discourse/select-kit/components/multi-select/selected-color.js b/frontend/discourse/select-kit/components/multi-select/selected-color.js
index c81e2cf24c1..4b8803e4061 100644
--- a/frontend/discourse/select-kit/components/multi-select/selected-color.js
+++ b/frontend/discourse/select-kit/components/multi-select/selected-color.js
@@ -1,14 +1,14 @@
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { classNames } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import SelectedNameComponent from "discourse/select-kit/components/selected-name";
@classNames("select-kit-selected-color")
export default class SelectedColor extends SelectedNameComponent {
- @discourseComputed("name")
- footerContent(name) {
+ @computed("name")
+ get footerContent() {
return htmlSafe(
- `<span class="color-preview" style="background:#${name}"></span>`
+ `<span class="color-preview" style="background:#${this.name}"></span>`
);
}
}
diff --git a/frontend/discourse/select-kit/components/none-category-row.gjs b/frontend/discourse/select-kit/components/none-category-row.gjs
index 5293a360be0..d4b5d657cb4 100644
--- a/frontend/discourse/select-kit/components/none-category-row.gjs
+++ b/frontend/discourse/select-kit/components/none-category-row.gjs
@@ -1,20 +1,20 @@
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { classNames } from "@ember-decorators/component";
import { categoryBadgeHTML } from "discourse/helpers/category-link";
import dirSpan from "discourse/helpers/dir-span";
-import discourseComputed from "discourse/lib/decorators";
import CategoryRowComponent from "discourse/select-kit/components/category-row";
@classNames("none category-row")
export default class NoneCategoryRow extends CategoryRowComponent {
- @discourseComputed("category")
- badgeForCategory(category) {
+ @computed("category")
+ get badgeForCategory() {
return htmlSafe(
- categoryBadgeHTML(category, {
+ categoryBadgeHTML(this.category, {
link: false,
allowUncategorized: true,
hideParent: true,
- ancestors: category?.predecessors,
+ ancestors: this.category?.predecessors,
})
);
}
diff --git a/frontend/discourse/select-kit/components/notifications-filter/notifications-filter-header.gjs b/frontend/discourse/select-kit/components/notifications-filter/notifications-filter-header.gjs
index 26c949d2698..2af4eacca62 100644
--- a/frontend/discourse/select-kit/components/notifications-filter/notifications-filter-header.gjs
+++ b/frontend/discourse/select-kit/components/notifications-filter/notifications-filter-header.gjs
@@ -1,7 +1,7 @@
+import { computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
import { fmt } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import DropdownSelectBoxHeaderComponent from "discourse/select-kit/components/dropdown-select-box/dropdown-select-box-header";
import { i18n } from "discourse-i18n";
@@ -9,9 +9,9 @@ import { i18n } from "discourse-i18n";
export default class NotificationsFilterHeader extends DropdownSelectBoxHeaderComponent {
@fmt("value", "user.user_notifications.filters.%@") label;
- @discourseComputed("selectKit.isExpanded")
- caretIcon(isExpanded) {
- return isExpanded ? "angle-up" : "angle-down";
+ @computed("selectKit.isExpanded")
+ get caretIcon() {
+ return this.selectKit?.isExpanded ? "angle-up" : "angle-down";
}
<template>
diff --git a/frontend/discourse/select-kit/components/period-chooser/period-chooser-header.gjs b/frontend/discourse/select-kit/components/period-chooser/period-chooser-header.gjs
index 2e24d890124..b607af47ddb 100644
--- a/frontend/discourse/select-kit/components/period-chooser/period-chooser-header.gjs
+++ b/frontend/discourse/select-kit/components/period-chooser/period-chooser-header.gjs
@@ -1,14 +1,14 @@
+import { computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
import periodTitle from "discourse/helpers/period-title";
-import discourseComputed from "discourse/lib/decorators";
import DropdownSelectBoxHeaderComponent from "discourse/select-kit/components/dropdown-select-box/dropdown-select-box-header";
@classNames("period-chooser-header", "btn-flat")
export default class PeriodChooserHeader extends DropdownSelectBoxHeaderComponent {
- @discourseComputed("selectKit.isExpanded")
- caretIcon(isExpanded) {
- return isExpanded ? "angle-up" : "angle-down";
+ @computed("selectKit.isExpanded")
+ get caretIcon() {
+ return this.selectKit?.isExpanded ? "angle-up" : "angle-down";
}
<template>
diff --git a/frontend/discourse/select-kit/components/period-chooser/period-chooser-row.gjs b/frontend/discourse/select-kit/components/period-chooser/period-chooser-row.gjs
index 070aa06e883..3bcec071b18 100644
--- a/frontend/discourse/select-kit/components/period-chooser/period-chooser-row.gjs
+++ b/frontend/discourse/select-kit/components/period-chooser/period-chooser-row.gjs
@@ -1,14 +1,14 @@
+import { computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
import periodTitle from "discourse/helpers/period-title";
-import discourseComputed from "discourse/lib/decorators";
import DropdownSelectBoxRowComponent from "discourse/select-kit/components/dropdown-select-box/dropdown-select-box-row";
import { i18n } from "discourse-i18n";
@classNames("period-chooser-row")
export default class PeriodChooserRow extends DropdownSelectBoxRowComponent {
- @discourseComputed("rowName")
- title(rowName) {
- return i18n(`filters.top.${rowName || "this_week"}`).title;
+ @computed("rowName")
+ get title() {
+ return i18n(`filters.top.${this.rowName || "this_week"}`).title;
}
<template>
diff --git a/frontend/discourse/select-kit/components/select-kit/select-kit-filter.gjs b/frontend/discourse/select-kit/components/select-kit/select-kit-filter.gjs
index 99776556e7e..09b479d90bb 100644
--- a/frontend/discourse/select-kit/components/select-kit/select-kit-filter.gjs
+++ b/frontend/discourse/select-kit/components/select-kit/select-kit-filter.gjs
@@ -10,7 +10,6 @@ import {
classNames,
} from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import discourseComputed from "discourse/lib/decorators";
import selectKitPropUtils from "discourse/select-kit/lib/select-kit-prop-utils";
import { i18n } from "discourse-i18n";
@@ -35,18 +34,18 @@ export default class SelectKitFilter extends Component {
);
}
- @discourseComputed(
+ @computed(
"selectKit.options.filterPlaceholder",
"selectKit.options.translatedFilterPlaceholder",
"selectKit.options.allowAny"
)
- placeholder(placeholder, translatedPlaceholder) {
- if (isPresent(translatedPlaceholder)) {
- return translatedPlaceholder;
+ get placeholder() {
+ if (isPresent(this.selectKit?.options?.translatedFilterPlaceholder)) {
+ return this.selectKit?.options?.translatedFilterPlaceholder;
}
- if (isPresent(placeholder)) {
- return i18n(placeholder);
+ if (isPresent(this.selectKit?.options?.filterPlaceholder)) {
+ return i18n(this.selectKit?.options?.filterPlaceholder);
}
return i18n(
diff --git a/frontend/discourse/select-kit/components/tag-row.gjs b/frontend/discourse/select-kit/components/tag-row.gjs
index 650eae96569..cb0bb1a54b1 100644
--- a/frontend/discourse/select-kit/components/tag-row.gjs
+++ b/frontend/discourse/select-kit/components/tag-row.gjs
@@ -1,13 +1,13 @@
+import { computed } from "@ember/object";
import { classNames } from "@ember-decorators/component";
import discourseTag from "discourse/helpers/discourse-tag";
-import discourseComputed from "discourse/lib/decorators";
import SelectKitRowComponent from "discourse/select-kit/components/select-kit/select-kit-row";
@classNames("tag-row")
export default class TagRow extends SelectKitRowComponent {
- @discourseComputed("item")
- isTag(item) {
- return item.id !== "no-tags" && item.id !== "all-tags";
+ @computed("item")
+ get isTag() {
+ return this.item.id !== "no-tags" && this.item.id !== "all-tags";
}
<template>
diff --git a/frontend/discourse/tests/unit/lib/plugin-api-test.js b/frontend/discourse/tests/unit/lib/plugin-api-test.js
index e896120ff5b..0a8257e16e6 100644
--- a/frontend/discourse/tests/unit/lib/plugin-api-test.js
+++ b/frontend/discourse/tests/unit/lib/plugin-api-test.js
@@ -6,7 +6,6 @@ import { module, test } from "qunit";
import { block } from "discourse/blocks";
import { BlockCondition, blockCondition } from "discourse/blocks/conditions";
import { rollbackAllPrepends } from "discourse/lib/class-prepend";
-import discourseComputed from "discourse/lib/decorators";
import { withPluginApi } from "discourse/lib/plugin-api";
import {
getBlockEntry,
@@ -45,8 +44,8 @@ module("Unit | Utility | plugin-api", function (hooks) {
test("modifyClass works with native class Ember objects", function (assert) {
class NativeTestThingy extends EmberObject {
- @discourseComputed
- prop() {
+ @computed
+ get prop() {
return "howdy";
}
}
diff --git a/frontend/discourse/tests/unit/utils/decorators-test.js b/frontend/discourse/tests/unit/utils/decorators-test.js
index 076b821eea2..f3cdd27fa9c 100644
--- a/frontend/discourse/tests/unit/utils/decorators-test.js
+++ b/frontend/discourse/tests/unit/utils/decorators-test.js
@@ -1,10 +1,11 @@
/* eslint-disable ember/no-classic-components, ember/no-observers */
import Component from "@ember/component";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { clearRender, render, settled } from "@ember/test-helpers";
import { observes as nativeClassObserves } from "@ember-decorators/object";
import { hbs } from "ember-cli-htmlbars";
import { module, test } from "qunit";
+// eslint-disable-next-line discourse/no-discourse-computed
import discourseComputed, {
afterRender,
debounce,
@@ -43,6 +44,7 @@ const EmberObjectComponent = Component.extend({
name: "",
layout: hbs`<span class="ember-object-component">{{this.text}}</span>`,
+ // eslint-disable-next-line discourse/no-discourse-computed
@discourseComputed("name")
text(name) {
return `hello, ${name}`;
@@ -53,9 +55,9 @@ class NativeComponent extends Component {
name = "";
layout = hbs`<span class="native-component">{{this.text}}</span>`;
- @discourseComputed("name")
- text(name) {
- return `hello, ${name}`;
+ @computed("name")
+ get text() {
+ return `hello, ${this.name}`;
}
}
diff --git a/package.json b/package.json
index a83355e8a1e..b5d413b207c 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"license": "GPL-2.0-only",
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.29.0",
- "@discourse/lint-configs": "^2.40.0",
+ "@discourse/lint-configs": "^2.41.0",
"@discourse/moment-timezone-names-translations": "^1.0.0",
"@fortawesome/fontawesome-free": "7.1.0",
"@glint/ember-tsc": "^1.1.1",
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.gjs
index bcde067db88..04a7f1fa4db 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.gjs
@@ -1,13 +1,13 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { fn } from "@ember/helper";
+import { computed } from "@ember/object";
import { alias, equal } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import ChooseTopic from "discourse/components/choose-topic";
import RadioButton from "discourse/components/radio-button";
import TextField from "discourse/components/text-field";
-import discourseComputed from "discourse/lib/decorators";
import CategoryChooser from "discourse/select-kit/components/category-chooser";
import TagChooser from "discourse/select-kit/components/tag-chooser";
import { and } from "discourse/truth-helpers";
@@ -37,18 +37,18 @@ export default class ChatToTopicSelector extends Component {
chatMessageIds = null;
chatChannelId = null;
- @discourseComputed()
- newTopicInstruction() {
+ @computed()
+ get newTopicInstruction() {
return htmlSafe(this.instructionLabels[NEW_TOPIC_SELECTION]);
}
- @discourseComputed()
- existingTopicInstruction() {
+ @computed()
+ get existingTopicInstruction() {
return htmlSafe(this.instructionLabels[EXISTING_TOPIC_SELECTION]);
}
- @discourseComputed()
- newMessageInstruction() {
+ @computed()
+ get newMessageInstruction() {
return htmlSafe(this.instructionLabels[NEW_MESSAGE_SELECTION]);
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
index 3fee38f1b03..fe777b7abb1 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
@@ -1,10 +1,10 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { alias, or } from "@ember/object/computed";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { throwAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import {
isNthPost,
isNthTopicListItem,
@@ -41,23 +41,29 @@ export default class AdComponent extends Component {
this.trackClick();
};
- @discourseComputed(
+ @computed(
"router.currentRoute.attributes.__type",
"router.currentRoute.attributes.id"
)
- topicListTag(type, tag) {
- if (type === "tag" && tag) {
- return tag;
+ get topicListTag() {
+ if (
+ this.router?.currentRoute?.attributes?.__type === "tag" &&
+ this.router?.currentRoute?.attributes?.id
+ ) {
+ return this.router?.currentRoute?.attributes?.id;
}
}
- @discourseComputed("router.currentRoute.parent.attributes.archetype")
- isPersonalMessage(topicType) {
- return topicType === "private_message";
+ @computed("router.currentRoute.parent.attributes.archetype")
+ get isPersonalMessage() {
+ return (
+ this.router?.currentRoute?.parent?.attributes?.archetype ===
+ "private_message"
+ );
}
- @discourseComputed
- showToGroups() {
+ @computed
+ get showToGroups() {
if (!this.currentUser) {
return true;
}
@@ -65,32 +71,29 @@ export default class AdComponent extends Component {
return this.currentUser.show_to_groups;
}
- @discourseComputed(
+ @computed(
"currentCategoryId",
"topicTagsDisableAds",
"topicListTag",
"isPersonalMessage",
"isRestrictedCategory"
)
- showOnCurrentPage(
- categoryId,
- topicTagsDisableAds,
- topicListTag,
- isPersonalMessage,
- isRestrictedCategory
- ) {
+ get showOnCurrentPage() {
return (
- !topicTagsDisableAds &&
- (!categoryId ||
+ !this.topicTagsDisableAds &&
+ (!this.currentCategoryId ||
!this.siteSettings.no_ads_for_categories ||
!this.siteSettings.no_ads_for_categories
.split("|")
- .includes(categoryId.toString())) &&
- (!topicListTag ||
+ .includes(this.currentCategoryId.toString())) &&
+ (!this.topicListTag ||
!this.siteSettings.no_ads_for_tags ||
- !this.siteSettings.no_ads_for_tags.split("|").includes(topicListTag)) &&
- (!isPersonalMessage || !this.siteSettings.no_ads_for_personal_messages) &&
- (!isRestrictedCategory ||
+ !this.siteSettings.no_ads_for_tags
+ .split("|")
+ .includes(this.topicListTag)) &&
+ (!this.isPersonalMessage ||
+ !this.siteSettings.no_ads_for_personal_messages) &&
+ (!this.isRestrictedCategory ||
!this.siteSettings.no_ads_for_restricted_categories)
);
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-slot.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-slot.gjs
index 89795ad822f..5d0f9236ac0 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-slot.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-slot.gjs
@@ -1,9 +1,8 @@
import { array } from "@ember/helper";
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { service } from "@ember/service";
import { isBlank } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { isNthPost, isNthTopicListItem } from "../helpers/slot-position";
import AdComponent from "./ad-component";
import AdbutlerAd from "./adbutler-ad";
@@ -195,14 +194,14 @@ export default class AdSlot extends AdComponent {
* For a given ad placement and optionally a post number if in between posts,
* list all ad network names that are configured to show there.
*/
- @discourseComputed("placement", "postNumber", "indexNumber")
- availableAdTypes(placement, postNumber, indexNumber) {
+ @computed("placement", "postNumber", "indexNumber")
+ get availableAdTypes() {
return slotContenders(
this.site,
this.siteSettings,
- placement,
- indexNumber,
- postNumber
+ this.placement,
+ this.indexNumber,
+ this.postNumber
);
}
@@ -213,15 +212,15 @@ export default class AdSlot extends AdComponent {
*
* Depends on `router.currentRoute` so that we refresh ads when navigating around.
*/
- @discourseComputed("placement", "availableAdTypes", "router.currentRoute")
- adComponentNames(placement, availableAdTypes) {
+ @computed("placement", "availableAdTypes", "router.currentRoute")
+ get adComponentNames() {
if (
- !availableAdTypes.includes("house-ad") ||
- availableAdTypes.length === 1
+ !this.availableAdTypes.includes("house-ad") ||
+ this.availableAdTypes.length === 1
) {
// Current behaviour is to allow multiple ads from different networks
// to show in the same place. We could change this to choose one somehow.
- return availableAdTypes;
+ return this.availableAdTypes;
}
const houseAds = this.site.get("house_creatives");
@@ -245,7 +244,7 @@ export default class AdSlot extends AdComponent {
}
}
- const networkNames = availableAdTypes.filter((x) => x !== "house-ad");
+ const networkNames = this.availableAdTypes.filter((x) => x !== "house-ad");
if (houseAdsSkipped) {
displayCounts.allAds += networkNames.length;
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs
index 9f48ac7c70d..8f95f5c3af5 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs
@@ -1,6 +1,6 @@
+import { computed } from "@ember/object";
import { scheduleOnce } from "@ember/runloop";
import RSVP from "rsvp";
-import discourseComputed from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import loadScript from "discourse/lib/load-script";
import AdComponent from "./ad-component";
@@ -111,8 +111,8 @@ export default class AdbutlerAd extends AdComponent {
scheduleOnce("afterRender", this, this._triggerAds);
}
- @discourseComputed
- showAdbutlerAds() {
+ @computed
+ get showAdbutlerAds() {
if (!this.currentUser) {
return true;
}
@@ -120,32 +120,26 @@ export default class AdbutlerAd extends AdComponent {
return this.currentUser.show_adbutler_ads;
}
- @discourseComputed(
+ @computed(
"publisherId",
"showAdbutlerAds",
"showToGroups",
"showAfterPost",
"showOnCurrentPage"
)
- showAd(
- publisherId,
- showAdbutlerAds,
- showToGroups,
- showAfterPost,
- showOnCurrentPage
- ) {
+ get showAd() {
return (
- publisherId &&
- showAdbutlerAds &&
- showToGroups &&
- showAfterPost &&
- showOnCurrentPage
+ this.publisherId &&
+ this.showAdbutlerAds &&
+ this.showToGroups &&
+ this.showAfterPost &&
+ this.showOnCurrentPage
);
}
- @discourseComputed("postNumber")
- showAfterPost(postNumber) {
- if (!postNumber) {
+ @computed("postNumber")
+ get showAfterPost() {
+ if (!this.postNumber) {
return true;
}
return this.isNthPost(parseInt(this.siteSettings.adbutler_nth_post, 10));
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs
index c51d7affbcc..486664f3572 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs
@@ -1,7 +1,7 @@
+import { computed } from "@ember/object";
import { and } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import AdComponent from "./ad-component";
@@ -145,33 +145,37 @@ export default class AmazonProductLinks extends AdComponent {
super.init();
}
- @discourseComputed("amazon_width", "amazon_height")
- adWrapperStyle(w, h) {
- return htmlSafe(`width: ${w}px; height: ${h}px;`);
+ @computed("amazon_width", "amazon_height")
+ get adWrapperStyle() {
+ return htmlSafe(
+ `width: ${this.amazon_width}px; height: ${this.amazon_height}px;`
+ );
}
- @discourseComputed("mobile_amazon_width", "mobile_amazon_height")
- adWrapperStyleMobile(w, h) {
- return htmlSafe(`width: ${w}px; height: ${h}px;`);
+ @computed("mobile_amazon_width", "mobile_amazon_height")
+ get adWrapperStyleMobile() {
+ return htmlSafe(
+ `width: ${this.mobile_amazon_width}px; height: ${this.mobile_amazon_height}px;`
+ );
}
- @discourseComputed("mobile_amazon_width")
- adTitleStyleMobile(w) {
- return htmlSafe(`width: ${w}px;`);
+ @computed("mobile_amazon_width")
+ get adTitleStyleMobile() {
+ return htmlSafe(`width: ${this.mobile_amazon_width}px;`);
}
- @discourseComputed("user_input")
- userInput(userInput) {
- return htmlSafe(`${userInput}`);
+ @computed("user_input")
+ get userInput() {
+ return htmlSafe(`${this.user_input}`);
}
- @discourseComputed("user_input_mobile")
- userInputMobile(userInput) {
- return htmlSafe(`${userInput}`);
+ @computed("user_input_mobile")
+ get userInputMobile() {
+ return htmlSafe(`${this.user_input_mobile}`);
}
- @discourseComputed
- showAmazonAds() {
+ @computed
+ get showAmazonAds() {
if (!this.currentUser) {
return true;
}
@@ -179,9 +183,9 @@ export default class AmazonProductLinks extends AdComponent {
return this.currentUser.show_amazon_ads;
}
- @discourseComputed("postNumber")
- showAfterPost(postNumber) {
- if (!postNumber) {
+ @computed("postNumber")
+ get showAfterPost() {
+ if (!this.postNumber) {
return true;
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs
index 286b0e50ca8..7d550cc6e3b 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
-import discourseComputed from "discourse/lib/decorators";
import AdComponent from "./ad-component";
export default class CarbonadsAd extends AdComponent {
@@ -12,15 +12,15 @@ export default class CarbonadsAd extends AdComponent {
super.init();
}
- @discourseComputed("serve_id", "placement")
- url(serveId, placement) {
+ @computed("serve_id", "placement")
+ get url() {
return htmlSafe(
- `//cdn.carbonads.com/carbon.js?serve=${serveId}&placement=${placement}`
+ `//cdn.carbonads.com/carbon.js?serve=${this.serve_id}&placement=${this.placement}`
);
}
- @discourseComputed
- showCarbonAds() {
+ @computed
+ get showCarbonAds() {
if (!this.currentUser) {
return true;
}
@@ -28,16 +28,20 @@ export default class CarbonadsAd extends AdComponent {
return this.currentUser.show_carbon_ads;
}
- @discourseComputed(
+ @computed(
"placement",
"serve_id",
"showCarbonAds",
"showToGroups",
"showOnCurrentPage"
)
- showAd(placement, serveId, showCarbonAds, showToGroups, showOnCurrentPage) {
+ get showAd() {
return (
- placement && serveId && showCarbonAds && showToGroups && showOnCurrentPage
+ this.placement &&
+ this.serve_id &&
+ this.showCarbonAds &&
+ this.showToGroups &&
+ this.showOnCurrentPage
);
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs
index 3283b63e746..5f44978ec15 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs
@@ -1,9 +1,9 @@
+import { computed } from "@ember/object";
import { scheduleOnce } from "@ember/runloop";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import RSVP from "rsvp";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import loadScript from "discourse/lib/load-script";
import { i18n } from "discourse-i18n";
@@ -171,40 +171,46 @@ export default class GoogleAdsense extends AdComponent {
scheduleOnce("afterRender", this, this._triggerAds);
}
- @discourseComputed("ad_width")
- isResponsive(adWidth) {
- return ["auto", "fluid"].includes(adWidth);
+ @computed("ad_width")
+ get isResponsive() {
+ return ["auto", "fluid"].includes(this.ad_width);
}
- @discourseComputed("ad_width")
- isFluid(adWidth) {
- return adWidth === "fluid";
+ @computed("ad_width")
+ get isFluid() {
+ return this.ad_width === "fluid";
}
- @discourseComputed("placement", "showAd")
- classForSlot(placement, showAd) {
- return showAd ? htmlSafe(`adsense-${placement}`) : "";
+ @computed("placement", "showAd")
+ get classForSlot() {
+ return this.showAd ? htmlSafe(`adsense-${this.placement}`) : "";
}
- @discourseComputed("isResponsive", "isFluid")
- autoAdFormat(isResponsive, isFluid) {
- return isResponsive ? htmlSafe(isFluid ? "fluid" : "auto") : false;
+ @computed("isResponsive", "isFluid")
+ get autoAdFormat() {
+ return this.isResponsive
+ ? htmlSafe(this.isFluid ? "fluid" : "auto")
+ : false;
}
- @discourseComputed("ad_width", "ad_height", "isResponsive")
- adWrapperStyle(w, h, isResponsive) {
- return htmlSafe(isResponsive ? "" : `width: ${w}; height: ${h};`);
+ @computed("ad_width", "ad_height", "isResponsive")
+ get adWrapperStyle() {
+ return htmlSafe(
+ this.isResponsive
+ ? ""
+ : `width: ${this.ad_width}; height: ${this.ad_height};`
+ );
}
- @discourseComputed("adWrapperStyle", "isResponsive")
- adInsStyle(adWrapperStyle, isResponsive) {
+ @computed("adWrapperStyle", "isResponsive")
+ get adInsStyle() {
return htmlSafe(
- `display: ${isResponsive ? "block" : "inline-block"}; ${adWrapperStyle}`
+ `display: ${this.isResponsive ? "block" : "inline-block"}; ${this.adWrapperStyle}`
);
}
- @discourseComputed
- showAdsenseAds() {
+ @computed
+ get showAdsenseAds() {
if (!this.currentUser) {
return true;
}
@@ -212,32 +218,26 @@ export default class GoogleAdsense extends AdComponent {
return this.currentUser.show_adsense_ads;
}
- @discourseComputed(
+ @computed(
"publisher_id",
"showAdsenseAds",
"showToGroups",
"showAfterPost",
"showOnCurrentPage"
)
- showAd(
- publisherId,
- showAdsenseAds,
- showToGroups,
- showAfterPost,
- showOnCurrentPage
- ) {
+ get showAd() {
return (
- publisherId &&
- showAdsenseAds &&
- showToGroups &&
- showAfterPost &&
- showOnCurrentPage
+ this.publisher_id &&
+ this.showAdsenseAds &&
+ this.showToGroups &&
+ this.showAfterPost &&
+ this.showOnCurrentPage
);
}
- @discourseComputed("postNumber")
- showAfterPost(postNumber) {
- if (!postNumber) {
+ @computed("postNumber")
+ get showAfterPost() {
+ if (!this.postNumber) {
return true;
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs
index 2cb3d4fe5ed..2ba4e34afe7 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs
@@ -1,10 +1,10 @@
+import { computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import { on } from "@ember-decorators/object";
import RSVP from "rsvp";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { isTesting } from "discourse/lib/environment";
import loadScript from "discourse/lib/load-script";
import { i18n } from "discourse-i18n";
@@ -254,8 +254,8 @@ export default class GoogleDfpAd extends AdComponent {
@alias("size.height") height;
- @discourseComputed
- size() {
+ @computed
+ get size() {
return getWidthAndHeight(
this.get("placement"),
this.siteSettings,
@@ -263,49 +263,52 @@ export default class GoogleDfpAd extends AdComponent {
);
}
- @discourseComputed(
+ @computed(
"siteSettings.dfp_publisher_id",
"siteSettings.dfp_publisher_id_mobile",
"site.mobileView"
)
- publisherId(globalId, mobileId, isMobile) {
- if (isMobile) {
- return mobileId || globalId;
+ get publisherId() {
+ if (this.site?.mobileView) {
+ return (
+ this.siteSettings?.dfp_publisher_id_mobile ||
+ this.siteSettings?.dfp_publisher_id
+ );
} else {
- return globalId;
+ return this.siteSettings?.dfp_publisher_id;
}
}
- @discourseComputed("placement", "postNumber")
- divId(placement, postNumber) {
+ @computed("placement", "postNumber")
+ get divId() {
let slotNum = getNextSlotNum();
- if (postNumber) {
- return `div-gpt-ad-${slotNum}-${placement}-${postNumber}`;
+ if (this.postNumber) {
+ return `div-gpt-ad-${slotNum}-${this.placement}-${this.postNumber}`;
} else {
- return `div-gpt-ad-${slotNum}-${placement}`;
+ return `div-gpt-ad-${slotNum}-${this.placement}`;
}
}
- @discourseComputed("placement", "showAd")
- adUnitClass(placement, showAd) {
- return showAd ? `dfp-ad-${placement}` : "";
+ @computed("placement", "showAd")
+ get adUnitClass() {
+ return this.showAd ? `dfp-ad-${this.placement}` : "";
}
- @discourseComputed("width", "height")
- adWrapperStyle(w, h) {
- if (w !== "fluid") {
- return htmlSafe(`width: ${w}px; height: ${h}px;`);
+ @computed("width", "height")
+ get adWrapperStyle() {
+ if (this.width !== "fluid") {
+ return htmlSafe(`width: ${this.width}px; height: ${this.height}px;`);
}
}
- @discourseComputed("width")
- adTitleStyleMobile(w) {
- if (w !== "fluid") {
- return htmlSafe(`width: ${w}px;`);
+ @computed("width")
+ get adTitleStyleMobile() {
+ if (this.width !== "fluid") {
+ return htmlSafe(`width: ${this.width}px;`);
}
}
- @discourseComputed(
+ @computed(
"publisherId",
"showDfpAds",
"showToGroups",
@@ -313,26 +316,19 @@ export default class GoogleDfpAd extends AdComponent {
"showOnCurrentPage",
"size"
)
- showAd(
- publisherId,
- showDfpAds,
- showToGroups,
- showAfterPost,
- showOnCurrentPage,
- size
- ) {
+ get showAd() {
return (
- publisherId &&
- showDfpAds &&
- showToGroups &&
- showAfterPost &&
- showOnCurrentPage &&
- size
+ this.publisherId &&
+ this.showDfpAds &&
+ this.showToGroups &&
+ this.showAfterPost &&
+ this.showOnCurrentPage &&
+ this.size
);
}
- @discourseComputed
- showDfpAds() {
+ @computed
+ get showDfpAds() {
if (!this.currentUser) {
return true;
}
@@ -340,9 +336,9 @@ export default class GoogleDfpAd extends AdComponent {
return this.currentUser.show_dfp_ads;
}
- @discourseComputed("postNumber")
- showAfterPost(postNumber) {
- if (!postNumber) {
+ @computed("postNumber")
+ get showAfterPost() {
+ if (!this.postNumber) {
return true;
}
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
index 6dc9718d872..3486f0cae16 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
@@ -1,8 +1,8 @@
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { isBlank } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import AdComponent from "./ad-component";
const adIndex = {
@@ -26,38 +26,33 @@ export default class HouseAd extends AdComponent {
}
};
- @discourseComputed
- colspanAttribute() {
+ @computed
+ get colspanAttribute() {
return this.tagName === "td" ? "5" : null;
}
- @discourseComputed("placement", "showAd")
- adUnitClass(placement, showAd) {
- return showAd ? `house-${placement}` : "";
+ @computed("placement", "showAd")
+ get adUnitClass() {
+ return this.showAd ? `house-${this.placement}` : "";
}
- @discourseComputed(
+ @computed(
"showToGroups",
"showAfterPost",
"showAfterTopicListItem",
"showOnCurrentPage"
)
- showAd(
- showToGroups,
- showAfterPost,
- showAfterTopicListItem,
- showOnCurrentPage
- ) {
+ get showAd() {
return (
- showToGroups &&
- (showAfterPost || showAfterTopicListItem) &&
- showOnCurrentPage
+ this.showToGroups &&
+ (this.showAfterPost || this.showAfterTopicListItem) &&
+ this.showOnCurrentPage
);
}
- @discourseComputed("postNumber", "placement")
- showAfterPost(postNumber, placement) {
- if (!postNumber && placement !== "topic-list-between") {
+ @computed("postNumber", "placement")
+ get showAfterPost() {
+ if (!this.postNumber && this.placement !== "topic-list-between") {
return true;
}
@@ -66,9 +61,9 @@ export default class HouseAd extends AdComponent {
);
}
- @discourseComputed("placement")
- showAfterTopicListItem(placement) {
- if (placement !== "topic-list-between") {
+ @computed("placement")
+ get showAfterTopicListItem() {
+ if (this.placement !== "topic-list-between") {
return true;
}
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/components/remind-assigns-frequency.gjs b/plugins/discourse-assign/assets/javascripts/discourse/components/remind-assigns-frequency.gjs
index f402402181c..13a30cdaf96 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/components/remind-assigns-frequency.gjs
+++ b/plugins/discourse-assign/assets/javascripts/discourse/components/remind-assigns-frequency.gjs
@@ -1,32 +1,32 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { fn } from "@ember/helper";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { i18n } from "discourse-i18n";
@tagName("")
export default class RemindAssignsFrequency extends Component {
- @discourseComputed(
+ @computed(
"user.custom_fields.remind_assigns_frequency",
"siteSettings.remind_assigns_frequency"
)
- selectedFrequency(userAssignsFrequency, siteDefaultAssignsFrequency) {
+ get selectedFrequency() {
if (
this.availableFrequencies
.map((freq) => freq.value)
- .includes(userAssignsFrequency)
+ .includes(this.user?.custom_fields?.remind_assigns_frequency)
) {
- return userAssignsFrequency;
+ return this.user?.custom_fields?.remind_assigns_frequency;
}
- return siteDefaultAssignsFrequency;
+ return this.siteSettings?.remind_assigns_frequency;
}
- @discourseComputed("user.reminders_frequency")
- availableFrequencies(userRemindersFrequency) {
- return userRemindersFrequency.map((freq) => ({
+ @computed("user.reminders_frequency")
+ get availableFrequencies() {
+ return this.user?.reminders_frequency?.map((freq) => ({
name: i18n(freq.name),
value: freq.value,
selected: false,
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/controllers/group/assigned.js b/plugins/discourse-assign/assets/javascripts/discourse/controllers/group/assigned.js
index 6b919429bea..fd4776e943c 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/controllers/group/assigned.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/controllers/group/assigned.js
@@ -1,10 +1,9 @@
import { tracked } from "@glimmer/tracking";
import Controller, { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import { autoTrackedArray } from "discourse/lib/tracked-tools";
@@ -18,24 +17,24 @@ export default class GroupAssigned extends Controller {
@tracked offset = 0;
@autoTrackedArray members = [];
- @discourseComputed("router.currentRoute.queryParams.order")
- order(order) {
- return order || "";
+ @computed("router.currentRoute.queryParams.order")
+ get order() {
+ return this.router?.currentRoute?.queryParams?.order || "";
}
- @discourseComputed("router.currentRoute.queryParams.ascending")
- ascending(ascending) {
- return ascending || false;
+ @computed("router.currentRoute.queryParams.ascending")
+ get ascending() {
+ return this.router?.currentRoute?.queryParams?.ascending || false;
}
- @discourseComputed("router.currentRoute.queryParams.search")
- search(search) {
- return search || "";
+ @computed("router.currentRoute.queryParams.search")
+ get search() {
+ return this.router?.currentRoute?.queryParams?.search || "";
}
- @discourseComputed("site.mobileView")
- isDesktop(mobileView) {
- return !mobileView;
+ @computed("site.mobileView")
+ get isDesktop() {
+ return !this.site?.mobileView;
}
_setFilter(filter) {
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/controllers/user-activity/assigned.js b/plugins/discourse-assign/assets/javascripts/discourse/controllers/user-activity/assigned.js
index 742a69fe642..a5ab23512ee 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/controllers/user-activity/assigned.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/controllers/user-activity/assigned.js
@@ -1,9 +1,8 @@
import { inject as controller } from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import UserTopicsList from "discourse/controllers/user-topics-list";
import discourseDebounce from "discourse/lib/debounce";
-import discourseComputed from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import getURL from "discourse/lib/get-url";
import { iconHTML } from "discourse/lib/icon-library";
@@ -17,13 +16,13 @@ export default class UserActivityAssigned extends UserTopicsList {
ascending = false;
search = "";
- @discourseComputed("model.topics.length", "search")
- doesntHaveAssignments(topicsLength, search) {
- return !search && !topicsLength;
+ @computed("model.topics.length", "search")
+ get doesntHaveAssignments() {
+ return !this.search && !this.model?.topics?.length;
}
- @discourseComputed
- emptyStateBody() {
+ @computed
+ get emptyStateBody() {
return htmlSafe(
i18n("user.no_assignments_body", {
preferencesUrl: getURL("/my/preferences/notifications"),
diff --git a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
index 175054b17a5..db2fd156cfd 100644
--- a/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
+++ b/plugins/discourse-assign/assets/javascripts/discourse/initializers/extend-for-assigns.js
@@ -1,7 +1,7 @@
+import { computed } from "@ember/object";
import { getOwner } from "@ember/owner";
import { htmlSafe } from "@ember/template";
import { renderAvatar } from "discourse/helpers/user-avatar";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { iconHTML } from "discourse/lib/icon-library";
import { withPluginApi } from "discourse/lib/plugin-api";
@@ -322,14 +322,14 @@ function initialize(api) {
"model:bookmark",
(Superclass) =>
class extends Superclass {
- @discourseComputed("assigned_to_user")
- assignedToUserPath(assignedToUser) {
- return assignedToUserPath(assignedToUser);
+ @computed("assigned_to_user")
+ get assignedToUserPath() {
+ return assignedToUserPath(this.assigned_to_user);
}
- @discourseComputed("assigned_to_group")
- assignedToGroupPath(assignedToGroup) {
- return assignedToGroupPath(assignedToGroup);
+ @computed("assigned_to_group")
+ get assignedToGroupPath() {
+ return assignedToGroupPath(this.assigned_to_group);
}
}
);
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/components/emoji-images.gjs b/plugins/discourse-cakeday/assets/javascripts/discourse/components/emoji-images.gjs
index 6b0eb363277..cf35216ced6 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/components/emoji-images.gjs
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/components/emoji-images.gjs
@@ -1,24 +1,24 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import icon from "discourse/helpers/d-icon";
-import computed from "discourse/lib/decorators";
import { emojiUnescape } from "discourse/lib/text";
import { i18n } from "discourse-i18n";
@tagName("")
export default class EmojiImages extends Component {
@computed("list")
- emojiHTML(list) {
- return list
+ get emojiHTML() {
+ return this.list
.split("|")
.map((et) => emojiUnescape(`:${et}:`, { skipTitle: true }));
}
@computed("title")
- titleText(title) {
- return i18n(title);
+ get titleText() {
+ return i18n(this.title);
}
<template>
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/all.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/all.js
index 0f5e7196337..60ba6589cf5 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/all.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/all.js
@@ -1,13 +1,12 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
export default class CakedayAnniversariesAllController extends Controller {
queryParams = ["month"];
month = moment().month() + 1;
@computed
- months() {
+ get months() {
return moment.months().map((month, index) => {
return { name: month, value: index + 1 };
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/today.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/today.js
index 649b14d3164..0d5554ddb94 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/today.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/today.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayAnniversariesTodayController extends Controller {
@computed
- title() {
+ get title() {
return i18n("anniversaries.today.title", {
date: moment().format(i18n("dates.full_no_year_no_time")),
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/tomorrow.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/tomorrow.js
index 7643a6e46e2..52ed8395482 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/tomorrow.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/tomorrow.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayAnniversariesTomorrowController extends Controller {
@computed
- title() {
+ get title() {
return i18n("anniversaries.today.title", {
date: moment().add(1, "day").format(i18n("dates.full_no_year_no_time")),
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/upcoming.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/upcoming.js
index 2b21e56019d..2d392ddd090 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/upcoming.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/anniversaries/upcoming.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayAnniversariesUpcomingController extends Controller {
@computed
- title() {
+ get title() {
const dateFormat = i18n("dates.full_no_year_no_time");
return i18n("anniversaries.upcoming.title", {
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/all.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/all.js
index a4e041183bf..18ffed52cd8 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/all.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/all.js
@@ -1,13 +1,12 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
export default class CakedayBirthdaysAllController extends Controller {
queryParams = ["month"];
month = moment().month() + 1;
@computed
- months() {
+ get months() {
return moment.months().map((month, index) => {
return { name: month, value: index + 1 };
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/today.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/today.js
index 635568cca9b..0d471e6f46d 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/today.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/today.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayBirthdaysTodayController extends Controller {
@computed
- title() {
+ get title() {
return i18n("birthdays.today.title", {
date: moment().format(i18n("dates.full_no_year_no_time")),
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/tomorrow.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/tomorrow.js
index 3dc7f1f4860..b05ef0c660e 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/tomorrow.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/tomorrow.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayBirthdaysTomorrowController extends Controller {
@computed
- title() {
+ get title() {
return i18n("birthdays.today.title", {
date: moment().add(1, "day").format(i18n("dates.full_no_year_no_time")),
});
diff --git a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/upcoming.js b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/upcoming.js
index 73fa3611e94..a53c86a6579 100644
--- a/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/upcoming.js
+++ b/plugins/discourse-cakeday/assets/javascripts/discourse/controllers/cakeday/birthdays/upcoming.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
-import computed from "discourse/lib/decorators";
+import { action, computed } from "@ember/object";
import { i18n } from "discourse-i18n";
export default class CakedayBirthdaysUpcomingController extends Controller {
@computed
- title() {
+ get title() {
const dateFormat = i18n("dates.full_no_year_no_time");
return i18n("birthdays.upcoming.title", {
diff --git a/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js b/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
index cec589f238e..d3ea857ecce 100644
--- a/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
+++ b/plugins/discourse-gamification/admin/assets/javascripts/discourse/controllers/admin-plugins/show/discourse-gamification-leaderboards/index.js
@@ -1,11 +1,10 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { compare } from "@ember/utils";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import RecalculateScoresForm from "discourse/plugins/discourse-gamification/discourse/components/modal/recalculate-scores-form";
@@ -16,10 +15,12 @@ export default class AdminPluginsShowDiscourseGamificationLeaderboardsIndexContr
creatingNew = false;
- @discourseComputed("[email protected]")
- sortedLeaderboards(leaderboards) {
+ @computed("[email protected]")
+ get sortedLeaderboards() {
return (
- leaderboards?.sort((a, b) => compare(b?.updatedAt, a?.updatedAt)) || []
+ this.model?.leaderboards?.sort((a, b) =>
+ compare(b?.updatedAt, a?.updatedAt)
+ ) || []
);
}
diff --git a/plugins/discourse-gamification/assets/javascripts/discourse/components/gamification-leaderboard.gjs b/plugins/discourse-gamification/assets/javascripts/discourse/components/gamification-leaderboard.gjs
index 8f63098e623..9ef87d38838 100644
--- a/plugins/discourse-gamification/assets/javascripts/discourse/components/gamification-leaderboard.gjs
+++ b/plugins/discourse-gamification/assets/javascripts/discourse/components/gamification-leaderboard.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { hash } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { tagName } from "@ember-decorators/component";
import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
@@ -12,7 +12,6 @@ import icon from "discourse/helpers/d-icon";
import number from "discourse/helpers/number";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import PeriodChooser from "discourse/select-kit/components/period-chooser";
import { or } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -66,30 +65,30 @@ export default class GamificationLeaderboard extends Component {
this.set("period", default_leaderboard_period);
}
- @discourseComputed("model.reason")
- isNotReady(reason) {
- return reason !== undefined;
+ @computed("model.reason")
+ get isNotReady() {
+ return this.model?.reason !== undefined;
}
- @discourseComputed("model.users")
- currentUserRanking() {
+ @computed("model.users")
+ get currentUserRanking() {
const user = this.model.personal;
return user || null;
}
- @discourseComputed("model.users")
- winners(users) {
- return users.slice(0, 3);
+ @computed("model.users")
+ get winners() {
+ return this.model?.users?.slice(0, 3);
}
- @discourseComputed("model.users.[]")
- ranking(users) {
- users.forEach((user) => {
+ @computed("model.users.[]")
+ get ranking() {
+ this.model?.users.forEach((user) => {
if (user.id === this.currentUser?.id) {
user.isCurrentUser = "true";
}
});
- return users.slice(3);
+ return this.model?.users.slice(3);
}
@action
diff --git a/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs b/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs
index 25ba4bf1510..b581178f1ba 100644
--- a/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs
+++ b/plugins/discourse-local-dates/assets/javascripts/discourse/components/modal/local-dates-create.gjs
@@ -2,7 +2,7 @@
import Component from "@ember/component";
import { fn, hash } from "@ember/helper";
import { on } from "@ember/modifier";
-import EmberObject, { action } from "@ember/object";
+import EmberObject, { action, computed } from "@ember/object";
import { notEmpty } from "@ember/object/computed";
import { schedule } from "@ember/runloop";
import { htmlSafe } from "@ember/template";
@@ -14,7 +14,7 @@ import DModal from "discourse/components/d-modal";
import TextField from "discourse/components/text-field";
import icon from "discourse/helpers/d-icon";
import { propertyNotEqual } from "discourse/lib/computed";
-import computed, { debounce } from "discourse/lib/decorators";
+import { debounce } from "discourse/lib/decorators";
import { INPUT_DELAY } from "discourse/lib/environment";
import { applyLocalDates } from "discourse/lib/local-dates";
import { cook } from "discourse/lib/text";
@@ -87,19 +87,22 @@ export default class LocalDatesCreate extends Component {
}
@computed("date", "toDate", "toTime")
- isRange(date, toDate, toTime) {
- return date && (toDate || toTime);
+ get isRange() {
+ return this.date && (this.toDate || this.toTime);
}
@computed("computedConfig", "isRange")
- isValid(config, isRange) {
- const fromConfig = config.from;
- if (!config.from.dateTime || !config.from.dateTime.isValid()) {
+ get isValid() {
+ const fromConfig = this.computedConfig.from;
+ if (
+ !this.computedConfig.from.dateTime ||
+ !this.computedConfig.from.dateTime.isValid()
+ ) {
return false;
}
- if (isRange) {
- const toConfig = config.to;
+ if (this.isRange) {
+ const toConfig = this.computedConfig.to;
if (
!toConfig.dateTime ||
@@ -114,7 +117,11 @@ export default class LocalDatesCreate extends Component {
}
@computed("date", "time", "isRange", "options.{format,timezone}")
- fromConfig(date, time, isRange, options = {}) {
+ get fromConfig() {
+ const date = this.date;
+ let time = this.time;
+ const isRange = this.isRange;
+ const options = this.options || {};
const timeInferred = time ? false : true;
let dateTime;
@@ -143,7 +150,11 @@ export default class LocalDatesCreate extends Component {
}
@computed("toDate", "toTime", "isRange", "options.{timezone,format}")
- toConfig(date, time, isRange, options = {}) {
+ get toConfig() {
+ let date = this.toDate;
+ let time = this.toTime;
+ const isRange = this.isRange;
+ const options = this.options || {};
const timeInferred = time ? false : true;
if (time && !date) {
@@ -176,46 +187,49 @@ export default class LocalDatesCreate extends Component {
}
@computed("recurring", "timezones", "timezone", "format")
- options(recurring, timezones, timezone, format) {
+ get options() {
return EmberObject.create({
- recurring,
- timezones,
- timezone,
- format,
+ recurring: this.recurring,
+ timezones: this.timezones,
+ timezone: this.timezone,
+ format: this.format,
});
}
@computed(
- "fromConfig.{date}",
- "toConfig.{date}",
+ "fromConfig.date",
+ "toConfig.date",
"options.{recurring,timezones,timezone,format}"
)
- computedConfig(fromConfig, toConfig, options) {
+ get computedConfig() {
return EmberObject.create({
- from: fromConfig,
- to: toConfig,
- options,
+ from: this.fromConfig,
+ to: this.toConfig,
+ options: this.options,
});
}
@computed
- currentUserTimezone() {
+ get currentUserTimezone() {
return this.currentUser.user_option.timezone || moment.tz.guess();
}
@computed
- allTimezones() {
+ get allTimezones() {
return moment.tz.names();
}
@computed("currentUserTimezone")
- formattedCurrentUserTimezone(timezone) {
- return timezone.replace("_", " ").replace("Etc/", "").replace("/", ", ");
+ get formattedCurrentUserTimezone() {
+ return this.currentUserTimezone
+ .replace("_", " ")
+ .replace("Etc/", "")
+ .replace("/", ", ");
}
@computed("formats")
- previewedFormats(formats) {
- return formats.map((format) => {
+ get previewedFormats() {
+ return this.formats.map((format) => {
return {
format,
preview: moment().format(format),
@@ -224,7 +238,7 @@ export default class LocalDatesCreate extends Component {
}
@computed
- recurringOptions() {
+ get recurringOptions() {
const key = "discourse_local_dates.create.form.recurring";
return [
@@ -268,40 +282,44 @@ export default class LocalDatesCreate extends Component {
}
@computed("advancedMode")
- toggleModeBtnLabel(advancedMode) {
- return advancedMode
+ get toggleModeBtnLabel() {
+ return this.advancedMode
? "discourse_local_dates.create.form.simple_mode"
: "discourse_local_dates.create.form.advanced_mode";
}
@computed("computedConfig.{from,to,options}", "options", "isValid", "isRange")
- markup(config, options, isValid, isRange) {
+ get markup() {
let text;
- if (isValid && config.from) {
- if (config.to && config.to.range) {
+ if (this.isValid && this.computedConfig?.from) {
+ if (this.computedConfig?.to && this.computedConfig?.to.range) {
text = this._generateDateMarkup(
- config.from,
- options,
- isRange,
- config.to
+ this.computedConfig?.from,
+ this.options,
+ this.isRange,
+ this.computedConfig?.to
);
} else {
- text = this._generateDateMarkup(config.from, options, isRange);
+ text = this._generateDateMarkup(
+ this.computedConfig?.from,
+ this.options,
+ this.isRange
+ );
}
}
return text;
}
@computed("fromConfig.dateTime")
- formattedFrom(dateTime) {
- return dateTime.format("LLLL");
+ get formattedFrom() {
+ return this.fromConfig?.dateTime?.format("LLLL");
}
@computed("toConfig.dateTime")
- formattedTo(dateTime) {
- return dateTime.isValid()
- ? dateTime.format("LLLL")
+ get formattedTo() {
+ return this.toConfig?.dateTime?.isValid()
+ ? this.toConfig?.dateTime?.format("LLLL")
: i18n("discourse_local_dates.create.form.until");
}
@@ -312,13 +330,13 @@ export default class LocalDatesCreate extends Component {
}
@computed("fromSelected", "toSelected")
- selectedDate(fromSelected) {
- return fromSelected ? this.date : this.toDate;
+ get selectedDate() {
+ return this.fromSelected ? this.date : this.toDate;
}
@computed("fromSelected", "toSelected")
- selectedTime(fromSelected) {
- return fromSelected ? this.time : this.toTime;
+ get selectedTime() {
+ return this.fromSelected ? this.time : this.toTime;
}
@action
diff --git a/plugins/discourse-lti/assets/javascripts/discourse-lti/api-initializers/hide-lti-login-button.js b/plugins/discourse-lti/assets/javascripts/discourse-lti/api-initializers/hide-lti-login-button.js
index bd0220423fb..5581f70bb64 100644
--- a/plugins/discourse-lti/assets/javascripts/discourse-lti/api-initializers/hide-lti-login-button.js
+++ b/plugins/discourse-lti/assets/javascripts/discourse-lti/api-initializers/hide-lti-login-button.js
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { apiInitializer } from "discourse/lib/api";
-import discourseComputed from "discourse/lib/decorators";
import { findAll } from "discourse/models/login-method";
export default apiInitializer((api) => {
@@ -9,8 +9,8 @@ export default apiInitializer((api) => {
"component:login-buttons",
(Superclass) =>
class extends Superclass {
- @discourseComputed
- buttons() {
+ @computed
+ get buttons() {
return super.buttons.filter((m) => m.name !== "lti");
}
}
diff --git a/plugins/discourse-patreon/assets/javascripts/discourse/controllers/admin-plugins/patreon.js b/plugins/discourse-patreon/assets/javascripts/discourse/controllers/admin-plugins/patreon.js
index e89b45a18f3..a2b0cfc8f35 100644
--- a/plugins/discourse-patreon/assets/javascripts/discourse/controllers/admin-plugins/patreon.js
+++ b/plugins/discourse-patreon/assets/javascripts/discourse/controllers/admin-plugins/patreon.js
@@ -1,10 +1,9 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { removeValueFromArray } from "discourse/lib/array-tools";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
import { i18n } from "discourse-i18n";
import FilterRule from "discourse/plugins/discourse-patreon/discourse/models/filter-rule";
@@ -18,8 +17,8 @@ export default class AdminPluginsPatreonController extends Controller {
return `$${reward.amount_cents / 100} - ${reward.title}`;
}
- @discourseComputed("rewards")
- rewardsNames() {
+ @computed("rewards")
+ get rewardsNames() {
return Object.values(this.rewards)
.filter((r) => r.id >= 0)
.map((r) => this.prettyPrintReward(r));
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/campaign-banner.gjs b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/campaign-banner.gjs
index 602b225c54a..71a3fa49559 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/campaign-banner.gjs
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/campaign-banner.gjs
@@ -1,7 +1,7 @@
/* eslint-disable ember/no-classic-components, ember/no-observers */
import Component from "@ember/component";
import { concat } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { LinkTo } from "@ember/routing";
import { later } from "@ember/runloop";
@@ -15,7 +15,6 @@ import avatar from "discourse/helpers/avatar";
import icon from "discourse/helpers/d-icon";
import { ajax } from "discourse/lib/ajax";
import { setting } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import formatCurrency from "../helpers/format-currency";
@@ -126,9 +125,9 @@ export default class CampaignBanner extends Component {
document.body.classList.remove(SIDEBAR_BODY_CLASS);
}
- @discourseComputed("backgroundImageUrl")
- bannerInfoStyle(backgroundImageUrl) {
- if (!backgroundImageUrl) {
+ @computed("backgroundImageUrl")
+ get bannerInfoStyle() {
+ if (!this.backgroundImageUrl) {
return "";
}
@@ -141,22 +140,22 @@ export default class CampaignBanner extends Component {
background-repeat: no-repeat;`;
}
- @discourseComputed(
+ @computed(
"router.currentRouteName",
"currentUser",
"siteSettings.discourse_subscriptions_campaign_enabled",
"visible"
)
- shouldShow(currentRoute, currentUser, enabled, visible) {
- if (!currentRoute) {
+ get shouldShow() {
+ if (!this.router?.currentRouteName) {
return false;
}
// do not show on admin or subscriptions pages
const showOnRoute =
- currentRoute !== "discovery.s" &&
- !currentRoute.split(".")[0].includes("admin") &&
- currentRoute.split(".")[0] !== "subscribe" &&
- currentRoute.split(".")[0] !== "subscriptions";
+ this.router?.currentRouteName !== "discovery.s" &&
+ !this.router?.currentRouteName?.split(".")[0].includes("admin") &&
+ this.router?.currentRouteName?.split(".")[0] !== "subscribe" &&
+ this.router?.currentRouteName?.split(".")[0] !== "subscriptions";
if (!this.site.show_campaign_banner) {
return false;
@@ -165,12 +164,17 @@ export default class CampaignBanner extends Component {
// make sure not to render above main container when inside a topic
if (
this.connectorName === "above-main-container" &&
- currentRoute.includes("topic")
+ this.router?.currentRouteName?.includes("topic")
) {
return false;
}
- return showOnRoute && currentUser && enabled && visible;
+ return (
+ showOnRoute &&
+ this.currentUser &&
+ this.siteSettings?.discourse_subscriptions_campaign_enabled &&
+ this.visible
+ );
}
@observes("dismissed")
@@ -180,8 +184,8 @@ export default class CampaignBanner extends Component {
}
}
- @discourseComputed("dismissed")
- visible(dismissed) {
+ @computed("dismissed")
+ get visible() {
const dismissedBannerKey = this.keyValueStore.get(
"dismissed_campaign_banner"
);
@@ -192,20 +196,20 @@ export default class CampaignBanner extends Component {
return (
(!dismissedBannerKey || now - bannerDismissedTime > threeMonths) &&
- !dismissed
+ !this.dismissed
);
}
- @discourseComputed
- subscribeRoute() {
+ @computed
+ get subscribeRoute() {
if (this.pricingTableEnabled) {
return "subscriptions";
}
return "subscribe";
}
- @discourseComputed
- isGoalMet() {
+ @computed
+ get isGoalMet() {
const currentVolume = this.subscriberGoal
? this.subscribers
: this.amountRaised;
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/create-coupon-form.gjs b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/create-coupon-form.gjs
index b2452d78d67..33271254fbf 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/create-coupon-form.gjs
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/create-coupon-form.gjs
@@ -2,11 +2,10 @@
import Component, { Input } from "@ember/component";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import withEventValue from "discourse/helpers/with-event-value";
-import discourseComputed from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { i18n } from "discourse-i18n";
@@ -17,8 +16,8 @@ export default class CreateCouponForm extends Component {
promoCode = null;
active = false;
- @discourseComputed
- discountTypes() {
+ @computed
+ get discountTypes() {
return [
{ id: "amount", name: "Amount" },
{ id: "percent", name: "Percent" },
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-options.gjs b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-options.gjs
index 3a4e1cba100..1229869ac53 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-options.gjs
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-options.gjs
@@ -1,17 +1,18 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import PaymentPlan from "./payment-plan";
@tagName("")
export default class PaymentOptions extends Component {
- @discourseComputed("plans")
- orderedPlans(plans) {
- if (plans) {
- return plans.sort((a, b) => (a.unit_amount > b.unit_amount ? 1 : -1));
+ @computed("plans")
+ get orderedPlans() {
+ if (this.plans) {
+ return this.plans.sort((a, b) =>
+ a.unit_amount > b.unit_amount ? 1 : -1
+ );
}
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-plan.gjs b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-plan.gjs
index e46eb91b668..f632fd2f6d0 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-plan.gjs
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/payment-plan.gjs
@@ -1,11 +1,10 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { concat } from "@ember/helper";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import DButton from "discourse/components/d-button";
import concatClass from "discourse/helpers/concat-class";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import formatCurrency from "../helpers/format-currency";
@@ -13,14 +12,14 @@ const RECURRING = "recurring";
@tagName("")
export default class PaymentPlan extends Component {
- @discourseComputed("selectedPlan")
- selectedClass(planId) {
- return planId === this.plan.id ? "btn-primary" : "";
+ @computed("selectedPlan")
+ get selectedClass() {
+ return this.selectedPlan === this.plan.id ? "btn-primary" : "";
}
- @discourseComputed("plan.type")
- recurringPlan(type) {
- return type === RECURRING;
+ @computed("plan.type")
+ get recurringPlan() {
+ return this.plan?.type === RECURRING;
}
@action
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/product-list.gjs b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/product-list.gjs
index 35e482da07b..b9d60e16e18 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/components/product-list.gjs
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/components/product-list.gjs
@@ -1,16 +1,16 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { isEmpty } from "@ember/utils";
import { tagName } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import ProductItem from "./product-item";
@tagName("")
export default class ProductList extends Component {
- @discourseComputed("products")
- emptyProducts(products) {
- return isEmpty(products);
+ @computed("products")
+ get emptyProducts() {
+ return isEmpty(this.products);
}
<template>
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions.js
index 77ebf18bba8..0349727a1a4 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions.js
@@ -1,10 +1,9 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
export default class AdminPluginsDiscourseSubscriptionsController extends Controller {
@@ -12,18 +11,18 @@ export default class AdminPluginsDiscourseSubscriptionsController extends Contro
loading = false;
- @discourseComputed
- stripeConfigured() {
+ @computed
+ get stripeConfigured() {
return !!this.siteSettings.discourse_subscriptions_public_key;
}
- @discourseComputed
- campaignEnabled() {
+ @computed
+ get campaignEnabled() {
return this.siteSettings.discourse_subscriptions_campaign_enabled;
}
- @discourseComputed
- campaignProductSet() {
+ @computed
+ get campaignProductSet() {
return !!this.siteSettings.discourse_subscriptions_campaign_product;
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions/products/show/plans/show.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions/products/show/plans/show.js
index e3226bcd458..6e4cd519dd2 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions/products/show/plans/show.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/admin-plugins/discourse-subscriptions/products/show/plans/show.js
@@ -1,8 +1,7 @@
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { alias } from "@ember/object/computed";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import DiscourseURL from "discourse/lib/url";
const RECURRING = "recurring";
@@ -13,24 +12,24 @@ export default class AdminPluginsDiscourseSubscriptionsProductsShowPlansShowCont
@alias("model.plan.currency") selectedCurrency;
@alias("model.plan.interval") selectedInterval;
- @discourseComputed("model.plan.metadata.group_name")
- selectedGroup(groupName) {
- return groupName || "no-group";
+ @computed("model.plan.metadata.group_name")
+ get selectedGroup() {
+ return this.model?.plan?.metadata?.group_name || "no-group";
}
- @discourseComputed("model.groups")
- availableGroups(groups) {
+ @computed("model.groups")
+ get availableGroups() {
return [
{
id: null,
name: "no-group",
},
- ...groups,
+ ...(this.model?.groups || []),
];
}
- @discourseComputed
- currencies() {
+ @computed
+ get currencies() {
return [
{ id: "AUD", name: "AUD" },
{ id: "CAD", name: "CAD" },
@@ -50,8 +49,8 @@ export default class AdminPluginsDiscourseSubscriptionsProductsShowPlansShowCont
];
}
- @discourseComputed
- availableIntervals() {
+ @computed
+ get availableIntervals() {
return [
{ id: "day", name: "day" },
{ id: "week", name: "week" },
@@ -60,14 +59,14 @@ export default class AdminPluginsDiscourseSubscriptionsProductsShowPlansShowCont
];
}
- @discourseComputed("model.plan.isNew")
- planFieldDisabled(isNew) {
- return !isNew;
+ @computed("model.plan.isNew")
+ get planFieldDisabled() {
+ return !this.model?.plan?.isNew;
}
- @discourseComputed("model.product.id")
- productId(id) {
- return id;
+ @computed("model.product.id")
+ get productId() {
+ return this.model?.product?.id;
}
redirect(product_id) {
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/index.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/index.js
index 55dfc4dda32..e914987bb76 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/index.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/index.js
@@ -1,10 +1,10 @@
import Controller from "@ember/controller";
-import discourseComputed from "discourse/lib/decorators";
+import { computed } from "@ember/object";
import User from "discourse/models/user";
export default class SubscribeIndexController extends Controller {
- @discourseComputed()
- isLoggedIn() {
+ @computed()
+ get isLoggedIn() {
return User.current();
}
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/show.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/show.js
index 5ee18220822..92ab2a9632d 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/show.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscribe/show.js
@@ -1,9 +1,8 @@
/* global Stripe */
import Controller from "@ember/controller";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { not } from "@ember/object/computed";
import { service } from "@ember/service";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import Subscription from "discourse/plugins/discourse-subscriptions/discourse/models/subscription";
import Transaction from "discourse/plugins/discourse-subscriptions/discourse/models/transaction";
@@ -46,9 +45,12 @@ export default class SubscribeShowController extends Controller {
this.dialog.alert(i18n(`discourse_subscriptions.${path}`));
}
- @discourseComputed("model.product.repurchaseable", "model.product.subscribed")
- canPurchase(repurchaseable, subscribed) {
- if (!repurchaseable && subscribed) {
+ @computed("model.product.repurchaseable", "model.product.subscribed")
+ get canPurchase() {
+ if (
+ !this.model?.product?.repurchaseable &&
+ this.model?.product?.subscribed
+ ) {
return false;
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-coupon.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-coupon.js
index 32553197034..75c5340f1c4 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-coupon.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-coupon.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
export default class AdminCoupon extends EmberObject {
static list() {
@@ -50,12 +49,12 @@ export default class AdminCoupon extends EmberObject {
});
}
- @discourseComputed("coupon.amount_off", "coupon.percent_off")
- discount(amount_off, percent_off) {
- if (amount_off) {
- return `${parseFloat(amount_off * 0.01).toFixed(2)}`;
- } else if (percent_off) {
- return `${percent_off}%`;
+ @computed("coupon.amount_off", "coupon.percent_off")
+ get discount() {
+ if (this.coupon?.amount_off) {
+ return `${parseFloat(this.coupon?.amount_off * 0.01).toFixed(2)}`;
+ } else if (this.coupon?.percent_off) {
+ return `${this.coupon?.percent_off}%`;
}
}
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-plan.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-plan.js
index 6c0f22cec0e..12f3aae8a22 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-plan.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-plan.js
@@ -1,5 +1,5 @@
+import { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import Plan from "discourse/plugins/discourse-subscriptions/discourse/models/plan";
export default class AdminPlan extends Plan {
@@ -22,10 +22,10 @@ export default class AdminPlan extends Plan {
intervals = ["day", "week", "month", "year"];
metadata = {};
- @discourseComputed("trial_period_days")
- parseTrialPeriodDays(trialDays) {
- if (trialDays) {
- return parseInt(0 + trialDays, 10);
+ @computed("trial_period_days")
+ get parseTrialPeriodDays() {
+ if (this.trial_period_days) {
+ return parseInt(0 + this.trial_period_days, 10);
} else {
return 0;
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-subscription.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-subscription.js
index 77099415288..eefc72103da 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-subscription.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/admin-subscription.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
export default class AdminSubscription extends EmberObject {
@@ -29,19 +28,21 @@ export default class AdminSubscription extends EmberObject {
});
}
- @discourseComputed("status")
- canceled(status) {
- return status === "canceled";
+ @computed("status")
+ get canceled() {
+ return this.status === "canceled";
}
- @discourseComputed("metadata")
- metadataUserExists(metadata) {
- return metadata.user_id && metadata.username;
+ @computed("metadata")
+ get metadataUserExists() {
+ return this.metadata.user_id && this.metadata.username;
}
- @discourseComputed("metadata")
- subscriptionUserPath(metadata) {
- return getURL(`/admin/users/${metadata.user_id}/${metadata.username}`);
+ @computed("metadata")
+ get subscriptionUserPath() {
+ return getURL(
+ `/admin/users/${this.metadata.user_id}/${this.metadata.username}`
+ );
}
destroy(refund) {
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/plan.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/plan.js
index 233240a26fb..85cd1d2e0b8 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/plan.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/plan.js
@@ -1,5 +1,4 @@
import EmberObject, { computed } from "@ember/object";
-import discourseComputed from "discourse/lib/decorators";
export default class Plan extends EmberObject {
@computed("unit_amount")
@@ -12,13 +11,13 @@ export default class Plan extends EmberObject {
this.set("unit_amount", decimal);
}
- @discourseComputed("recurring.interval")
- billingInterval(interval) {
- return interval || "one-time";
+ @computed("recurring.interval")
+ get billingInterval() {
+ return this.recurring?.interval || "one-time";
}
- @discourseComputed("amountDollars", "currency", "billingInterval")
- subscriptionRate(amountDollars, currency, interval) {
- return `${amountDollars} ${currency.toUpperCase()} / ${interval}`;
+ @computed("amountDollars", "currency", "billingInterval")
+ get subscriptionRate() {
+ return `${this.amountDollars} ${this.currency.toUpperCase()} / ${this.billingInterval}`;
}
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/subscription.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/subscription.js
index 4d3373a2310..8ec0064d614 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/subscription.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/subscription.js
@@ -1,15 +1,14 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
export default class Subscription extends EmberObject {
static show(id) {
return ajax(`/s/${id}`, { method: "get" });
}
- @discourseComputed("status")
- canceled(status) {
- return status === "canceled";
+ @computed("status")
+ get canceled() {
+ return this.status === "canceled";
}
save() {
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-payment.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-payment.js
index 71b0daa7d93..bf805ed4804 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-payment.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-payment.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
export default class UserPayment extends EmberObject {
static findAll() {
@@ -11,8 +10,8 @@ export default class UserPayment extends EmberObject {
);
}
- @discourseComputed("amount")
- amountDollars(amount) {
- return parseFloat(amount / 100).toFixed(2);
+ @computed("amount")
+ get amountDollars() {
+ return parseFloat(this.amount / 100).toFixed(2);
}
}
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-subscription.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-subscription.js
index b77f4e46106..6e3834c281e 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-subscription.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/models/user-subscription.js
@@ -1,6 +1,5 @@
-import EmberObject from "@ember/object";
+import EmberObject, { computed } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
-import discourseComputed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import Plan from "discourse/plugins/discourse-subscriptions/discourse/models/plan";
@@ -14,25 +13,25 @@ export default class UserSubscription extends EmberObject {
);
}
- @discourseComputed("status")
- canceled(status) {
- return status === "canceled";
+ @computed("status")
+ get canceled() {
+ return this.status === "canceled";
}
- @discourseComputed("current_period_end", "canceled_at")
- endDate(current_period_end, canceled_at) {
- if (!canceled_at) {
- return moment.unix(current_period_end).format("LL");
+ @computed("current_period_end", "canceled_at")
+ get endDate() {
+ if (!this.canceled_at) {
+ return moment.unix(this.current_period_end).format("LL");
} else {
return i18n("discourse_subscriptions.user.subscriptions.cancelled");
}
}
- @discourseComputed("discount")
- discounted(discount) {
- if (discount) {
- const amount_off = discount.coupon.amount_off;
- const percent_off = discount.coupon.percent_off;
+ @computed("discount")
+ get discounted() {
+ if (this.discount) {
+ const amount_off = this.discount.coupon.amount_off;
+ const percent_off = this.discount.coupon.percent_off;
if (amount_off) {
return `${parseFloat(amount_off * 0.01).toFixed(2)}`;
diff --git a/plugins/poll/assets/javascripts/discourse/components/modal/poll-breakdown.gjs b/plugins/poll/assets/javascripts/discourse/components/modal/poll-breakdown.gjs
index 0ab5a2c21d2..1c601d1910e 100644
--- a/plugins/poll/assets/javascripts/discourse/components/modal/poll-breakdown.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/modal/poll-breakdown.gjs
@@ -2,7 +2,7 @@
import Component from "@ember/component";
import { fn, get } from "@ember/helper";
import { on } from "@ember/modifier";
-import { action } from "@ember/object";
+import { action, computed } from "@ember/object";
import { service } from "@ember/service";
import { classify } from "@ember/string";
import { htmlSafe } from "@ember/template";
@@ -11,7 +11,6 @@ import DModal from "discourse/components/d-modal";
import concatClass from "discourse/helpers/concat-class";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import discourseComputed from "discourse/lib/decorators";
import ComboBox from "discourse/select-kit/components/combo-box";
import { eq } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
@@ -37,9 +36,11 @@ export default class PollBreakdownModal extends Component {
super.init(...arguments);
}
- @discourseComputed("model.poll.title", "model.post.topic.title")
- title(pollTitle, topicTitle) {
- return pollTitle ? htmlSafe(pollTitle) : topicTitle;
+ @computed("model.poll.title", "model.post.topic.title")
+ get title() {
+ return this.model?.poll?.title
+ ? htmlSafe(this.model?.poll?.title)
+ : this.model?.post?.topic?.title;
}
get groupableUserFields() {
@@ -57,9 +58,12 @@ export default class PollBreakdownModal extends Component {
});
}
- @discourseComputed("model.poll.options")
- totalVotes(options) {
- return options.reduce((sum, option) => sum + option.votes, 0);
+ @computed("model.poll.options")
+ get totalVotes() {
+ return this.model?.poll?.options?.reduce(
+ (sum, option) => sum + option.votes,
+ 0
+ );
}
fetchGroupedPollData() {
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-chart.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-chart.gjs
index be3df0a4368..118a610041d 100644
--- a/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-chart.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-chart.gjs
@@ -1,10 +1,10 @@
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { mapBy } from "@ember/object/computed";
import { next } from "@ember/runloop";
import { htmlSafe } from "@ember/template";
import { classNames } from "@ember-decorators/component";
-import discourseComputed from "discourse/lib/decorators";
import loadChartJS, {
loadChartJSDatalabels,
} from "discourse/lib/load-chart-js";
@@ -64,22 +64,24 @@ export default class PollBreakdownChart extends Component {
}
}
- @discourseComputed("optionColors", "index")
- colorStyle(optionColors, index) {
- return htmlSafe(`background: ${optionColors[index]};`);
+ @computed("optionColors", "index")
+ get colorStyle() {
+ return htmlSafe(`background: ${this.optionColors[this.index]};`);
}
- @discourseComputed("data", "displayMode")
- chartConfig(data, displayMode) {
+ @computed("data", "displayMode")
+ get chartConfig() {
+ const data = this.data;
+ const displayMode = this.displayMode;
const transformedData = [];
let counter = 0;
- this._optionToSlice = {};
+ this._optionToSlice = {}; // eslint-disable-line ember/no-side-effects
data.forEach((votes, index) => {
if (votes > 0) {
transformedData.push(votes);
- this._optionToSlice[index] = counter++;
+ this._optionToSlice[index] = counter++; // eslint-disable-line ember/no-side-effects
}
});
diff --git a/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-option.gjs b/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-option.gjs
index 5911b09b6ab..af7a35f2e68 100644
--- a/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-option.gjs
+++ b/plugins/poll/assets/javascripts/discourse/components/poll-breakdown-option.gjs
@@ -1,11 +1,11 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
import { on } from "@ember/modifier";
+import { computed } from "@ember/object";
import { equal } from "@ember/object/computed";
import { htmlSafe } from "@ember/template";
import { tagName } from "@ember-decorators/component";
import { propertyEqual } from "discourse/lib/computed";
-import discourseComputed from "discourse/lib/decorators";
import loadChartJS from "discourse/lib/load-chart-js";
import I18n, { i18n } from "discourse-i18n";
import { getColors } from "discourse/plugins/poll/lib/chart-colors";
@@ -34,29 +34,31 @@ export default class PollBreakdownOption extends Component {
});
}
- @discourseComputed("option.votes", "totalVotes")
- percent(votes, total) {
- return I18n.toNumber((votes / total) * 100.0, { precision: 1 });
+ @computed("option.votes", "totalVotes")
+ get percent() {
+ return I18n.toNumber((this.option?.votes / this.totalVotes) * 100.0, {
+ precision: 1,
+ });
}
- @discourseComputed("optionsCount")
- optionColors(optionsCount) {
- return getColors(optionsCount);
+ @computed("optionsCount")
+ get optionColors() {
+ return getColors(this.optionsCount);
}
- @discourseComputed("highlighted")
- colorBackgroundStyle(highlighted) {
- if (highlighted) {
+ @computed("highlighted")
+ get colorBackgroundStyle() {
+ if (this.highlighted) {
// TODO: Use CSS variables (#10341)
return htmlSafe("background: rgba(0, 0, 0, 0.1);");
}
}
- @discourseComputed("Chart", "highlighted", "optionColors", "index")
- colorPreviewStyle(Chart, highlighted, optionColors, index) {
- const color = highlighted
- ? Chart?.helpers.getHoverColor(optionColors[index])
- : optionColors[index];
+ @computed("Chart", "highlighted", "optionColors", "index")
+ get colorPreviewStyle() {
+ const color = this.highlighted
+ ? this.Chart?.helpers.getHoverColor(this.optionColors[this.index])
+ : this.optionColors[this.index];
return htmlSafe(`background: ${color};`);
}
diff --git a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-section.gjs b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-section.gjs
index e441e880852..7f641aab4f4 100644
--- a/plugins/styleguide/assets/javascripts/discourse/components/styleguide-section.gjs
+++ b/plugins/styleguide/assets/javascripts/discourse/components/styleguide-section.gjs
@@ -1,8 +1,8 @@
/* eslint-disable ember/no-classic-components */
import Component from "@ember/component";
+import { computed } from "@ember/object";
import { tagName } from "@ember-decorators/component";
import concatClass from "discourse/helpers/concat-class";
-import computed from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
import sectionTitle from "discourse/plugins/styleguide/discourse/helpers/section-title";
@@ -14,9 +14,9 @@ export default class StyleguideSection extends Component {
}
@computed("section")
- sectionClass(section) {
- if (section) {
- return `${section.id}-examples`;
+ get sectionClass() {
+ if (this.section) {
+ return `${this.section.id}-examples`;
}
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 03ee09759d1..ccd215d9f1f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -35,8 +35,8 @@ importers:
specifier: ^7.29.0
version: 7.29.0(@babel/[email protected])
'@discourse/lint-configs':
- specifier: ^2.40.0
+ specifier: ^2.41.0
'@discourse/moment-timezone-names-translations':
specifier: ^1.0.0
version: 1.0.0
@@ -1758,8 +1758,8 @@ packages:
'@discourse/[email protected]':
resolution: {integrity: sha512-Jn1gdiyHMGUsmUfLFf4Q7VnTAv0l7NePbegU6pKhKHEmbzV3FosGxq30fTOYgVyTS1bxqGjlA6LvQttJpv3ROw==}
- '@discourse/[email protected]':
- resolution: {integrity: sha512-bVZ4qeBv02UOt7tTL7xSmp69n4NcQ6fAS6gp+J+iA5x2BFBxqaY7xdxVbxlTHoYkZdyNRl8PruDrmTpyPyf8CA==}
+ '@discourse/[email protected]':
+ resolution: {integrity: sha512-jqc1NaASyQY0zxICx8tXe92Wt1kGD0PcDml+CdOhQHhCKAc4JODa4NuWGmhP1kHYhsTuNknfC1BqzRX9mK1rOg==}
peerDependencies:
ember-template-lint: 7.9.3
eslint: 9.39.2
@@ -10419,7 +10419,7 @@ snapshots:
'@discourse/[email protected]': {}
dependencies:
'@babel/core': 7.29.0([email protected])
'@babel/eslint-parser': 7.28.6(@babel/[email protected])([email protected]([email protected]))