Skip to content

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

DEV: Introduce `@dedupeTracked` (#27084)

David Taylor23b02a38249b
diff --git a/app/assets/javascripts/discourse/app/lib/tracked-tools.js b/app/assets/javascripts/discourse/app/lib/tracked-tools.js
index 94b7cf3430e..e711629025f 100644
--- a/app/assets/javascripts/discourse/app/lib/tracked-tools.js
+++ b/app/assets/javascripts/discourse/app/lib/tracked-tools.js
@@ -74,3 +74,49 @@ export function resettableTracked(prototype, key, descriptor) {
},
};
}
+
+/**
+ * @decorator
+ *
+ * Same as `@tracked`, but skips notifying about updates if the value is unchanged. This introduces some
+ * performance overhead, so should only be used where excessive downstream re-evaluations are a problem.
+ *
+ * @example
+ *
+ * ```js
+ * class UserRenameForm {
+ * ⁣@dedupeTracked fullName;
+ * }
+ *
+ * const form = new UserRenameForm();
+ * form.fullName = "Alice"; // Downstream consumers will be notified
+ * form.fullName = "Alice"; // Downstream consumers will not be re-notified
+ * form.fullName = "Bob"; // Downstream consumers will be notified
+ * ```
+ *
+ */
+export function dedupeTracked(target, key, desc) {
+ let { initializer } = desc;
+ let { get, set } = tracked(target, key, desc);
+
+ let values = new WeakMap();
+
+ return {
+ get() {
+ if (!values.has(this)) {
+ let value = initializer?.call(this);
+ values.set(this, value);
+ set.call(this, value);
+ }
+
+ return get.call(this);
+ },
+
+ set(value) {
+ if (!values.has(this) || values.get(this) !== value) {
+ values.set(this, value);
+ set.call(this, value);
+ }
+ },
+ };
+}
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs b/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs
new file mode 100644
index 00000000000..b20649e72e1
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/unit/lib/tracked-tools-test.gjs
@@ -0,0 +1,48 @@
+import { cached } from "@glimmer/tracking";
+import { module, test } from "qunit";
+import { dedupeTracked } from "discourse/lib/tracked-tools";
+
+module("Unit | tracked-tools", function () {
+ test("@dedupeTracked", async function (assert) {
+ class Pet {
+ initialsEvaluatedCount = 0;
+
+ @dedupeTracked name;
+
+ @cached
+ get initials() {
+ this.initialsEvaluatedCount++;
+ return this.name
+ ?.split(" ")
+ .map((n) => n[0])
+ .join("");
+ }
+ }
+
+ const pet = new Pet();
+ pet.name = "Scooby Doo";
+
+ assert.strictEqual(pet.initials, "SD", "Initials are correct");
+ assert.strictEqual(
+ pet.initialsEvaluatedCount,
+ 1,
+ "Initials getter evaluated once"
+ );
+
+ pet.name = "Scooby Doo";
+ assert.strictEqual(pet.initials, "SD", "Initials are correct");
+ assert.strictEqual(
+ pet.initialsEvaluatedCount,
+ 1,
+ "Initials getter not re-evaluated"
+ );
+
+ pet.name = "Fluffy";
+ assert.strictEqual(pet.initials, "F", "Initials are correct");
+ assert.strictEqual(
+ pet.initialsEvaluatedCount,
+ 2,
+ "Initials getter re-evaluated"
+ );
+ });
+});