-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsignal.ts
319 lines (284 loc) · 7.22 KB
/
signal.ts
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// A signal implementation designed specifically for animations.
import type { Action } from "./action.js"
import { linear, type Easer, type Interpolator } from "./animation.js"
let currentEffect: (() => void) | undefined
let currentTrackedSet: Set<Set<() => void>> | undefined
let currentBatch: Set<() => void> | undefined
/**
* Runs an effect. Whenever any signals accessed in the effect change, the
* effect is re-run.
*
* @param effect - The effect to run.
* @returns A function that unsubscribes from all tracked signals.
*
* @example
* ```ts
* const [name, setName] = signal("Alice")
*
* // Logs "Hello, Alice" because the effect runs once.
* effect(() => {
* console.log(`Hello, ${name()}`)
* })
*
* name() // "Alice"
*
* // Logs "Hello, Bob" because the `name` signal has changed.
* setName("Bob")
*
* // Logs "Hello, Charlie".
* setName("Charlie")
*
* name() // "Charlie"
* ```
*/
export function effect(effect: () => void) {
const tracked = new Set<Set<() => void>>()
function effectFn() {
const parentEffect = currentEffect
const parentTrackedSet = currentTrackedSet
try {
currentEffect = effectFn
currentTrackedSet = tracked
effect()
} finally {
currentEffect = parentEffect
currentTrackedSet = parentTrackedSet
}
}
effectFn()
return () => tracked.forEach((set) => set.delete(effectFn))
}
function signalCore<T>(
value: T,
): [getUntracked: () => T, get: () => T, set: (value: T) => void] {
const tracked = new Set<() => void>()
return [
() => value,
() => {
if (currentEffect) {
tracked.add(currentEffect)
}
currentTrackedSet?.add(tracked)
return value
},
(newValue) => {
value = newValue
if (currentBatch) {
tracked.forEach((fn) => currentBatch!.add(fn))
} else {
tracked.forEach((fn) => fn())
}
},
]
}
export type SignalLike<T> = T | (() => T)
export type Signal<I, O = I> = {
/**
* Gets the current value of this signal.
*
* @returns The current value of this signal.
*/
(): O
/**
* Sets the current value of this signal.
*
* @param value - The value to set the signal to.
*/
(value: I | (() => I)): void
/**
* Animates the current value over a given number of frames.
*
* @param value - The value to animate to.
* @param frames - The number of frames to animate over.
* @param easer - A timing function that accepts a number from 0 to 1 and returns another number.
* @param interpolator - A function that interpolates between the start and end points.
*
* @returns An action that must be consumed to animate the signal.
*/
(
value: I,
frames: number,
easer?: Easer,
interpolator?: Interpolator<O>,
): AnimationAction<O>
}
export function isSignal<T>(value: SignalLike<T>): value is () => T
export function isSignal<T>(value: SignalLike<T>): boolean {
return typeof value == "function"
}
function noop() {}
export type AnimationAction<T> = Action & {
to(
value: T,
frames: number,
easer: Easer | undefined,
interpolator: Interpolator<T>,
): AnimationAction<T>
}
/**
* Creates a signal that tracks when it's accessed and runs effect that depend
* on it when the signal's value changes.
*
* @param initialValue - The initial value of the signal.
* @returns A tuple containing a getter and setter for the current value.
*
* @example
* ```ts
* const [name, setName] = signal("Alice")
*
* // Logs "Hello, Alice" because the effect runs once.
* effect(() => {
* console.log(Hello, ${name()})
* })
*
* name() // "Alice"
*
* // Logs "Hello, Bob" because the `name` signal has changed.
* setName("Bob")
*
* // Logs "Hello, Charlie".
* setName("Charlie")
*
* name() // "Charlie"
* ```
*/
export function signal<T>(
initialValue: SignalLike<T>,
defaultInterpolator: Interpolator<T> = linear as any,
): Signal<T> {
const [getUntracked, get, set] = signalCore<T>(
isSignal(initialValue) ? untrack(initialValue) : initialValue,
)
let unsub = isSignal(initialValue) ? effect(() => set(initialValue())) : noop
function signalFn(
value?: SignalLike<T>,
frames?: number,
easer?: Easer,
interpolator?: Interpolator<T>,
) {
if (value === void 0) {
return get()
}
if (frames === void 0) {
unsub()
unsub = isSignal(value) ? effect(() => set(value())) : (set(value), noop)
return
}
return toAnimationAction(
animate(
isSignal(value) ? untrack(value) : value,
frames,
easer,
interpolator,
),
)
}
function* animate(
end: T,
frames: number,
easer: Easer = linear,
interpolator: Interpolator<T> = defaultInterpolator,
): Action {
const start = getUntracked()
set(interpolator(easer(0), start, end))
for (let frame = 1; frame <= frames; frame++) {
yield
set(interpolator(easer(frame / frames), start, end))
}
set(end)
}
function toAnimationAction(action: Action): AnimationAction<T> {
const output = action as AnimationAction<T>
output.to = (...args) =>
toAnimationAction(
(function* (): Action {
yield* output
yield* animate(...args)
})(),
)
return output
}
return signalFn as Signal<T>
}
/**
* Calls a function that accesses signals without tracking the associated
* signals in an effect.
*
* @param get A function that accesses signals and gets a value.
* @returns The value returned from {@link get `get`}.
*
* @example
* ```ts
* const [name, setName] = signal("Dave")
* const [age, setAge] = signal(27)
*
* // Logs "Dave is 27"
* // Only `name` is tracked, not `age`
* effect(() => {
* console.log(`${name()} is ${untrack(age)}`)
* })
*
* // Logs "Eamon is 27"
* setName("Eamon")
*
* // The effect isn't re-run because `age` was in `untrack`
* setAge(42)
*
* // 42, because the signal still changes its value.
* age()
*
* // Logs "Frida is 42"
* setName("Frida")
* ```
*/
export function untrack<T>(get: (() => T) | Signal<T>): T {
const parentEffect = currentEffect
const parentTrackedSet = currentTrackedSet
try {
currentEffect = currentTrackedSet = undefined
return get()
} finally {
currentEffect = parentEffect
currentTrackedSet = parentTrackedSet
}
}
/**
* Allows multiple signals to be modified while only triggering one re-run of
* dependent effects.
*
* @param get A function that modifies signals and (optionally) returns a value.
* @returns The value returned from {@link get `get`}.
*
* @example
* ```ts
* const [first, setFirst] = signal("Alice")
* const [last, setLast] = signal("Xavier")
*
* // Logs "Alice Xavier"
* effect(() => {
* console.log(`Hello, ${first()} ${last}`)
* })
*
* // Logs "Bob Xavier", then "Bob Young" because
* // each `set...` call triggers the effect.
* setFirst("Bob")
* setLast("Young")
*
* // Logs "Charlie Zagata" because `batch`
* // batches the updates.
* batch(() => {
* setFirst("Charlie")
* setLast("Zagata")
* })
* ```
*/
export function batch<T>(get: () => T): T {
const parentBatch = currentBatch
const batch = (currentBatch = new Set())
try {
return get()
} finally {
currentBatch = parentBatch
batch.forEach((fn) => fn())
}
}