-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathsignals.ts
More file actions
81 lines (62 loc) · 1.56 KB
/
signals.ts
File metadata and controls
81 lines (62 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// signals.ts
type Subscriber = () => void;
export interface Signal<T> {
_get(): T;
_subs: Set<Subscriber>;
set(value: T): void;
subscribe(fn: Subscriber): () => void;
}
export type GetFunction = <T>(sig: Signal<T>) => T;
export function signal<T>(initialValue: T): Signal<T> {
let value = initialValue;
const subscribers = new Set<Subscriber>();
function _get(): T {
return value;
}
function set(newValue: T): void {
if (newValue !== value) {
value = newValue;
for (const fn of subscribers) {
if (isBatching) {
batchQueue.add(fn);
} else {
fn();
}
}
}
}
function subscribe(fn: Subscriber): () => void {
subscribers.add(fn);
return () => subscribers.delete(fn);
}
return { _get, _subs: subscribers, set, subscribe };
}
// computed
export function computed<T>(fn: (get: GetFunction) => T) {
const s = signal<T>(undefined as unknown as T);
const cleanupFns = new Set<() => void>();
const run = (): void => {
s.set(fn(get));
};
const get: GetFunction = (signal) => {
signal._subs.add(run);
cleanupFns.add(() => signal._subs.delete(run));
return signal._get();
};
run();
return s;
}
// Batching system
let isBatching = false;
const batchQueue = new Set<Subscriber>();
function flushBatch(): void {
const queue = Array.from(batchQueue);
batchQueue.clear();
isBatching = false;
for (const fn of queue) fn();
}
export function batch(fn: (get: GetFunction) => void): void {
isBatching = true;
fn((sig) => sig._get());
flushBatch();
}