A platform for community discussion. Free, open, simple.
DEV: Update remaining Ember deprecated array methods to native array methods (#36070)
Sérgio Saquetim61fc77d72cbf
diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex c42beb0db86..5ec99a3353f 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -8411,6 +8411,7 @@ en:experimental: "Experimental"secret_list:invalid_input: "Input fields cannot be empty or contain vertical bar character."+ already_exists: "Entry for %{key} already exists."default_categories:modal_description:one: "Would you like to apply this change historically? This will change preferences for %{count} existing user."diff --git a/frontend/discourse/admin/components/admin-config-areas/flags.gjs b/frontend/discourse/admin/components/admin-config-areas/flags.gjsindex 5c02dffece3..5cebafeeba4 100644--- a/frontend/discourse/admin/components/admin-config-areas/flags.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/flags.gjs@@ -1,17 +1,18 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";import { service } from "@ember/service";import AdminFlagItem from "discourse/admin/components/admin-flag-item";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";import { bind } from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";export default class AdminConfigAreasFlags extends Component {@service site;- @tracked flags = this.site.flagTypes;+ @trackedArray flags = this.site.flagTypes;@bindisFirstFlag(flag) {@@ -24,7 +25,7 @@ export default class AdminConfigAreasFlags extends Component {}@action- moveFlagCallback(flag, direction) {+ async moveFlagCallback(flag, direction) {const fallbackFlags = [...this.flags];const flags = this.flags;@@ -39,23 +40,27 @@ export default class AdminConfigAreasFlags extends Component {this.flags = flags;- return ajax(`/admin/config/flags/${flag.id}/reorder/${direction}`, {- type: "PUT",- }).catch((error) => {+ try {+ await ajax(`/admin/config/flags/${flag.id}/reorder/${direction}`, {+ type: "PUT",+ });+ } catch (error) {this.flags = fallbackFlags;return popupAjaxError(error);- });+ }}@action- deleteFlagCallback(flag) {- return ajax(`/admin/config/flags/${flag.id}`, {- type: "DELETE",- })- .then(() => {- this.flags.removeObject(flag);- })- .catch((error) => popupAjaxError(error));+ async deleteFlagCallback(flag) {+ try {+ await ajax(`/admin/config/flags/${flag.id}`, {+ type: "DELETE",+ });++ removeValueFromArray(this.flags, flag);+ } catch (error) {+ popupAjaxError(error);+ }}<template>diff --git a/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs b/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjsindex 361ec20eb78..8cba1e2ff8a 100644--- a/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/user-fields-list.gjs@@ -28,7 +28,7 @@ export default class AdminConfigAreasUserFieldsList extends Component {moveUp(field) {const idx = this.sortedFields.indexOf(field);if (idx) {- const prev = this.sortedFields.objectAt(idx - 1);+ const prev = this.sortedFields[idx - 1];const prevPos = prev.get("position");prev.update({ position: field.get("position") });@@ -40,7 +40,7 @@ export default class AdminConfigAreasUserFieldsList extends Component {moveDown(field) {const idx = this.sortedFields.indexOf(field);if (idx > -1) {- const next = this.sortedFields.objectAt(idx + 1);+ const next = this.sortedFields[idx + 1];const nextPos = next.get("position");next.update({ position: field.get("position") });diff --git a/frontend/discourse/admin/components/admin-config-areas/webhooks-form.gjs b/frontend/discourse/admin/components/admin-config-areas/webhooks-form.gjsindex 6a7485689c2..c2a89feb4c6 100644--- a/frontend/discourse/admin/components/admin-config-areas/webhooks-form.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/webhooks-form.gjs@@ -11,6 +11,7 @@ import GroupSelector from "discourse/components/group-selector";import PluginOutlet from "discourse/components/plugin-outlet";import lazyHash from "discourse/helpers/lazy-hash";import { popupAjaxError } from "discourse/lib/ajax-error";+import { trackedArray } from "discourse/lib/tracked-tools";import CategorySelector from "discourse/select-kit/components/category-selector";import TagChooser from "discourse/select-kit/components/tag-chooser";import { eq } from "discourse/truth-helpers";@@ -25,11 +26,11 @@ export default class AdminConfigAreasWebhookForm extends Component {@tracked loadingExtras = true;- @tracked webhookEventTypes = [];@tracked defaultEventTypes = {};@tracked groupedEventTypes = {};@tracked contentTypes = [];@tracked deliveryStatuses = [];+ @trackedArray webhookEventTypes = [];constructor() {super(...arguments);diff --git a/frontend/discourse/admin/components/admin-config-areas/webhooks-list.gjs b/frontend/discourse/admin/components/admin-config-areas/webhooks-list.gjsindex 9dd6bcf850a..298dec6dd22 100644--- a/frontend/discourse/admin/components/admin-config-areas/webhooks-list.gjs+++ b/frontend/discourse/admin/components/admin-config-areas/webhooks-list.gjs@@ -4,6 +4,8 @@ import { action } from "@ember/object";import { service } from "@ember/service";import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";import WebhookItem from "discourse/admin/components/webhook-item";+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";+import LoadMore from "discourse/components/load-more";import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";import { i18n } from "discourse-i18n";@@ -31,33 +33,44 @@ export default class AdminConfigAreasWebhooksList extends Component {<template><div class="container admin-api_keys">{{#if this.webhooks.content}}- <table class="d-table admin-web_hooks__items">- <thead class="d-table__header">- <tr class="d-table__row">- <th class="d-table__header-cell">{{i18n- "admin.web_hooks.delivery_status.title"- }}</th>- <th class="d-table__header-cell">{{i18n- "admin.web_hooks.payload_url"- }}</th>- <th class="d-table__header-cell">{{i18n- "admin.web_hooks.description_label"- }}</th>- <th class="d-table__header-cell">{{i18n- "admin.web_hooks.controls"- }}</th>- </tr>- </thead>- <tbody class="d-table__body">- {{#each this.webhooks.content as |webhook|}}- <WebhookItem- @webhook={{webhook}}- @deliveryStatuses={{this.webhooks.extras.delivery_statuses}}- @destroy={{this.destroyWebhook}}- />- {{/each}}- </tbody>- </table>+ <LoadMore @action={{this.webhooks.loadMore}}>+ <table class="d-table admin-web_hooks__items">+ <thead class="d-table__header">+ <tr class="d-table__row">+ <th class="d-table__header-cell">{{i18n+ "admin.web_hooks.delivery_status.title"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "admin.web_hooks.payload_url"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "admin.web_hooks.description_label"+ }}</th>+ <th class="d-table__header-cell">{{i18n+ "admin.web_hooks.controls"+ }}</th>+ </tr>+ </thead>+ <tbody class="d-table__body">+ {{#each this.webhooks.content as |webhook|}}+ <WebhookItem+ @webhook={{webhook}}+ @deliveryStatuses={{this.webhooks.extras.delivery_statuses}}+ @destroy={{this.destroyWebhook}}+ />+ {{/each}}+ {{#if this.webhooks.loadingMore}}+ <tr class="d-table__row">+ <td class="d-table__cell" colspan="4">+ <ConditionalLoadingSpinner+ @condition={{this.webhooks.loadingMore}}+ />+ </td>+ </tr>+ {{/if}}+ </tbody>+ </table>+ </LoadMore>{{else}}<AdminConfigAreaEmptyList@ctaLabel="admin.web_hooks.add"diff --git a/frontend/discourse/admin/components/admin-flags-form.gjs b/frontend/discourse/admin/components/admin-flags-form.gjsindex a26e95e6b96..9b26f8ea586 100644--- a/frontend/discourse/admin/components/admin-flags-form.gjs+++ b/frontend/discourse/admin/components/admin-flags-form.gjs@@ -96,7 +96,7 @@ export default class AdminFlagsForm extends Component {type: "POST",data,});- this.site.flagTypes.pushObject(response.flag);+ this.site.flagTypes.push(response.flag);this.router.transitionTo("adminConfig.flags");} catch (error) {popupAjaxError(error);diff --git a/frontend/discourse/admin/components/admin-user-fields-form.gjs b/frontend/discourse/admin/components/admin-user-fields-form.gjsindex 16c286e164e..25c39c7a5df 100644--- a/frontend/discourse/admin/components/admin-user-fields-form.gjs+++ b/frontend/discourse/admin/components/admin-user-fields-form.gjs@@ -94,7 +94,7 @@ export default class AdminUserFieldsForm extends Component {this.originalRequirement = data.requirement;if (isNew) {- this.adminUserFields.userFields.pushObject(this.args.userField);+ this.adminUserFields.userFields.push(this.args.userField);}this.router.transitionTo("adminUserFields.index");diff --git a/frontend/discourse/admin/components/dashboard-problems.gjs b/frontend/discourse/admin/components/dashboard-problems.gjsindex d9231cec59e..ffbf3a5d9c6 100644--- a/frontend/discourse/admin/components/dashboard-problems.gjs+++ b/frontend/discourse/admin/components/dashboard-problems.gjs@@ -9,6 +9,7 @@ import concatClass from "discourse/helpers/concat-class";import icon from "discourse/helpers/d-icon";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";import { eq } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";@@ -17,14 +18,16 @@ export default class DashboardProblems extends Component {async dismissProblem(problem) {try {await ajax(`/admin/admin_notices/${problem.id}`, { type: "DELETE" });- this.args.problems.removeObject(problem);+ removeValueFromArray(this.args.problems, problem);} catch (error) {popupAjaxError(error);}}get problems() {- return this.args.problems.sort((a, b) => compare(a?.priority, b?.priority));+ return this.args.problems.toSorted((a, b) =>+ compare(a?.priority, b?.priority)+ );}<template>diff --git a/frontend/discourse/admin/components/edit-category-security.gjs b/frontend/discourse/admin/components/edit-category-security.gjsindex eeb69d91c18..4cd180947f9 100644--- a/frontend/discourse/admin/components/edit-category-security.gjs+++ b/frontend/discourse/admin/components/edit-category-security.gjs@@ -5,7 +5,6 @@ import { buildCategoryPanel } from "discourse/admin/components/edit-category-panimport CategoryPermissionRow from "discourse/components/category-permission-row";import PluginOutlet from "discourse/components/plugin-outlet";import lazyHash from "discourse/helpers/lazy-hash";-import discourseComputed from "discourse/lib/decorators";import PermissionType from "discourse/models/permission-type";import ComboBox from "discourse/select-kit/components/combo-box";import { i18n } from "discourse-i18n";@@ -17,23 +16,20 @@ export default class EditCategorySecurity extends buildCategoryPanel(@not("selectedGroup") noGroupSelected;- @discourseComputed("[email protected]_type")- everyonePermission(permissions) {- return permissions.find((p) => p.group_name === "everyone");+ get everyonePermission() {+ return this.category.permissions.find((p) => p.group_name === "everyone");}- @discourseComputed("[email protected]_type")- everyoneGrantedFull() {+ get everyoneGrantedFull() {return (this.everyonePermission &&this.everyonePermission.permission_type === PermissionType.FULL);}- @discourseComputed("everyonePermission")- minimumPermission(everyonePermission) {- return everyonePermission- ? everyonePermission.permission_type+ get minimumPermission() {+ return this.everyonePermission+ ? this.everyonePermission.permission_type: PermissionType.READONLY;}diff --git a/frontend/discourse/admin/components/edit-category-tab.gjs b/frontend/discourse/admin/components/edit-category-tab.gjsindex e23b2e22854..d3f2f92dd2e 100644--- a/frontend/discourse/admin/components/edit-category-tab.gjs+++ b/frontend/discourse/admin/components/edit-category-tab.gjs@@ -6,6 +6,7 @@ import { empty } from "@ember/object/computed";import { scheduleOnce } from "@ember/runloop";import { underscore } from "@ember/string";import { classNameBindings, tagName } from "@ember-decorators/component";+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";@@ -43,7 +44,7 @@ export default class EditCategoryTab extends Component {}_addToCollection() {- this.panels.addObject(this.tabClassName);+ addUniqueValueToArray(this.panels, this.tabClassName);}@discourseComputed("params.slug", "params.parentSlug")diff --git a/frontend/discourse/admin/components/edit-category-tags.gjs b/frontend/discourse/admin/components/edit-category-tags.gjsindex 90930c62ab2..1d0e3bf0c83 100644--- a/frontend/discourse/admin/components/edit-category-tags.gjs+++ b/frontend/discourse/admin/components/edit-category-tags.gjs@@ -6,6 +6,7 @@ import { LinkTo } from "@ember/routing";import { buildCategoryPanel } from "discourse/admin/components/edit-category-panel";import DButton from "discourse/components/d-button";import TextField from "discourse/components/text-field";+import { removeValueFromArray } from "discourse/lib/array-tools";import TagChooser from "discourse/select-kit/components/tag-chooser";import TagGroupChooser from "discourse/select-kit/components/tag-group-chooser";import { i18n } from "discourse-i18n";@@ -25,14 +26,14 @@ export default class EditCategoryTags extends buildCategoryPanel("tags") {@actionaddRequiredTagGroup() {- this.category.required_tag_groups.pushObject({+ this.category.required_tag_groups.push({min_count: 1,});}@actiondeleteRequiredTagGroup(rtg) {- this.category.required_tag_groups.removeObject(rtg);+ removeValueFromArray(this.category.required_tag_groups, rtg);}<template>diff --git a/frontend/discourse/admin/components/emoji-value-list.gjs b/frontend/discourse/admin/components/emoji-value-list.gjsindex 1e09adb78c1..4b4224823a8 100644--- a/frontend/discourse/admin/components/emoji-value-list.gjs+++ b/frontend/discourse/admin/components/emoji-value-list.gjs@@ -1,30 +1,23 @@-/* eslint-disable ember/no-classic-components */-import Component from "@ember/component";+import Component from "@glimmer/component";+import { cached } from "@glimmer/tracking";import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action, set, setProperties } from "@ember/object";-import { schedule } from "@ember/runloop";import { service } from "@ember/service";-import { classNameBindings } from "@ember-decorators/component";import DButton from "discourse/components/d-button";import EmojiPicker from "discourse/components/emoji-picker";import EmojiPickerDetached from "discourse/components/emoji-picker/detached";-import discourseComputed from "discourse/lib/decorators";+import { addUniqueValueToArray } from "discourse/lib/array-tools";import { emojiUrlFor } from "discourse/lib/text";import { not } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";-@classNameBindings(":value-list", ":emoji-list")export default class EmojiValueList extends Component {@service menu;- values = null;-- @discourseComputed("values")- collection(values) {- values = values || "";-- return values+ @cached+ get collection() {+ return this.args.values.split("|").filter(Boolean).map((value) => {@@ -39,19 +32,19 @@ export default class EmojiValueList extends Component {@actionemojiSelected(code) {- if (!this._validateInput(code)) {+ if (!this.#validateInput(code)) {return;}- const item = this.collection.find((emoji) => emoji.isEditing);+ const newCollection = [...this.collection];+ const item = newCollection.find((emoji) => emoji.isEditing);+if (item) {setProperties(item, {value: code,emojiUrl: emojiUrlFor(code),isEditing: false,});-- this._saveValues();} else {const newCollectionValue = {value: code,@@ -59,164 +52,151 @@ export default class EmojiValueList extends Component {isEditable: true,isEditing: false,};- this.collection.addObject(newCollectionValue);- this._saveValues();++ addUniqueValueToArray(newCollection, newCollectionValue);}- }- @discourseComputed("collection")- showUpDownButtons(collection) {- return collection.length - 1 ? true : false;+ this.#saveValues(newCollection);}- _splitValues(values) {- if (values && values.length) {- const emojiList = [];- const emojis = values.split("|").filter(Boolean);- emojis.forEach((emojiName) => {- const emoji = {- isEditable: true,- isEditing: false,- };- emoji.value = emojiName;- emoji.emojiUrl = emojiUrlFor(emojiName);-- emojiList.push(emoji);- });-- return emojiList;- } else {- return [];- }+ get showUpDownButtons() {+ return this.collection.length > 1;}@actioneditValue(index, event) {- schedule("afterRender", () => {- if (parseInt(index, 10) >= 0) {- const item = this.collection[index];- if (item.isEditable) {- set(item, "isEditing", true);- }+ if (parseInt(index, 10) >= 0) {+ const item = this.collection[index];+ if (item.isEditable) {+ set(item, "isEditing", true);}+ }- this.menu.show(event.target, {- identifier: "emoji-picker",- groupIdentifier: "emoji-picker",- component: EmojiPickerDetached,- modalForMobile: true,- data: {- context: "chat",- didSelectEmoji: (emoji) => {- this._replaceValue(index, emoji);- },+ this.menu.show(event.target, {+ identifier: "emoji-picker",+ groupIdentifier: "emoji-picker",+ component: EmojiPickerDetached,+ modalForMobile: true,+ data: {+ context: "chat",+ didSelectEmoji: (emoji) => {+ this.#replaceValue(index, emoji);},- });+ },});}@action- removeValue(value) {- this._removeValue(value);+ removeValue(item) {+ const newCollection = [...this.collection].filter(+ (emoji) => emoji.value !== item.value+ );+ this.#saveValues(newCollection);}@actionshift(operation, index) {+ const updateCollection = [...this.collection];+let futureIndex = index + operation;- if (futureIndex > this.collection.length - 1) {+ if (futureIndex > updateCollection.length - 1) {futureIndex = 0;} else if (futureIndex < 0) {- futureIndex = this.collection.length - 1;+ futureIndex = updateCollection.length - 1;}- const shiftedEmoji = this.collection[index];- this.collection.removeAt(index);- this.collection.insertAt(futureIndex, shiftedEmoji);+ const shiftedEmoji = updateCollection[index];+ updateCollection.splice(index, 1);+ updateCollection.splice(futureIndex, 0, shiftedEmoji);- this._saveValues();+ this.#saveValues(updateCollection);}- _validateInput(input) {+ #validateInput(input) {if (!emojiUrlFor(input)) {- this.setValidationMessage(+ this.args.setValidationMessage(i18n("admin.site_settings.emoji_list.invalid_input"));return false;}- this.setValidationMessage(null);+ this.args.setValidationMessage(null);return true;}- _removeValue(value) {- this.collection.removeObject(value);- this._saveValues();- }+ #replaceValue(index, newValue) {+ const updateCollection = [...this.collection];- _replaceValue(index, newValue) {- const item = this.collection[index];+ const item = updateCollection[index];if (item.value === newValue) {return;}set(item, "value", newValue);- this._saveValues();++ this.#saveValues(updateCollection);}- _saveValues() {- this.set("values", this.collection.map((item) => item.value).join("|"));+ #saveValues(updateCollection) {+ this.args.changeValueCallback(+ updateCollection.map((item) => item.value).join("|")+ );}<template>- {{#if this.collection}}- <ul class="values emoji-value-list">- {{#each this.collection as |data index|}}- <li class="value" data-index={{index}}>- <DButton- @action={{fn this.removeValue data}}- @icon="xmark"- @disabled={{not data.isEditable}}- class="btn-default remove-value-btn btn-small"- />-- <div- class="value-input emoji-details- {{if data.isEditable 'can-edit'}}- {{if data.isEditing 'd-editor-textarea-wrapper'}}"- {{on "click" (fn this.editValue index)}}- role="button"- >- <img- height="15px"- width="15px"- src={{data.emojiUrl}}- class="emoji-list-emoji"- />- <span class="emoji-name">{{data.value}}</span>- </div>-- {{#if this.showUpDownButtons}}+ <div class="value-list emoji-list">+ {{#if this.collection}}+ <ul class="values emoji-value-list">+ {{#each this.collection key="value" as |data index|}}+ <li class="value" data-index={{index}}><DButton- @action={{fn this.shift -1 index}}- @icon="arrow-up"- class="btn-default shift-up-value-btn btn-small"+ @action={{fn this.removeValue data}}+ @icon="xmark"+ @disabled={{not data.isEditable}}+ class="btn-default remove-value-btn btn-small"/>- <DButton- @action={{fn this.shift 1 index}}- @icon="arrow-down"- class="btn-default shift-down-value-btn btn-small"- />- {{/if}}- </li>- {{/each}}- </ul>- {{/if}}-- <div class="value">- <EmojiPicker- @label={{i18n "admin.site_settings.emoji_list.add_emoji_button.label"}}- @didSelectEmoji={{this.emojiSelected}}- />++ <div+ class="value-input emoji-details+ {{if data.isEditable 'can-edit'}}+ {{if data.isEditing 'd-editor-textarea-wrapper'}}"+ {{on "click" (fn this.editValue index)}}+ role="button"+ >+ <img+ height="15px"+ width="15px"+ src={{data.emojiUrl}}+ class="emoji-list-emoji"+ />+ <span class="emoji-name">{{data.value}}</span>+ </div>++ {{#if this.showUpDownButtons}}+ <DButton+ @action={{fn this.shift -1 index}}+ @icon="arrow-up"+ class="btn-default shift-up-value-btn btn-small"+ />+ <DButton+ @action={{fn this.shift 1 index}}+ @icon="arrow-down"+ class="btn-default shift-down-value-btn btn-small"+ />+ {{/if}}+ </li>+ {{/each}}+ </ul>+ {{/if}}++ <div class="value">+ <EmojiPicker+ @label={{i18n+ "admin.site_settings.emoji_list.add_emoji_button.label"+ }}+ @didSelectEmoji={{this.emojiSelected}}+ />+ </div></div></template>}diff --git a/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs b/frontend/discourse/admin/components/modal/edit-badge-groupings.gjsindex c6ad3deb9a3..ba5648d9f4a 100644--- a/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs+++ b/frontend/discourse/admin/components/modal/edit-badge-groupings.gjs@@ -1,32 +1,22 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { A } from "@ember/array";import { Input } from "@ember/component";import { fn } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";-import { TrackedArray } from "@ember-compat/tracked-built-ins";import DButton from "discourse/components/d-button";import DModal from "discourse/components/d-modal";import { ajax } from "discourse/lib/ajax";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";export default class EditBadgeGroupings extends Component {@service dialog;@service store;- @tracked workingCopy = new TrackedArray();-- constructor() {- super(...arguments);- let copy = A();- if (this.args.model.badgeGroupings) {- this.args.model.badgeGroupings.forEach((o) =>- copy.pushObject(this.store.createRecord("badge-grouping", o))- );- }- this.workingCopy = copy;- }+ @trackedArray workingCopy = this.args.model.badgeGroupings.map((o) =>+ this.store.createRecord("badge-grouping", o)+ );@actionup(item) {@@ -40,7 +30,7 @@ export default class EditBadgeGroupings extends Component {@actiondelete(item) {- this.workingCopy.removeObject(item);+ removeValueFromArray(this.workingCopy, item);}@action@@ -49,7 +39,7 @@ export default class EditBadgeGroupings extends Component {editing: true,name: i18n("admin.badges.badge_grouping"),});- this.workingCopy.pushObject(obj);+ this.workingCopy.push(obj);}@action@@ -63,7 +53,7 @@ export default class EditBadgeGroupings extends Component {});this.workingCopy.clear();data.badge_groupings.forEach((badgeGroup) => {- this.workingCopy.pushObject(+ this.workingCopy.push(this.store.createRecord("badge-grouping", {...badgeGroup,editing: false,@@ -82,8 +72,8 @@ export default class EditBadgeGroupings extends Component {if (index + delta < 0 || index + delta >= this.workingCopy.length) {return;}- this.workingCopy.removeAt(index);- this.workingCopy.insertAt(index + delta, item);+ this.workingCopy.splice(index, 1); // remove the item from the old position+ this.workingCopy.splice(index + delta, 0, item); // insert it in the new position}<template>diff --git a/frontend/discourse/admin/components/modal/uploaded-image-list.gjs b/frontend/discourse/admin/components/modal/uploaded-image-list.gjsindex 633612e8ba6..f824f8b7669 100644--- a/frontend/discourse/admin/components/modal/uploaded-image-list.gjs+++ b/frontend/discourse/admin/components/modal/uploaded-image-list.gjs@@ -1,5 +1,4 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";@@ -8,10 +7,15 @@ import DButton from "discourse/components/d-button";import DModal from "discourse/components/d-modal";import boundAvatarTemplate from "discourse/helpers/bound-avatar-template";import icon from "discourse/helpers/d-icon";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";+import { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";export default class UploadedImageList extends Component {- @tracked+ @trackedArrayimages = this.args.model.value?.length? this.args.model.value.split("|"): [];@@ -19,12 +23,12 @@ export default class UploadedImageList extends Component {@actionremove(url, event) {event.preventDefault();- this.images.removeObject(url);+ removeValueFromArray(this.images, url);}@actionuploadDone({ url }) {- this.images.addObject(url);+ addUniqueValueToArray(this.images, url);}@actiondiff --git a/frontend/discourse/admin/components/schema-setting/editor.gjs b/frontend/discourse/admin/components/schema-setting/editor.gjsindex ee4c0ee37e6..7f998c58ac6 100644--- a/frontend/discourse/admin/components/schema-setting/editor.gjs+++ b/frontend/discourse/admin/components/schema-setting/editor.gjs@@ -1,8 +1,10 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";+import { isArray } from "@ember/array";import { fn } from "@ember/helper";import { action } from "@ember/object";import { service } from "@ember/service";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import Tree from "discourse/admin/components/schema-setting/editor/tree";import FieldInput from "discourse/admin/components/schema-setting/field";import DButton from "discourse/components/d-button";@@ -24,7 +26,7 @@ export default class SchemaSettingNewEditor extends Component {@trackedArray history = [];inputFieldObserver = new Map();- data = cloneJSON(this.args.setting.value);+ data = this.#trackNestedArrays(cloneJSON(this.args.setting.value));schema = this.args.schema;@action@@ -191,7 +193,7 @@ export default class SchemaSettingNewEditor extends Component {@actionaddChildItem(propertyName, parentNodeIndex) {- this.activeData[parentNodeIndex][propertyName].pushObject({});+ this.activeData[parentNodeIndex][propertyName].push({});this.onChildClick(this.activeData[parentNodeIndex][propertyName].length - 1,@@ -202,7 +204,7 @@ export default class SchemaSettingNewEditor extends Component {@actionaddItem() {- this.activeData.pushObject({});+ this.activeData.push({});this.activeIndex = this.activeData.length - 1;}@@ -218,7 +220,7 @@ export default class SchemaSettingNewEditor extends Component {return;}- this.activeData.removeAt(this.activeIndex);+ this.activeData.splice(this.activeIndex, 1);if (this.activeData.length > 0) {this.activeIndex = Math.max(this.activeIndex - 1, 0);@@ -260,8 +262,8 @@ export default class SchemaSettingNewEditor extends Component {const toCallback = this.inputFieldObserver[toIndex];// Move the data- this.activeData.removeAt(fromIndex);- this.activeData.insertAt(toIndex, item);+ this.activeData.splice(fromIndex, 1);+ this.activeData.splice(toIndex, 0, item);// Swap the observer callbacks to match new positionsthis.inputFieldObserver[toIndex] = fromCallback;@@ -308,6 +310,38 @@ export default class SchemaSettingNewEditor extends Component {});}+ /**+ * Recursively converts nested arrays to TrackedArrays for reactivity+ *+ * @param {*} input - The input value to convert+ * @returns {TrackedArray|*} The converted value with TrackedArrays+ *+ * @private+ */+ #trackNestedArrays(input) {+ // Return early if input is null/undefined/empty+ if (!input) {+ return input;+ }++ // If input is an array, convert it to a TrackedArray and recursively convert its items+ if (isArray(input)) {+ return new TrackedArray(+ input.map((item) => this.#trackNestedArrays(item))+ );+ }++ // If input is an object, recursively convert its values+ if (typeof input === "object") {+ Object.keys(input).forEach((key) => {+ input[key] = this.#trackNestedArrays(input[key]);+ });+ }++ // Return the input after converting any arrays to TrackedArrays+ return input;+ }+<template><div class="schema-setting-editor">{{#if this.validationErrorMessage}}diff --git a/frontend/discourse/admin/components/secret-value-list.gjs b/frontend/discourse/admin/components/secret-value-list.gjsindex 858e30b82c8..9a08f5b8d4d 100644--- a/frontend/discourse/admin/components/secret-value-list.gjs+++ b/frontend/discourse/admin/components/secret-value-list.gjs@@ -1,112 +1,130 @@-/* eslint-disable ember/no-classic-components */-import Component, { Input } from "@ember/component";+import Component from "@glimmer/component";+import { cached, tracked } from "@glimmer/tracking";+import { Input } from "@ember/component";import { fn } from "@ember/helper";import { on } from "@ember/modifier";import { action, set } from "@ember/object";import { isEmpty } from "@ember/utils";-import { classNameBindings } from "@ember-decorators/component";import DButton from "discourse/components/d-button";import TextField from "discourse/components/text-field";+import { addUniqueValueToArray } from "discourse/lib/array-tools";import { i18n } from "discourse-i18n";-@classNameBindings(":value-list", ":secret-value-list")-export default class SecretValueList extends Component {- inputDelimiter = null;- collection = null;- values = null;+const INPUT_DELIMITER = "\n";- didReceiveAttrs() {- super.didReceiveAttrs(...arguments);+export default class SecretValueList extends Component {+ @tracked newKey;+ @tracked newSecret;- this.set(- "collection",- this._splitValues(this.values, this.inputDelimiter || "\n")- );+ @cached+ get collection() {+ return this.#splitValues(this.args.values, INPUT_DELIMITER);}@actionchangeKey(index, event) {const newValue = event.target.value;- if (this._checkInvalidInput(newValue)) {+ if (this.#checkInvalidInput(newValue)) {return;}- this._replaceValue(index, newValue, "key");+ this.#replaceValue(index, newValue, "key");}@actionchangeSecret(index, event) {const newValue = event.target.value;- if (this._checkInvalidInput(newValue)) {+ if (this.#checkInvalidInput(newValue)) {return;}- this._replaceValue(index, newValue, "secret");+ this.#replaceValue(index, newValue, "secret");}@actionaddValue() {- if (this._checkInvalidInput([this.newKey, this.newSecret])) {+ if (this.#checkInvalidInput([this.newKey, this.newSecret])) {return;}- this._addValue(this.newKey, this.newSecret);- this.setProperties({ newKey: "", newSecret: "" });+ this.#addValue(this.newKey, this.newSecret);++ this.newKey = "";+ this.newSecret = "";}@actionremoveValue(value) {- this._removeValue(value);+ this.#removeValue(value);}- _checkInvalidInput(inputs) {- for (let input of inputs) {+ #checkInvalidInput(inputs) {+ for (const input of inputs) {if (isEmpty(input) || input.includes("|")) {- this.setValidationMessage(+ this.args.setValidationMessage(i18n("admin.site_settings.secret_list.invalid_input"));return true;}}- this.setValidationMessage(null);++ if (this.collection.some((item) => item.key.trim() === inputs[0].trim())) {+ this.args.setValidationMessage(+ i18n("admin.site_settings.secret_list.already_exists", {+ key: inputs[0],+ })+ );+ return true;+ }++ this.args.setValidationMessage(null);}- _addValue(value, secret) {- this.collection.addObject({ key: value, secret });- this._saveValues();+ #addValue(value, secret) {+ const updatedCollection = addUniqueValueToArray(+ [...this.collection],+ {+ key: value,+ secret,+ },+ (item) => item.key+ );+ this.#saveValues(updatedCollection);}- _removeValue(value) {- const collection = this.collection;- collection.removeObject(value);- this._saveValues();+ #removeValue(value) {+ const updatedCollection = [...this.collection].filter(+ (item) => !(item.key === value.key && item.secret === value.secret)+ );+ this.#saveValues(updatedCollection);}- _replaceValue(index, newValue, keyName) {- let item = this.collection[index];+ #replaceValue(index, newValue, keyName) {+ const updatedCollection = [...this.collection];++ const item = updatedCollection[index];set(item, keyName, newValue);- this._saveValues();+ this.#saveValues(updatedCollection);}- _saveValues() {- this.set(- "values",- this.collection+ #saveValues(updatedCollection) {+ this.args.changeValueCallback(+ updatedCollection.map(function (elem) {return `${elem.key}|${elem.secret}`;})- .join("\n")+ .join(INPUT_DELIMITER));}- _splitValues(values, delimiter) {+ #splitValues(values, delimiter) {if (values && values.length) {const keys = ["key", "secret"];- let res = [];+ const res = [];values.split(delimiter).forEach(function (str) {- let object = {};+ const object = {};str.split("|").forEach(function (a, i) {object[keys[i]] = a;});@@ -120,48 +138,50 @@ export default class SecretValueList extends Component {}<template>- {{#if this.collection}}- <div class="values">- {{#each this.collection as |value index|}}- <div class="value" data-index={{index}}>- <DButton- @action={{fn this.removeValue value}}- @icon="xmark"- class="btn-default remove-value-btn btn-small"- />- <Input- @value={{value.key}}- class="value-input"- {{on "focusout" (fn this.changeKey index)}}- />- <Input- @value={{value.secret}}- class="value-input"- @type={{if this.isSecret "password" "text"}}- {{on "focusout" (fn this.changeSecret index)}}- />- </div>- {{/each}}+ <div class="value-list secret-value-list">+ {{#if this.collection}}+ <div class="values">+ {{#each this.collection as |value index|}}+ <div class="value" data-index={{index}}>+ <DButton+ @action={{fn this.removeValue value}}+ @icon="xmark"+ class="btn-default remove-value-btn btn-small"+ />+ <Input+ @value={{value.key}}+ class="value-input"+ {{on "focusout" (fn this.changeKey index)}}+ />+ <Input+ @value={{value.secret}}+ class="value-input"+ @type={{if @isSecret "password" "text"}}+ {{on "focusout" (fn this.changeSecret index)}}+ />+ </div>+ {{/each}}+ </div>+ {{/if}}++ <div class="value">+ <TextField+ @value={{this.newKey}}+ @placeholder={{this.setting.placeholder.key}}+ class="new-value-input key"+ />+ <Input+ @type={{if @isSecret "password" "text"}}+ @value={{this.newSecret}}+ class="new-value-input secret"+ placeholder={{this.setting.placeholder.value}}+ />+ <DButton+ @action={{this.addValue}}+ @icon="plus"+ class="add-value-btn btn-small"+ /></div>- {{/if}}-- <div class="value">- <TextField- @value={{this.newKey}}- @placeholder={{this.setting.placeholder.key}}- class="new-value-input key"- />- <Input- @type="password"- @value={{this.newSecret}}- class="new-value-input secret"- placeholder={{this.setting.placeholder.value}}- />- <DButton- @action={{this.addValue}}- @icon="plus"- class="add-value-btn btn-small"- /></div></template>}diff --git a/frontend/discourse/admin/components/simple-list.gjs b/frontend/discourse/admin/components/simple-list.gjsindex 82c461f7e58..94ddd9e9e8f 100644--- a/frontend/discourse/admin/components/simple-list.gjs+++ b/frontend/discourse/admin/components/simple-list.gjs@@ -56,7 +56,7 @@ export default class SimpleList extends Component {}@action- removeAt(index) {+ removeItem(index) {this.collection.splice(index, 1);this.args.onChange?.(this.collection);}@@ -85,7 +85,7 @@ export default class SimpleList extends Component {{{#each this.collection as |value index|}}<div data-index={{index}} class="value"><DButton- @action={{fn this.removeAt index}}+ @action={{fn this.removeItem index}}@icon="xmark"class="btn-default remove-value-btn btn-small"/>diff --git a/frontend/discourse/admin/components/site-settings/emoji-list.gjs b/frontend/discourse/admin/components/site-settings/emoji-list.gjsindex 8a6879aa765..8f712cc0eb0 100644--- a/frontend/discourse/admin/components/site-settings/emoji-list.gjs+++ b/frontend/discourse/admin/components/site-settings/emoji-list.gjs@@ -5,6 +5,7 @@ const EmojiList = <template>@setting={{@setting}}@values={{@value}}@setValidationMessage={{@setValidationMessage}}+ @changeValueCallback={{@changeValueCallback}}/></template>;diff --git a/frontend/discourse/admin/components/site-settings/secret-list.gjs b/frontend/discourse/admin/components/site-settings/secret-list.gjsindex b0de3486491..b13052dd1ad 100644--- a/frontend/discourse/admin/components/site-settings/secret-list.gjs+++ b/frontend/discourse/admin/components/site-settings/secret-list.gjs@@ -1,14 +1,13 @@-/* eslint-disable ember/no-classic-components */-import Component from "@ember/component";import SecretValueList from "discourse/admin/components/secret-value-list";-export default class SecretList extends Component {- <template>- <SecretValueList- @setting={{this.setting}}- @values={{this.value}}- @isSecret={{this.isSecret}}- @setValidationMessage={{this.setValidationMessage}}- />- </template>-}+const SecretList = <template>+ <SecretValueList+ @setting={{@setting}}+ @values={{@value}}+ @isSecret={{@isSecret}}+ @setValidationMessage={{@setValidationMessage}}+ @changeValueCallback={{@changeValueCallback}}+ />+</template>;++export default SecretList;diff --git a/frontend/discourse/admin/components/value-list.gjs b/frontend/discourse/admin/components/value-list.gjsindex fce2fddaae4..7eedd47e965 100644--- a/frontend/discourse/admin/components/value-list.gjs+++ b/frontend/discourse/admin/components/value-list.gjs@@ -4,22 +4,27 @@ import { fn, hash } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { empty, reads } from "@ember/object/computed";-import { TrackedArray } from "@ember-compat/tracked-built-ins";import { classNames } from "@ember-decorators/component";import DButton from "discourse/components/d-button";-import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import {+ addUniqueValueToArray,+ removeValueFromArray,+ uniqueItemsFromArray,+} from "discourse/lib/array-tools";import discourseComputed from "discourse/lib/decorators";import { makeArray } from "discourse/lib/helpers";+import { trackedArray } from "discourse/lib/tracked-tools";import ComboBox from "discourse/select-kit/components/combo-box";@classNames("value-list")export default class ValueList extends Component {+ @trackedArray collection = null;+@empty("newValue") inputInvalid;inputDelimiter = null;inputType = null;newValue = "";- collection = null;values = null;onChange = null;@@ -29,10 +34,7 @@ export default class ValueList extends Component {super.didReceiveAttrs(...arguments);if (this.inputType === "array") {- this.set(- "collection",- new TrackedArray(this.values ? [...this.values] : [])- );+ this.set("collection", this.values ? [...this.values] : []);return;}@@ -89,14 +91,14 @@ export default class ValueList extends Component {}const shiftedValue = this.collection[index];- this.collection.removeAt(index);- this.collection.insertAt(futureIndex, shiftedValue);+ this.collection.splice(index, 1);+ this.collection.splice(futureIndex, 0, shiftedValue);this._saveValues();}_addValue(value) {- this.collection.addObject(value);+ addUniqueValueToArray(this.collection, value);if (this.choices) {this.set(@@ -111,7 +113,7 @@ export default class ValueList extends Component {}_removeValue(value) {- this.collection.removeObject(value);+ removeValueFromArray(this.collection, value);if (this.choices) {this.set("choices", uniqueItemsFromArray(this.choices.concat([value])));diff --git a/frontend/discourse/admin/components/webhook-event-chooser.gjs b/frontend/discourse/admin/components/webhook-event-chooser.gjsindex 14ef118d926..71b654f772b 100644--- a/frontend/discourse/admin/components/webhook-event-chooser.gjs+++ b/frontend/discourse/admin/components/webhook-event-chooser.gjs@@ -1,5 +1,9 @@import Component from "@glimmer/component";import { Input } from "@ember/component";+import {+ addUniqueValueToArray,+ removeValuesFromArray,+} from "discourse/lib/array-tools";import { i18n } from "discourse-i18n";export default class WebhookEventChooser extends Component {@@ -28,9 +32,10 @@ export default class WebhookEventChooser extends Component {}if (value) {- eventTypes.addObject(this.args.type);+ addUniqueValueToArray(eventTypes, this.args.type);} else {- eventTypes.removeObjects(+ removeValuesFromArray(+ eventTypes,eventTypes.filter((eventType) => eventType.name === this.args.type.name));}diff --git a/frontend/discourse/admin/components/webhook-events.gjs b/frontend/discourse/admin/components/webhook-events.gjsindex 0388384179c..b0c7d8a1a53 100644--- a/frontend/discourse/admin/components/webhook-events.gjs+++ b/frontend/discourse/admin/components/webhook-events.gjs@@ -16,6 +16,7 @@ import LoadMore from "discourse/components/load-more";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";import ComboBox from "discourse/select-kit/components/combo-box";import { not } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";@@ -25,10 +26,10 @@ export default class WebhookEvents extends Component {@service store;@service dialog;- @tracked pingEnabled = true;@tracked events = [];- @tracked incomingEventIds = [];+ @tracked pingEnabled = true;@tracked redeliverEnabled = true;+ @trackedArray incomingEventIds = [];@readOnly("incomingEventIds.length") incomingCount;@gt("incomingCount", 0) hasIncoming;@@ -126,7 +127,7 @@ export default class WebhookEvents extends Component {}if (!this.incomingEventIds.includes(data.web_hook_event_id)) {- this.incomingEventIds.pushObject(data.web_hook_event_id);+ this.incomingEventIds.push(data.web_hook_event_id);}}diff --git a/frontend/discourse/admin/controllers/admin-config/color-palettes/index.js b/frontend/discourse/admin/controllers/admin-config/color-palettes/index.jsindex 4e35ec64a65..bcf62c36848 100644--- a/frontend/discourse/admin/controllers/admin-config/color-palettes/index.js+++ b/frontend/discourse/admin/controllers/admin-config/color-palettes/index.js@@ -4,6 +4,7 @@ import { action } from "@ember/object";import { service } from "@ember/service";import ColorSchemeSelectBaseModal from "discourse/admin/components/modal/color-scheme-select-base";import { setDefaultColorScheme } from "discourse/admin/lib/color-scheme-manager";+import { removeValueFromArray } from "discourse/lib/array-tools";import { currentThemeId } from "discourse/lib/theme-selector";import { i18n } from "discourse-i18n";@@ -190,7 +191,7 @@ export default class AdminConfigColorPalettesIndexController extends ControllernewColorScheme.colors.forEach((color) => {color.default_hex = color.originals.hex;});- this.model.pushObject(newColorScheme);+ this.model.push(newColorScheme);newColorScheme.set("savingStatus", null);this.router.replaceWith("adminConfig.colorPalettes.show", newColorScheme);@@ -276,15 +277,14 @@ export default class AdminConfigColorPalettesIndexController extends Controllerreturn new Promise((resolve, reject) => {this.dialog.deleteConfirm({title: i18n("admin.customize.colors.delete_confirm"),- didConfirm: () => {- return scheme- .destroy()- .then(() => {- this.model.removeObject(scheme);-- resolve();- })- .catch(reject);+ didConfirm: async () => {+ try {+ await scheme.destroy();+ removeValueFromArray(this.model, scheme);+ resolve();+ } catch (error) {+ reject(error);+ }},didCancel: () => {reject(new Error("Deletion cancelled"));diff --git a/frontend/discourse/admin/controllers/admin-embedding/index.js b/frontend/discourse/admin/controllers/admin-embedding/index.jsindex d410bfce246..d8749bb2376 100644--- a/frontend/discourse/admin/controllers/admin-embedding/index.js+++ b/frontend/discourse/admin/controllers/admin-embedding/index.js@@ -1,27 +1,27 @@import Controller, { inject as controller } from "@ember/controller";import { action } from "@ember/object";-import { alias } from "@ember/object/computed";import { service } from "@ember/service";-import discourseComputed from "discourse/lib/decorators";+import { removeValueFromArray } from "discourse/lib/array-tools";export default class AdminEmbeddingIndexController extends Controller {@service site;@controller adminEmbedding;- @alias("adminEmbedding.embedding") embedding;+ get embedding() {+ return this.adminEmbedding.embedding;+ }get showEmbeddingCode() {return this.site.desktopView;}- @discourseComputed("embedding.base_url")- embeddingCode(baseUrl) {+ get embeddingCode() {const html = `<div id='discourse-comments'></div><meta name='discourse-username' content='DISCOURSE_USERNAME'><script type="text/javascript">DiscourseEmbed = {- discourseUrl: '${baseUrl}/',+ discourseUrl: '${this.embedding.base_url}/',discourseEmbedUrl: 'EMBED_URL',// className: 'CLASS_NAME',};@@ -38,6 +38,6 @@ export default class AdminEmbeddingIndexController extends Controller {@actiondeleteHost(host) {- this.get("embedding.embeddable_hosts").removeObject(host);+ removeValueFromArray(this.embedding.embeddable_hosts, host);}}diff --git a/frontend/discourse/admin/controllers/admin-logs/screened-ip-addresses.js b/frontend/discourse/admin/controllers/admin-logs/screened-ip-addresses.jsindex 09d24bb431c..081ee2e0a71 100644--- a/frontend/discourse/admin/controllers/admin-logs/screened-ip-addresses.js+++ b/frontend/discourse/admin/controllers/admin-logs/screened-ip-addresses.js@@ -1,31 +1,28 @@+import { tracked } from "@glimmer/tracking";import Controller from "@ember/controller";import { action } from "@ember/object";import { service } from "@ember/service";import { observes } from "@ember-decorators/object";import ScreenedIpAddress from "discourse/admin/models/screened-ip-address";+import { removeValueFromArray } from "discourse/lib/array-tools";import discourseDebounce from "discourse/lib/debounce";import { INPUT_DELAY } from "discourse/lib/environment";import { exportEntity } from "discourse/lib/export-csv";import { outputExportResult } from "discourse/lib/export-result";+import { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";export default class AdminLogsScreenedIpAddressesController extends Controller {@service dialog;- loading = false;- filter = null;- savedIpAddress = null;-- _debouncedShow() {- this.set("loading", true);- ScreenedIpAddress.findAll(this.filter).then((result) => {- this.setProperties({ model: result, loading: false });- });- }+ @tracked filter = null;+ @tracked loading = false;+ @tracked savedIpAddress = null;+ @trackedArray model;@observes("filter")show() {- discourseDebounce(this, this._debouncedShow, INPUT_DELAY);+ discourseDebounce(this, this.#debouncedShow, INPUT_DELAY);}@action@@ -82,39 +79,47 @@ export default class AdminLogsScreenedIpAddressesController extends Controller {}@action- destroyRecord(record) {+ async destroyRecord(record) {return this.dialog.yesNoConfirm({message: i18n("admin.logs.screened_ips.delete_confirm", {ip_address: record.get("ip_address"),}),- didConfirm: () => {- return record- .destroy()- .then((deleted) => {- if (deleted) {- this.model.removeObject(record);- } else {- this.dialog.alert(i18n("generic_error"));- }- })- .catch((e) => {- this.dialog.alert(- i18n("generic_error_with_reason", {- error: `http: ${e.status} - ${e.body}`,- })- );- });+ didConfirm: async () => {+ try {+ const deleted = await record.destroy();+ if (deleted) {+ removeValueFromArray(this.model, record);+ } else {+ this.dialog.alert(i18n("generic_error"));+ }+ } catch (e) {+ this.dialog.alert(+ i18n("generic_error_with_reason", {+ error: `http: ${e.status} - ${e.body}`,+ })+ );+ }},});}@actionrecordAdded(arg) {- this.model.unshiftObject(arg);+ this.model.unshift(arg);}@actionexportScreenedIpList() {exportEntity("screened_ip").then(outputExportResult);}++ async #debouncedShow() {+ this.loading = true;++ try {+ this.model = await ScreenedIpAddress.findAll(this.filter);+ } finally {+ this.loading = false;+ }+ }}diff --git a/frontend/discourse/admin/controllers/admin-permalinks/index.js b/frontend/discourse/admin/controllers/admin-permalinks/index.jsindex 5233bdbf04c..22b1a051634 100644--- a/frontend/discourse/admin/controllers/admin-permalinks/index.js+++ b/frontend/discourse/admin/controllers/admin-permalinks/index.js@@ -1,11 +1,13 @@+import { tracked } from "@glimmer/tracking";import Controller from "@ember/controller";import { action } from "@ember/object";-import { or } from "@ember/object/computed";import { service } from "@ember/service";import { observes } from "@ember-decorators/object";import Permalink from "discourse/admin/models/permalink";+import { removeValueFromArray } from "discourse/lib/array-tools";import discourseDebounce from "discourse/lib/debounce";import { INPUT_DELAY } from "discourse/lib/environment";+import { trackedArray } from "discourse/lib/tracked-tools";import { clipboardCopy } from "discourse/lib/utilities";import { i18n } from "discourse-i18n";@@ -13,21 +15,17 @@ export default class AdminPermalinksIndexController extends Controller {@service dialog;@service toasts;- loading = false;- filter = null;+ @tracked loading = false;+ @tracked filter = null;+ @trackedArray model;- @or("model.length", "filter") showSearch;-- _debouncedShow() {- Permalink.findAll(this.filter).then((result) => {- this.set("model", result);- this.set("loading", false);- });+ get showSearch() {+ return !!(this.model.length || this.filter);}@observes("filter")show() {- discourseDebounce(this, this._debouncedShow, INPUT_DELAY);+ discourseDebounce(this, this.#debouncedShow, INPUT_DELAY);}@action@@ -49,11 +47,21 @@ export default class AdminPermalinksIndexController extends Controller {didConfirm: async () => {try {await this.store.destroyRecord("permalink", permalink);- this.model.removeObject(permalink);+ removeValueFromArray(this.model, permalink);} catch {this.dialog.alert(i18n("generic_error"));}},});}++ async #debouncedShow() {+ this.loading = true;++ try {+ this.model = await Permalink.findAll(this.filter);+ } finally {+ this.loading = false;+ }+ }}diff --git a/frontend/discourse/admin/controllers/admin-user/badges.js b/frontend/discourse/admin/controllers/admin-user/badges.jsindex fd3231514f9..c3489407e30 100644--- a/frontend/discourse/admin/controllers/admin-user/badges.js+++ b/frontend/discourse/admin/controllers/admin-user/badges.js@@ -1,5 +1,7 @@+import { tracked } from "@glimmer/tracking";import Controller, { inject as controller } from "@ember/controller";import { action } from "@ember/object";+import { dependentKeyCompat } from "@ember/object/compat";import { alias, empty, sort } from "@ember/object/computed";import { next } from "@ember/runloop";import { service } from "@ember/service";@@ -7,7 +9,6 @@ import { compare } from "@ember/utils";import AdminUser from "discourse/admin/models/admin-user";import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";-import discourseComputed from "discourse/lib/decorators";import { grantableBadges } from "discourse/lib/grant-badge-utils";import { trackedArray } from "discourse/lib/tracked-tools";import UserBadge from "discourse/models/user-badge";@@ -17,20 +18,30 @@ export default class AdminUserBadgesController extends Controller {@service dialog;@controller adminUser;+ @tracked loading;+ @tracked selectedBadgeId;+ @trackedArray badges;@trackedArray expandedBadges = [];- @trackedArray model;@alias("adminUser.model") user;- @alias("model") userBadges;- @alias("badges") allBadges;@sort("model", "badgeSortOrder") sortedBadges;@empty("availableBadges") noAvailableBadges;badgeSortOrder = ["granted_at:desc"];- @discourseComputed("allBadges.[]", "userBadges.[]")- availableBadges() {- return grantableBadges(this.get("allBadges"), this.get("userBadges"));+ @dependentKeyCompat+ get allBadges() {+ return this.badges;+ }++ @dependentKeyCompat+ get userBadges() {+ return this.model;+ }++ @dependentKeyCompat+ get availableBadges() {+ return grantableBadges(this.allBadges, this.userBadges);}get groupedBadges() {@@ -86,37 +97,35 @@ export default class AdminUserBadgesController extends Controller {}@action- performGrantBadge() {- UserBadge.grant(- this.selectedBadgeId,- this.get("user.username"),- this.badgeReason- ).then(- (newBadge) => {- this.set("badgeReason", "");- this.userBadges.pushObject(newBadge);- next(() => {- // Update the selected badge ID after the combobox has re-rendered.- const newSelectedBadge = this.availableBadges[0];- if (newSelectedBadge) {- this.set("selectedBadgeId", newSelectedBadge.get("id"));- }- });- },- function (error) {- popupAjaxError(error);- }- );+ async performGrantBadge() {+ try {+ const newBadge = await UserBadge.grant(+ this.selectedBadgeId,+ this.get("user.username"),+ this.badgeReason+ );++ this.set("badgeReason", "");+ this.model.push(newBadge);+ next(() => {+ // Update the selected badge ID after the combobox has re-rendered.+ const newSelectedBadge = this.availableBadges[0];+ if (newSelectedBadge) {+ this.set("selectedBadgeId", newSelectedBadge.get("id"));+ }+ });+ } catch (error) {+ popupAjaxError(error);+ }}@actionrevokeBadge(userBadge) {return this.dialog.yesNoConfirm({message: i18n("admin.badges.revoke_confirm"),- didConfirm: () => {- return userBadge.revoke().then(() => {- removeValueFromArray(this.model, userBadge);- });+ didConfirm: async () => {+ await userBadge.revoke();+ removeValueFromArray(this.model, userBadge);},});}diff --git a/frontend/discourse/admin/controllers/admin-user/index.js b/frontend/discourse/admin/controllers/admin-user/index.jsindex 85a19d6df61..05f6956e309 100644--- a/frontend/discourse/admin/controllers/admin-user/index.js+++ b/frontend/discourse/admin/controllers/admin-user/index.js@@ -70,14 +70,12 @@ export default class AdminUserIndexController extends Controller {.join(", ");}- @discourseComputed("model.associated_accounts")- associatedAccountsLoaded(associatedAccounts) {- return typeof associatedAccounts !== "undefined";+ get associatedAccountsLoaded() {+ return typeof this.model.associated_accounts !== "undefined";}- @discourseComputed("model.associated_accounts")- associatedAccounts(associatedAccounts) {- return associatedAccounts+ get associatedAccounts() {+ return this.model.associated_accounts?.map((provider) => `${provider.name} (${provider.description})`)?.join(", ");}diff --git a/frontend/discourse/admin/controllers/admin-web-hooks/edit.js b/frontend/discourse/admin/controllers/admin-web-hooks/edit.jsdeleted file mode 100644index 8cf44e58346..00000000000--- a/frontend/discourse/admin/controllers/admin-web-hooks/edit.js+++ /dev/null@@ -1,104 +0,0 @@-import Controller, { inject as controller } from "@ember/controller";-import EmberObject, { action } from "@ember/object";-import { alias } from "@ember/object/computed";-import { service } from "@ember/service";-import { isEmpty } from "@ember/utils";-import { popupAjaxError } from "discourse/lib/ajax-error";-import discourseComputed from "discourse/lib/decorators";-import { i18n } from "discourse-i18n";--export default class AdminWebHooksEditController extends Controller {- @service router;- @service siteSettings;-- @controller adminWebHooks;-- @alias("adminWebHooks.groupedEventTypes") groupedEventTypes;- @alias("adminWebHooks.defaultEventTypes") defaultEventTypes;- @alias("adminWebHooks.contentTypes") contentTypes;-- @discourseComputed- showTagsFilter() {- return this.siteSettings.tagging_enabled;- }-- @discourseComputed("model.isSaving", "saved", "saveButtonDisabled")- savingStatus(isSaving, saved, saveButtonDisabled) {- if (isSaving) {- return i18n("saving");- } else if (!saveButtonDisabled && saved) {- return i18n("saved");- }- // Use side effect of validation to clear saved text- this.set("saved", false);- return "";- }-- @discourseComputed("model.isNew")- saveButtonText(isNew) {- return isNew- ? i18n("admin.web_hooks.create")- : i18n("admin.web_hooks.save");- }-- @discourseComputed("model.secret")- secretValidation(secret) {- if (!isEmpty(secret)) {- if (secret.includes(" ")) {- return EmberObject.create({- failed: true,- reason: i18n("admin.web_hooks.secret_invalid"),- });- }-- if (secret.length < 12) {- return EmberObject.create({- failed: true,- reason: i18n("admin.web_hooks.secret_too_short"),- });- }- }- }-- @discourseComputed("model.wildcard_web_hook", "model.web_hook_event_types.[]")- eventTypeValidation(isWildcard, eventTypes) {- if (!isWildcard && isEmpty(eventTypes)) {- return EmberObject.create({- failed: true,- reason: i18n("admin.web_hooks.event_type_missing"),- });- }- }-- @discourseComputed(- "model.isSaving",- "secretValidation",- "eventTypeValidation",- "model.payload_url"- )- saveButtonDisabled(- isSaving,- secretValidation,- eventTypeValidation,- payloadUrl- ) {- return isSaving- ? false- : secretValidation || eventTypeValidation || isEmpty(payloadUrl);- }-- @action- async save() {- this.set("saved", false);-- try {- await this.model.save();-- this.set("saved", true);- this.adminWebHooks.model.addObject(this.model);- this.router.transitionTo("adminWebHooks.show", this.model);- } catch (e) {- popupAjaxError(e);- }- }-}diff --git a/frontend/discourse/admin/controllers/admin-web-hooks/index.js b/frontend/discourse/admin/controllers/admin-web-hooks/index.jsdeleted file mode 100644index a8e064d7cce..00000000000--- a/frontend/discourse/admin/controllers/admin-web-hooks/index.js+++ /dev/null@@ -1,37 +0,0 @@-import Controller, { inject as controller } from "@ember/controller";-import { action } from "@ember/object";-import { alias } from "@ember/object/computed";-import { service } from "@ember/service";-import { popupAjaxError } from "discourse/lib/ajax-error";-import { i18n } from "discourse-i18n";--export default class AdminWebHooksIndexController extends Controller {- @service dialog;- @controller adminWebHooks;-- @alias("adminWebHooks.contentTypes") contentTypes;- @alias("adminWebHooks.defaultEventTypes") defaultEventTypes;- @alias("adminWebHooks.deliveryStatuses") deliveryStatuses;- @alias("adminWebHooks.eventTypes") eventTypes;- @alias("adminWebHooks.model") model;-- @action- destroyWebhook(webhook) {- return this.dialog.deleteConfirm({- message: i18n("admin.web_hooks.delete_confirm"),- didConfirm: async () => {- try {- await webhook.destroyRecord();- this.model.removeObject(webhook);- } catch (e) {- popupAjaxError(e);- }- },- });- }-- @action- loadMore() {- this.model.loadMore();- }-}diff --git a/frontend/discourse/admin/controllers/admin-web-hooks/show.js b/frontend/discourse/admin/controllers/admin-web-hooks/show.jsindex 503d984bd06..192d8ec2b5b 100644--- a/frontend/discourse/admin/controllers/admin-web-hooks/show.js+++ b/frontend/discourse/admin/controllers/admin-web-hooks/show.js@@ -26,7 +26,6 @@ export default class AdminWebHooksShowController extends Controller {didConfirm: async () => {try {await this.model.destroyRecord();- this.adminWebHooks.model.removeObject(this.model);this.router.transitionTo("adminWebHooks");} catch (e) {popupAjaxError(e);diff --git a/frontend/discourse/admin/controllers/admin/dashboard.js b/frontend/discourse/admin/controllers/admin/dashboard.jsindex b79d348ace9..51d091db0c6 100644--- a/frontend/discourse/admin/controllers/admin/dashboard.js+++ b/frontend/discourse/admin/controllers/admin/dashboard.js@@ -1,3 +1,4 @@+import { tracked } from "@glimmer/tracking";import Controller, { inject as controller } from "@ember/controller";import { action, computed } from "@ember/object";import { service } from "@ember/service";@@ -5,6 +6,7 @@ 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 { trackedArray } from "discourse/lib/tracked-tools";const PROBLEMS_CHECK_MINUTES = 1;@@ -13,6 +15,10 @@ export default class AdminDashboardController extends Controller {@service siteSettings;@controller("exception") exceptionController;+ @tracked loadingProblems = false;+ @tracked problemsFetchedAt;+ @trackedArray problems;+isLoading = false;dashboardFetchedAt = null;@@ -89,15 +95,18 @@ export default class AdminDashboardController extends Controller {}}- _loadProblems() {+ async _loadProblems() {this.setProperties({loadingProblems: true,problemsFetchedAt: new Date(),});- AdminDashboard.fetchProblems()- .then((model) => this.set("problems", model.problems))- .finally(() => this.set("loadingProblems", false));+ try {+ const model = await AdminDashboard.fetchProblems();+ this.problems = model.problems;+ } finally {+ this.loadingProblems = false;+ }}@discourseComputed("problemsFetchedAt")diff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.jsindex 2f6097b5322..88d847d6d4b 100644--- a/frontend/discourse/admin/controllers/edit-category/tabs.js+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js@@ -6,6 +6,7 @@ import { service } from "@ember/service";import { underscore } from "@ember/string";import { popupAjaxError } from "discourse/lib/ajax-error";import discourseComputed from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";import DiscourseURL from "discourse/lib/url";import Category from "discourse/models/category";import { i18n } from "discourse-i18n";@@ -29,11 +30,11 @@ export default class EditCategoryTabsController extends Controller {@service router;@tracked breadcrumbCategories = this.site.get("categoriesList");+ @trackedArray panels = [];selectedTab = "general";saving = false;deleting = false;- panels = [];showTooltip = false;createdCategory = false;expandedMenu = false;diff --git a/frontend/discourse/admin/lib/setting-object-helper.js b/frontend/discourse/admin/lib/setting-object-helper.jsindex 11698e61ce5..9fe9e692465 100644--- a/frontend/discourse/admin/lib/setting-object-helper.js+++ b/frontend/discourse/admin/lib/setting-object-helper.js@@ -1,5 +1,6 @@import { dependentKeyCompat } from "@ember/object/compat";import { isPresent } from "@ember/utils";+import { addUniqueValueToArray } from "discourse/lib/array-tools";import { deepEqual } from "discourse/lib/object";import { i18n } from "discourse-i18n";@@ -55,9 +56,9 @@ export default class SettingObjectHelper {(originalValidValues || []).forEach((v) => {if (v.name && v.name.length > 0 && translateNames) {- values.addObject({ name: i18n(v.name), value: v.value });+ addUniqueValueToArray(values, { name: i18n(v.name), value: v.value });} else {- values.addObject(v);+ addUniqueValueToArray(values, v);}});return values;diff --git a/frontend/discourse/admin/models/admin-user.js b/frontend/discourse/admin/models/admin-user.jsindex 35c974bfab1..3d08ef3e30a 100644--- a/frontend/discourse/admin/models/admin-user.js+++ b/frontend/discourse/admin/models/admin-user.js@@ -82,11 +82,13 @@ export default class AdminUser extends User {);}- groupAdded(added) {- return ajax(`/admin/users/${this.id}/groups`, {+ async groupAdded(added) {+ await ajax(`/admin/users/${this.id}/groups`, {type: "POST",data: { group_id: added.id },- }).then(() => this.groups.pushObject(added));+ });++ this.groups.push(added);}groupRemoved(groupId) {diff --git a/frontend/discourse/admin/models/color-scheme.js b/frontend/discourse/admin/models/color-scheme.jsindex 48fc28cf288..a47d806d716 100644--- a/frontend/discourse/admin/models/color-scheme.js+++ b/frontend/discourse/admin/models/color-scheme.js@@ -1,36 +1,38 @@import { tracked } from "@glimmer/tracking";-import { A } from "@ember/array";-import ArrayProxy from "@ember/array/proxy";import EmberObject 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 { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";-class ColorSchemes extends ArrayProxy {}+class ColorSchemes extends LegacyArrayLikeObject {+ @tracked loading = false;+}export default class ColorScheme extends EmberObject {- static findAll() {+ static async findAll() {const colorSchemes = ColorSchemes.create({ content: [], loading: true });-- return ajax("/admin/color_schemes").then((all) => {- all.forEach((colorScheme) => {- colorSchemes.pushObject(- ColorScheme.create({- id: colorScheme.id,- name: colorScheme.name,- is_base: colorScheme.is_base,- theme_id: colorScheme.theme_id,- theme_name: colorScheme.theme_name,- base_scheme_id: colorScheme.base_scheme_id,- user_selectable: colorScheme.user_selectable,- colors: colorScheme.colors,- })- );- });- return colorSchemes;+ const all = await ajax("/admin/color_schemes");++ all.forEach((colorScheme) => {+ colorSchemes.push(+ ColorScheme.create({+ id: colorScheme.id,+ name: colorScheme.name,+ is_base: colorScheme.is_base,+ theme_id: colorScheme.theme_id,+ theme_name: colorScheme.theme_name,+ base_scheme_id: colorScheme.base_scheme_id,+ user_selectable: colorScheme.user_selectable,+ colors: colorScheme.colors,+ })+ );});++ return colorSchemes;}static async find(id) {@@ -49,6 +51,7 @@ export default class ColorScheme extends EmberObject {@tracked name;@tracked user_selectable;+ @trackedArray colors;@not("id") newRecord;@@ -56,7 +59,7 @@ export default class ColorScheme extends EmberObject {super.init(...arguments);/** @type Array */- const colors = A(this.colors ?? []);+ const colors = this.colors ?? [];this.colors = colors.map((c) => {return ColorSchemeColor.create(c);});@@ -105,10 +108,10 @@ export default class ColorScheme extends EmberObject {name: this.name,can_edit: true,/** @type Array */- colors: A(),+ colors: [],});this.colors.forEach((c) => {- newScheme.colors.pushObject(+ newScheme.colors.push(ColorSchemeColor.create(c.getProperties("name", "hex", "default_hex")));});@@ -166,7 +169,7 @@ export default class ColorScheme extends EmberObject {data.colors = [];this.colors.forEach((c) => {if (!this.id || c.get("changed")) {- data.colors.pushObject(c.getProperties("name", "hex"));+ data.colors.push(c.getProperties("name", "hex"));}});}diff --git a/frontend/discourse/admin/models/embedding.js b/frontend/discourse/admin/models/embedding.jsnew file mode 100644index 00000000000..c21d86b6b9d--- /dev/null+++ b/frontend/discourse/admin/models/embedding.js@@ -0,0 +1,6 @@+import { trackedArray } from "discourse/lib/tracked-tools";+import RestModel from "discourse/models/rest";++export default class Embedding extends RestModel {+ @trackedArray embeddable_hosts;+}diff --git a/frontend/discourse/admin/models/site-setting.js b/frontend/discourse/admin/models/site-setting.jsindex 657910b01da..942411273d3 100644--- a/frontend/discourse/admin/models/site-setting.js+++ b/frontend/discourse/admin/models/site-setting.js@@ -27,7 +27,7 @@ export default class SiteSetting extends EmberObject {if (!categories[s.category]) {categories[s.category] = [];}- categories[s.category].pushObject(SiteSetting.create(s));+ categories[s.category].push(SiteSetting.create(s));});return Object.keys(categories).map(function (n) {return {diff --git a/frontend/discourse/admin/models/theme.js b/frontend/discourse/admin/models/theme.jsindex 2a4ee4f7dbd..90474528e78 100644--- a/frontend/discourse/admin/models/theme.js+++ b/frontend/discourse/admin/models/theme.js@@ -4,7 +4,12 @@ import { isBlank, isEmpty } from "@ember/utils";import ThemeSettings from "discourse/admin/models/theme-settings";import ThemeSiteSettings from "discourse/admin/models/theme-site-settings";import { popupAjaxError } from "discourse/lib/ajax-error";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";import discourseComputed from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";import RestModel from "discourse/models/rest";import { i18n } from "discourse-i18n";@@ -34,6 +39,10 @@ class Theme extends RestModel {return json;}+ @trackedArray childThemes;+ @trackedArray parentThemes;+ @trackedArray theme_fields;+@or("default", "user_selectable") isActive;@gt("remote_theme.commits_behind", 0) isPendingUpdates;@gt("editedFields.length", 0) hasEditedFields;@@ -220,7 +229,7 @@ class Theme extends RestModel {existing.value = value;existing.upload_id = upload_id;} else {- fields.pushObject(field);+ fields.push(field);}return;}@@ -229,7 +238,7 @@ class Theme extends RestModel {let key = this.getKey({ target, name });let existingField = themeFields[key];if (!existingField) {- this.theme_fields.pushObject(field);+ this.theme_fields.push(field);themeFields[key] = field;} else {const changed =@@ -258,8 +267,7 @@ class Theme extends RestModel {}removeChildTheme(theme) {- const childThemes = this.childThemes;- childThemes.removeObject(theme);+ removeValueFromArray(this.childThemes, theme);return this.saveChanges("child_theme_ids");}@@ -269,8 +277,10 @@ class Theme extends RestModel {childThemes = [];this.set("childThemes", childThemes);}- childThemes.removeObject(theme);- childThemes.pushObject(theme);++ removeValueFromArray(childThemes, theme);+ childThemes.push(theme);+return this.saveChanges("child_theme_ids");}@@ -280,7 +290,8 @@ class Theme extends RestModel {parentThemes = [];this.set("parentThemes", parentThemes);}- parentThemes.addObject(theme);++ addUniqueValueToArray(parentThemes, theme);}checkForUpdates() {diff --git a/frontend/discourse/admin/routes/admin-config/color-palettes/index.js b/frontend/discourse/admin/routes/admin-config/color-palettes/index.jsindex 70d4a95161b..08be82cbefe 100644--- a/frontend/discourse/admin/routes/admin-config/color-palettes/index.js+++ b/frontend/discourse/admin/routes/admin-config/color-palettes/index.js@@ -1,11 +1,13 @@import Route from "@ember/routing/route";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import ColorScheme from "discourse/admin/models/color-scheme";import Theme from "discourse/admin/models/theme";import { ajax } from "discourse/lib/ajax";export default class AdminConfigColorPalettesIndexRoute extends Route {async model() {- return await ajax("/admin/config/colors");+ const value = await ajax("/admin/config/colors");+ return value;}setupController(controller, model) {@@ -15,7 +17,9 @@ export default class AdminConfigColorPalettesIndexRoute extends Route {: null;controller.set("model",- model.palettes.map((palette) => ColorScheme.create(palette))+ new TrackedArray(+ model.palettes.map((palette) => ColorScheme.create(palette))+ ));controller.set("defaultTheme", defaultTheme);diff --git a/frontend/discourse/admin/routes/admin-user/badges.js b/frontend/discourse/admin/routes/admin-user/badges.jsindex 6887bbfb466..235de0d2140 100644--- a/frontend/discourse/admin/routes/admin-user/badges.js+++ b/frontend/discourse/admin/routes/admin-user/badges.js@@ -1,3 +1,4 @@+import { TrackedArray } from "@ember-compat/tracked-built-ins";import Badge from "discourse/models/badge";import UserBadge from "discourse/models/user-badge";import DiscourseRoute from "discourse/routes/discourse";@@ -8,20 +9,22 @@ export default class AdminUserBadgesRoute extends DiscourseRoute {return UserBadge.findByUsername(username);}- setupController(controller) {- super.setupController(...arguments);+ async setupController(controller, model) {+ super.setupController(controller, new TrackedArray(model));// Find all badges.- controller.set("loading", true);- Badge.findAll().then(function (badges) {+ controller.loading = true;+ try {+ const badges = await Badge.findAll();controller.setProperties({ badges, expandedBadges: [] });if (badges.length > 0) {- let grantableBadges = controller.get("availableBadges");+ let grantableBadges = controller.availableBadges;if (grantableBadges.length > 0) {- controller.set("selectedBadgeId", grantableBadges[0].get("id"));+ controller.selectedBadgeId = grantableBadges[0].get("id");}}- controller.set("loading", false);- });+ } finally {+ controller.loading = false;+ }}}diff --git a/frontend/discourse/admin/routes/admin/backups.js b/frontend/discourse/admin/routes/admin/backups.jsindex bb4720dd7ac..46179d7afc0 100644--- a/frontend/discourse/admin/routes/admin/backups.js+++ b/frontend/discourse/admin/routes/admin/backups.js@@ -5,6 +5,7 @@ import Backup from "discourse/admin/models/backup";import BackupStatus from "discourse/admin/models/backup-status";import { ajax } from "discourse/lib/ajax";import { extractError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";import { bind } from "discourse/lib/decorators";import getURL from "discourse/lib/get-url";import PreloadStore from "discourse/lib/preload-store";@@ -73,7 +74,7 @@ export default class AdminBackupsRoute extends DiscourseRoute {} else {this.controllerFor("admin.backups.logs").get("logs")- .pushObject(EmberObject.create(log));+ .push(EmberObject.create(log));}}@@ -95,17 +96,13 @@ export default class AdminBackupsRoute extends DiscourseRoute {}@action- destroyBackup(backup) {+ async destroyBackup(backup) {return this.dialog.yesNoConfirm({message: i18n("admin.backups.operations.destroy.confirm"),- didConfirm: () => {- backup- .destroy()- .then(() =>- this.controllerFor("admin.backups.index")- .get("model")- .removeObject(backup)- );+ didConfirm: async () => {+ await backup.destroy();+ const list = this.controllerFor("admin.backups.index").get("model");+ removeValueFromArray(list, backup);},});}diff --git a/frontend/discourse/admin/routes/admin/backups/index.js b/frontend/discourse/admin/routes/admin/backups/index.jsindex a985418a5c5..2d901bac597 100644--- a/frontend/discourse/admin/routes/admin/backups/index.js+++ b/frontend/discourse/admin/routes/admin/backups/index.js@@ -1,4 +1,5 @@import Route from "@ember/routing/route";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import Backup from "discourse/admin/models/backup";import { bind } from "discourse/lib/decorators";@@ -13,7 +14,7 @@ export default class AdminBackupsIndexRoute extends Route {async model() {const backups = await Backup.find();- return backups.map((backup) => Backup.create(backup));+ return new TrackedArray(backups.map((backup) => Backup.create(backup)));}@binddiff --git a/frontend/discourse/admin/services/admin-emojis.js b/frontend/discourse/admin/services/admin-emojis.jsindex 8f46a983f96..1da82c073a1 100644--- a/frontend/discourse/admin/services/admin-emojis.js+++ b/frontend/discourse/admin/services/admin-emojis.js@@ -3,7 +3,11 @@ import EmberObject, { action } from "@ember/object";import Service, { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import {+ removeValueFromArray,+ uniqueItemsFromArray,+} from "discourse/lib/array-tools";+import { trackedArray } from "discourse/lib/tracked-tools";import { i18n } from "discourse-i18n";const ALL_FILTER = "all";@@ -12,10 +16,9 @@ const DEFAULT_GROUP = "default";export default class AdminEmojis extends Service {@service dialog;- @tracked emojis = [];-@tracked filter = ALL_FILTER;@tracked sorting = ["group", "name"];+ @trackedArray emojis = [];constructor() {super(...arguments);@@ -69,7 +72,7 @@ export default class AdminEmojis extends Service {await ajax("/admin/config/emoji/" + emoji.get("name"), {type: "DELETE",});- this.emojis.removeObject(emoji);+ removeValueFromArray(this.emojis, emoji);} catch (err) {popupAjaxError(err);}diff --git a/frontend/discourse/admin/services/admin-user-fields.js b/frontend/discourse/admin/services/admin-user-fields.jsindex 32a246dbd80..543fe789ca7 100644--- a/frontend/discourse/admin/services/admin-user-fields.js+++ b/frontend/discourse/admin/services/admin-user-fields.js@@ -1,12 +1,12 @@-import { tracked } from "@glimmer/tracking";import { sort } from "@ember/object/computed";import Service, { service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";+import { trackedArray } from "discourse/lib/tracked-tools";export default class AdminUserFields extends Service {@service store;- @tracked userFields = [];+ @trackedArray userFields = [];@sort("userFields", "fieldSortOrder") sortedUserFields;diff --git a/frontend/discourse/admin/templates/admin-permalinks/index.gjs b/frontend/discourse/admin/templates/admin-permalinks/index.gjsindex 6f566b2bdc1..56dabd073b2 100644--- a/frontend/discourse/admin/templates/admin-permalinks/index.gjs+++ b/frontend/discourse/admin/templates/admin-permalinks/index.gjs@@ -11,21 +11,21 @@ import icon from "discourse/helpers/d-icon";import { i18n } from "discourse-i18n";export default <template>- <ConditionalLoadingSpinner @condition={{@controller.loading}}>- {{#if @controller.hasPermalinks}}- <div class="d-admin-filter">- <div class="admin-filter__input-container permalink-search">- <TextField- @value={{@controller.filter}}- @placeholderKey="admin.permalink.form.filter"- @autocorrect="off"- @autocapitalize="off"- class="admin-filter__input"- />- </div>+ {{#if @controller.hasPermalinks}}+ <div class="d-admin-filter">+ <div class="admin-filter__input-container permalink-search">+ <TextField+ @value={{@controller.filter}}+ @placeholderKey="admin.permalink.form.filter"+ @autocorrect="off"+ @autocapitalize="off"+ class="admin-filter__input"+ /></div>- {{/if}}+ </div>+ {{/if}}+ <ConditionalLoadingSpinner @condition={{@controller.loading}}><div class="permalink-results">{{#if @controller.model.length}}<table class="d-table permalinks">diff --git a/frontend/discourse/app/components/bookmark-list.gjs b/frontend/discourse/app/components/bookmark-list.gjsindex 3c9591b9582..5588b3f3804 100644--- a/frontend/discourse/app/components/bookmark-list.gjs+++ b/frontend/discourse/app/components/bookmark-list.gjs@@ -25,6 +25,10 @@ import lazyHash from "discourse/helpers/lazy-hash";import replaceEmoji from "discourse/helpers/replace-emoji";import topicLink from "discourse/helpers/topic-link";import { ajax } from "discourse/lib/ajax";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";import { BookmarkFormData } from "discourse/lib/bookmark-form-data";import {openLinkInNewTab,@@ -153,14 +157,14 @@ export default class BookmarkList extends Component {}_removeBookmarkFromList(bookmark) {- this.content.removeObject(bookmark);+ removeValueFromArray(this.content, bookmark);}_toggleSelection(target, bookmark, isSelectingRange) {const selected = this.selected;if (target.checked) {- selected.addObject(bookmark);+ addUniqueValueToArray(selected, bookmark);if (isSelectingRange) {const bulkSelects = Array.from(@@ -180,7 +184,7 @@ export default class BookmarkList extends Component {}this.set("lastChecked", target);} else {- selected.removeObject(bookmark);+ removeValueFromArray(selected, bookmark);this.set("lastChecked", null);}}diff --git a/frontend/discourse/app/components/composer-messages.gjs b/frontend/discourse/app/components/composer-messages.gjsindex a15b6aeb16e..349fa4c9bab 100644--- a/frontend/discourse/app/components/composer-messages.gjs+++ b/frontend/discourse/app/components/composer-messages.gjs@@ -9,6 +9,10 @@ import { classNameBindings } from "@ember-decorators/component";import ComposerMessage from "discourse/components/composer-message";import ShareTopic from "discourse/components/modal/share-topic";import { ajax } from "discourse/lib/ajax";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";import { debounce } from "discourse/lib/decorators";import { INPUT_DELAY } from "discourse/lib/environment";import LinkLookup from "discourse/lib/link-lookup";@@ -21,9 +25,9 @@ let _messagesCache = {};export default class ComposerMessages extends Component {@tracked showShareModal;@trackedArray similarTopics = null;+ @trackedArray messages = null;checkedMessages = false;- messages = null;messagesByTemplate = null;queuedForTyping = null;usersNotSeen = null;@@ -60,12 +64,12 @@ export default class ComposerMessages extends Component {return;}- this.messages.popObject();+ this.messages.pop();this.set("messageCount", this.messages.length);}_removeMessage(message) {- this.messages.removeObject(message);+ removeValueFromArray(this.messages, message);this.set("messageCount", this.messages.length);}@@ -290,7 +294,7 @@ export default class ComposerMessages extends Component {messages.content.forEach((msg) => {if (msg.wait_for_typing) {- this.queuedForTyping.addObject(msg);+ addUniqueValueToArray(this.queuedForTyping, msg);} else {this.popup(msg);}@@ -318,7 +322,7 @@ export default class ComposerMessages extends Component {}if (!this.messagesByTemplate[message.templateName]) {- this.messages.pushObject(message);+ this.messages.push(message);this.set("messageCount", this.messages.length);this.messagesByTemplate[message.templateName] = message;}diff --git a/frontend/discourse/app/components/composer-user-selector.gjs b/frontend/discourse/app/components/composer-user-selector.gjsindex 2cac8a822f7..fbf41f06377 100644--- a/frontend/discourse/app/components/composer-user-selector.gjs+++ b/frontend/discourse/app/components/composer-user-selector.gjs@@ -25,19 +25,17 @@ export default class ComposerUserSelector extends Component {}_updateGroups(selected, newGroups) {- const groups = [];+ const groups = new Set();this._groups.forEach((existing) => {if (selected.includes(existing)) {- groups.addObject(existing);+ groups.add(existing);}});newGroups.forEach((newGroup) => {- if (!groups.includes(newGroup)) {- groups.addObject(newGroup);- }+ groups.add(newGroup);});this.setProperties({- _groups: groups,+ _groups: Array.from(groups),hasGroups: groups.length > 0,});}diff --git a/frontend/discourse/app/components/form-template-field/upload.gjs b/frontend/discourse/app/components/form-template-field/upload.gjsindex 26a16ab25d8..7b548ab88df 100644--- a/frontend/discourse/app/components/form-template-field/upload.gjs+++ b/frontend/discourse/app/components/form-template-field/upload.gjs@@ -7,15 +7,16 @@ import { htmlSafe } from "@ember/template";import PickFilesButton from "discourse/components/pick-files-button";import icon from "discourse/helpers/d-icon";import { bind } from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";import { isAudio, isImage, isVideo } from "discourse/lib/uploads";import UppyUpload from "discourse/lib/uppy/uppy-upload";export default class FormTemplateFieldUpload extends Component {@tracked uploadValue;- @tracked uploadedFiles = [];@tracked fileInputSelector = `#${this.fileUploadElementId}`;@trackedfileUploadElementId = `${dasherize(this.args.id.toString())}-uploader`;+ @trackedArray uploadedFiles = [];uppyUpload = new UppyUpload(getOwner(this), {id: this.args.id,@@ -62,7 +63,7 @@ export default class FormTemplateFieldUpload extends Component {this.uploadValue = "";}- this.uploadedFiles.pushObject(upload);+ this.uploadedFiles.push(upload);const uploadMarkdown = this.buildMarkdown(upload);if (this.uploadValue && this.uppyUpload.allowMultipleFiles) {diff --git a/frontend/discourse/app/components/ignored-user-list.gjs b/frontend/discourse/app/components/ignored-user-list.gjsindex 1177b5979a1..f38a9ba456e 100644--- a/frontend/discourse/app/components/ignored-user-list.gjs+++ b/frontend/discourse/app/components/ignored-user-list.gjs@@ -3,6 +3,10 @@ import { action } from "@ember/object";import { service } from "@ember/service";import DButton from "discourse/components/d-button";import { popupAjaxError } from "discourse/lib/ajax-error";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";import User from "discourse/models/user";import { i18n } from "discourse-i18n";import IgnoredUserListItem from "./ignored-user-list-item";@@ -13,7 +17,7 @@ export default class IgnoredUserList extends Component {@actionasync removeIgnoredUser(item) {- this.args.items.removeObject(item);+ removeValueFromArray(this.args.items, item);try {const user = await User.findByUsername(item);@@ -33,7 +37,7 @@ export default class IgnoredUserList extends Component {actingUser: this.args.model,ignoredUsername: null,onUserIgnored: (username) => {- this.args.items.addObject(username);+ addUniqueValueToArray(this.args.items, username);},},});diff --git a/frontend/discourse/app/components/invite-panel.gjs b/frontend/discourse/app/components/invite-panel.gjsindex 4b15e37d32c..49eb4130800 100644--- a/frontend/discourse/app/components/invite-panel.gjs+++ b/frontend/discourse/app/components/invite-panel.gjs@@ -362,7 +362,7 @@ export default class InvitePanel extends Component {.then((result) => {model.setProperties({ saving: false, finished: true });if (this.isPM && result && result.user) {- this.get("inviteModel.details.allowed_users").pushObject(+ this.get("inviteModel.details.allowed_users").push(EmberObject.create(result.user));this.toasts.success({diff --git a/frontend/discourse/app/components/modal/create-invite.gjs b/frontend/discourse/app/components/modal/create-invite.gjsindex 6d03b34bb4a..e3d6ba81ea3 100644--- a/frontend/discourse/app/components/modal/create-invite.gjs+++ b/frontend/discourse/app/components/modal/create-invite.gjs@@ -132,7 +132,7 @@ export default class CreateInvite extends Component {await this.invite.save(data);const invites = this.model?.invites;if (invites && !invites.some((i) => i.id === this.invite.id)) {- invites.unshiftObject(this.invite);+ invites.unshift(this.invite);}if (!this.simpleMode) {diff --git a/frontend/discourse/app/components/modal/grant-badge.gjs b/frontend/discourse/app/components/modal/grant-badge.gjsindex 7e1b69ce6cf..c207a2a645a 100644--- a/frontend/discourse/app/components/modal/grant-badge.gjs+++ b/frontend/discourse/app/components/modal/grant-badge.gjs@@ -12,6 +12,7 @@ import {grantableBadges,isBadgeGrantable,} from "discourse/lib/grant-badge-utils";+import { trackedArray } from "discourse/lib/tracked-tools";import Badge from "discourse/models/badge";import UserBadge from "discourse/models/user-badge";import ComboBox from "discourse/select-kit/components/combo-box";@@ -24,8 +25,8 @@ export default class GrantBadgeModal extends Component {@tracked flash = null;@tracked flashType = null;@tracked allBadges = [];- @tracked userBadges = [];@tracked availableBadges = [];+ @trackedArray userBadges = [];get noAvailableBadges() {!this.availableBadges.length;@@ -71,7 +72,7 @@ export default class GrantBadgeModal extends Component {username,getURL(this.post.url));- this.userBadges.pushObject(newBadge);+ this.userBadges.push(newBadge);this.#updateAvailableBadges();this.selectedBadgeId = null;this.flash = i18n("badges.successfully_granted", {diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjsindex 1932cd63747..5d290bfae79 100644--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs@@ -1,6 +1,5 @@/* eslint-disable ember/no-classic-components */import { cached, tracked } from "@glimmer/tracking";-import { A } from "@ember/array";import Component, { Input } from "@ember/component";import { fn } from "@ember/helper";import { on } from "@ember/modifier";@@ -15,16 +14,18 @@ import icon from "discourse/helpers/d-icon";import withEventValue from "discourse/helpers/with-event-value";import { ajax } from "discourse/lib/ajax";import { extractError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";import { SIDEBAR_SECTION, SIDEBAR_URL } from "discourse/lib/constants";import { afterRender, bind } from "discourse/lib/decorators";import { sanitize } from "discourse/lib/text";+import { trackedArray } from "discourse/lib/tracked-tools";import { and, not } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";class Section {@tracked title;- @tracked links;- @tracked secondaryLinks;+ @trackedArray links;+ @trackedArray secondaryLinks;constructor({title,@@ -241,26 +242,26 @@ export default class SidebarSectionForm extends Component {acc.push(this.initLink(link));}return acc;- }, A()),+ }, []),secondaryLinks: section.links.reduce((acc, link) => {if (link.segment === "secondary") {this.nextObjectId++;acc.push(this.initLink(link));}return acc;- }, A()),+ }, []),id: section.id,hideTitleInput: this.model.hideSectionHeader,});} else {return new Section({- links: A([+ links: [new SectionLink({router: this.router,objectId: this.nextObjectId,segment: "primary",}),- ]),+ ],});}}@@ -406,28 +407,16 @@ export default class SidebarSectionForm extends Component {return;}- if (this.draggedLink.isPrimary) {- this.transformedModel.links.removeObject(this.draggedLink);- } else {- this.transformedModel.secondaryLinks?.removeObject(this.draggedLink);- }+ const links = this.draggedLink.isPrimary+ ? this.transformedModel.links+ : this.transformedModel.secondaryLinks;- if (targetLink.isPrimary) {- const toPosition = this.transformedModel.links.indexOf(targetLink);- this.draggedLink.segment = "primary";- this.transformedModel.links.insertAt(- above ? toPosition : toPosition + 1,- this.draggedLink- );- } else {- this.draggedLink.segment = "secondary";- const toPosition =- this.transformedModel.secondaryLinks.indexOf(targetLink);- this.transformedModel.secondaryLinks.insertAt(- above ? toPosition : toPosition + 1,- this.draggedLink- );- }+ removeValueFromArray(links, this.draggedLink);++ const toPosition = links.indexOf(targetLink);+ this.draggedLink.segment = targetLink.isPrimary ? "primary" : "secondary";++ links.splice(above ? toPosition : toPosition + 1, 0, this.draggedLink);}get canDelete() {@@ -439,18 +428,18 @@ export default class SidebarSectionForm extends Component {if (link.id) {link._destroy = "1";} else {- if (link.isPrimary) {- this.transformedModel.links.removeObject(link);- } else {- this.transformedModel.secondaryLinks.removeObject(link);- }+ const links = link.isPrimary+ ? this.transformedModel.links+ : this.transformedModel.secondaryLinks;++ removeValueFromArray(links, link);}}@actionaddLink() {this.nextObjectId = this.nextObjectId + 1;- this.transformedModel.links.pushObject(+ this.transformedModel.links.push(new SectionLink({router: this.router,objectId: this.nextObjectId,@@ -464,7 +453,7 @@ export default class SidebarSectionForm extends Component {@actionaddSecondaryLink() {this.nextObjectId = this.nextObjectId + 1;- this.transformedModel.secondaryLinks.pushObject(+ this.transformedModel.secondaryLinks.push(new SectionLink({router: this.router,objectId: this.nextObjectId,@@ -484,10 +473,8 @@ export default class SidebarSectionForm extends Component {type: "PUT",}).then((data) => {- this.currentUser.sidebar_sections.shiftObject();- this.currentUser.sidebar_sections.unshiftObject(- data["sidebar_section"]- );+ this.currentUser.sidebar_sections.shift();+ this.currentUser.sidebar_sections.unshift(data["sidebar_section"]);this.closeModal();}).catch((e) => {diff --git a/frontend/discourse/app/components/tag-info.gjs b/frontend/discourse/app/components/tag-info.gjsindex d4fa8df9bce..e37e2962ad4 100644--- a/frontend/discourse/app/components/tag-info.gjs+++ b/frontend/discourse/app/components/tag-info.gjs@@ -7,6 +7,7 @@ import { and, reads } from "@ember/object/computed";import { service } from "@ember/service";import { htmlSafe } from "@ember/template";import { isEmpty } from "@ember/utils";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import { tagName } from "@ember-decorators/component";import DButton from "discourse/components/d-button";import PluginOutlet from "discourse/components/plugin-outlet";@@ -19,6 +20,7 @@ import lazyHash from "discourse/helpers/lazy-hash";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";@@ -93,7 +95,9 @@ export default class TagInfo extends Component {this.set("tagInfo", result);this.set("tagInfo.synonyms",- result.synonyms.map((s) => this.store.createRecord("tag", s))+ new TrackedArray(+ result.synonyms.map((s) => this.store.createRecord("tag", s))+ ));}).finally(() => this.set("loading", false))@@ -120,7 +124,7 @@ export default class TagInfo extends Component {ajax(`/tag/${this.tagInfo.name}/synonyms/${tag.id}`, {type: "DELETE",})- .then(() => this.tagInfo.synonyms.removeObject(tag))+ .then(() => removeValueFromArray(this.tagInfo.synonyms, tag)).catch(popupAjaxError);}@@ -135,7 +139,7 @@ export default class TagInfo extends Component {didConfirm: () => {return tag.destroyRecord()- .then(() => this.tagInfo.synonyms.removeObject(tag))+ .then(() => removeValueFromArray(this.tagInfo.synonyms, tag)).catch(popupAjaxError);},});diff --git a/frontend/discourse/app/components/topic-list/item.gjs b/frontend/discourse/app/components/topic-list/item.gjsindex cb65964df6f..d3c15df1602 100644--- a/frontend/discourse/app/components/topic-list/item.gjs+++ b/frontend/discourse/app/components/topic-list/item.gjs@@ -19,6 +19,10 @@ import discourseTags from "discourse/helpers/discourse-tags";import formatDate from "discourse/helpers/format-date";import lazyHash from "discourse/helpers/lazy-hash";import topicFeaturedLink from "discourse/helpers/topic-featured-link";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";import { wantsNewWindow } from "discourse/lib/intercept-click";import {applyBehaviorTransformer,@@ -127,13 +131,13 @@ export default class Item extends Component {}unselectTopic(topicNode) {- this.args.selected.removeObject(this.args.topic);+ removeValueFromArray(this.args.selected, this.args.topic);this.args.bulkSelectHelper.lastCheckedElementId = null;topicNode.classList.remove("bulk-selected");}selectTopic(topicNode, shiftKey) {- this.args.selected.addObject(this.args.topic);+ addUniqueValueToArray(this.args.selected, this.args.topic);if (this.args.bulkSelectHelper.lastCheckedElementId && shiftKey) {const topics = Array.from(topicNode.parentNode.children);diff --git a/frontend/discourse/app/components/track-selected.gjs b/frontend/discourse/app/components/track-selected.gjsindex ca67b9828e3..38bc97a7548 100644--- a/frontend/discourse/app/components/track-selected.gjs+++ b/frontend/discourse/app/components/track-selected.gjs@@ -1,14 +1,18 @@import Component from "@glimmer/component";import { on } from "@ember/modifier";import { action } from "@ember/object";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";export default class TrackSelected extends Component {@actiononToggle(e) {if (e.target.checked) {- this.args.selectedList.addObject(this.args.selectedId);+ addUniqueValueToArray(this.args.selectedList, this.args.selectedId);} else {- this.args.selectedList.removeObject(this.args.selectedId);+ removeValueFromArray(this.args.selectedList, this.args.selectedId);}}diff --git a/frontend/discourse/app/components/user-menu/menu.gjs b/frontend/discourse/app/components/user-menu/menu.gjsindex 8ae5794f466..0ede9aced24 100644--- a/frontend/discourse/app/components/user-menu/menu.gjs+++ b/frontend/discourse/app/components/user-menu/menu.gjs@@ -248,7 +248,7 @@ export default class UserMenu extends Component {if (reviewQueueTabIndex === -1) {tabs.push(tab);} else {- tabs.insertAt(reviewQueueTabIndex, tab);+ tabs.splice(reviewQueueTabIndex, 0, tab);reviewQueueTabIndex++;}}diff --git a/frontend/discourse/app/components/user-notification-schedule.gjs b/frontend/discourse/app/components/user-notification-schedule.gjsindex 6f41ee60e3b..007c9007c36 100644--- a/frontend/discourse/app/components/user-notification-schedule.gjs+++ b/frontend/discourse/app/components/user-notification-schedule.gjs@@ -91,19 +91,17 @@ export default class UserNotificationSchedule extends Component {}));- this.set("days", []);-- DAYS.forEach((day, index) => {- this.days.pushObject(- Day.create({- id: index,- day,- model: this.model,- buildTimeOptions: this.buildTimeOptions,- startTimeOptions: this.startTimeOptions,- })- );- });+ const days = DAYS.map((day, index) =>+ Day.create({+ id: index,+ day,+ model: this.model,+ buildTimeOptions: this.buildTimeOptions,+ startTimeOptions: this.startTimeOptions,+ })+ );++ this.set("days", days);}buildTimeOptions(startAt, opts = { includeNone: false, showMidnight: true }) {diff --git a/frontend/discourse/app/controllers/group/index.js b/frontend/discourse/app/controllers/group/index.jsindex c1344d63105..142857bffcb 100644--- a/frontend/discourse/app/controllers/group/index.js+++ b/frontend/discourse/app/controllers/group/index.js@@ -3,9 +3,13 @@ import { action } from "@ember/object";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 discourseComputed, { debounce } from "discourse/lib/decorators";+import { trackedArray } from "discourse/lib/tracked-tools";export default class GroupIndexController extends Controller {+ @trackedArray bulkSelection = null;+queryParams = ["order", "asc", "filter"];order = null;asc = true;@@ -14,7 +18,6 @@ export default class GroupIndexController extends Controller {loading = false;isBulk = false;showActions = false;- bulkSelection = null;get hasMembers() {return this.model.members?.length > 0;@@ -235,9 +238,9 @@ export default class GroupIndexController extends Controller {this.set("bulkSelection", this.bulkSelection || []);if (e.target.checked) {- this.bulkSelection.pushObject(member);+ this.bulkSelection.push(member);} else {- this.bulkSelection.removeObject(member);+ removeValueFromArray(this.bulkSelection, member);}}diff --git a/frontend/discourse/app/controllers/group/manage/logs.js b/frontend/discourse/app/controllers/group/manage/logs.jsindex 3b74fabc96b..e4f79262f73 100644--- a/frontend/discourse/app/controllers/group/manage/logs.js+++ b/frontend/discourse/app/controllers/group/manage/logs.js@@ -1,6 +1,7 @@import Controller, { inject as controller } from "@ember/controller";import EmberObject, { action } 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 {@@ -59,7 +60,7 @@ export default class GroupManageLogsController extends Controller {.findLogs(this.offset + 1, this.filterParams).then((results) => {results.logs.forEach((result) =>- this.get("model.logs").addObject(result)+ addUniqueValueToArray(this.get("model.logs"), result));this.incrementProperty("offset");this.set("model.all_loaded", results.all_loaded);diff --git a/frontend/discourse/app/controllers/invites/show.js b/frontend/discourse/app/controllers/invites/show.jsindex 206d64df41b..3aa138c3fa0 100644--- a/frontend/discourse/app/controllers/invites/show.js+++ b/frontend/discourse/app/controllers/invites/show.js@@ -10,6 +10,7 @@ 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";+import { trackedArray } from "discourse/lib/tracked-tools";import DiscourseURL from "discourse/lib/url";import UserFieldsValidationHelper from "discourse/lib/user-fields-validation-helper";import UsernameValidationHelper from "discourse/lib/username-validation-helper";@@ -21,6 +22,8 @@ export default class InvitesShowController extends Controller {@tracked accountPassword;@tracked accountUsername;@tracked isDeveloper;+ @trackedArray rejectedEmails = [];+queryParams = ["t"];nameValidationHelper = new NameValidationHelper(this);usernameValidationHelper = new UsernameValidationHelper({@@ -58,7 +61,6 @@ export default class InvitesShowController extends Controller {@not("externalAuthsOnly") passwordRequired;errorMessage = null;authOptions = null;- rejectedEmails = [];maskPassword = true;get userFields() {@@ -393,7 +395,7 @@ export default class InvitesShowController extends Controller {result.errors.email.length > 0 &&result.values) {- this.rejectedEmails.pushObject(result.values.email);+ this.rejectedEmails.push(result.values.email);}if (result.errors?.["user_password.password"]?.length > 0) {this.passwordValidationHelper.rejectedPasswords.push(diff --git a/frontend/discourse/app/controllers/preferences/account.js b/frontend/discourse/app/controllers/preferences/account.jsindex fc45021fee2..a0c331f102d 100644--- a/frontend/discourse/app/controllers/preferences/account.js+++ b/frontend/discourse/app/controllers/preferences/account.js@@ -5,6 +5,7 @@ import { next } from "@ember/runloop";import { service } from "@ember/service";import UserStatusModal from "discourse/components/modal/user-status";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";@@ -80,17 +81,17 @@ export default class AccountController extends Controller {);}- @discourseComputed("model.associated_accounts")- associatedAccountsLoaded(associatedAccounts) {- return typeof associatedAccounts !== "undefined";+ get associatedAccountsLoaded() {+ return typeof this.model.associated_accounts !== "undefined";}- @discourseComputed("model.associated_accounts.[]")- authProviders(accounts) {+ get authProviders() {return findAll().map((method) => ({method,- account: accounts.find(({ name }) => name === method.name),+ account: this.model.associated_accounts.find(+ ({ name }) => name === method.name+ ),})).filter((value) => value.account || value.method.can_connect);}@@ -251,7 +252,7 @@ export default class AccountController extends Controller {.revokeAssociatedAccount(account.name).then((result) => {if (result.success) {- this.model.associated_accounts.removeObject(account);+ removeValueFromArray(this.model.associated_accounts, account);} else {this.dialog.alert(result.message);}diff --git a/frontend/discourse/app/controllers/preferences/security.js b/frontend/discourse/app/controllers/preferences/security.jsindex 60e50de52a1..aa9a7e88623 100644--- a/frontend/discourse/app/controllers/preferences/security.js+++ b/frontend/discourse/app/controllers/preferences/security.js@@ -2,7 +2,6 @@ import Controller from "@ember/controller";import { action, computed } from "@ember/object";import { gt } from "@ember/object/computed";import { service } from "@ember/service";-import typeOf from "@ember/utils/lib/type-of";import ConfirmSession from "discourse/components/dialog-messages/confirm-session";import AuthTokenModal from "discourse/components/modal/auth-token";import { ajax } from "discourse/lib/ajax";@@ -150,9 +149,8 @@ export default class SecurityController extends Controller {);}- @discourseComputed("model.associated_accounts")- associatedAccountsLoaded(associatedAccounts) {- return typeOf(associatedAccounts) !== "undefined";+ get associatedAccountsLoaded() {+ return typeof this.model.associated_accounts !== "undefined";}removePasswordConfirm() {diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.jsindex 0729e698ba3..01590c0aac3 100644--- a/frontend/discourse/app/controllers/topic.js+++ b/frontend/discourse/app/controllers/topic.js@@ -19,7 +19,11 @@ import { MIN_POSTS_COUNT } from "discourse/components/topic-map/topic-map-summarimport { spinnerHTML } from "discourse/helpers/loading-spinner";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import {+ addUniqueValueToArray,+ removeValueFromArray,+ uniqueItemsFromArray,+} 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";@@ -78,6 +82,7 @@ export default class TopicController extends Controller {@tracked multiSelect = false;@tracked hasScrolled = null;+ @trackedArray bookmarks = [];@trackedArray selectedPostIds = [];queryParams = ["filter", "username_filters", "replies_to_post_number"];@@ -88,7 +93,6 @@ export default class TopicController extends Controller {@or("model.errorHtml", "model.errorMessage") hasError;@not("hasError") noErrorYet;@alias("site.categoriesList") categories;- @alias("selectedPostIds.length") selectedPostsCount;@alias("selectedAllPosts") canDeselectAll;@or("model.postStream.loadedAllPosts", "model.postStream.loadingLastPost")loadedAllPosts;@@ -132,6 +136,11 @@ export default class TopicController extends Controller {});}+ @dependentKeyCompat+ get selectedPostsCount() {+ return this.selectedPostIds.length;+ }+get titleIsVisibleOnHeader() {return !this.header.mainTopicTitleVisible;}@@ -341,7 +350,7 @@ export default class TopicController extends Controller {),}).then((result) => {- result.post_ids.pushObject(post.get("id"));+ result.post_ids.push(post.get("id"));this._updateSelectedPostIds(result.post_ids);}).finally(() => {@@ -469,7 +478,7 @@ export default class TopicController extends Controller {deletePending(pending) {return ajax(`/review/${pending.id}`, { type: "DELETE" }).then(() => {- this.get("model.pending_posts").removeObject(pending);+ removeValueFromArray(this.model.pending_posts, pending);}).catch(popupAjaxError);}@@ -1096,9 +1105,12 @@ export default class TopicController extends Controller {@actiontogglePostSelection(post) {const selected = this.selectedPostIds;- selected.includes(post.id)- ? selected.removeObject(post.id)- : selected.addObject(post.id);++ if (selected.includes(post.id)) {+ removeValueFromArray(selected, post.id);+ } else {+ addUniqueValueToArray(selected, post.id);+ }}@action@@ -1534,7 +1546,7 @@ export default class TopicController extends Controller {const bookmark = this.model.bookmarks.find((b) => b.id === data.id);if (!bookmark) {- this.model.bookmarks.pushObject(Bookmark.create(data));+ this.model.bookmarks.push(Bookmark.create(data));} else {bookmark.reminder_at = data.reminder_at;bookmark.name = data.name;@@ -1628,22 +1640,12 @@ export default class TopicController extends Controller {: undefined;}- @discourseComputed(- "selectedPostsCount",- "model.postStream.isMegaTopic",- "model.postStream.stream.length",- "model.posts_count"- )- selectedAllPosts(- selectedPostsCount,- isMegaTopic,- postsCount,- topicPostsCount- ) {- if (isMegaTopic) {- return selectedPostsCount >= topicPostsCount;+ @dependentKeyCompat+ get selectedAllPosts() {+ if (this.model.postStream.isMegaTopic) {+ return this.selectedPostsCount >= this.model.posts_count;} else {- return selectedPostsCount >= postsCount;+ return this.selectedPostsCount >= this.model.postStream.stream.length;}}diff --git a/frontend/discourse/app/controllers/user-invited/show.js b/frontend/discourse/app/controllers/user-invited/show.jsindex e0d862eb87a..d607d78d397 100644--- a/frontend/discourse/app/controllers/user-invited/show.js+++ b/frontend/discourse/app/controllers/user-invited/show.js@@ -7,6 +7,7 @@ import { observes } from "@ember-decorators/object";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 { INPUT_DELAY } from "discourse/lib/environment";import Invite from "discourse/models/invite";@@ -83,7 +84,7 @@ export default class UserInvitedShowController extends Controller {async destroyInvite(invite) {try {await invite.destroy();- this.model.invites.removeObject(invite);+ removeValueFromArray(this.model.invites, invite);} catch (error) {popupAjaxError(error);}diff --git a/frontend/discourse/app/deprecation-workflow.js b/frontend/discourse/app/deprecation-workflow.jsindex e25c3694305..08cb3028a08 100644--- a/frontend/discourse/app/deprecation-workflow.js+++ b/frontend/discourse/app/deprecation-workflow.js@@ -259,93 +259,7 @@ const DeprecationWorkflow = new DiscourseDeprecationWorkflow([},{handler: "log",- matchId: "discourse.native-array-extensions.[]",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.addObjects",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.any",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.clear",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.compact",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.filterBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.findBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.get",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.isAny",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.mapBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.pushObjects",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.reject",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.rejectBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.replace",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.set",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.sortBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.toArray",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.uniq",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.uniqBy",- },- {- handler: "log",- matchId: "discourse.native-array-extensions.without",- },- {- handler: ["silence", "counter"],- matchId: /^discourse\.native-array-extensions\..+$/,- env: ["test"],- },- {- handler: "silence",matchId: /^discourse\.native-array-extensions\..+$/,- env: ["development", "production"],},]);diff --git a/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js b/frontend/discourse/app/instance-initializers/subscribe-user-notifications.jsindex dbc90cef69d..012acb13aca 100644--- a/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js+++ b/frontend/discourse/app/instance-initializers/subscribe-user-notifications.js@@ -196,8 +196,9 @@ class SubscribeUserNotificationsInit {}}- oldNotifications.insertAt(+ oldNotifications.splice(insertPosition,+ 0,Notification.create(lastNotification));}diff --git a/frontend/discourse/app/lib/array-tools.js b/frontend/discourse/app/lib/array-tools.jsindex 637b4322956..9181b86c8ea 100644--- a/frontend/discourse/app/lib/array-tools.js+++ b/frontend/discourse/app/lib/array-tools.js@@ -6,10 +6,24 @@ import { TrackedArray } from "@ember-compat/tracked-built-ins";** @param {Array} target - The array to check and add the value to.* @param {*} value - The value to add to the array if it doesn't already exist.+ * @param {Function} [selector] - Optional function used to transform each value for uniqueness comparison.+ * If undefined, strict equality comparison will be used.* @return {Array} The updated array containing the value if it was not already present.+ * @example+ * // Using simple value comparison+ * addUniqueValueToArray([1, 2], 3) // returns [1, 2, 3]+ * addUniqueValueToArray([1, 2], 2) // returns [1, 2]+ *+ * // Using selector function+ * const arr = [{id: 1}, {id: 2}];+ * addUniqueValueToArray(arr, {id: 3}, (item) => item.id) // adds object with id 3*/-export function addUniqueValueToArray(target, value) {- if (!target.includes(value)) {+export function addUniqueValueToArray(target, value, selector) {+ const uniqByValue = selector && selector(value);+ const exists = selector+ ? target.some((item) => selector(item) === uniqByValue)+ : target.includes(value);+ if (!exists) {target.push(value);}@@ -20,11 +34,14 @@ export function addUniqueValueToArray(target, value) {* Adds multiple values to the specified array only if they do not already exist in the array.* This function iterates through the provided values and ensures each value is checked and added individually.*- * @param {Array} target The array to which values will be added if they do not already exist.- * @param {Array} values The array of values to check and add to the target array if they are not present.+ * @param {Array} target - The array to which values will be added if they do not already exist.+ * @param {Array} values - The array of values to check and add to the target array if they are not present.+ * @param {Function} [selector] - Optional function used to transform each value for uniqueness comparison.+ * If undefined, strict equality comparison will be used.+ * @throws {TypeError} When target or values parameters are not arrays.* @return {void} This function does not return a value; it directly modifies the input array.*/-export function addUniqueValuesToArray(target, values) {+export function addUniqueValuesToArray(target, values, selector) {if (!Array.isArray(target)) {throw new TypeError("addUniqueValuesToArray: 'target' must be an array");}@@ -33,7 +50,7 @@ export function addUniqueValuesToArray(target, values) {}for (const value of values) {- addUniqueValueToArray(target, value);+ addUniqueValueToArray(target, value, selector);}}diff --git a/frontend/discourse/app/lib/legacy-array-like-object.js b/frontend/discourse/app/lib/legacy-array-like-object.jsindex 28b490f82a0..13e746981fa 100644--- a/frontend/discourse/app/lib/legacy-array-like-object.js+++ b/frontend/discourse/app/lib/legacy-array-like-object.js@@ -54,6 +54,8 @@ const ARRAY_PROPERTIES = new Set();/**+ * @deprecated+ ** LegacyArrayLikeObject is an EmberObject that proxies array-like behavior to a TrackedArray,* while exposing additional properties and methods. Access array methods via `.content`.*diff --git a/frontend/discourse/app/lib/post-bookmark-manager.js b/frontend/discourse/app/lib/post-bookmark-manager.jsindex 057666952eb..86c8c1b5893 100644--- a/frontend/discourse/app/lib/post-bookmark-manager.js+++ b/frontend/discourse/app/lib/post-bookmark-manager.js@@ -71,14 +71,14 @@ export default class PostBookmarkManager {_syncBookmarks(data) {if (!this.topicController.bookmarks) {- this.topicController.set("bookmarks", []);+ this.topicController.bookmarks = [];}const bookmark = this.topicController.bookmarks.find((b) => b.id === data.id);if (!bookmark) {- this.topicController.bookmarks.pushObject(Bookmark.create(data));+ this.topicController.bookmarks.push(Bookmark.create(data));} else {bookmark.reminder_at = data.reminder_at;bookmark.name = data.name;diff --git a/frontend/discourse/app/lib/search.js b/frontend/discourse/app/lib/search.jsindex 9a32e083dc6..30b8dc71f24 100644--- a/frontend/discourse/app/lib/search.js+++ b/frontend/discourse/app/lib/search.js@@ -274,10 +274,10 @@ export function updateRecentSearches(currentUser, term) {if (recentSearches.includes(term)) {recentSearches = recentSearches.filter((item) => item !== term);} else if (recentSearches.length === MAX_RECENT_SEARCHES) {- recentSearches.popObject();+ recentSearches.pop();}- recentSearches.unshiftObject(term);+ recentSearches.unshift(term);currentUser.set("recent_searches", recentSearches);}diff --git a/frontend/discourse/app/lib/sidebar/section.js b/frontend/discourse/app/lib/sidebar/section.jsindex 87444732c2a..163d8b51f22 100644--- a/frontend/discourse/app/lib/sidebar/section.js+++ b/frontend/discourse/app/lib/sidebar/section.js@@ -6,6 +6,7 @@ import SidebarSectionForm from "discourse/components/modal/sidebar-section-form"import { ajax } from "discourse/lib/ajax";import { bind } from "discourse/lib/decorators";import SectionLink from "discourse/lib/sidebar/section-link";+import { trackedArray } from "discourse/lib/tracked-tools";import { unicodeSlugify } from "discourse/lib/utilities";import { i18n } from "discourse-i18n";@@ -15,7 +16,7 @@ export default class Section {@service router;@tracked dragCss;- @tracked links;+ @trackedArray links;constructor({ section, owner }) {setOwner(this, owner);@@ -69,16 +70,16 @@ export default class Section {@bindmoveLinkDown(link) {- const position = this.links.indexOf(link) + 1;- this.links = this.links.removeObject(link);- this.links.splice(position, 0, link);+ const position = this.links.indexOf(link);+ this.links.splice(position, 1);+ this.links.splice(position + 1, 0, link);}@bindmoveLinkUp(link) {- const position = this.links.indexOf(link) - 1;- this.links = this.links.removeObject(link);- this.links.splice(position, 0, link);+ const position = this.links.indexOf(link);+ this.links.splice(position, 1);+ this.links.splice(position - 1, 0, link);}@binddiff --git a/frontend/discourse/app/lib/topic-bookmark-manager.js b/frontend/discourse/app/lib/topic-bookmark-manager.jsindex c3862dc35f5..decb56af467 100644--- a/frontend/discourse/app/lib/topic-bookmark-manager.js+++ b/frontend/discourse/app/lib/topic-bookmark-manager.js@@ -80,7 +80,7 @@ export default class TopicBookmarkManager {(b) => b.id === data.id);if (!bookmark) {- this.topicController.bookmarks.pushObject(Bookmark.create(data));+ this.topicController.bookmarks.push(Bookmark.create(data));} else {bookmark.reminder_at = data.reminder_at;bookmark.name = data.name;diff --git a/frontend/discourse/app/lib/tracked-tools.js b/frontend/discourse/app/lib/tracked-tools.jsindex ecd451aa080..cb5191b6c85 100644--- a/frontend/discourse/app/lib/tracked-tools.js+++ b/frontend/discourse/app/lib/tracked-tools.js@@ -1,4 +1,6 @@import { tracked } from "@glimmer/tracking";+import { meta as metaFor } from "@ember/-internals/meta";+import { TrackedDescriptor } from "@ember/-internals/metal";import { next } from "@ember/runloop";import { TrackedArray, TrackedSet } from "@ember-compat/tracked-built-ins";@@ -178,15 +180,16 @@ export class DeferredTrackedSet {}/**- * Converts a value to TrackedArray if needed and validates the type+ * Converts a value to TrackedArray if needed and validates the type.*- * @param {*} value - Value to convert- * @returns {TrackedArray|null} Converted value- * @throws {Error} If value is not an array, TrackedArray, or null+ * @param {TrackedArray|Array|null|undefined} value - Value to convert+ * @returns {TrackedArray|null|undefined} - Returns the value converted to TrackedArray if needed,+ * or null/undefined if those values were passed+ * @throws {Error} If value is not an array, TrackedArray, null or undefined*/function ensureTrackedArray(value) {- if (value === null) {- return null;+ if (typeof value === "undefined" || value === null) {+ return value;}if (value instanceof TrackedArray) {@@ -197,7 +200,9 @@ function ensureTrackedArray(value) {return new TrackedArray(value);}- throw new Error(`Expected an array or TrackedArray, got ${typeof value}`);+ throw new Error(+ `Expected an array, TrackedArray, null, or undefined, got ${typeof value}. Value received: ${value}`+ );}/**@@ -227,16 +232,29 @@ export function trackedArray(target, key, desc) {...desc,enumerable: true,configurable: true,+ isTracked: true,});+ function trackedArraySetter(value) {+ set.call(this, ensureTrackedArray(value));+ }++ // When using EmberObject.create(...), Ember accesses the tracked properties directly+ // through internal references, bypassing the getter/setter defined in this decorator.+ // To work around this, we are using Ember lower level APIs to override the stored references.+ // https://github.com/emberjs/ember.js/blob/d4f7c5c4075bc5b04736e0e965468bdbe6da135c/packages/%40ember/-internals/metal/lib/tracked.ts#L185+ metaFor(target).writeDescriptors(+ key,+ new TrackedDescriptor(get, trackedArraySetter)+ );+return {get() {return get.call(this);},- set(value) {- set.call(this, ensureTrackedArray(value));- },+ set: trackedArraySetter,enumerable: true,configurable: true,+ isTracked: true,};}diff --git a/frontend/discourse/app/lib/uppy/composer-upload.js b/frontend/discourse/app/lib/uppy/composer-upload.jsindex c7b4c9301c9..1e4b998a05c 100644--- a/frontend/discourse/app/lib/uppy/composer-upload.js+++ b/frontend/discourse/app/lib/uppy/composer-upload.js@@ -329,7 +329,7 @@ export default class UppyComposerUpload {// The inProgressUploads is meant to be used to display these uploads// in a UI, and Ember will only update the array in the UI if pushObject// is used to notify it.- this.#inProgressUploads.pushObject(+ this.#inProgressUploads.push(EmberObject.create({fileName: file.name,id: file.id,diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.jsindex 825edfba764..f6ba3a97578 100644--- a/frontend/discourse/app/models/category.js+++ b/frontend/discourse/app/models/category.js@@ -1,14 +1,21 @@import { tracked } from "@glimmer/tracking";import { warn } from "@ember/debug";import { computed, get } from "@ember/object";+import { dependentKeyCompat } from "@ember/object/compat";import { service } from "@ember/service";import { compare } from "@ember/utils";+import { TrackedObject } from "@ember-compat/tracked-built-ins";import { ajax } from "discourse/lib/ajax";+import {+ addUniqueValueToArray,+ removeValueFromArray,+} from "discourse/lib/array-tools";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";import { NotificationLevels } from "discourse/lib/notification-levels";+import { trackedArray } from "discourse/lib/tracked-tools";import { applyValueTransformer } from "discourse/lib/transformer";import PermissionType from "discourse/models/permission-type";import RestModel from "discourse/models/rest";@@ -468,11 +475,14 @@ export default class Category extends RestModel {@service currentUser;@tracked color;- @tracked styleType = this.style_type;@tracked emoji;@tracked icon;@tracked localizations = this.category_localizations;- permissions = null;+ @tracked minimum_required_tags;+ @tracked styleType = this.style_type;+ @trackedArray available_groups;+ @trackedArray permissions;+ @trackedArray required_tag_groups;init() {super.init(...arguments);@@ -484,19 +494,19 @@ export default class Category extends RestModel {return;}- this.set("availableGroups", this.available_groups);-if (this.group_permissions) {- this.set(- "permissions",- this.group_permissions.map((elem) => {- this.available_groups.removeObject(elem.group_name);- return elem;- })- );+ this.permissions = this.group_permissions.map((elem) => {+ removeValueFromArray(this.available_groups, elem.group_name);+ return new TrackedObject(elem);+ });}}+ @dependentKeyCompat+ get availableGroups() {+ return this.available_groups;+ }+get descriptionText() {return applyValueTransformer("category-description-text",@@ -553,8 +563,8 @@ export default class Category extends RestModel {});}- @discourseComputed("required_tag_groups", "minimum_required_tags")- minimumRequiredTags() {+ @dependentKeyCompat+ get minimumRequiredTags() {if (this.required_tag_groups?.length > 0) {// it should require the max between the bare minimum set in the category and the sum of the min_count of the// required_tag_groups@@ -843,24 +853,25 @@ export default class Category extends RestModel {}addPermission(permission) {- this.permissions.addObject(permission);- this.availableGroups.removeObject(permission.group_name);+ addUniqueValueToArray(this.permissions, new TrackedObject(permission));+ removeValueFromArray(this.available_groups, permission.group_name);}removePermission(group_name) {const permission = this.permissions.find((p) => p.group_name === group_name);+if (permission) {- this.permissions.removeObject(permission);- this.availableGroups.addObject(group_name);+ removeValueFromArray(this.permissions, permission);+ addUniqueValueToArray(this.available_groups, group_name);}}updatePermission(group_name, type) {this.permissions.forEach((p, i) => {if (p.group_name === group_name) {- this.set(`permissions.${i}.permission_type`, type);+ this.permissions[i].permission_type = type;}});}diff --git a/frontend/discourse/app/models/group.js b/frontend/discourse/app/models/group.jsindex 8a882b3013d..385f145a22d 100644--- a/frontend/discourse/app/models/group.js+++ b/frontend/discourse/app/models/group.js@@ -439,7 +439,9 @@ export default class Group extends RestModel {data: { offset, filters },}).then((results) => {return EmberObject.create({- logs: results["logs"].map((log) => GroupHistory.create(log)),+ logs: new TrackedArray(+ results["logs"].map((log) => GroupHistory.create(log))+ ),all_loaded: results["all_loaded"],});});diff --git a/frontend/discourse/app/models/site.js b/frontend/discourse/app/models/site.jsindex dce81475b65..0f82f7975c0 100644--- a/frontend/discourse/app/models/site.js+++ b/frontend/discourse/app/models/site.js@@ -5,6 +5,8 @@ import { alias, sort } from "@ember/object/computed";import { service } from "@ember/service";import { htmlSafe } from "@ember/template";import { isEmpty } from "@ember/utils";+import { TrackedArray } from "@ember-compat/tracked-built-ins";+import { removeValueFromArray } from "discourse/lib/array-tools";import discourseComputed from "discourse/lib/decorators";import deprecated, { withSilencedDeprecations } from "discourse/lib/deprecated";import { isRailsTesting, isTesting } from "discourse/lib/environment";@@ -84,7 +86,7 @@ export default class Site extends RestModel {@service siteSettings;@service capabilities;- @trackedArray categories;+ @trackedArray categories = [];@alias("is_readonly") isReadOnly;@@ -96,7 +98,6 @@ export default class Site extends RestModel {super.init(...arguments);this.topicCountDesc = ["topic_count:desc"];- this.categories = this.categories || [];}@dependentKeyCompat@@ -160,11 +161,9 @@ export default class Site extends RestModel {return this.mobileView;}- @computed("categories.[]")+ @dependentKeyCompatget categoriesById() {- const map = new Map();- this.categories.forEach((c) => map.set(c.id, c));- return map;+ return new Map(this.categories.map((c) => [c.id, c]));}@computed("[email protected]_category_id")@@ -193,7 +192,7 @@ export default class Site extends RestModel {if (!postActionTypes) {return [];}- return postActionTypes.filter((type) => type.is_flag);+ return new TrackedArray(postActionTypes.filter((type) => type.is_flag));}collectUserFields(fields) {@@ -255,7 +254,7 @@ export default class Site extends RestModel {const categories = this.categories;const existingCategory = categories.find((c) => c.id === id);if (existingCategory) {- categories.removeObject(existingCategory);+ removeValueFromArray(categories, existingCategory);}}@@ -281,7 +280,7 @@ export default class Site extends RestModel {} else {// TODO insert in right order?newCategory = this.store.createRecord("category", newCategory);- categories.pushObject(newCategory);+ categories.push(newCategory);return newCategory;}}diff --git a/frontend/discourse/app/models/topic-details.js b/frontend/discourse/app/models/topic-details.jsindex 1ee0537e175..77752f3b500 100644--- a/frontend/discourse/app/models/topic-details.js+++ b/frontend/discourse/app/models/topic-details.js@@ -2,6 +2,8 @@ import { tracked } from "@glimmer/tracking";import EmberObject from "@ember/object";import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { trackedArray } from "discourse/lib/tracked-tools";import RestModel from "discourse/models/rest";/**@@ -19,6 +21,8 @@ export default class TopicDetails extends RestModel {@tracked can_split_merge_topic;@tracked created_by;@tracked notification_level;+ @trackedArray allowed_groups;+ @trackedArray allowed_users;loaded = false;@@ -54,27 +58,33 @@ export default class TopicDetails extends RestModel {});}- removeAllowedGroup(group) {+ async removeAllowedGroup(group) {const groups = this.allowed_groups;const name = group.name;- return ajax("/t/" + this.get("topic.id") + "/remove-allowed-group", {+ await ajax(`/t/${this.get("topic.id")}/remove-allowed-group`, {type: "PUT",data: { name },- }).then(() => {- groups.removeObject(groups.find((item) => item.name === name));});++ removeValueFromArray(+ groups,+ groups.find((item) => item.name === name)+ );}- removeAllowedUser(user) {+ async removeAllowedUser(user) {const users = this.allowed_users;const username = user.get("username");- return ajax("/t/" + this.get("topic.id") + "/remove-allowed-user", {+ await ajax(`/t/${this.get("topic.id")}/remove-allowed-user`, {type: "PUT",data: { username },- }).then(() => {- users.removeObject(users.find((item) => item.username === username));});++ removeValueFromArray(+ users,+ users.find((item) => item.username === username)+ );}}diff --git a/frontend/discourse/app/models/topic-list.js b/frontend/discourse/app/models/topic-list.jsindex 564bf4eaf6d..8959082edd3 100644--- a/frontend/discourse/app/models/topic-list.js+++ b/frontend/discourse/app/models/topic-list.js@@ -5,8 +5,10 @@ import { service } from "@ember/service";import { isEmpty } from "@ember/utils";import { Promise } from "rsvp";import { ajax } from "discourse/lib/ajax";+import { removeValuesFromArray } from "discourse/lib/array-tools";import deprecated from "discourse/lib/deprecated";import { getOwnerWithFallback } from "discourse/lib/get-owner";+import { trackedArray } from "discourse/lib/tracked-tools";import RestModel from "discourse/models/rest";import Site from "discourse/models/site";import User from "discourse/models/user";@@ -124,6 +126,8 @@ export default class TopicList extends RestModel {@service session;@tracked loadingBefore = false;+ @trackedArray topics;+@notEmpty("more_topics_url") canLoadMore;forEachNew(topics, callback) {@@ -196,7 +200,7 @@ export default class TopicList extends RestModel {this.forEachNew(newTopics, (t) => {t.set("highlight", topicsAdded++ === 0);- this.topics.pushObject(t);+ this.topics.push(t);});this.setProperties({@@ -224,7 +228,8 @@ export default class TopicList extends RestModel {const result = await ajax({ url, data: this.params });// refresh dupes- this.topics.removeObjects(+ removeValuesFromArray(+ this.topics,this.topics.filter((topic) => topic_ids.includes(topic.id)));@@ -232,7 +237,7 @@ export default class TopicList extends RestModel {this.forEachNew(TopicList.topicsFrom(this.store, result), (t) => {// highlight the first of the new topics so we can get a visual feedbackt.set("highlight", true);- this.topics.insertAt(i, t);+ this.topics.splice(i, 0, t);i++;});diff --git a/frontend/discourse/app/models/topic.js b/frontend/discourse/app/models/topic.jsindex 1d99de1c22d..9e839452a6e 100644--- a/frontend/discourse/app/models/topic.js+++ b/frontend/discourse/app/models/topic.js@@ -7,6 +7,7 @@ import { Promise } from "rsvp";import { resolveShareUrl } from "discourse/helpers/share-url";import { ajax } from "discourse/lib/ajax";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";@@ -18,6 +19,7 @@ import { deepMerge } from "discourse/lib/object";import PreloadStore from "discourse/lib/preload-store";import { emojiUnescape } from "discourse/lib/text";import { fancyTitle } from "discourse/lib/topic-fancy-title";+import { trackedArray } from "discourse/lib/tracked-tools";import DiscourseURL, { userPath } from "discourse/lib/url";import ActionSummary from "discourse/models/action-summary";import Bookmark from "discourse/models/bookmark";@@ -315,6 +317,8 @@ export default class Topic extends RestModel {@tracked posts_count;@tracked replies_to_post_number;@tracked suggested_topics;+ @trackedArray bookmarks;+ @trackedArray pending_posts;message = null;@@ -459,17 +463,13 @@ export default class Topic extends RestModel {@dependentKeyCompat@cachedget relatedMessages() {- return this.get("related_messages")?.map((st) =>- this.store.createRecord("topic", st)- );+ return this.get("related_messages")?.map((data) => Topic.create(data));}@dependentKeyCompat@cachedget suggestedTopics() {- return this.get("suggested_topics")?.map((st) =>- this.store.createRecord("topic", st)- );+ return this.get("suggested_topics")?.map((data) => Topic.create(data));}@discourseComputed("posts_count")@@ -813,7 +813,7 @@ export default class Topic extends RestModel {if (!json.view_hidden) {this.details.updateFromJson(json.details);- keys.removeObjects(["details", "post_stream"]);+ removeValuesFromArray(keys, ["details", "post_stream"]);if (json.published_page) {this.set(diff --git a/frontend/discourse/app/models/user-stream.js b/frontend/discourse/app/models/user-stream.jsindex af337610088..f69fe7340e9 100644--- a/frontend/discourse/app/models/user-stream.js+++ b/frontend/discourse/app/models/user-stream.js@@ -1,5 +1,6 @@import { tracked } from "@glimmer/tracking";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 { trackedArray } from "discourse/lib/tracked-tools";@@ -76,7 +77,7 @@ export default class UserStream extends RestModel {["likes", "stars", "edits", "bookmarks"].forEach((group) => {const items = ua.get(`childGroups.${group}.items`);if (items) {- items.removeObject(userAction);+ removeValueFromArray(items, userAction);}});});diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.jsindex 23fad1e8087..346f6e64267 100644--- a/frontend/discourse/app/models/user.js+++ b/frontend/discourse/app/models/user.js@@ -12,7 +12,11 @@ import { isEmpty } from "@ember/utils";import { TrackedArray } from "@ember-compat/tracked-built-ins";import { Promise } from "rsvp";import { ajax } from "discourse/lib/ajax";-import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import {+ addUniqueValueToArray,+ removeValueFromArray,+ uniqueItemsFromArray,+} from "discourse/lib/array-tools";import { url } from "discourse/lib/computed";import {INTERFACE_COLOR_MODES,@@ -30,6 +34,7 @@ import { NotificationLevels } from "discourse/lib/notification-levels";import PreloadStore from "discourse/lib/preload-store";import singleton from "discourse/lib/singleton";import { emojiUnescape } from "discourse/lib/text";+import { trackedArray } from "discourse/lib/tracked-tools";import { userPath } from "discourse/lib/url";import { defaultHomepage, escapeExpression } from "discourse/lib/utilities";import Badge from "discourse/models/badge";@@ -218,6 +223,12 @@ export default class User extends RestModel.extend(Evented) {@tracked do_not_disturb_until;@tracked status;@tracked dismissed_banner_key;+ @trackedArray associated_accounts;+ @trackedArray ignored_usernames;+ @trackedArray ignored_users;+ @trackedArray secondary_emails;+ @trackedArray sidebar_sections;+ @trackedArray unconfirmed_emails;@userOption("mailing_list_mode") mailing_list_mode;@userOption("external_links_in_new_tab") external_links_in_new_tab;@@ -494,7 +505,7 @@ export default class User extends RestModel.extend(Evented) {this.set("unconfirmed_emails", []);}- this.unconfirmed_emails.pushObject(email);+ this.unconfirmed_emails.push(email);});}@@ -507,7 +518,7 @@ export default class User extends RestModel.extend(Evented) {this.set("unconfirmed_emails", []);}- this.unconfirmed_emails.pushObject(email);+ this.unconfirmed_emails.push(email);});}@@ -586,23 +597,24 @@ export default class User extends RestModel.extend(Evented) {type: "PUT",data: { email },}).then(() => {- this.secondary_emails.removeObject(email);- this.secondary_emails.pushObject(this.email);+ removeValueFromArray(this.secondary_emails, email);+ this.secondary_emails.push(this.email);this.set("email", email);});}- destroyEmail(email) {- return ajax(userPath(`${this.username}/preferences/email.json`), {+ async destroyEmail(email) {+ await ajax(userPath(`${this.username}/preferences/email.json`), {type: "DELETE",data: { email },- }).then(() => {- if (this.unconfirmed_emails.includes(email)) {- this.unconfirmed_emails.removeObject(email);- } else {- this.secondary_emails.removeObject(email);- }});++ removeValueFromArray(+ this.unconfirmed_emails.includes(email)+ ? this.unconfirmed_emails+ : this.secondary_emails,+ );}changePassword() {@@ -749,8 +761,8 @@ export default class User extends RestModel.extend(Evented) {ua.title = emojiUnescape(escapeExpression(ua.title));const action = UserAction.collapseStream([UserAction.create(ua)]);- this.stream.set("itemsLoaded", this.stream.get("itemsLoaded") + 1);- this.stream.get("content").insertAt(0, action[0]);+ this.stream.itemsLoaded += 1;+ this.stream.content.unshift(action[0]);}inAllStream(ua) {@@ -1065,9 +1077,9 @@ export default class User extends RestModel.extend(Evented) {actingUser.ignored_users = [];}if (level === "normal" || level === "mute") {- actingUser.ignored_users.removeObject(this.username);+ removeValueFromArray(actingUser.ignored_users, this.username);} else if (level === "ignore") {- actingUser.ignored_users.addObject(this.username);+ addUniqueValueToArray(actingUser.ignored_users, this.username);}});}diff --git a/frontend/discourse/app/routes/discovery/categories.js b/frontend/discourse/app/routes/discovery/categories.jsindex 14c462b194b..a84d4695acd 100644--- a/frontend/discourse/app/routes/discovery/categories.js+++ b/frontend/discourse/app/routes/discovery/categories.js@@ -2,6 +2,7 @@ import { action } from "@ember/object";import { service } from "@ember/service";import { hash } from "rsvp";import { ajax } from "discourse/lib/ajax";+import { removeValuesFromArray } from "discourse/lib/array-tools";import { MAX_UNOPTIMIZED_CATEGORIES } from "discourse/lib/constants";import PreloadStore from "discourse/lib/preload-store";import { defaultHomepage } from "discourse/lib/utilities";@@ -70,31 +71,31 @@ export default class DiscoveryCategoriesRoute extends DiscourseRoute {_loadBefore(store) {const session = this.session;- return function (topic_ids, storeInSession) {+ return async function (topic_ids, storeInSession) {// refresh dupes- this.topics.removeObjects(+ removeValuesFromArray(+ this.topics, // this is a CategoryList instancethis.topics.filter((topic) => topic_ids.includes(topic.id)));const url = `/latest.json?topic_ids=${topic_ids.join(",")}`;- return ajax({ url, data: this.params }).then((result) => {- const topicIds = new Set();- this.topics.forEach((topic) => topicIds.add(topic.id));+ const result = await ajax({ url, data: this.params });+ const topicIds = new Set();+ this.topics.forEach((topic) => topicIds.add(topic.id));- let i = 0;- TopicList.topicsFrom(store, result).forEach((topic) => {- if (!topicIds.has(topic.id)) {- topic.set("highlight", true);- this.topics.insertAt(i, topic);- i++;- }- });-- if (storeInSession) {- session.set("topicList", this);+ let i = 0;+ TopicList.topicsFrom(store, result).forEach((topic) => {+ if (!topicIds.has(topic.id)) {+ topic.set("highlight", true);+ this.topics.splice(i, 0, topic);+ i++;}});++ if (storeInSession) {+ session.set("topicList", this);+ }};}diff --git a/frontend/discourse/app/routes/new-invite.js b/frontend/discourse/app/routes/new-invite.jsindex 930efefe85b..83377828637 100644--- a/frontend/discourse/app/routes/new-invite.js+++ b/frontend/discourse/app/routes/new-invite.js@@ -1,5 +1,6 @@import { next } from "@ember/runloop";import { service } from "@ember/service";+import { TrackedArray } from "@ember-compat/tracked-built-ins";import CreateInvite from "discourse/components/modal/create-invite";import { defaultHomepage } from "discourse/lib/utilities";import DiscourseRoute from "discourse/routes/discourse";@@ -34,7 +35,9 @@ export default class extends DiscourseRoute {#openInviteModalIfAllowed() {next(() => {if (this.currentUser.can_invite_to_forum) {- this.modal.show(CreateInvite, { model: { invites: [] } });+ this.modal.show(CreateInvite, {+ model: { invites: new TrackedArray() },+ });} else {this.dialog.alert(i18n("user.invited.cannot_invite_to_forum"));}diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex 033af61a82b..d16c9b25ecf 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -1185,9 +1185,9 @@ export default class ComposerService extends Service {if (result.responseJson.action === "enqueued") {this.postWasEnqueued(result.responseJson);if (result.responseJson.pending_post) {- let pendingPosts = this.get("topicController.model.pending_posts");+ let pendingPosts = this.topicController.model.pending_posts;if (pendingPosts) {- pendingPosts.pushObject(result.responseJson.pending_post);+ pendingPosts.push(result.responseJson.pending_post);}}diff --git a/frontend/discourse/tests/integration/components/bulk-select-topics-dropdown-test.gjs b/frontend/discourse/tests/integration/components/bulk-select-topics-dropdown-test.gjsindex 87ff408149c..6720fce80c9 100644--- a/frontend/discourse/tests/integration/components/bulk-select-topics-dropdown-test.gjs+++ b/frontend/discourse/tests/integration/components/bulk-select-topics-dropdown-test.gjs@@ -2,6 +2,7 @@ import { getOwner } from "@ember/owner";import { click, render } from "@ember/test-helpers";import { module, test } from "qunit";import BulkSelectTopicsDropdown from "discourse/components/bulk-select-topics-dropdown";+import { addUniqueValueToArray } from "discourse/lib/array-tools";import BulkSelectHelper from "discourse/lib/bulk-select-helper";import { TOPIC_VISIBILITY_REASONS } from "discourse/lib/constants";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -36,7 +37,7 @@ function createBulkSelectHelper(testThis, opts = {}) {const bulkSelectHelper = new BulkSelectHelper(testThis);topics.forEach((t) => {- bulkSelectHelper.selected.addObject(t);+ addUniqueValueToArray(bulkSelectHelper.selected, t);});return bulkSelectHelper;}diff --git a/frontend/discourse/tests/integration/components/secret-value-list-test.gjs b/frontend/discourse/tests/integration/components/secret-value-list-test.gjsindex f59b20e7873..bf40b6e4f7c 100644--- a/frontend/discourse/tests/integration/components/secret-value-list-test.gjs+++ b/frontend/discourse/tests/integration/components/secret-value-list-test.gjs@@ -9,12 +9,14 @@ module("Integration | Component | secret-value-list", function (hooks) {test("adding a value", async function (assert) {this.set("setValidationMessage", () => {});+ this.set("changeValueCallback", (values) => this.set("values", values));await render(<template><SecretValueList@values={{this.values}}@setValidationMessage={{this.setValidationMessage}}+ @changeValueCallback={{this.changeValueCallback}}/></template>);@@ -62,12 +64,14 @@ module("Integration | Component | secret-value-list", function (hooks) {this.set("message", message);};this.set("setValidationMessage", setValidationMessage);+ this.set("changeValueCallback", (values) => this.set("values", values));await render(<template><SecretValueList@values={{this.values}}@setValidationMessage={{this.setValidationMessage}}+ @changeValueCallback={{this.changeValueCallback}}/></template>);@@ -95,12 +99,14 @@ module("Integration | Component | secret-value-list", function (hooks) {test("changing a value", async function (assert) {this.set("setValidationMessage", () => {});+ this.set("changeValueCallback", (values) => this.set("values", values));await render(<template><SecretValueList@values={{this.values}}@setValidationMessage={{this.setValidationMessage}}+ @changeValueCallback={{this.changeValueCallback}}/></template>);@@ -135,12 +141,14 @@ module("Integration | Component | secret-value-list", function (hooks) {test("removing a value", async function (assert) {this.set("setValidationMessage", () => {});+ this.set("changeValueCallback", (values) => this.set("values", values));await render(<template><SecretValueList@values={{this.values}}@setValidationMessage={{this.setValidationMessage}}+ @changeValueCallback={{this.changeValueCallback}}/></template>);diff --git a/frontend/discourse/tests/unit/controllers/topic-test.js b/frontend/discourse/tests/unit/controllers/topic-test.jsindex daf01732f76..145752ffad7 100644--- a/frontend/discourse/tests/unit/controllers/topic-test.js+++ b/frontend/discourse/tests/unit/controllers/topic-test.js@@ -4,6 +4,7 @@ import { settled } from "@ember/test-helpers";import { setupTest } from "ember-qunit";import { module, test } from "qunit";import sinon from "sinon";+import { removeValueFromArray } from "discourse/lib/array-tools";import { forceMobile } from "discourse/lib/mobile";import { Placeholder } from "discourse/models/post-stream";import pretender, { response } from "discourse/tests/helpers/create-pretender";@@ -109,7 +110,7 @@ module("Unit | Controller | topic", function (hooks) {"multi selection mode is disabled by default");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.strictEqual(controller.selectedPostIds.length, 1);controller.send("toggleMultiSelect");@@ -125,7 +126,7 @@ module("Unit | Controller | topic", function (hooks) {"toggling 'multiSelect' clears 'selectedPostIds'");- controller.selectedPostIds.pushObject(2);+ controller.selectedPostIds.push(2);assert.strictEqual(controller.selectedPostIds.length, 1);controller.send("toggleMultiSelect");@@ -170,10 +171,10 @@ module("Unit | Controller | topic", function (hooks) {controller.set("selectedPostIds", [1, 2]);assert.false(controller.selectedAllPosts, "not all posts are selected");- controller.selectedPostIds.pushObject(3);+ controller.selectedPostIds.push(3);assert.true(controller.selectedAllPosts, "all posts are selected");- controller.selectedPostIds.pushObject(42);+ controller.selectedPostIds.push(42);assert.true(controller.selectedAllPosts,"all posts (including filtered posts) are selected"@@ -207,21 +208,21 @@ module("Unit | Controller | topic", function (hooks) {"no username when no selected posts");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.strictEqual(controller.selectedPostsUsername,"gary","username of the selected posts");- controller.selectedPostIds.pushObject(2);+ controller.selectedPostIds.push(2);assert.strictEqual(controller.selectedPostsUsername,"gary","username of all the selected posts when same user");- controller.selectedPostIds.pushObject(3);+ controller.selectedPostIds.push(3);assert.strictEqual(controller.selectedPostsUsername,undefined,@@ -279,7 +280,7 @@ module("Unit | Controller | topic", function (hooks) {"false when no posts are selected");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canDeleteSelected,"false when can't delete one of the selected posts"@@ -291,7 +292,7 @@ module("Unit | Controller | topic", function (hooks) {"true when all selected posts can be deleted");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canDeleteSelected,"false when all posts are selected and user is staff"@@ -323,7 +324,7 @@ module("Unit | Controller | topic", function (hooks) {"can't merge topic when no posts are selected");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canMergeTopic,@@ -334,15 +335,15 @@ module("Unit | Controller | topic", function (hooks) {assert.true(controller.canMergeTopic, "can merge topic");- controller.selectedPostIds.removeObject(1);- controller.selectedPostIds.pushObject(2);+ removeValueFromArray(controller.selectedPostIds, 1);+ controller.selectedPostIds.push(2);assert.true(controller.canMergeTopic,"can merge topic when 1st post is not a regular post");- controller.selectedPostIds.pushObject(3);+ controller.selectedPostIds.push(3);assert.true(controller.canMergeTopic,@@ -366,7 +367,7 @@ module("Unit | Controller | topic", function (hooks) {assert.false(controller.canChangeOwner, "false when no posts are selected");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canChangeOwner, "false when not admin");currentUser.set("admin", true);@@ -375,7 +376,7 @@ module("Unit | Controller | topic", function (hooks) {"true when admin and one post is selected");- controller.selectedPostIds.pushObject(2);+ controller.selectedPostIds.push(2);assert.false(controller.canChangeOwner,"false when admin but more than 1 user"@@ -401,7 +402,7 @@ module("Unit | Controller | topic", function (hooks) {assert.false(controller.canChangeOwner, "false when no posts are selected");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canChangeOwner, "false when not moderator");currentUser.set("moderator", true);@@ -410,7 +411,7 @@ module("Unit | Controller | topic", function (hooks) {"true when moderator and one post is selected");- controller.selectedPostIds.pushObject(2);+ controller.selectedPostIds.push(2);assert.false(controller.canChangeOwner,"false when moderator but more than 1 user"@@ -433,13 +434,13 @@ module("Unit | Controller | topic", function (hooks) {assert.false(controller.canMergePosts, "false when no posts are selected");- controller.selectedPostIds.pushObject(1);+ controller.selectedPostIds.push(1);assert.false(controller.canMergePosts,"false when only one post is selected");- controller.selectedPostIds.pushObject(2);+ controller.selectedPostIds.push(2);assert.false(controller.canMergePosts,"false when selected posts are from different users"diff --git a/frontend/discourse/tests/unit/lib/array-tools-test.js b/frontend/discourse/tests/unit/lib/array-tools-test.jsindex 60e59a2fc9b..da375624590 100644--- a/frontend/discourse/tests/unit/lib/array-tools-test.js+++ b/frontend/discourse/tests/unit/lib/array-tools-test.js@@ -74,6 +74,49 @@ module("Unit | Lib | array-tools", function () {"new distinct value appended");});++ test("adds object with selector based on property value", function (assert) {+ const arr = [{ id: 1, name: "Alice" }];+ addUniqueValueToArray(arr, { id: 2, name: "Bob" }, (item) => item.id);++ assert.strictEqual(arr.length, 2, "object with different id added");+ assert.deepEqual(+ arr.map((o) => o.name),+ ["Alice", "Bob"],+ "both objects present"+ );+ });++ test("does not add object with selector when value already exists", function (assert) {+ const arr = [+ { id: 1, name: "Alice" },+ { id: 2, name: "Bob" },+ ];+ addUniqueValueToArray(arr, { id: 1, name: "Alice2" }, (item) => item.id);++ assert.strictEqual(arr.length, 2, "duplicate id not added");+ assert.deepEqual(+ arr.map((o) => o.name),+ ["Alice", "Bob"],+ "original objects unchanged"+ );+ });++ test("selector compares the transformed value", function (assert) {+ const arr = [{ value: "apple" }, { value: "banana" }];+ addUniqueValueToArray(arr, { value: "APPLE" }, (item) =>+ item.value.toLowerCase()+ );++ assert.strictEqual(arr.length, 2, "case-insensitive duplicate not added");++ addUniqueValueToArray(arr, { value: "CHERRY" }, (item) =>+ item.value.toLowerCase()+ );++ assert.strictEqual(arr.length, 3, "unique value added");+ assert.strictEqual(arr[2].value, "CHERRY", "new value appended");+ });});module("addUniqueValuesToArray()", function () {@@ -146,6 +189,74 @@ module("Unit | Lib | array-tools", function () {addUniqueValuesToArray(arr, [1, 2]);assert.deepEqual(arr, [1, 2], "second call no-ops");});++ test("adds multiple objects with selector based on property value", function (assert) {+ const arr = [{ id: 1, name: "Alice" }];+ addUniqueValuesToArray(+ arr,+ [+ { id: 2, name: "Bob" },+ { id: 3, name: "Charlie" },+ { id: 4, name: "David" },+ ],+ (item) => item.id+ );++ assert.strictEqual(arr.length, 4, "three new objects added");+ assert.deepEqual(+ arr.map((o) => o.name),+ ["Alice", "Bob", "Charlie", "David"],+ "all unique objects present"+ );+ });++ test("does not add objects with selector when values already exist", function (assert) {+ const arr = [+ { id: 1, name: "Alice" },+ { id: 2, name: "Bob" },+ ];+ addUniqueValuesToArray(+ arr,+ [+ { id: 1, name: "Alice2" },+ { id: 3, name: "Charlie" },+ { id: 2, name: "Bob2" },+ ],+ (item) => item.id+ );++ assert.strictEqual(arr.length, 3, "only unique id added");+ assert.deepEqual(+ arr.map((o) => o.name),+ ["Alice", "Bob", "Charlie"],+ "duplicate ids not added, new id added"+ );+ });++ test("selector compares transformed values across multiple additions", function (assert) {+ const arr = [{ value: "apple" }];+ addUniqueValuesToArray(+ arr,+ [+ { value: "APPLE" },+ { value: "banana" },+ { value: "BANANA" },+ { value: "cherry" },+ ],+ (item) => item.value.toLowerCase()+ );++ assert.strictEqual(+ arr.length,+ 3,+ "only case-insensitive unique values added"+ );+ assert.deepEqual(+ arr.map((o) => o.value),+ ["apple", "banana", "cherry"],+ "first occurrence of each unique value kept"+ );+ });});module("removeValueFromArray()", function () {diff --git a/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs b/frontend/discourse/tests/unit/lib/tracked-tools-test.gjsindex 4d499579958..3db4a9881c0 100644--- a/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs+++ b/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs@@ -153,6 +153,19 @@ module("Unit | tracked-tools", function () {);});+ test("accepts undefined as initial value", function (assert) {+ class TestClass {+ @trackedArray items;+ }++ const instance = new TestClass();+ assert.strictEqual(+ instance.items,+ undefined,+ "should allow undefined as initial value"+ );+ });+test("handles setting regular arrays", function (assert) {class TestClass {@trackedArray items;@@ -204,6 +217,21 @@ module("Unit | tracked-tools", function () {assert.strictEqual(instance.items, null, "should allow setting to null");});+ test("allows setting to undefined", function (assert) {+ class TestClass {+ @trackedArray items = ["initial"];+ }++ const instance = new TestClass();+ instance.items = undefined;++ assert.strictEqual(+ instance.items,+ undefined,+ "should allow setting to undefined"+ );+ });+test("throws error for invalid values", function (assert) {class TestClass {@trackedArray items = [];@@ -215,7 +243,7 @@ module("Unit | tracked-tools", function () {() => {instance.items = "not an array";},- /Expected an array or TrackedArray, got string/,+ /Expected an array, TrackedArray, null, or undefined, got/,"should throw for strings");@@ -223,7 +251,7 @@ module("Unit | tracked-tools", function () {() => {instance.items = 42;},- /Expected an array or TrackedArray, got number/,+ /Expected an array, TrackedArray, null, or undefined, got/,"should throw for numbers");@@ -231,17 +259,9 @@ module("Unit | tracked-tools", function () {() => {instance.items = {};},- /Expected an array or TrackedArray, got object/,+ /Expected an array, TrackedArray, null, or undefined, got/,"should throw for plain objects");-- assert.throws(- () => {- instance.items = undefined;- },- /Expected an array or TrackedArray, got undefined/,- "should throw for undefined"- );});test("tracks changes to array contents", function (assert) {diff --git a/frontend/discourse/tests/unit/models/nav-item-test.js b/frontend/discourse/tests/unit/models/nav-item-test.jsindex c8a6d0f01eb..d284ba71850 100644--- a/frontend/discourse/tests/unit/models/nav-item-test.js+++ b/frontend/discourse/tests/unit/models/nav-item-test.js@@ -1,6 +1,7 @@import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";import { module, test } from "qunit";+import { addUniqueValueToArray } from "discourse/lib/array-tools";import Category from "discourse/models/category";import NavItem from "discourse/models/nav-item";@@ -14,7 +15,7 @@ module("Unit | Model | nav-item", function (hooks) {id: 123,});const site = getOwner(this).lookup("service:site");- site.categories.addObject(fooCategory);+ addUniqueValueToArray(site.categories, fooCategory);});test("href", function (assert) {diff --git a/frontend/discourse/tests/unit/models/site-test.js b/frontend/discourse/tests/unit/models/site-test.jsindex be4714bd67e..bc4ef3e1b5d 100644--- a/frontend/discourse/tests/unit/models/site-test.js+++ b/frontend/discourse/tests/unit/models/site-test.js@@ -1,6 +1,7 @@import { getOwner } from "@ember/owner";import { setupTest } from "ember-qunit";import { module, test } from "qunit";+import { removeValuesFromArray } from "discourse/lib/array-tools";import Site from "discourse/models/site";module("Unit | Model | site", function (hooks) {@@ -42,8 +43,10 @@ module("Unit | Model | site", function (hooks) {);// remove invalid category and child- site.categories.removeObject(site.categories[2]);- site.categories.removeObject(site.categories[0]);+ removeValuesFromArray(site.categories, [+ site.categories[2],+ site.categories[0],+ ]);assert.strictEqual(site.categoriesByCount.length,