Skip to content

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

DEV: Bridge `@trackedArray` content mutations to `@computed` dependencies (#38071)

Sérgio Saquetim11fac4c6bca1
diff --git a/frontend/discourse/admin/controllers/admin-user/badges.js b/frontend/discourse/admin/controllers/admin-user/badges.js
index c3489407e30..09abe3d39c7 100644
--- a/frontend/discourse/admin/controllers/admin-user/badges.js
+++ b/frontend/discourse/admin/controllers/admin-user/badges.js
@@ -2,13 +2,16 @@ 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 { alias, empty } from "@ember/object/computed";
import { next } from "@ember/runloop";
import { service } from "@ember/service";
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 {
+ arraySortedByProperties,
+ removeValueFromArray,
+} from "discourse/lib/array-tools";
import { grantableBadges } from "discourse/lib/grant-badge-utils";
import { trackedArray } from "discourse/lib/tracked-tools";
import UserBadge from "discourse/models/user-badge";
@@ -24,11 +27,15 @@ export default class AdminUserBadgesController extends Controller {
@trackedArray expandedBadges = [];
@alias("adminUser.model") user;
- @sort("model", "badgeSortOrder") sortedBadges;
@empty("availableBadges") noAvailableBadges;
badgeSortOrder = ["granted_at:desc"];
+ @dependentKeyCompat
+ get sortedBadges() {
+ return arraySortedByProperties(this.model, this.badgeSortOrder);
+ }
+
@dependentKeyCompat
get allBadges() {
return this.badges;
diff --git a/frontend/discourse/admin/models/theme.js b/frontend/discourse/admin/models/theme.js
index 90474528e78..fa73d82b23a 100644
--- a/frontend/discourse/admin/models/theme.js
+++ b/frontend/discourse/admin/models/theme.js
@@ -212,12 +212,15 @@ class Theme extends RestModel {
setField(target, name, value, upload_id, type_id) {
this.set("changed", true);
+
+ // Normalize JS field target/name consistently with getField()
+ if (target === "common" && name === "js") {
+ target = "extra_js";
+ name = JS_FILENAME;
+ }
+
let themeFields = this.themeFields;
let field = { name, target, value, upload_id, type_id };
- if (field.name === "js" && target === "common") {
- field.target = "extra_js";
- field.name = JS_FILENAME;
- }
// slow path for uploads and so on
if (type_id && type_id > 1) {
diff --git a/frontend/discourse/app/components/tag-info.gjs b/frontend/discourse/app/components/tag-info.gjs
index aad85a90544..9f628741ada 100644
--- a/frontend/discourse/app/components/tag-info.gjs
+++ b/frontend/discourse/app/components/tag-info.gjs
@@ -1,8 +1,10 @@
/* eslint-disable ember/no-classic-components */
+import { tracked } from "@glimmer/tracking";
import Component, { Textarea } from "@ember/component";
import { array, fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
+import { dependentKeyCompat } from "@ember/object/compat";
import { and, reads } from "@ember/object/computed";
import { LinkTo } from "@ember/routing";
import { service } from "@ember/service";
@@ -32,8 +34,9 @@ export default class TagInfo extends Component {
@service router;
@service siteSettings;
+ @tracked tagInfo = null;
+
loading = false;
- tagInfo = null;
newSynonyms = null;
showEditControls = false;
editing = false;
@@ -63,10 +66,22 @@ export default class TagInfo extends Component {
});
}
+ // Bridge TrackedArray content changes to the classic tag system. `@tracked tagInfo` lets the getter invalidate when
+ // tagInfo is reassigned (reload). Consuming `synonyms.length` captures the TrackedArray's collection tag so the
+ // getter also invalidates on in-place mutations (push/splice/remove).
+ @dependentKeyCompat
+ get synonyms() {
+ const synonyms = this.tagInfo?.synonyms;
+ if (synonyms) {
+ synonyms.length;
+ }
+ return synonyms;
+ }
+
@discourseComputed(
"tagInfo.tag_group_names",
"tagInfo.categories",
- "tagInfo.synonyms"
+ "synonyms"
)
nothingToShow(tagGroupNames, categories, synonyms) {
return isEmpty(tagGroupNames) && isEmpty(categories) && isEmpty(synonyms);
@@ -132,7 +147,7 @@ export default class TagInfo extends Component {
ajax(`/tag/${id}/synonyms/${synonym.id}.json`, {
type: "DELETE",
})
- .then(() => removeValueFromArray(this.tagInfo.synonyms, synonym))
+ .then(() => removeValueFromArray(this.synonyms, synonym))
.catch(popupAjaxError);
}
@@ -147,7 +162,7 @@ export default class TagInfo extends Component {
didConfirm: () => {
return tag
.destroyRecord()
- .then(() => removeValueFromArray(this.tagInfo.synonyms, tag))
+ .then(() => removeValueFromArray(this.synonyms, tag))
.catch(popupAjaxError);
},
});
@@ -201,11 +216,11 @@ export default class TagInfo extends Component {
? i18n("tagging.delete_confirm_no_topics")
: i18n("tagging.delete_confirm", { count: numTopics });
- if (this.tagInfo.synonyms.length > 0) {
+ if (this.synonyms?.length > 0) {
confirmText +=
" " +
i18n("tagging.delete_confirm_synonyms", {
- count: this.tagInfo.synonyms.length,
+ count: this.synonyms.length,
});
}
@@ -357,7 +372,7 @@ export default class TagInfo extends Component {
{{/if}}
{{/if~}}
</div>
- {{#if this.tagInfo.synonyms}}
+ {{#if this.synonyms}}
<div class="synonyms-list">
<h3>{{i18n "tagging.synonyms"}}</h3>
<div>{{htmlSafe
@@ -366,7 +381,7 @@ export default class TagInfo extends Component {
)
}}</div>
<div class="tag-list">
- {{#each this.tagInfo.synonyms as |tag|}}
+ {{#each this.synonyms as |tag|}}
<div class="tag-box">
{{discourseTag tag.name pmOnly=tag.pmOnly tagName="div"}}
{{#if this.editSynonymsMode}}
diff --git a/frontend/discourse/app/controllers/user-activity/bookmarks.js b/frontend/discourse/app/controllers/user-activity/bookmarks.js
index b8576de880f..00b9fb25b2f 100644
--- a/frontend/discourse/app/controllers/user-activity/bookmarks.js
+++ b/frontend/discourse/app/controllers/user-activity/bookmarks.js
@@ -1,6 +1,7 @@
import Controller, { inject as controller } from "@ember/controller";
import EmberObject, { action, computed } from "@ember/object";
-import { equal, notEmpty } from "@ember/object/computed";
+import { dependentKeyCompat } from "@ember/object/compat";
+import { notEmpty } from "@ember/object/computed";
import { service } from "@ember/service";
import { htmlSafe } from "@ember/template";
import { Promise } from "rsvp";
@@ -26,7 +27,11 @@ export default class UserActivityBookmarksController extends Controller {
bulkSelectHelper = new BulkSelectHelper(this);
@notEmpty("q") inSearchMode;
- @equal("model.bookmarks.length", 0) noContent;
+
+ @dependentKeyCompat
+ get noContent() {
+ return this.model?.bookmarks?.length === 0;
+ }
@computed("q")
get searchTerm() {
diff --git a/frontend/discourse/app/lib/array-tools.js b/frontend/discourse/app/lib/array-tools.js
index 9181b86c8ea..3da92612c1b 100644
--- a/frontend/discourse/app/lib/array-tools.js
+++ b/frontend/discourse/app/lib/array-tools.js
@@ -1,4 +1,5 @@
import { get } from "@ember/object";
+import { compare } from "@ember/utils";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
/**
@@ -161,3 +162,30 @@ export function uniqueItemsFromArray(array, selector) {
return array instanceof TrackedArray ? new TrackedArray(items) : items;
}
+
+/**
+ * Returns a sorted copy of an array using Ember-style sort definitions.
+ *
+ * Each definition is a string `"property"` or `"property:direction"` where
+ * direction is `"asc"` (default) or `"desc"`. Dot-notation paths are supported
+ * (e.g., `"badge.badge_type_id"`).
+ *
+ * @param {Array} array - The array to sort. Returns `[]` if not an array.
+ * @param {string[]} sortDefinitions - Sort definition strings.
+ * @returns {Array} A new sorted array.
+ */
+export function arraySortedByProperties(array, sortDefinitions) {
+ if (!Array.isArray(array)) {
+ return [];
+ }
+ return array.toSorted((a, b) => {
+ for (const s of sortDefinitions ?? []) {
+ const [prop, dir = "asc"] = s.split(":");
+ const result = compare(get(a, prop), get(b, prop));
+ if (result !== 0) {
+ return dir === "desc" ? -result : result;
+ }
+ }
+ return 0;
+ });
+}
diff --git a/frontend/discourse/app/lib/tracked-tools.js b/frontend/discourse/app/lib/tracked-tools.js
index fc5285ba4b5..d8794f4441f 100644
--- a/frontend/discourse/app/lib/tracked-tools.js
+++ b/frontend/discourse/app/lib/tracked-tools.js
@@ -1,4 +1,5 @@
import { tracked } from "@glimmer/tracking";
+import { tagFor, track, updateTag } from "@glimmer/validator";
import { meta as metaFor, peekMeta } from "@ember/-internals/meta";
import { TrackedDescriptor } from "@ember/-internals/metal";
import { next } from "@ember/runloop";
@@ -239,19 +240,47 @@ export function trackedArray(target, key, desc) {
set.call(this, ensureTrackedArray(value, key));
}
+ // Bridge TrackedArray content changes to the classic computed property tag
+ // system. Without this, @computed('prop') only invalidates on reference
+ // changes (this.prop = newArray), not on content mutations like push().
+ //
+ // This manually implements the same bridging that @dependentKeyCompat does
+ // (we can't use @dependentKeyCompat directly because it rejects properties
+ // that are already @tracked). The getter captures the TrackedArray's
+ // collection tag via track(), then updates tagFor(obj, key) so that
+ // @computed properties watching this key see content changes.
+ function trackedArrayGetter() {
+ // Read the value outside track() to avoid a tag cycle. get.call(this)
+ // consumes the property's own tag (tagFor(this, key)) via the tracked
+ // storage. If we captured that inside track() and then called updateTag
+ // on the same tag, it would create a self-referential cycle.
+ const value = get.call(this);
+
+ if (value != null) {
+ // Only capture the TrackedArray's collection tag. TrackedArray's Proxy
+ // get trap for 'length' calls getValue(collection), registering the
+ // collection storage as an autotracking dependency. All mutations
+ // (push, pop, splice, etc.) dirty this same storage via
+ // setValue(collection, null).
+ const propertyTag = tagFor(this, key);
+ const collectionTag = track(() => value.length);
+ updateTag(propertyTag, collectionTag);
+ }
+
+ return 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)
+ new TrackedDescriptor(trackedArrayGetter, trackedArraySetter)
);
return {
- get() {
- return get.call(this);
- },
+ get: trackedArrayGetter,
set: trackedArraySetter,
enumerable: true,
configurable: true,
diff --git a/frontend/discourse/tests/unit/lib/array-tools-test.js b/frontend/discourse/tests/unit/lib/array-tools-test.js
index da375624590..90687f2ff0c 100644
--- a/frontend/discourse/tests/unit/lib/array-tools-test.js
+++ b/frontend/discourse/tests/unit/lib/array-tools-test.js
@@ -3,6 +3,7 @@ import { module, test } from "qunit";
import {
addUniqueValuesToArray,
addUniqueValueToArray,
+ arraySortedByProperties,
removeValueFromArray,
removeValuesFromArray,
uniqueItemsFromArray,
@@ -430,6 +431,98 @@ module("Unit | Lib | array-tools", function () {
});
});
+ module("arraySortedByProperties()", function () {
+ test("sorts by a single ascending property", function (assert) {
+ const input = [{ name: "Charlie" }, { name: "Alice" }, { name: "Bob" }];
+ const result = arraySortedByProperties(input, ["name"]);
+
+ assert.deepEqual(
+ result.map((o) => o.name),
+ ["Alice", "Bob", "Charlie"]
+ );
+ });
+
+ test("sorts by a single descending property", function (assert) {
+ const input = [{ age: 10 }, { age: 30 }, { age: 20 }];
+ const result = arraySortedByProperties(input, ["age:desc"]);
+
+ assert.deepEqual(
+ result.map((o) => o.age),
+ [30, 20, 10]
+ );
+ });
+
+ test("sorts by multiple properties with mixed directions", function (assert) {
+ const input = [
+ { group: "B", score: 3 },
+ { group: "A", score: 1 },
+ { group: "A", score: 2 },
+ { group: "B", score: 1 },
+ ];
+ const result = arraySortedByProperties(input, [
+ "group:asc",
+ "score:desc",
+ ]);
+
+ assert.deepEqual(
+ result.map((o) => `${o.group}${o.score}`),
+ ["A2", "A1", "B3", "B1"]
+ );
+ });
+
+ test("supports dot-notation paths", function (assert) {
+ const input = [
+ { badge: { type_id: 3 } },
+ { badge: { type_id: 1 } },
+ { badge: { type_id: 2 } },
+ ];
+ const result = arraySortedByProperties(input, ["badge.type_id"]);
+
+ assert.deepEqual(
+ result.map((o) => o.badge.type_id),
+ [1, 2, 3]
+ );
+ });
+
+ test("returns empty array for non-array input", function (assert) {
+ assert.deepEqual(arraySortedByProperties(null, ["name"]), []);
+ assert.deepEqual(arraySortedByProperties(undefined, ["name"]), []);
+ assert.deepEqual(arraySortedByProperties("string", ["name"]), []);
+ });
+
+ test("does not mutate the original array", function (assert) {
+ const input = [{ v: 3 }, { v: 1 }, { v: 2 }];
+ const snapshot = input.map((o) => o.v);
+ arraySortedByProperties(input, ["v"]);
+
+ assert.deepEqual(
+ input.map((o) => o.v),
+ snapshot
+ );
+ });
+
+ test("handles empty sort definitions", function (assert) {
+ const input = [{ v: 3 }, { v: 1 }];
+ const result = arraySortedByProperties(input, []);
+
+ assert.deepEqual(
+ result.map((o) => o.v),
+ [3, 1],
+ "order is preserved when no sort definitions provided"
+ );
+ });
+
+ test("defaults to ascending when no direction specified", function (assert) {
+ const input = [{ v: 2 }, { v: 1 }, { v: 3 }];
+ const result = arraySortedByProperties(input, ["v"]);
+
+ assert.deepEqual(
+ result.map((o) => o.v),
+ [1, 2, 3]
+ );
+ });
+ });
+
module("uniqueItemsFromArray()", function () {
test("throws when input is not an array", function (assert) {
assert.throws(
diff --git a/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs b/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs
index 9ffacf7492a..a867136ab1a 100644
--- a/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs
+++ b/frontend/discourse/tests/unit/lib/tracked-tools-test.gjs
@@ -1,4 +1,5 @@
import { cached, tracked } from "@glimmer/tracking";
+import { computed } from "@ember/object";
import { run } from "@ember/runloop";
import { settled } from "@ember/test-helpers";
import { TrackedArray } from "@ember-compat/tracked-built-ins";
@@ -315,6 +316,92 @@ module("Unit | tracked-tools", function () {
"array contains correct items"
);
});
+
+ test("invalidates @computed when TrackedArray contents are mutated", function (assert) {
+ class TestClass {
+ computeCount = 0;
+ @trackedArray items = ["a"];
+
+ @computed("items")
+ get itemCount() {
+ this.computeCount++;
+ return this.items?.length ?? 0;
+ }
+ }
+
+ const instance = new TestClass();
+ assert.strictEqual(instance.itemCount, 1, "initial count is correct");
+ assert.strictEqual(instance.computeCount, 1, "computed evaluated once");
+
+ // In-place mutation via push
+ instance.items.push("b");
+ assert.strictEqual(
+ instance.itemCount,
+ 2,
+ "computed invalidated after push"
+ );
+ assert.strictEqual(instance.computeCount, 2, "computed re-evaluated");
+
+ // In-place mutation via splice
+ instance.items.splice(0, 1);
+ assert.strictEqual(
+ instance.itemCount,
+ 1,
+ "computed invalidated after splice"
+ );
+ assert.strictEqual(instance.computeCount, 3, "computed re-evaluated");
+
+ // Reference change still works
+ instance.items = ["x", "y", "z"];
+ assert.strictEqual(
+ instance.itemCount,
+ 3,
+ "computed invalidated after reference change"
+ );
+ assert.strictEqual(instance.computeCount, 4, "computed re-evaluated");
+ });
+
+ test("invalidates @computed with .[] dependent key on mutations", function (assert) {
+ class TestClass {
+ computeCount = 0;
+ @trackedArray items = [];
+
+ @computed("items.[]")
+ get itemCount() {
+ this.computeCount++;
+ return this.items?.length ?? 0;
+ }
+ }
+
+ const instance = new TestClass();
+ assert.strictEqual(instance.itemCount, 0, "initial count is correct");
+ assert.strictEqual(instance.computeCount, 1, "computed evaluated once");
+
+ instance.items.push("a");
+ assert.strictEqual(
+ instance.itemCount,
+ 1,
+ "computed invalidated after push"
+ );
+ assert.strictEqual(instance.computeCount, 2, "computed re-evaluated");
+ });
+
+ test("@computed works with null @trackedArray value", function (assert) {
+ class TestClass {
+ @trackedArray items = null;
+
+ @computed("items")
+ get hasItems() {
+ return this.items != null && this.items.length > 0;
+ }
+ }
+
+ const instance = new TestClass();
+ assert.false(instance.hasItems, "no items when null");
+
+ instance.items = ["a"];
+ assert.true(instance.hasItems, "has items after setting array");
+ });
});
module("enumerateTrackedKeys", function () {