uneventful 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,470 @@
1
+ import { A as AnyFunction, D as DisposeFn, O as OptionalCleanup, L as SignalSource, Y as Yielding, S as Source, P as PlainFunction, a as Stream } from './types-N2ua11te.js';
2
+ import { U as UntilMethod } from './sinks-kEzJo6Hc.js';
3
+
4
+ /**
5
+ * A decorator function that supports both TC39 and "legacy" decorator protocols
6
+ *
7
+ * @template F the type of method this decorator can decorate. If the method
8
+ * doesn't conform to this type, compile-time type checks will fail.
9
+ *
10
+ * @category Types and Interfaces
11
+ */
12
+ type GenericMethodDecorator<F extends AnyFunction> = {
13
+ /** TC39 Method Decorator @hidden */
14
+ (fn: F, ctx?: {
15
+ kind: "method";
16
+ }): F;
17
+ /** Legacy Method Decorator @hidden */
18
+ (proto: object, name: string | symbol, desc?: {
19
+ value?: F;
20
+ }): void;
21
+ };
22
+ /**
23
+ * The interface provided by {@link rule}, and other {@link rule.factory}()
24
+ * functions.
25
+ *
26
+ * @category Types and Interfaces
27
+ */
28
+ interface RuleFactory {
29
+ /**
30
+ * @inheritdoc rule factory tied to a specific scheduler. See {@link rule} for
31
+ * more details.
32
+ */
33
+ (fn: (stop: DisposeFn) => OptionalCleanup): DisposeFn;
34
+ /**
35
+ * A function that will stop the currently-executing rule. (Accessing this
36
+ * attribute will throw an error if no rule is currently running.)
37
+ *
38
+ * Note: this returns the stop for the current rule regardless of its
39
+ * scheduler, so you can access `rule.stop` even if the rule was created
40
+ * with a different scheduler.
41
+ */
42
+ readonly stop: DisposeFn;
43
+ /**
44
+ * Observe a condition and apply an action.
45
+ *
46
+ * For a given {@link RuleFactory} `r` (such as `rule`), `r.if(condition,
47
+ * action)` is roughly equivalent to `r(() => { if (condition()) return
48
+ * action(); })`, except that the rule is *only* rerun if the `action`'s
49
+ * dependencies change, *or* the **truthiness** of `condition()` changes. It
50
+ * will *not* be re-run if only the dependencies of `condition()` have
51
+ * changed, without affecting its truthiness.
52
+ *
53
+ * This behavior can be important for rules that nest other rules, have
54
+ * cleanups, fire off tasks, etc., as it may be wasteful to constantly tear
55
+ * them down and set them back up if the enabling condition is a calculation
56
+ * with frequently-changing dependencies.
57
+ *
58
+ * @remarks This is just a shortcut for wrapping `condition` as a signal
59
+ * that converts it to boolean. So if you already *have* a boolean signal,
60
+ * you can get the same effect with just `if (condition()) { ... }`.
61
+ */
62
+ if(condition: () => any, action: () => OptionalCleanup): DisposeFn;
63
+ /**
64
+ * Decorate a method or function to behave as a rule, e.g.
65
+ *
66
+ * ```ts
67
+ * const animate = rule.factory(requestAnimationFrame);
68
+ *
69
+ * class Draggable {
70
+ * ⁣@animate.method
71
+ * trackPosition(handleTop: number, handleLeft: number) {
72
+ * const {clientX, clientY} = lastMouseEvent();
73
+ * this.element.style.top = `${clientY - handleTop}px`;
74
+ * this.element.style.left = `${clientX - handleLeft}px`;
75
+ * }
76
+ * }
77
+ *
78
+ * // Start running the method in an animation frame for every change to
79
+ * // lastMouseEvent, until the current job ends:
80
+ * someDraggable.trackPosition(top, left);
81
+ * ```
82
+ * or:
83
+ * ```ts
84
+ * const logger = rule.method((formatString, signal) => { log(formatString, signal()); });
85
+ * ```
86
+ *
87
+ * Each time it's (explicitly) called, the decorated method will start a new
88
+ * rule, which will repeatedly run the method body (with the original
89
+ * arguments and `this`) whenever its dependencies change, according to the
90
+ * schedule defined by the rule factory. (So e.g. `@rule.method` will
91
+ * update on the microtask after a change, etc.)
92
+ *
93
+ * The decorated method will always return a {@link DisposeFn} to let you
94
+ * explicitly stop the rule before the current job end. But if the original
95
+ * method body doesn't return a dispose function of its own, TypeScript will
96
+ * consider the method to return void, unless you explicitly declare its
97
+ * return type to be `DisposeFn | void`.
98
+ *
99
+ * Also note that since rule methods can accept arbitrary parameters, they
100
+ * do not receive a `stop` parameter, and must therefore use {@link
101
+ * RuleFactory.stop rule.stop}() if they wish to terminate themselves.
102
+ */
103
+ readonly method: GenericMethodDecorator<(...args: any[]) => OptionalCleanup>;
104
+ /**
105
+ * Return a rule factory for the given scheduling function, that you can
106
+ * then use to make rules that run in a specific time frame.
107
+ *
108
+ * ```ts
109
+ * // `animate` will now create rules that run during animation fames
110
+ * const animate = rule.factory(requestAnimationFrame);
111
+ *
112
+ * animate(() => {
113
+ * // ... do stuff in an animation frame when signals used here change
114
+ * })
115
+ * ```
116
+ *
117
+ * (In addition to being callable, the returned function is also a
118
+ * {@link RuleFactory}, and thus has a `.method` decorator, `.if()` method,
119
+ * and so on.)
120
+ *
121
+ * @param scheduleFn A single-argument scheduling function (such as
122
+ * requestAnimationFrame, setImmediate, or queueMicrotask). The rule
123
+ * scheduler will call it from time to time with a single callback. The
124
+ * scheduling function should then arrange for that callback to be invoked
125
+ * *once* at some future point, when it is the desired time for all pending
126
+ * rules on that scheduler to run.
127
+ *
128
+ * @returns A {@link RuleFactory}, like {@link rule}. If called with the
129
+ * same scheduling function more than once, it returns the same factory.
130
+ *
131
+ */
132
+ factory(scheduleFn: SchedulerFn): RuleFactory;
133
+ /**
134
+ * Create a "detached" or standalone rule, that is not attached to any job.
135
+ *
136
+ * `r.detached(fn)` is shorthand for calling `detached.run(r, fn)`. (Where
137
+ * `r` is a {@link RuleFactory} such as `rule`.)
138
+ *
139
+ * Note that since the created rule isn't attached to a job, it *must* be
140
+ * explicitly stopped, either by calling the returned disposal function or
141
+ * by the rule function arranging to stop itself via {@link rule.stop}() or
142
+ * its stop parameter.
143
+ */
144
+ detached(fn: (stop: DisposeFn) => OptionalCleanup): DisposeFn;
145
+ /**
146
+ * Change the scheduler used for the currently-executing rule. Throws an
147
+ * error if no rule is running.
148
+ *
149
+ * @param scheduleFn Optional: The {@link SchedulerFn scheduling function}
150
+ * to use; the default microtask scheduler will be used if none is given or
151
+ * the given value is falsy.
152
+ *
153
+ * @remarks It's best to only use scheduling functions that were created
154
+ * *outside* the current rule, otherwise you'll be creating a new scheduling
155
+ * queue object on every run of the rule. (These will get garbage collected
156
+ * with the scheduling functions, but you'll be creating more memory
157
+ * pressure and using more GC time if the rule runs frequently.)
158
+ */
159
+ setScheduler(scheduleFn?: SchedulerFn): void;
160
+ }
161
+ /**
162
+ * Subscribe a function to run every time certain values change.
163
+ *
164
+ * The function is run asynchronously, first after being created, then again
165
+ * after there are changes in any of the values or cached functions it read
166
+ * during its previous run.
167
+ *
168
+ * The created subscription is tied to the currently-active job (which may be
169
+ * another rule). So when that job is ended or restarted, the rule will be
170
+ * terminated automatically. You can also terminate it early by calling the
171
+ * "stop" function that is both passed to the rule function and returned by
172
+ * `rule()`.
173
+ *
174
+ * Note: this function will throw an error if called without an active job. If
175
+ * you need a standalone rule, use {@link RuleFactory.detached rule.detached}().
176
+ *
177
+ * @param fn The function that will be run each time its dependencies change.
178
+ * The function will be run in a restarted job each time, with any resources
179
+ * used by the previous run being cleaned up. The function is passed a single
180
+ * argument: a function that can be called to terminate the rule. The function
181
+ * should return a cleanup function or void.
182
+ *
183
+ * @returns A function that can be called to terminate the rule.
184
+ *
185
+ * @category Signals
186
+ */
187
+ declare const rule: ((action: (stop: DisposeFn) => OptionalCleanup) => DisposeFn) & RuleFactory;
188
+ /**
189
+ * Synchronously run any pending rules tied to a specific schedule.
190
+ *
191
+ * (Note: "pending" rules are ones with at least one changed ancestor
192
+ * dependency; this doesn't mean they will actually *do* anything, since
193
+ * intermediate cached() function results might end up unchanged.)
194
+ *
195
+ * You should normally only need to call this when you need to *force*
196
+ * side-effects to occur within a specific *synchronous* timeframe, e.g. if
197
+ * rules need to be able to cancel a synchronous event or continue an IndexedDB
198
+ * transaction. (Otherwise, this is really only useful for testing.)
199
+ *
200
+ * @param scheduleFn The {@link SchedulerFn scheduler} used to create the rule
201
+ * factory you wish to run pending rules for. If not given, the default
202
+ * {@link rule}() factory is targeted.
203
+ *
204
+ * @category Signals
205
+ */
206
+ declare function runRules(scheduleFn?: SchedulerFn): void;
207
+ /**
208
+ * A single-argument scheduling function (such as requestAnimationFrame,
209
+ * setImmediate, or queueMicrotask). The rule scheduler will call it from time
210
+ * to time with a single callback. The scheduling function should then arrange
211
+ * for that callback to be invoked *once* at some future point, when it is the
212
+ * desired time for all pending rules on that scheduler to run.
213
+ *
214
+ * @category Types and Interfaces
215
+ */
216
+ type SchedulerFn = (cb: () => unknown) => unknown;
217
+
218
+ /**
219
+ * Error indicating a rule has attempted to write a value it indirectly
220
+ * depends on, or which has already been read by another rule in the current
221
+ * batch. (Also thrown when a cached function attempts to write a value at all,
222
+ * directly or indirectly.)
223
+ *
224
+ * @category Errors
225
+ */
226
+ declare class WriteConflict extends Error {
227
+ }
228
+ /**
229
+ * Error indicating a rule has attempted to write a value it directly depends
230
+ * on, or a cached function has called itself, directly or indirectly.
231
+ *
232
+ * @category Errors
233
+ */
234
+ declare class CircularDependency extends Error {
235
+ }
236
+
237
+ /**
238
+ * The Signals API for uneventful.
239
+ *
240
+ * @module uneventful/signals
241
+ */
242
+
243
+ /**
244
+ * An observable value, as a zero-argument callable with extra methods.
245
+ *
246
+ * In addition to being callable, signals also offer a `.value` getter, and
247
+ * implement the standard JS methods `.toString()`, `.valueOf()`, and
248
+ * `.toJSON()` in such a way that they reflect the signal's contents rather than
249
+ * the signal itself.
250
+ *
251
+ * Signals also implement the {@link Source} interface, and can thus be
252
+ * subscribed to. Subscribers receive the current value first, and then any
253
+ * changes thereafter. They can be waited on by {@link until}(), in which case
254
+ * the calling job resumes when the signal's value is truthy.
255
+ *
256
+ * You can also transform a signal to a {@link Writable} by calling its
257
+ * .{@link Signal.withSet withSet}() method, or create a writable value using
258
+ * {@link value}().
259
+ *
260
+ * @category Types and Interfaces
261
+ */
262
+ interface Signal<T> extends SignalSource<T>, UntilMethod<T> {
263
+ /**
264
+ * The current value
265
+ *
266
+ * @category Reading
267
+ */
268
+ readonly value: T;
269
+ /** Current value @hidden */
270
+ valueOf(): T;
271
+ /** Current value as a string @hidden */
272
+ toString(): string;
273
+ /** The current value @hidden */
274
+ toJSON(): T;
275
+ /**
276
+ * Get the signal's current value, without adding the signal as a dependency
277
+ *
278
+ * (This is exactly equivalent to calling {@link peek}(signal), and exists
279
+ * here mainly for interop with other signal frameworks.)
280
+ *
281
+ * @category Reading */
282
+ peek(): T;
283
+ /** Get a read-only version of this signal @category Reading */
284
+ asReadonly(): Signal<T>;
285
+ /** New writable signal with a custom setter @category Writing */
286
+ withSet(set: (v: T) => unknown): Writable<T>;
287
+ /** @hidden */
288
+ "uneventful.until"(): Yielding<T>;
289
+ }
290
+ /**
291
+ * A {@link Signal} with a {@link Writable.set | .set()} method and writable
292
+ * {@link Writable.value | .value} property.
293
+ *
294
+ * @category Types and Interfaces
295
+ */
296
+ interface Writable<T> extends Signal<T> {
297
+ /**
298
+ * Set the current value. (Note: this is a bound method so it can be used
299
+ * as a callback.)
300
+ *
301
+ * @category Writing
302
+ */
303
+ readonly set: (val: T) => void;
304
+ get value(): T;
305
+ /** Set the current value */
306
+ set value(val: T);
307
+ }
308
+ /**
309
+ * A writable signal that can be set to either a value or an expression.
310
+ *
311
+ * Like a spreadsheet cell, a configurable signal can contain either a value or
312
+ * a formula. If you .set() a value or change the .value property of the
313
+ * signal, the formula is cleared. Conversely, if you set a formula with
314
+ * .setf(), then the value is calculated using that formula from then on, until
315
+ * another formula is set, or the value is changed directly again.
316
+ *
317
+ * @category Types and Interfaces
318
+ */
319
+ interface Configurable<T> extends Writable<T> {
320
+ /**
321
+ * Set a formula that will be used to calculate the signal's value. If it
322
+ * uses the value of other signals, this signal's value will be recalculated
323
+ * when they change.
324
+ *
325
+ * @category Writing
326
+ */
327
+ setf(expr: () => T): this;
328
+ }
329
+ /**
330
+ * Create a {@link Configurable} signal with the given inital value
331
+ *
332
+ * @category Signals
333
+ */
334
+ declare function value<T>(val?: T): Configurable<T>;
335
+ /**
336
+ * Create a cached version of a function. The returned callable is also a
337
+ * {@link Signal}.
338
+ *
339
+ * Note: If the supplied function has a non-zero `.length` (i.e., it explicitly
340
+ * takes arguments), it is assumed to be a {@link Source}, and the second
341
+ * calling signature below will apply, even if TypeScript doesn't see it that
342
+ * way!)
343
+ *
344
+ * @category Signals
345
+ */
346
+ declare function cached<T>(compute: () => T): Signal<T>;
347
+ /**
348
+ * If the supplied function has a non-zero `.length` (i.e., it explicitly takes
349
+ * arguments), it is assumed to be a {@link Source}, and the second argument is
350
+ * a default value for the created signal to use as default value until the
351
+ * source produces a value.
352
+ *
353
+ * The source will be subscribed *only* while the signal is subscribed as a
354
+ * stream, or observed (directly or indirectly) by a rule. While subscribed,
355
+ * the signal will update itself with the most recent value produced by the
356
+ * source, triggering rules or events as appropriate if the value changes. When
357
+ * the signal is once again unobserved (or if the source ends without an error),
358
+ * its value will revert to the supplied default.
359
+ *
360
+ * If the source ends *with* an error, however, then the cached function will
361
+ * throw that error whenever called, until/unless it becomes unobserved again.
362
+ * (And thus reverts to the default value once more.)
363
+ *
364
+ * @param source A {@link Source} providing data which will become this signal's
365
+ * value
366
+ * @param defaultVal The value to use when the signal is unobserved or waiting for
367
+ * the first item from the source.
368
+ */
369
+ declare function cached<T>(source: Source<T>, defaultVal?: T): Signal<T>;
370
+ declare function cached<T extends Signal<any>>(signal: T): T;
371
+ /**
372
+ * Call a function without creating a dependency on any signals it reads. (Like
373
+ * {@link Signal.peek}, but for any function with any arguments.)
374
+ *
375
+ * You can also pass in any arguments the function takes, and the function's
376
+ * return value is returned.
377
+ *
378
+ * (Note: Typed overloads are not supported: TypeScript will use the function's
379
+ * *last* overload for argument-typing purposes. If you need to call a function
380
+ * with a specific overload, wrap the function with {@link action}() instead, and
381
+ * then TypeScript will be able to detect which overload you're using.)
382
+ *
383
+ * @returns The result of calling `fn(..args)`
384
+ *
385
+ * @category Signals
386
+ */
387
+ declare function peek<F extends PlainFunction>(fn: F, ...args: Parameters<F>): ReturnType<F>;
388
+ /**
389
+ * Wrap a function (or decorate a method) so that signals it reads are not added
390
+ * as dependencies to the current rule (if any). (Basically, it's shorthand for
391
+ * wrapping the function or method body in a giant call to {@link peek}().)
392
+ *
393
+ * So, instead of writing an action function like this:
394
+ *
395
+ * ```ts
396
+ * function outer(arg1, arg2) {
397
+ * return peek(() => {
398
+ * // reactive values used here will not be added to the running rule
399
+ * })
400
+ * }
401
+ * ```
402
+ * you can just write this:
403
+ * ```ts
404
+ * const outer = action((arg1, arg2) => {
405
+ * // reactive values used here will not be added to the running rule
406
+ * });
407
+ * ```
408
+ * or this:
409
+ * ```ts
410
+ * class Something {
411
+ * ⁣⁣@action // auto-detects TC39 or legacy decorators
412
+ * someMethod(arg1) {
413
+ * // reactive values used here will not be added to the running rule
414
+ * }
415
+ * }
416
+ * ```
417
+ *
418
+ * @param fn The function to wrap. It can take any arguments or return value,
419
+ * and overloads are supported. However, any non-standard properties the
420
+ * function may have had will *not* be present on the wrapped function, even if
421
+ * TypeScript will act as if they are!
422
+ *
423
+ * @returns A wrapped version of the function that passes through its arguments
424
+ * to the original function, while running with dependency tracking suppressed
425
+ * (as with {@link peek}()).
426
+ *
427
+ * @category Signals
428
+ */
429
+ declare function action<F extends AnyFunction>(fn: F): F;
430
+ /** @hidden TC39 Decorator protocol */
431
+ declare function action<F extends AnyFunction>(fn: F, ctx: {
432
+ kind: "method";
433
+ }): F;
434
+ /** @hidden Legacy Decorator protocol */
435
+ declare function action<F extends AnyFunction, D extends {
436
+ value?: F;
437
+ }>(clsOrProto: any, name: string | symbol, desc: D): D;
438
+ /**
439
+ * Wait for and return the next truthy value (or error) from a data source (when
440
+ * processed with `yield *` within a {@link Job}).
441
+ *
442
+ * This differs from {@link next}() in that it waits for the next "truthy" value
443
+ * (i.e., not null, false, zero, empty string, etc.), and when used with signals
444
+ * or a signal-using function, it can resume *immediately* if the result is
445
+ * already truthy. (It also supports zero-argument signal-using functions,
446
+ * automatically wrapping them with {@link cached}(), as the common use case for
447
+ * until() is to wait for an arbitrary condition to be satisfied.)
448
+ *
449
+ * @param source The source to wait on, which can be:
450
+ * - An object with an `"uneventful.until"` method returning a {@link Yielding}
451
+ * (in which case the result will be the the result of calling that method)
452
+ * - A {@link Signal}, or a zero-argument function returning a value based on
453
+ * signals (in which case the job resumes as soon as the result is truthy,
454
+ * perhaps immediately)
455
+ * - A {@link Source} (in which case the job resumes on the next truthy value
456
+ * it produces
457
+ *
458
+ * (Note: if the supplied source is a function with a non-zero `.length`, it is
459
+ * assumed to be a {@link Source}.)
460
+ *
461
+ * @returns a Yieldable that when processed with `yield *` in a job, will return
462
+ * the triggered event, or signal value. An error is thrown if event stream
463
+ * throws or closes early, or the signal throws.
464
+ *
465
+ * @category Signals
466
+ * @category Scheduling
467
+ */
468
+ declare function until<T>(source: UntilMethod<T> | Stream<T> | (() => T)): Yielding<T>;
469
+
470
+ export { CircularDependency, type Configurable, type GenericMethodDecorator, type RuleFactory, type SchedulerFn, type Signal, type Writable, WriteConflict, action, cached, peek, rule, runRules, until, value };