Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add watched and unwatched #634

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/tough-rice-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@preact/signals-core": minor
"@preact/signals": minor
"@preact/signals-react": minor
---

Add an option to specify a watched/unwatched callback to a signal
2 changes: 2 additions & 0 deletions mangle.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
"cname": 6,
"props": {
"core: Node": "",
"$_watched": "W",
"$_unwatched": "Z",
"$_source": "S",
"$_prevSource": "p",
"$_nextSource": "n",
Expand Down
55 changes: 41 additions & 14 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ declare class Signal<T = any> {
/** @internal */
_targets?: Node;

constructor(value?: T);
constructor(value?: T, options?: SignalOptions<T>);

/** @internal */
_refresh(): boolean;
Expand All @@ -250,6 +250,12 @@ declare class Signal<T = any> {
/** @internal */
_unsubscribe(node: Node): void;

/** @internal */
_watched?(this: Signal<T>): void;

/** @internal */
_unwatched?(this: Signal<T>): void;

subscribe(fn: (value: T) => void): () => void;

valueOf(): T;
Expand All @@ -266,6 +272,11 @@ declare class Signal<T = any> {
set value(value: T);
}

export interface SignalOptions<T = any> {
watched: (this: Signal<T>) => void;
unwatched: (this: Signal<T>) => void;
}

/** @internal */
// @ts-ignore: "Cannot redeclare exported variable 'Signal'."
//
Expand All @@ -274,11 +285,13 @@ declare class Signal<T = any> {
//
// The previously declared class is implemented here with ES5-style prototypes.
// This enables better control of the transpiled output size.
function Signal(this: Signal, value?: unknown) {
function Signal(this: Signal, value?: unknown, options?: SignalOptions) {
this._value = value;
this._version = 0;
this._node = undefined;
this._targets = undefined;
this._watched = options?.watched;
this._unwatched = options?.unwatched;
}

Signal.prototype.brand = BRAND_SYMBOL;
Expand All @@ -288,12 +301,16 @@ Signal.prototype._refresh = function () {
};

Signal.prototype._subscribe = function (node) {
if (this._targets !== node && node._prevTarget === undefined) {
node._nextTarget = this._targets;
if (this._targets !== undefined) {
this._targets._prevTarget = node;
}
const targets = this._targets;
if (targets !== node && node._prevTarget === undefined) {
node._nextTarget = targets;
this._targets = node;

if (targets !== undefined) {
targets._prevTarget = node;
} else if (this._watched !== undefined) {
this._watched();
}
}
};

Expand All @@ -306,12 +323,17 @@ Signal.prototype._unsubscribe = function (node) {
prev._nextTarget = next;
node._prevTarget = undefined;
}

if (next !== undefined) {
next._prevTarget = prev;
node._nextTarget = undefined;
}

if (node === this._targets) {
this._targets = next;
if (next === undefined && this._unwatched !== undefined) {
this._unwatched();
}
}
}
};
Expand Down Expand Up @@ -392,10 +414,10 @@ Object.defineProperty(Signal.prototype, "value", {
* @param value The initial value for the signal.
* @returns A new signal.
*/
export function signal<T>(value: T): Signal<T>;
export function signal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function signal<T = undefined>(): Signal<T | undefined>;
export function signal<T>(value?: T): Signal<T> {
return new Signal(value);
export function signal<T>(value?: T, options?: SignalOptions<T>): Signal<T> {
return new Signal(value, options);
}

function needsToRecompute(target: Computed | Effect): boolean {
Expand Down Expand Up @@ -515,19 +537,21 @@ declare class Computed<T = any> extends Signal<T> {
_globalVersion: number;
_flags: number;

constructor(fn: () => T);
constructor(fn: () => T, options?: SignalOptions<T>);

_notify(): void;
get value(): T;
}

function Computed(this: Computed, fn: () => unknown) {
function Computed(this: Computed, fn: () => unknown, options?: SignalOptions) {
Signal.call(this, undefined);

this._fn = fn;
this._sources = undefined;
this._globalVersion = globalVersion - 1;
this._flags = OUTDATED;
this._watched = options?.watched;
this._unwatched = options?.unwatched;
}

Computed.prototype = new Signal() as Computed;
Expand Down Expand Up @@ -677,8 +701,11 @@ interface ReadonlySignal<T = any> {
* @param fn The effect callback.
* @returns A new read-only signal.
*/
function computed<T>(fn: () => T): ReadonlySignal<T> {
return new Computed(fn);
function computed<T>(
fn: () => T,
options?: SignalOptions<T>
): ReadonlySignal<T> {
return new Computed(fn, options);
}

function cleanupEffect(effect: Effect) {
Expand Down
47 changes: 47 additions & 0 deletions packages/core/test/signal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,22 @@ describe("signal", () => {
});
});

describe(".(un)watched()", () => {
it("should call watched when first subscription occurs", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = signal(1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
unsubscribe();
unsubscribe2();
expect(unwatched).to.be.calledOnce;
});
});

it("signals should be identified with a symbol", () => {
const a = signal(0);
expect(a.brand).to.equal(Symbol.for("preact-signals"));
Expand Down Expand Up @@ -1064,6 +1080,37 @@ describe("computed()", () => {
expect(spy).not.to.be.called;
});

describe(".(un)watched()", () => {
it("should call watched when first subscription occurs", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = computed(() => 1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledOnce;
unsubscribe();
unsubscribe2();
expect(unwatched).to.be.calledOnce;
});

it("should call watched when first subscription occurs w/ nested signal", () => {
const watched = sinon.spy();
const unwatched = sinon.spy();
const s = signal(1, { watched, unwatched });
const c = computed(() => s.value + 1, { watched, unwatched });
expect(watched).to.not.be.called;
const unsubscribe = c.subscribe(() => {});
expect(watched).to.be.calledTwice;
const unsubscribe2 = s.subscribe(() => {});
expect(watched).to.be.calledTwice;
unsubscribe2();
unsubscribe();
expect(unwatched).to.be.calledTwice;
});
});

it("should consider undefined value separate from uninitialized value", () => {
const a = signal(0);
const spy = sinon.spy(() => undefined);
Expand Down
14 changes: 9 additions & 5 deletions packages/preact/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Signal,
type ReadonlySignal,
untracked,
SignalOptions,
} from "@preact/signals-core";
import {
VNode,
Expand Down Expand Up @@ -362,17 +363,20 @@ Component.prototype.shouldComponentUpdate = function (
return false;
};

export function useSignal<T>(value: T): Signal<T>;
export function useSignal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function useSignal<T = undefined>(): Signal<T | undefined>;
export function useSignal<T>(value?: T) {
return useMemo(() => signal<T | undefined>(value), []);
export function useSignal<T>(value?: T, options?: SignalOptions<T>) {
return useMemo(
() => signal<T | undefined>(value, options as SignalOptions),
[]
);
}

export function useComputed<T>(compute: () => T) {
export function useComputed<T>(compute: () => T, options?: SignalOptions<T>) {
const $compute = useRef(compute);
$compute.current = compute;
(currentComponent as AugmentedComponent)._updateFlags |= HAS_COMPUTEDS;
return useMemo(() => computed<T>(() => $compute.current()), []);
return useMemo(() => computed<T>(() => $compute.current(), options), []);
}

let oldNotify: (this: Effect) => void,
Expand Down
17 changes: 12 additions & 5 deletions packages/react/runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
effect,
Signal,
ReadonlySignal,
SignalOptions,
} from "@preact/signals-core";
import {
useRef,
Expand Down Expand Up @@ -384,16 +385,22 @@ export function useSignals(usage?: EffectStoreUsage): EffectStore {
return _useSignalsImplementation(usage);
}

export function useSignal<T>(value: T): Signal<T>;
export function useSignal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function useSignal<T = undefined>(): Signal<T | undefined>;
export function useSignal<T>(value?: T) {
return useMemo(() => signal<T | undefined>(value), Empty);
export function useSignal<T>(value?: T, options?: SignalOptions<T>) {
return useMemo(
() => signal<T | undefined>(value, options as SignalOptions),
Empty
);
}

export function useComputed<T>(compute: () => T): ReadonlySignal<T> {
export function useComputed<T>(
compute: () => T,
options?: SignalOptions<T>
): ReadonlySignal<T> {
const $compute = useRef(compute);
$compute.current = compute;
return useMemo(() => computed<T>(() => $compute.current()), Empty);
return useMemo(() => computed<T>(() => $compute.current(), options), Empty);
}

export function useSignalEffect(cb: () => void | (() => void)) {
Expand Down
Loading