From 9355d962b0d21b409b1661abcead799886e3cdb3 Mon Sep 17 00:00:00 2001 From: Jovi De Croock Date: Mon, 4 Sep 2023 10:46:24 +0200 Subject: [PATCH] feat(core): add unique identifier for signals (#405) * add unique identifier for signals * avoid name collision --- .changeset/wild-spies-glow.md | 5 +++++ mangle.json | 6 +++++- packages/core/src/index.ts | 6 ++++++ packages/core/test/signal.test.tsx | 10 ++++++++++ tsconfig.json | 2 +- 5 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 .changeset/wild-spies-glow.md diff --git a/.changeset/wild-spies-glow.md b/.changeset/wild-spies-glow.md new file mode 100644 index 000000000..d1e43efd5 --- /dev/null +++ b/.changeset/wild-spies-glow.md @@ -0,0 +1,5 @@ +--- +"@preact/signals-core": minor +--- + +Add unique identifier to every `Signal`, this will be present on the `type` property of a Signal coming from either `signal()` or `computed()` diff --git a/mangle.json b/mangle.json index 5c69d0411..9fbccc3fa 100644 --- a/mangle.json +++ b/mangle.json @@ -5,7 +5,11 @@ }, "minify": { "mangle": { - "reserved": ["useSignal", "useComputed", "useSignalEffect"], + "reserved": [ + "useSignal", + "useComputed", + "useSignalEffect" + ], "keep_classnames": true, "properties": { "regex": "^_[^_]", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 10a49efc5..965da128c 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,6 +5,8 @@ function mutationDetected(): never { throw new Error("Computed cannot have side-effects"); } +const identifier = Symbol.for('preact-signals') + // Flags for Computed and Effect. const RUNNING = 1 << 0; const NOTIFIED = 1 << 1; @@ -242,6 +244,8 @@ declare class Signal { peek(): T; + brand: typeof identifier; + get value(): T; set value(value: T); } @@ -255,6 +259,8 @@ function Signal(this: Signal, value?: unknown) { this._targets = undefined; } +Signal.prototype.brand = identifier + Signal.prototype._refresh = function () { return true; }; diff --git a/packages/core/test/signal.test.tsx b/packages/core/test/signal.test.tsx index b467c8583..38698806b 100644 --- a/packages/core/test/signal.test.tsx +++ b/packages/core/test/signal.test.tsx @@ -164,6 +164,16 @@ describe("signal", () => { expect(spy).not.to.be.called; }); }); + + it("signals should be identified with a symbol", () => { + const a = signal(0); + expect(a.brand).to.equal(Symbol.for('preact-signals')) + }) + + it("should be identified with a symbol", () => { + const a = computed(() => {}); + expect(a.brand).to.equal(Symbol.for('preact-signals')) + }) }); describe("effect()", () => { diff --git a/tsconfig.json b/tsconfig.json index abc542352..9843714d6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "target": "ES2020", - "lib": ["ES2021.WeakRef"], + "lib": ["ES2021.WeakRef", "ES2015.Symbol"], "moduleResolution": "node", "esModuleInterop": true, "strict": true,