Skip to content

Proposal: deepSignal listenable container #126

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

Closed
wants to merge 3 commits into from
Closed
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
73 changes: 73 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,3 +302,76 @@ export function batch<T>(cb: () => T): T {
}
}
}

type Signalable = Array<any> | ((...args: any[]) => any) | string | boolean | number | bigint | symbol | undefined | null;

export type Storeable = {
[key: string]: (() => any) | Signalable | Storeable
};

type ReadOnlyDeep<T> = {
readonly [P in keyof T]: ReadOnlyDeep<T[P]>;
}

export interface IDeepSignal<T extends Storeable> { value: ReadOnlyDeep<T>, peek: () => ReadOnlyDeep<T> }

export type DeepSignal<T extends Storeable> = IDeepSignal<T> & {
[K in keyof T]:
T[K] extends Signalable ? Signal<T[K]> :
T[K] extends Storeable ? DeepSignal<T[K]> :
Signal<T[K]>;
};

export class DeepSignalImpl<T extends Storeable> implements IDeepSignal<T> {
get value(): ReadOnlyDeep<T> {
return getValue(this as any as DeepSignal<T>);
}

set value(payload: ReadOnlyDeep<T>) {
batch(() => setValue(this as any as DeepSignal<T>, payload));
}

peek(): ReadOnlyDeep<T> {
return getValue(this as any as DeepSignal<T>, { peek: true });
}
}

export const deepSignal = <T extends Storeable>(initialValue: T): DeepSignal<T> =>
Object.assign(
new DeepSignalImpl(),
Object.entries(initialValue).reduce(
(acc, [key, value]) => {
if (["value", "peek"].some(iKey => iKey === key)) {
throw new Error(`${key} is a reserved property name`);
} else if (typeof value !== "object" || value === null || Array.isArray(value)) {
acc[key] = signal(value);
} else {
acc[key] = deepSignal(value);
}
return acc;
}, {} as { [key: string]: unknown })
) as DeepSignal<T>;

const setValue = <U extends Storeable, T extends DeepSignal<U>>(
deepSignal: T,
payload: U
): void =>
Object.keys(payload).forEach((key: keyof U) =>
deepSignal[key].value = payload[key]
);

const getValue = <U extends Storeable, T extends DeepSignal<U>>(
deepSignal: T,
{ peek = false }: { peek?: boolean } = {}
): ReadOnlyDeep<U> =>
Object.entries(deepSignal).reduce((
acc,
[key, value]
) => {
if (value instanceof Signal) {
acc[key] = peek ? value.peek() : value.value;
} else if (value instanceof DeepSignalImpl) {
acc[key] = getValue(value as DeepSignal<Storeable>, { peek });
}
return acc;
}, {} as { [key: string]: unknown }) as ReadOnlyDeep<U>;
36 changes: 34 additions & 2 deletions packages/core/test/signal.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { signal, computed, effect, batch } from "@preact/signals-core";
import { signal, computed, effect, batch, deepSignal, Signal } from "@preact/signals-core";

describe("signal", () => {
it("should return value", () => {
Expand Down Expand Up @@ -211,7 +211,6 @@ describe("computed()", () => {
const a = signal(2);

const b = computed(() => a.value - 1);
const c = computed(() => a.value + 1);

const d = computed(() => a.value + b.value);

Expand Down Expand Up @@ -682,3 +681,36 @@ describe("batch/transaction", () => {
expect(result).to.equal("aa bb cc");
});
});

describe("deepSignal", () => {
it("turns deeply nested atomic properties into Signals with peek and value", () => {
const a = deepSignal({
b: {
c: {
d: "a"
}
}
});
expect(a.b.c.d instanceof Signal).to.equal(true);
expect(a.value.b.c.d).to.equal("a");
expect(a.b.value.c.d).to.equal("a");
expect(a.b.c.value.d).to.equal("a");
expect(a.b.c.d.value).to.equal("a");
a.value = { b: { c: { d: "b" }} };
expect(a.peek().b.c.d).to.equal("b");
expect(a.b.peek().c.d).to.equal("b");
expect(a.b.c.peek().d).to.equal("b");
expect(a.b.c.d.peek()).to.equal("b");
a.b.c.d.value = "c"
expect(a.value.b.c.d).to.equal("c");
expect(a.b.value.c.d).to.equal("c");
expect(a.b.c.value.d).to.equal("c");
expect(a.b.c.d.value).to.equal("c");
});

it("doesn't allow you to set a property with keys named peek or value", () => {
expect(() => deepSignal({ value: "a" })).to.throw(/reserved property name/);
expect(() => deepSignal({ peek: "a" })).to.throw(/reserved property name/);
});

});
11 changes: 10 additions & 1 deletion packages/preact/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import {
batch,
effect,
Signal,
deepSignal,
DeepSignalImpl,
type IDeepSignal,
type DeepSignal,
type Storeable,
type ReadonlySignal,
} from "@preact/signals-core";
import {
Expand All @@ -17,7 +22,7 @@ import {
ElementUpdater,
} from "./internal";

export { signal, computed, batch, effect, Signal, type ReadonlySignal };
export { signal, computed, batch, effect, Signal, DeepSignalImpl, deepSignal, type ReadonlySignal, type Storeable, type IDeepSignal, type DeepSignal };

// Components that have a pending Signal update: (used to bypass default sCU:false)
const hasPendingUpdate = new WeakSet<Component>();
Expand Down Expand Up @@ -300,6 +305,10 @@ export function useComputed<T>(compute: () => T) {
return useMemo(() => computed<T>(() => $compute.current()), []);
}

export function useDeepSignal<T extends Storeable> (initial: T | (() => T)) {
return useMemo(() => deepSignal(typeof initial === "function" ? initial() : initial), []);
}

/**
* @todo Determine which Reactive implementation we'll be using.
* @internal
Expand Down
11 changes: 10 additions & 1 deletion packages/react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ import {
batch,
effect,
Signal,
deepSignal,
DeepSignalImpl,
type Storeable,
type IDeepSignal,
type DeepSignal,
type ReadonlySignal,
} from "@preact/signals-core";
import { Updater, ReactOwner, ReactDispatcher } from "./internal";

export { signal, computed, batch, effect, Signal, type ReadonlySignal };
export { signal, computed, batch, effect, Signal, DeepSignalImpl, deepSignal, type ReadonlySignal, type Storeable, type IDeepSignal, type DeepSignal };

/**
* Install a middleware into React.createElement to replace any Signals in props with their value.
Expand Down Expand Up @@ -151,3 +156,7 @@ export function useComputed<T>(compute: () => T) {
$compute.current = compute;
return useMemo(() => computed<T>(() => $compute.current()), []);
}

export function useDeepSignal<T extends Storeable> (initial: T | (() => T)) {
return useMemo(() => deepSignal(typeof initial === "function" ? initial() : initial), []);
}