-
-
Notifications
You must be signed in to change notification settings - Fork 883
/
signal.ts
1708 lines (1581 loc) · 53.2 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Inspired by S.js by Adam Haile, https://github.com/adamhaile/S
import { requestCallback, Task } from "./scheduler.js";
import { setHydrateContext, sharedConfig } from "../render/hydration.js";
import type { JSX } from "../jsx.js";
import type { FlowComponent, FlowProps } from "../render/index.js";
export const equalFn = <T>(a: T, b: T) => a === b;
export const $PROXY = Symbol("solid-proxy");
export const $TRACK = Symbol("solid-track");
export const $DEVCOMP = Symbol("solid-dev-component");
const signalOptions = { equals: equalFn };
let ERROR: symbol | null = null;
let runEffects = runQueue;
const STALE = 1;
const PENDING = 2;
const UNOWNED: Owner = {
owned: null,
cleanups: null,
context: null,
owner: null
};
const NO_INIT = {};
export var Owner: Owner | null = null;
export let Transition: TransitionState | null = null;
let Scheduler: ((fn: () => void) => any) | null = null;
let ExternalSourceFactory: ExternalSourceFactory | null = null;
let Listener: Computation<any> | null = null;
let Updates: Computation<any>[] | null = null;
let Effects: Computation<any>[] | null = null;
let ExecCount = 0;
let rootCount = 0;
// keep immediately evaluated module code, below its indirect declared let dependencies like Listener
const [transPending, setTransPending] = /*@__PURE__*/ createSignal(false);
declare global {
var _$afterUpdate: () => void;
var _$afterCreateRoot: (root: Owner) => void;
}
export interface SignalState<T> {
value?: T;
observers: Computation<any>[] | null;
observerSlots: number[] | null;
tValue?: T;
comparator?: (prev: T, next: T) => boolean;
name?: string;
}
export interface Owner {
owned: Computation<any>[] | null;
cleanups: (() => void)[] | null;
owner: Owner | null;
context: any | null;
sourceMap?: Record<string, { value: unknown }>;
name?: string;
componentName?: string;
}
export interface Computation<Init, Next extends Init = Init> extends Owner {
fn: EffectFunction<Init, Next>;
state: number;
tState?: number;
sources: SignalState<Next>[] | null;
sourceSlots: number[] | null;
value?: Init;
updatedAt: number | null;
pure: boolean;
user?: boolean;
suspense?: SuspenseContextType;
}
export interface TransitionState {
sources: Set<SignalState<any>>;
effects: Computation<any>[];
promises: Set<Promise<any>>;
disposed: Set<Computation<any>>;
queue: Set<Computation<any>>;
scheduler?: (fn: () => void) => unknown;
running: boolean;
done?: Promise<void>;
resolve?: () => void;
}
type ExternalSourceFactory = <Prev, Next extends Prev = Prev>(
fn: EffectFunction<Prev, Next>,
trigger: () => void
) => ExternalSource;
export interface ExternalSource {
track: EffectFunction<any, any>;
dispose: () => void;
}
export type RootFunction<T> = (dispose: () => void) => T;
/**
* Creates a new non-tracked reactive context that doesn't auto-dispose
*
* @param fn a function in which the reactive state is scoped
* @param detachedOwner optional reactive context to bind the root to
* @returns the output of `fn`.
*
* @description https://www.solidjs.com/docs/latest/api#createroot
*/
export function createRoot<T>(fn: RootFunction<T>, detachedOwner?: Owner): T {
const listener = Listener,
owner = Owner,
unowned = fn.length === 0,
root: Owner =
unowned && !"_SOLID_DEV_"
? UNOWNED
: { owned: null, cleanups: null, context: null, owner: detachedOwner || owner },
updateFn = unowned
? "_SOLID_DEV_"
? () =>
fn(() => {
throw new Error("Dispose method must be an explicit argument to createRoot function");
})
: fn
: () => fn(() => untrack(() => cleanNode(root)));
if ("_SOLID_DEV_") {
if (owner) root.name = `${owner.name}-r${rootCount++}`;
globalThis._$afterCreateRoot && globalThis._$afterCreateRoot(root);
}
Owner = root;
Listener = null;
try {
return runUpdates(updateFn as () => T, true)!;
} finally {
Listener = listener;
Owner = owner;
}
}
export type Accessor<T> = () => T;
export type Setter<T> = (undefined extends T ? () => undefined : {}) &
(<U extends T>(value: (prev: T) => U) => U) &
(<U extends T>(value: Exclude<U, Function>) => U) &
(<U extends T>(value: Exclude<U, Function> | ((prev: T) => U)) => U);
export type Signal<T> = [get: Accessor<T>, set: Setter<T>];
export interface SignalOptions<T> extends MemoOptions<T> {
internal?: boolean;
}
/**
* Creates a simple reactive state with a getter and setter
* ```typescript
* const [state: Accessor<T>, setState: Setter<T>] = createSignal<T>(
* value: T,
* options?: { name?: string, equals?: false | ((prev: T, next: T) => boolean) }
* )
* ```
* @param value initial value of the state; if empty, the state's type will automatically extended with undefined; otherwise you need to extend the type manually if you want setting to undefined not be an error
* @param options optional object with a name for debugging purposes and equals, a comparator function for the previous and next value to allow fine-grained control over the reactivity
*
* @returns ```typescript
* [state: Accessor<T>, setState: Setter<T>]
* ```
* * the Accessor is merely a function that returns the current value and registers each call to the reactive root
* * the Setter is a function that allows directly setting or mutating the value:
* ```typescript
* const [count, setCount] = createSignal(0);
* setCount(count => count + 1);
* ```
*
* @description https://www.solidjs.com/docs/latest/api#createsignal
*/
export function createSignal<T>(): Signal<T | undefined>;
export function createSignal<T>(value: T, options?: SignalOptions<T>): Signal<T>;
export function createSignal<T>(value?: T, options?: SignalOptions<T>): Signal<T | undefined> {
options = options ? Object.assign({}, signalOptions, options) : signalOptions;
const s: SignalState<T> = {
value,
observers: null,
observerSlots: null,
comparator: options.equals || undefined
};
if ("_SOLID_DEV_" && !options.internal)
s.name = registerGraph(options.name || hashValue(value), s as { value: unknown });
const setter: Setter<T | undefined> = (value?: unknown) => {
if (typeof value === "function") {
if (Transition && Transition.running && Transition.sources.has(s)) value = value(s.tValue);
else value = value(s.value);
}
return writeSignal(s, value);
};
return [readSignal.bind(s), setter];
}
export interface BaseOptions {
name?: string;
}
// Magic type that when used at sites where generic types are inferred from, will prevent those sites from being involved in the inference.
// https://github.com/microsoft/TypeScript/issues/14829
// TypeScript Discord conversation: https://discord.com/channels/508357248330760243/508357248330760249/911266491024949328
export type NoInfer<T extends any> = [T][T extends any ? 0 : never];
export interface EffectOptions extends BaseOptions {}
// Also similar to OnEffectFunction
export type EffectFunction<Prev, Next extends Prev = Prev> = (v: Prev) => Next;
/**
* Creates a reactive computation that runs immediately before render, mainly used to write to other reactive primitives
* ```typescript
* export function createComputed<Next, Init = Next>(
* fn: (v: Init | Next) => Next,
* value?: Init,
* options?: { name?: string }
* ): void;
* ```
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
* @param options allows to set a name in dev mode for debugging purposes
*
* @description https://www.solidjs.com/docs/latest/api#createcomputed
*/
export function createComputed<Next>(fn: EffectFunction<undefined | NoInfer<Next>, Next>): void;
export function createComputed<Next, Init = Next>(
fn: EffectFunction<Init | Next, Next>,
value: Init,
options?: EffectOptions
): void;
export function createComputed<Next, Init>(
fn: EffectFunction<Init | Next, Next>,
value?: Init,
options?: EffectOptions
): void {
const c = createComputation(fn, value!, true, STALE, "_SOLID_DEV_" ? options : undefined);
if (Scheduler && Transition && Transition.running) Updates!.push(c);
else updateComputation(c);
}
/**
* Creates a reactive computation that runs during the render phase as DOM elements are created and updated but not necessarily connected
* ```typescript
* export function createRenderEffect<T>(
* fn: (v: T) => T,
* value?: T,
* options?: { name?: string }
* ): void;
* ```
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
* @param options allows to set a name in dev mode for debugging purposes
*
* @description https://www.solidjs.com/docs/latest/api#createrendereffect
*/
export function createRenderEffect<Next>(fn: EffectFunction<undefined | NoInfer<Next>, Next>): void;
export function createRenderEffect<Next, Init = Next>(
fn: EffectFunction<Init | Next, Next>,
value: Init,
options?: EffectOptions
): void;
export function createRenderEffect<Next, Init>(
fn: EffectFunction<Init | Next, Next>,
value?: Init,
options?: EffectOptions
): void {
const c = createComputation(fn, value!, false, STALE, "_SOLID_DEV_" ? options : undefined);
if (Scheduler && Transition && Transition.running) Updates!.push(c);
else updateComputation(c);
}
/**
* Creates a reactive computation that runs after the render phase
* ```typescript
* export function createEffect<T>(
* fn: (v: T) => T,
* value?: T,
* options?: { name?: string }
* ): void;
* ```
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
* @param options allows to set a name in dev mode for debugging purposes
*
* @description https://www.solidjs.com/docs/latest/api#createeffect
*/
export function createEffect<Next>(fn: EffectFunction<undefined | NoInfer<Next>, Next>): void;
export function createEffect<Next, Init = Next>(
fn: EffectFunction<Init | Next, Next>,
value: Init,
options?: EffectOptions
): void;
export function createEffect<Next, Init>(
fn: EffectFunction<Init | Next, Next>,
value?: Init,
options?: EffectOptions
): void {
runEffects = runUserEffects;
const c = createComputation(fn, value!, false, STALE, "_SOLID_DEV_" ? options : undefined),
s = SuspenseContext && lookup(Owner, SuspenseContext.id);
if (s) c.suspense = s;
c.user = true;
Effects ? Effects.push(c) : updateComputation(c);
}
/**
* Creates a reactive computation that runs after the render phase with flexible tracking
* ```typescript
* export function createReaction(
* onInvalidate: () => void,
* options?: { name?: string }
* ): (fn: () => void) => void;
* ```
* @param invalidated a function that is called when tracked function is invalidated.
* @param options allows to set a name in dev mode for debugging purposes
*
* @description https://www.solidjs.com/docs/latest/api#createreaction
*/
export function createReaction(onInvalidate: () => void, options?: EffectOptions) {
let fn: (() => void) | undefined;
const c = createComputation(
() => {
fn ? fn() : untrack(onInvalidate);
fn = undefined;
},
undefined,
false,
0,
"_SOLID_DEV_" ? options : undefined
),
s = SuspenseContext && lookup(Owner, SuspenseContext.id);
if (s) c.suspense = s;
c.user = true;
return (tracking: () => void) => {
fn = tracking;
updateComputation(c);
};
}
interface Memo<Prev, Next = Prev> extends SignalState<Next>, Computation<Next> {
tOwned?: Computation<Prev | Next, Next>[];
}
export interface MemoOptions<T> extends EffectOptions {
equals?: false | ((prev: T, next: T) => boolean);
}
/**
* Creates a readonly derived reactive memoized signal
* ```typescript
* export function createMemo<T>(
* fn: (v: T) => T,
* value?: T,
* options?: { name?: string, equals?: false | ((prev: T, next: T) => boolean) }
* ): () => T;
* ```
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param value an optional initial value for the computation; if set, fn will never receive undefined as first argument
* @param options allows to set a name in dev mode for debugging purposes and use a custom comparison function in equals
*
* @description https://www.solidjs.com/docs/latest/api#creatememo
*/
// The extra Prev generic parameter separates inference of the effect input
// parameter type from inference of the effect return type, so that the effect
// return type is always used as the memo Accessor's return type.
export function createMemo<Next extends Prev, Prev = Next>(
fn: EffectFunction<undefined | NoInfer<Prev>, Next>
): Accessor<Next>;
export function createMemo<Next extends Prev, Init = Next, Prev = Next>(
fn: EffectFunction<Init | Prev, Next>,
value: Init,
options?: MemoOptions<Next>
): Accessor<Next>;
export function createMemo<Next extends Prev, Init, Prev>(
fn: EffectFunction<Init | Prev, Next>,
value?: Init,
options?: MemoOptions<Next>
): Accessor<Next> {
options = options ? Object.assign({}, signalOptions, options) : signalOptions;
const c: Partial<Memo<Init, Next>> = createComputation(
fn,
value!,
true,
0,
"_SOLID_DEV_" ? options : undefined
) as Partial<Memo<Init, Next>>;
c.observers = null;
c.observerSlots = null;
c.comparator = options.equals || undefined;
if (Scheduler && Transition && Transition.running) {
c.tState = STALE;
Updates!.push(c as Memo<Init, Next>);
} else updateComputation(c as Memo<Init, Next>);
return readSignal.bind(c as Memo<Init, Next>);
}
interface Unresolved {
state: "unresolved";
loading: false;
error: undefined;
latest: undefined;
(): undefined;
}
interface Pending {
state: "pending";
loading: true;
error: undefined;
latest: undefined;
(): undefined;
}
interface Ready<T> {
state: "ready";
loading: false;
error: undefined;
latest: T;
(): T;
}
interface Refreshing<T> {
state: "refreshing";
loading: true;
error: undefined;
latest: T;
(): T;
}
interface Errored {
state: "errored";
loading: false;
error: any;
latest: never;
(): never;
}
export type Resource<T> = Unresolved | Pending | Ready<T> | Refreshing<T> | Errored;
export type InitializedResource<T> = Ready<T> | Refreshing<T> | Errored;
export type ResourceActions<T, R = unknown> = {
mutate: Setter<T>;
refetch: (info?: R) => T | Promise<T> | undefined | null;
};
export type ResourceSource<S> = S | false | null | undefined | (() => S | false | null | undefined);
export type ResourceFetcher<S, T, R = unknown> = (
k: S,
info: ResourceFetcherInfo<T, R>
) => T | Promise<T>;
export type ResourceFetcherInfo<T, R = unknown> = {
value: T | undefined;
refetching: R | boolean;
};
export type ResourceOptions<T, S = unknown> = {
initialValue?: T;
name?: string;
deferStream?: boolean;
ssrLoadFrom?: "initial" | "server";
storage?: (init: T | undefined) => [Accessor<T | undefined>, Setter<T | undefined>];
onHydrated?: (k: S | undefined, info: { value: T | undefined }) => void;
};
export type InitializedResourceOptions<T, S = unknown> = ResourceOptions<T, S> & {
initialValue: T;
};
export type ResourceReturn<T, R = unknown> = [Resource<T>, ResourceActions<T | undefined, R>];
export type InitializedResourceReturn<T, R = unknown> = [
InitializedResource<T>,
ResourceActions<T, R>
];
/**
* Creates a resource that wraps a repeated promise in a reactive pattern:
* ```typescript
* // Without source
* const [resource, { mutate, refetch }] = createResource(fetcher, options);
* // With source
* const [resource, { mutate, refetch }] = createResource(source, fetcher, options);
* ```
* @param source - reactive data function which has its non-nullish and non-false values passed to the fetcher, optional
* @param fetcher - function that receives the source (true if source not provided), the last or initial value, and whether the resource is being refetched, and returns a value or a Promise:
* ```typescript
* const fetcher: ResourceFetcher<S, T, R> = (
* sourceOutput: S,
* info: { value: T | undefined, refetching: R | boolean }
* ) => T | Promise<T>;
* ```
* @param options - an optional object with the initialValue and the name (for debugging purposes); see {@link ResourceOptions}
*
* @returns ```typescript
* [Resource<T>, { mutate: Setter<T>, refetch: () => void }]
* ```
*
* * Setting an `initialValue` in the options will mean that both the prev() accessor and the resource should never return undefined (if that is wanted, you need to extend the type with undefined)
* * `mutate` allows to manually overwrite the resource without calling the fetcher
* * `refetch` will re-run the fetcher without changing the source, and if called with a value, that value will be passed to the fetcher via the `refetching` property on the fetcher's second parameter
*
* @description https://www.solidjs.com/docs/latest/api#createresource
*/
export function createResource<T, R = unknown>(
fetcher: ResourceFetcher<true, T, R>,
options: InitializedResourceOptions<NoInfer<T>, true>
): InitializedResourceReturn<T, R>;
export function createResource<T, R = unknown>(
fetcher: ResourceFetcher<true, T, R>,
options?: ResourceOptions<NoInfer<T>, true>
): ResourceReturn<T, R>;
export function createResource<T, S, R = unknown>(
source: ResourceSource<S>,
fetcher: ResourceFetcher<S, T, R>,
options: InitializedResourceOptions<NoInfer<T>, S>
): InitializedResourceReturn<T, R>;
export function createResource<T, S, R = unknown>(
source: ResourceSource<S>,
fetcher: ResourceFetcher<S, T, R>,
options?: ResourceOptions<NoInfer<T>, S>
): ResourceReturn<T, R>;
export function createResource<T, S, R>(
pSource: ResourceSource<S> | ResourceFetcher<S, T, R>,
pFetcher?: ResourceFetcher<S, T, R> | ResourceOptions<T, S>,
pOptions?: ResourceOptions<T, S> | undefined
): ResourceReturn<T, R> {
let source: ResourceSource<S>;
let fetcher: ResourceFetcher<S, T, R>;
let options: ResourceOptions<T, S>;
if ((arguments.length === 2 && typeof pFetcher === "object") || arguments.length === 1) {
source = true as ResourceSource<S>;
fetcher = pSource as ResourceFetcher<S, T, R>;
options = (pFetcher || {}) as ResourceOptions<T, S>;
} else {
source = pSource as ResourceSource<S>;
fetcher = pFetcher as ResourceFetcher<S, T, R>;
options = pOptions || ({} as ResourceOptions<T, S>);
}
let pr: Promise<T> | null = null,
initP: Promise<T> | T | typeof NO_INIT = NO_INIT,
id: string | null = null,
loadedUnderTransition: boolean | null = false,
scheduled = false,
resolved = "initialValue" in options,
dynamic =
typeof source === "function" && createMemo(source as () => S | false | null | undefined);
const contexts = new Set<SuspenseContextType>(),
[value, setValue] = (options.storage || createSignal)(options.initialValue) as Signal<
T | undefined
>,
[error, setError] = createSignal<unknown>(undefined),
[track, trigger] = createSignal(undefined, { equals: false }),
[state, setState] = createSignal<"unresolved" | "pending" | "ready" | "refreshing" | "errored">(
resolved ? "ready" : "unresolved"
);
if (sharedConfig.context) {
id = `${sharedConfig.context.id}${sharedConfig.context.count++}`;
let v;
if (options.ssrLoadFrom === "initial") initP = options.initialValue as T;
else if (sharedConfig.load && (v = sharedConfig.load(id))) initP = v[0];
}
function loadEnd(p: Promise<T> | null, v: T | undefined, error?: any, key?: S) {
if (pr === p) {
pr = null;
resolved = true;
if ((p === initP || v === initP) && options.onHydrated)
queueMicrotask(() => options.onHydrated!(key, { value: v }));
initP = NO_INIT;
if (Transition && p && loadedUnderTransition) {
Transition.promises.delete(p);
loadedUnderTransition = false;
runUpdates(() => {
Transition!.running = true;
if (!Transition!.promises.size) {
Effects!.push.apply(Effects, Transition!.effects);
Transition!.effects = [];
}
completeLoad(v, error);
}, false);
} else completeLoad(v, error);
}
return v;
}
function completeLoad(v: T | undefined, err: any) {
runUpdates(() => {
if (!err) setValue(() => v);
setError(err);
setState(err ? "errored" : "ready");
for (const c of contexts.keys()) c.decrement!();
contexts.clear();
}, false);
}
function read() {
const c = SuspenseContext && lookup(Owner, SuspenseContext.id),
v = value(),
err = error();
if (err && !pr) throw err;
if (Listener && !Listener.user && c) {
createComputed(() => {
track();
if (pr) {
if (c.resolved && Transition) Transition.promises.add(pr);
else if (!contexts.has(c)) {
c.increment();
contexts.add(c);
}
}
});
}
return v;
}
function load(refetching: R | boolean = true) {
if (refetching !== false && scheduled) return;
scheduled = false;
const lookup = dynamic ? dynamic() : (source as S);
loadedUnderTransition = Transition && Transition.running;
if (lookup == null || lookup === false) {
loadEnd(pr, untrack(value));
return;
}
if (Transition && pr) Transition.promises.delete(pr);
const p =
initP !== NO_INIT
? (initP as T | Promise<T>)
: untrack(() =>
fetcher(lookup, {
value: value(),
refetching
})
);
if (typeof p !== "object" || !(p && "then" in p)) {
loadEnd(pr, p);
return p;
}
pr = p;
scheduled = true;
queueMicrotask(() => (scheduled = false));
runUpdates(() => {
setState(resolved ? "refreshing" : "pending");
trigger();
}, false);
return p.then(
v => loadEnd(p, v, undefined, lookup),
e => loadEnd(p, undefined, castError(e))
) as Promise<T>;
}
Object.defineProperties(read, {
state: { get: () => state() },
error: { get: () => error() },
loading: {
get() {
const s = state();
return s === "pending" || s === "refreshing";
}
},
latest: {
get() {
if (!resolved) return read();
const err = error();
if (err && !pr) throw err;
return value();
}
}
});
if (dynamic) createComputed(() => load(false));
else load(false);
return [read as Resource<T>, { refetch: load, mutate: setValue }];
}
export interface DeferredOptions<T> {
equals?: false | ((prev: T, next: T) => boolean);
name?: string;
timeoutMs?: number;
}
/**
* Creates a reactive computation that only runs and notifies the reactive context when the browser is idle
* ```typescript
* export function createDeferred<T>(
* fn: (v: T) => T,
* options?: { timeoutMs?: number, name?: string, equals?: false | ((prev: T, next: T) => boolean) }
* ): () => T);
* ```
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param options allows to set the timeout in milliseconds, use a custom comparison function and set a name in dev mode for debugging purposes
*
* @description https://www.solidjs.com/docs/latest/api#createdeferred
*/
export function createDeferred<T>(source: Accessor<T>, options?: DeferredOptions<T>) {
let t: Task,
timeout = options ? options.timeoutMs : undefined;
const node = createComputation(
() => {
if (!t || !t.fn)
t = requestCallback(
() => setDeferred(() => node.value as T),
timeout !== undefined ? { timeout } : undefined
);
return source();
},
undefined,
true
);
const [deferred, setDeferred] = createSignal(node.value as T, options);
updateComputation(node);
setDeferred(() => node.value as T);
return deferred;
}
export type EqualityCheckerFunction<T, U> = (a: U, b: T) => boolean;
/**
* Creates a conditional signal that only notifies subscribers when entering or exiting their key matching the value
* ```typescript
* export function createSelector<T, U>(
* source: () => T
* fn: (a: U, b: T) => boolean,
* options?: { name?: string }
* ): (k: U) => boolean;
* ```
* @param source
* @param fn a function that receives its previous or the initial value, if set, and returns a new value used to react on a computation
* @param options allows to set a name in dev mode for debugging purposes, optional
*
* ```typescript
* const isSelected = createSelector(selectedId);
* <For each={list()}>
* {(item) => <li classList={{ active: isSelected(item.id) }}>{item.name}</li>}
* </For>
* ```
*
* This makes the operation O(2) instead of O(n).
*
* @description https://www.solidjs.com/docs/latest/api#createselector
*/
export function createSelector<T, U>(
source: Accessor<T>,
fn: EqualityCheckerFunction<T, U> = equalFn as TODO,
options?: BaseOptions
): (key: U) => boolean {
const subs = new Map<U, Set<Computation<any>>>();
const node = createComputation(
(p: T | undefined) => {
const v = source();
for (const [key, val] of subs.entries())
if (fn(key, v) !== fn(key, p!)) {
for (const c of val.values()) {
c.state = STALE;
if (c.pure) Updates!.push(c);
else Effects!.push(c);
}
}
return v;
},
undefined,
true,
STALE,
"_SOLID_DEV_" ? options : undefined
) as Memo<any>;
updateComputation(node);
return (key: U) => {
const listener = Listener;
if (listener) {
let l: Set<Computation<any>> | undefined;
if ((l = subs.get(key))) l.add(listener);
else subs.set(key, (l = new Set([listener])));
onCleanup(() => {
l!.delete(listener!);
!l!.size && subs.delete(key);
});
}
return fn(
key,
Transition && Transition.running && Transition.sources.has(node) ? node.tValue : node.value!
);
};
}
/**
* Holds changes inside the block before the reactive context is updated
* @param fn wraps the reactive updates that should be batched
* @returns the return value from `fn`
*
* @description https://www.solidjs.com/docs/latest/api#batch
*/
export function batch<T>(fn: Accessor<T>): T {
return runUpdates(fn, false) as T;
}
/**
* Ignores tracking context inside its scope
* @param fn the scope that is out of the tracking context
* @returns the return value of `fn`
*
* @description https://www.solidjs.com/docs/latest/api#untrack
*/
export function untrack<T>(fn: Accessor<T>): T {
let result: T,
listener = Listener;
Listener = null;
result = fn();
Listener = listener;
return result;
}
/** @deprecated */
export type ReturnTypes<T> = T extends readonly Accessor<unknown>[]
? { [K in keyof T]: T[K] extends Accessor<infer I> ? I : never }
: T extends Accessor<infer I>
? I
: never;
// transforms a tuple to a tuple of accessors in a way that allows generics to be inferred
export type AccessorArray<T> = [...Extract<{ [K in keyof T]: Accessor<T[K]> }, readonly unknown[]>];
// Also similar to EffectFunction
export type OnEffectFunction<S, Prev, Next extends Prev = Prev> = (
input: S,
prevInput: S | undefined,
prev: Prev
) => Next;
export interface OnOptions {
defer?: boolean;
}
/**
* on - make dependencies of a computation explicit
* ```typescript
* export function on<S, U>(
* deps: Accessor<S> | AccessorArray<S>,
* fn: (input: S, prevInput: S | undefined, prevValue: U | undefined) => U,
* options?: { defer?: boolean } = {}
* ): (prevValue: U | undefined) => U;
* ```
* @param deps list of reactive dependencies or a single reactive dependency
* @param fn computation on input; the current previous content(s) of input and the previous value are given as arguments and it returns a new value
* @param options optional, allows deferred computation until at the end of the next change
* @returns an effect function that is passed into createEffect. For example:
*
* ```typescript
* createEffect(on(a, (v) => console.log(v, b())));
*
* // is equivalent to:
* createEffect(() => {
* const v = a();
* untrack(() => console.log(v, b()));
* });
* ```
*
* @description https://www.solidjs.com/docs/latest/api#on
*/
export function on<S, Next extends Prev, Prev = Next>(
deps: AccessorArray<S> | Accessor<S>,
fn: OnEffectFunction<S, undefined | NoInfer<Prev>, Next>,
options?: OnOptions & { defer?: false }
): EffectFunction<undefined | NoInfer<Next>, NoInfer<Next>>;
export function on<S, Next extends Prev, Prev = Next>(
deps: AccessorArray<S> | Accessor<S>,
fn: OnEffectFunction<S, undefined | NoInfer<Prev>, Next>,
options: OnOptions & { defer: true }
): EffectFunction<undefined | NoInfer<Next>>;
export function on<S, Next extends Prev, Prev = Next>(
deps: AccessorArray<S> | Accessor<S>,
fn: OnEffectFunction<S, undefined | NoInfer<Prev>, Next>,
options?: OnOptions
): EffectFunction<undefined | NoInfer<Next>> {
const isArray = Array.isArray(deps);
let prevInput: S;
let defer = options && options.defer;
return prevValue => {
let input: S;
if (isArray) {
input = Array(deps.length) as unknown as S;
for (let i = 0; i < deps.length; i++) (input as unknown as TODO[])[i] = deps[i]();
} else input = deps();
if (defer) {
defer = false;
return undefined;
}
const result = untrack(() => fn(input, prevInput, prevValue));
prevInput = input;
return result;
};
}
/**
* onMount - run an effect only after initial render on mount
* @param fn an effect that should run only once on mount
*
* @description https://www.solidjs.com/docs/latest/api#onmount
*/
export function onMount(fn: () => void) {
createEffect(() => untrack(fn));
}
/**
* onCleanup - run an effect once before the reactive scope is disposed
* @param fn an effect that should run only once on cleanup
*
* @description https://www.solidjs.com/docs/latest/api#oncleanup
*/
export function onCleanup(fn: () => void) {
if (Owner === null)
"_SOLID_DEV_" &&
console.warn("cleanups created outside a `createRoot` or `render` will never be run");
else if (Owner.cleanups === null) Owner.cleanups = [fn];
else Owner.cleanups.push(fn);
return fn;
}
/**
* onError - run an effect whenever an error is thrown within the context of the child scopes
* @param fn an error handler that receives the error
*
* * If the error is thrown again inside the error handler, it will trigger the next available parent handler
*
* @description https://www.solidjs.com/docs/latest/api#onerror
*/
export function onError(fn: (err: any) => void): void {
ERROR || (ERROR = Symbol("error"));
if (Owner === null)
"_SOLID_DEV_" &&
console.warn("error handlers created outside a `createRoot` or `render` will never be run");
else if (Owner.context === null) Owner.context = { [ERROR]: [fn] };
else if (!Owner.context[ERROR]) Owner.context[ERROR] = [fn];
else Owner.context[ERROR].push(fn);
}
export function getListener() {
return Listener;
}
export function getOwner() {
return Owner;
}
export function runWithOwner<T>(o: Owner, fn: () => T): T {
const prev = Owner;
Owner = o;
try {
return runUpdates(fn, true)!;
} finally {
Owner = prev;
}
}
// Transitions
export function enableScheduling(scheduler = requestCallback) {
Scheduler = scheduler;
}
/**
* ```typescript
* export function startTransition(fn: () => void) => Promise<void>
*
* @description https://www.solidjs.com/docs/latest/api#usetransition
*/
export function startTransition(fn: () => unknown): Promise<void> {
if (Transition && Transition.running) {
fn();
return Transition.done!;
}
const l = Listener;
const o = Owner;
return Promise.resolve().then(() => {
Listener = l;
Owner = o;
let t: TransitionState | undefined;
if (Scheduler || SuspenseContext) {
t =
Transition ||
(Transition = {
sources: new Set(),
effects: [],
promises: new Set(),
disposed: new Set(),
queue: new Set(),
running: true
});
t.done || (t.done = new Promise(res => (t!.resolve = res)));
t.running = true;
}
runUpdates(fn, false);