Repository navigation
Expand file tree
/
Copy pathship-final.patch
More file actions
6806 lines (6590 loc) · 260 KB
/
Copy pathship-final.patch
File metadata and controls
6806 lines (6590 loc) · 260 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
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
diff --git a/core/attributes.ts b/core/attributes.ts
index f148b5c..66aaba3 100644
--- a/core/attributes.ts
+++ b/core/attributes.ts
@@ -14,6 +14,7 @@ export function attributeName(name: string, isSvg = false): string {
if (name === 'acceptCharset') return 'accept-charset'
if (name === 'crossOrigin') return 'crossorigin'
if (name === 'noModule') return 'nomodule'
+ if (name === 'maskType') return 'mask-type'
if (name === 'viewBox') return 'viewBox'
return name.startsWith('aria-') || name.startsWith('data-')
? name
diff --git b/core/browser.ts b/core/browser.ts
new file mode 100644
index 0000000..ccf0ca4
--- /dev/null
+++ b/core/browser.ts
@@ -0,0 +1,33 @@
+export const REACT_RECOVERABLE_TYPE = Symbol.for('react.recoverable')
+
+export interface BrowserToken {
+ readonly $$typeof: typeof REACT_RECOVERABLE_TYPE
+ readonly _reason: string | (() => unknown) | undefined
+}
+
+export function browser(reason?: string | (() => unknown)): BrowserToken {
+ return { $$typeof: REACT_RECOVERABLE_TYPE, _reason: reason }
+}
+
+export function isBrowserToken(value: any): value is BrowserToken {
+ return value?.$$typeof === REACT_RECOVERABLE_TYPE
+}
+
+export function browserError(token: BrowserToken): Error {
+ let cause: unknown = token._reason
+ if (typeof cause === 'function') {
+ try {
+ cause = cause()
+ } catch {
+ cause = 'The reason for browser-only rendering could not be determined because its initializer threw.'
+ }
+ }
+ const error = new Error('Browser-only rendering was requested by `browser()`.',
+ token._reason === undefined ? undefined : { cause })
+ Object.defineProperty(error, REACT_RECOVERABLE_TYPE, { value: true })
+ return error
+}
+
+export function isBrowserError(error: any): error is Error {
+ return error?.[REACT_RECOVERABLE_TYPE] === true
+}
diff --git a/core/internal.ts b/core/internal.ts
index 3ec9b40..15b5c39 100644
--- a/core/internal.ts
+++ b/core/internal.ts
@@ -14,6 +14,8 @@ export const enum FiberTag {
Lazy = 10,
Suspense = 11,
Root = 12,
+ Activity = 13,
+ Resource = 14,
}
export interface Hook {
@@ -21,12 +23,13 @@ export interface Hook {
q: any
d: any
c: any
- n: Hook | null
}
export interface Effect {
- t: 0 | 1
+ t: 0 | 1 | 2
c: () => any
+ d?: () => void
+ s?: boolean // Store subscriptions run in layout but stay connected in Suspense.
}
export interface Fiber {
@@ -42,24 +45,39 @@ export interface Fiber {
parent: Fiber | null
child: Fiber | null
sibling: Fiber | null
- hooks: Hook | null
+ hooks: Hook[] | null
cu: Array<() => void> | null
dy: boolean
um: boolean
+ pd?: boolean
+ su?: Fiber | null // Retained Suspense primary update target.
+ ld?: boolean // Layout effects and refs are disconnected, not passive effects.
root: FiberRoot | null
+ depth?: number
+ cx?: Map<any, any> | null
+ cr?: Ref<any> | null
+ rc?: (() => void) | null
}
+export type RecoverableErrorHandler = (error: unknown, info: { componentStack: string | null; errorBoundary?: unknown }) => void
+
export interface FiberRoot {
c: Element | DocumentFragment
r: Fiber
p: Set<Fiber>
s: boolean
- re?: ((err: unknown) => void) | undefined
- ce?: ((err: unknown) => void) | undefined
- ue?: ((err: unknown) => void) | undefined
+ u?: (() => void) | undefined
+ er?: Array<{ error: unknown; stack: string }> | undefined
+ eb?: boolean
+ sp?: boolean
+ re?: RecoverableErrorHandler | undefined
+ ce?: RecoverableErrorHandler | undefined
+ ue?: RecoverableErrorHandler | undefined
i: string | undefined
ic: number
h: boolean
+ a?: boolean
+ fr?: boolean
}
export function createFiber(tag: FiberTag, type: any, key: string | null): Fiber {
diff --git b/core/resource-hints.ts b/core/resource-hints.ts
new file mode 100644
index 0000000..82bf80e
--- /dev/null
+++ b/core/resource-hints.ts
@@ -0,0 +1,36 @@
+export type ResourceHintKind =
+ | 'dns-prefetch'
+ | 'preconnect'
+ | 'preload'
+ | 'modulepreload'
+ | 'stylesheet'
+ | 'script'
+ | 'module-script'
+
+// Only supported string options reach the dispatcher, using the public camelCase
+// names. Fonts have crossOrigin: ''. Stylesheet precedence defaults to 'default'.
+// Module preloads omit as for the implicit script destination. href is non-empty.
+// A server renderer returns true to consume a hint in its current request, even
+// when deduplication means no new output. Returning false falls through to the DOM.
+export type ResourceHintOptions = Record<string, string>
+
+export const resourceHintDispatcher: {
+ emit?: (kind: ResourceHintKind, href: string, options: ResourceHintOptions) => boolean
+} = {}
+
+// The renderer excludes SVG before calling this. A ref does not opt a resource
+// out of sharing, but event ownership, disabled sheets and itemProp do.
+export function resourceKind(type: string, props: any): 'style' | 'stylesheet' | 'script' | undefined {
+ if (props.itemProp != null) return
+ if (type === 'style') {
+ if (typeof props.precedence === 'string' && typeof props.href === 'string' && props.href) return 'style'
+ } else if (type === 'link') {
+ if (props.rel === 'stylesheet' && typeof props.href === 'string' && props.href && typeof props.precedence === 'string' && props.disabled == null && !props.onLoad && !props.onError) return 'stylesheet'
+ } else if (type === 'script' && props.async && typeof props.async !== 'function' && typeof props.async !== 'symbol' && typeof props.src === 'string' && props.src && !props.onLoad && !props.onError) return 'script'
+}
+
+export function resourceURL(value: string): string {
+ return /^[\u0000-\u0020]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i.test(value)
+ ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')"
+ : value
+}
diff --git a/dom/_all.ts b/dom/_all.ts
index e7dda6d..ef8f5c2 100644
--- a/dom/_all.ts
+++ b/dom/_all.ts
@@ -18,13 +18,7 @@ export type { Root, RootOptions } from './root'
export { createPortal } from './portal'
export { act } from './test-utils'
-// Resource hints — stubs
-export function preconnect(_href: string, _opts?: any): void {}
-export function prefetchDNS(_href: string): void {}
-export function preload(_href: string, _opts?: any): void {}
-export function preinit(_href: string, _opts?: any): void {}
-export function preloadModule(_href: string, _opts?: any): void {}
-export function preinitModule(_href: string, _opts?: any): void {}
+export { preconnect, prefetchDNS, preload, preinit, preloadModule, preinitModule } from './resource-hints'
export const version = '19.2.3'
diff --git b/dom/commit.ts b/dom/commit.ts
new file mode 100644
index 0000000..7f4f908
--- /dev/null
+++ b/dom/commit.ts
@@ -0,0 +1,186 @@
+import { FiberTag, type Fiber, type Hook } from '../core'
+import { setProp } from './dom'
+
+export interface CommitPlan {
+ q: any[][] // Before-mutation, mutation, effect, rollback and failure queues.
+ c: number[][] // Queue lengths saved at each rollback checkpoint.
+ b: number // Next before-mutation callback, including reentrant commits.
+ m: boolean // Mutation phase has started, preventing duplicate commits.
+}
+
+export let currentCommit: CommitPlan | null = null
+let activeCommit: CommitPlan | null = null
+let reusableCommit: CommitPlan | undefined
+let checkpointHook: (() => void) | undefined
+
+function createCommit(): CommitPlan {
+ return { q: [[], [], [], [], []], c: [], b: 0, m: false }
+}
+
+export function prepareCommit(render: () => void, plan = createCommit()): CommitPlan {
+ const previous = currentCommit
+ currentCommit = plan
+ try { render() } catch (error) {
+ currentCommit = null
+ const failed = plan.q[4]!
+ for (let i = 0; i < failed.length; i++) {
+ const work = failed[i]
+ if (typeof work === 'function') work()
+ else {
+ const children = failed[++i] as Fiber[] | undefined
+ work.child = children?.[0] ?? null
+ if (children) for (let j = 0; j < children.length; j++) children[j]!.sibling = children[j + 1] ?? null
+ }
+ }
+ throw error
+ } finally { currentCommit = previous }
+ return plan
+}
+
+export function queueMutation(work: () => void): void {
+ if (!currentCommit) { work(); return }
+ currentCommit.q[1]!.push(work)
+}
+
+export function queueText(node: Text, value: string): void {
+ if (currentCommit) currentCommit.q[1]!.push(value, node)
+ else node.data = value
+}
+
+export function queueProp(node: Element, key: string, value: any, previous: any, svg: boolean): void {
+ if (currentCommit) currentCommit.q[1]!.push(node, key, value, previous, svg)
+ else setProp(node, key, value, previous, svg)
+}
+
+export function queueBeforeMutation(work: () => void): void {
+ if (currentCommit) currentCommit.q[0]!.push(work)
+ else work()
+}
+
+export function queueCommitEffects(work: () => void): void {
+ const plan = currentCommit || activeCommit
+ if (plan) plan.q[2]!.push(work)
+ else work()
+}
+
+export function onCommitRollback(work: () => void): void {
+ currentCommit?.q[3]!.push(work)
+}
+
+export function onCommitFailure(work: () => void): void {
+ if (currentCommit) currentCommit.q[4]!.push(work)
+ else work()
+}
+
+// Structural reconciliation already builds the previous child list. Keep
+// that list for a failed preparation without allocating per-fiber closures.
+export function rememberChildList(parent: Fiber, children?: Fiber[]): void {
+ currentCommit?.q[4]!.push(parent, children)
+}
+
+export function setCommitCheckpointHook(hook: () => void): void {
+ checkpointHook = hook
+}
+
+export function checkpointCommit(fiber?: Fiber): number {
+ if (!currentCommit) return -1
+ const checkpoint = currentCommit.c.length
+ currentCommit.c.push(currentCommit.q.map(queue => queue.length))
+ if (fiber) rememberSubtree(fiber)
+ checkpointHook?.()
+ return checkpoint
+}
+
+function rememberSubtree(fiber: Fiber): void {
+ const saved = { ...fiber }
+ // Memo and lazy preserve their wrapper tag around the same class instance.
+ const instance = fiber.sn?._fiber === fiber ? fiber.sn : null
+ // Hook has four fields. One flat snapshot preserves slot and dispatch
+ // identity without a tuple and object clone for every hook.
+ const hooks: any[] | null = fiber.hooks && []
+ if (hooks) for (const hook of fiber.hooks!) {
+ const queue = hook.q
+ hooks.push(hook, hook.s, queue, hook.d, hook.c, queue && typeof queue === 'object' ? { ...queue } : null)
+ }
+ const memoized = fiber.ms && (instance || fiber.tag === FiberTag.Suspense || fiber.tag === FiberTag.Fragment)
+ ? { ...fiber.ms } : null
+ if (fiber.cx) saved.cx = new Map(fiber.cx)
+ if (fiber.cu) saved.cu = fiber.cu.slice()
+ const props = instance?.props, state = instance?.state, context = instance?.context
+ onCommitRollback(() => {
+ Object.assign(fiber, saved)
+ if (memoized) {
+ for (const key in fiber.ms) if (!(key in memoized)) delete fiber.ms[key]
+ Object.assign(fiber.ms, memoized)
+ }
+ if (hooks) {
+ fiber.hooks!.length = hooks.length / 6
+ for (let index = 0; index < hooks.length; index += 6) {
+ const hook: Hook = fiber.hooks![index / 6] = hooks[index]
+ hook.s = hooks[index + 1]
+ hook.q = hooks[index + 2]
+ hook.d = hooks[index + 3]
+ hook.c = hooks[index + 4]
+ const queue = hooks[index + 5]
+ if (queue) Object.assign(hook.q, queue)
+ }
+ }
+ if (instance) { instance.props = props; instance.state = state; instance.context = context }
+ })
+ for (let child = fiber.child; child; child = child.sibling) rememberSubtree(child)
+ if (fiber.tag === FiberTag.Suspense && fiber.ms?.f) rememberSubtree(fiber.ms.f)
+}
+
+export function rewindCommit(checkpoint: number): void {
+ if (!currentCommit || checkpoint < 0) return
+ const lengths = currentCommit.c[checkpoint]!
+ const undo = currentCommit.q[3]!
+ for (let index = undo.length - 1; index >= lengths[3]!; index--) undo[index]!()
+ currentCommit.q.forEach((queue, index) => { queue.length = lengths[index]! })
+ currentCommit.c.length = checkpoint
+}
+
+export function commitBeforeMutation(plan: CommitPlan): void {
+ const queue = plan.q[0]!
+ while (plan.b < queue.length) queue[plan.b++]!()
+}
+
+export function commitMutation(plan: CommitPlan): void {
+ if (plan.m) return
+ commitBeforeMutation(plan)
+ if (plan.m) return
+ plan.m = true
+ const previous = activeCommit
+ activeCommit = plan
+ try {
+ const mutations = plan.q[1]!
+ for (let index = 0; index < mutations.length; index++) {
+ const work = mutations[index]
+ if (typeof work === 'function') work()
+ else if (typeof work === 'string') mutations[++index].data = work
+ else setProp(work, mutations[++index], mutations[++index], mutations[++index], mutations[++index])
+ }
+ for (const work of plan.q[2]!) work()
+ } finally {
+ activeCommit = previous
+ for (const queue of plan.q) queue.length = 0
+ plan.c.length = 0
+ }
+}
+
+export function commitSynchronously(render: () => void): void {
+ if (currentCommit) { render(); return }
+ const plan = reusableCommit || createCommit()
+ reusableCommit = undefined
+ plan.b = 0
+ plan.m = false
+ try { commitMutation(prepareCommit(render, plan)) }
+ finally {
+ // Failed preparation must not leave work for a later synchronous root.
+ if (!plan.m) {
+ for (const queue of plan.q) queue.length = 0
+ plan.c.length = 0
+ }
+ reusableCommit = plan
+ }
+}
diff --git a/dom/dispatcher.ts b/dom/dispatcher.ts
index 2eadebd..c5ea564 100644
--- a/dom/dispatcher.ts
+++ b/dom/dispatcher.ts
@@ -1,6 +1,9 @@
-import type { Hook, Fiber, FiberRoot, Effect } from '../core'
-import { ReactSharedInternals, REACT_CONTEXT_TYPE } from '../react'
-import { scheduleUpdate, enqueueEffect, readContext } from './reconcile'
+import type { Hook, Fiber, FiberRoot, Effect, ReactNode } from '../core'
+import { ReactSharedInternals, REACT_CONTEXT_TYPE, startTransition } from '../react'
+import { scheduleUpdate, enqueueEffect, readContext, rememberActivityEffect, handleCommitError } from './reconcile'
+import { REACT_RECOVERABLE_TYPE } from '../core/browser'
+import { queueCommitEffects } from './commit'
+import { deferTransitionPassive } from './features/view-transition'
function getCurrentFiber(): Fiber {
const f = ReactSharedInternals.F
@@ -14,32 +17,9 @@ function getCurrentFiber(): Fiber {
}
function nextHook(): Hook {
- const fiber = getCurrentFiber()
- const idx = ReactSharedInternals.I++
-
- let prev = ReactSharedInternals.K
-
- if (idx === 0) {
- if (fiber.hooks) {
- ReactSharedInternals.K = fiber.hooks
- return fiber.hooks
- }
- const h: Hook = { s: undefined, q: undefined, d: undefined, c: undefined, n: null }
- fiber.hooks = h
- ReactSharedInternals.K = h
- return h
- }
-
- if (prev && prev.n) {
- ReactSharedInternals.K = prev.n
- return prev.n
- }
-
- const h: Hook = { s: undefined, q: undefined, d: undefined, c: undefined, n: null }
- if (prev) prev.n = h
- else fiber.hooks = h
- ReactSharedInternals.K = h
- return h
+ const hooks = getCurrentFiber().hooks ||= []
+ const index = ReactSharedInternals.I++
+ return hooks[index] ||= { s: undefined, q: undefined, d: undefined, c: undefined }
}
function depsEqual(
@@ -57,110 +37,185 @@ function depsEqual(
type BasicStateAction<S> = S | ((p: S) => S)
+function initializeReducer(hook: Hook, fiber: Fiber, initialArg: any, init?: (arg: any) => any): void {
+ hook.s = init ? init(initialArg) : initialArg
+ hook.c = null
+ hook.q = (action: any) => {
+ if (fiber.um || fiber.pd) return
+ ;(hook.c ||= []).push(action)
+ scheduleUpdate(fiber)
+ }
+}
+
+// Reducer slots reuse the effect-cleanup field for pending actions. Zero marks
+// eager state work, null means no update. Replacing arrays lets retries restore
+// pending actions without copying or shifting them.
+function reducePending(hook: Hook, reducer: (state: any, action: any) => any, previous = hook.s): void {
+ const actions = hook.c
+ if (actions == null) return
+ hook.c = null
+ let state = hook.s
+ if (actions) for (const action of actions) state = reducer(state, action)
+ hookFlags |= Object.is(state, previous) ? 2 : 3
+ hook.s = state
+}
+
+let hookEffects: any[] | undefined
+// Bit 1 records a changed value; bit 2 records a processed reducer queue.
+let hookFlags = 0
+export const HOOK_BAILOUT = Symbol()
+
+function resetHookEffects(effects: any[]): void {
+ for (let index = 0; index < effects.length; index += 4) effects[index].d = effects[index + 1]
+}
+
+export function renderWithHooks(
+ fiber: Fiber,
+ render: (props: any, ref?: any) => ReactNode,
+ props: any,
+ ref?: any,
+ canBail = false,
+): ReactNode | typeof HOOK_BAILOUT {
+ const previousDispatcher = ReactSharedInternals.H, previousFiber = ReactSharedInternals.F, previousIndex = ReactSharedInternals.I
+ const previousEffects = hookEffects, previousFlags = hookFlags
+ hookEffects = undefined
+ hookFlags = 0
+ ReactSharedInternals.H = DISPATCHER
+ ReactSharedInternals.F = fiber
+ try {
+ let rendered: ReactNode, attempts = 0
+ do {
+ if (++attempts > 25) throw new Error(process.env.NODE_ENV !== 'production' ? 'Too many re-renders.' : '')
+ if (hookEffects) {
+ resetHookEffects(hookEffects)
+ hookEffects = undefined
+ }
+ ReactSharedInternals.I = 0
+ fiber.dy = false
+ rendered = render(props, ref)
+ } while (fiber.dy)
+ if (canBail && hookFlags === 2) {
+ // React accepts the rendered dependencies on a reducer bailout, but
+ // keeps the previous committed effect descriptions until real work.
+ hookEffects = undefined
+ return HOOK_BAILOUT
+ }
+ if (hookEffects) {
+ const effects: any[] = hookEffects
+ for (let index = 0; index < effects.length; index += 4) {
+ const hook = effects[index], effect = effects[index + 2]
+ rememberActivityEffect(fiber, hook, effect)
+ if (effects[index + 3]) enqueueEffect(fiber, effect)
+ }
+ hookEffects = undefined
+ }
+ return rendered
+ } finally {
+ if (hookEffects) resetHookEffects(hookEffects)
+ hookEffects = previousEffects
+ hookFlags = previousFlags
+ ReactSharedInternals.H = previousDispatcher
+ ReactSharedInternals.F = previousFiber
+ ReactSharedInternals.I = previousIndex
+ }
+}
+
+export function cleanupEffect(hook: Hook, fiber: Fiber): void {
+ if (!hook.c) return
+ const cleanup = hook.c
+ hook.c = null
+ if (fiber.cu) {
+ const index = fiber.cu.indexOf(cleanup)
+ if (index >= 0) fiber.cu.splice(index, 1)
+ }
+ try { cleanup() } catch (error) { handleCommitError(fiber, error) }
+}
+
+function useEffectImpl(type: Effect['t'], create: () => any, deps?: ReadonlyArray<unknown>): void {
+ const hook = nextHook()
+ const fiber = getCurrentFiber()
+ const changed = hook.d === undefined || !depsEqual(hook.d, deps)
+ if (!changed && !fiber.root?.a && !(type === 1 && fiber.root?.sp)) return
+ const previous = hook.d
+ hook.d = deps
+ const effect: Effect = {
+ t: type,
+ c: () => {
+ cleanupEffect(hook, fiber)
+ const cleanup = create()
+ // Each effect owns its cleanup even when hooks return the same function.
+ hook.c = typeof cleanup === 'function' ? () => {
+ if (type === 0) {
+ const dispose = () => {
+ try { cleanup() } catch (error) { handleCommitError(fiber, error) }
+ }
+ if (!deferTransitionPassive(dispose)) queueCommitEffects(dispose)
+ } else cleanup()
+ } : null
+ return hook.c
+ },
+ }
+ if (type === 1) effect.d = () => cleanupEffect(hook, fiber)
+ ;(hookEffects ||= []).push(hook, previous, effect, changed)
+}
+
// Singleton — every method reads render context via ReactSharedInternals,
// and per-hook closures live on the hook itself, so nothing is render-local
// to capture. Allocating a fresh wrapper + 17 method closures per function-
// component render was pure GC pressure.
const DISPATCHER = makeDispatcherImpl()
-export function makeDispatcher() {
- return DISPATCHER
-}
-
function makeDispatcherImpl() {
return {
useState<S>(initial: S | (() => S)): [S, (a: BasicStateAction<S>) => void] {
- return this.useReducer(
- basicReducer as (state: S, action: BasicStateAction<S>) => S,
- typeof initial == 'function' ? (initial as () => S)() : initial,
- )
- },
-
- useReducer<S, A>(reducer: (s: S, a: A) => S, initialArg: any, init?: (a: any) => S) {
- const hook = nextHook()
- const fiber = getCurrentFiber()
+ const hook = nextHook(), fiber = getCurrentFiber()
if (hook.q === undefined) {
- hook.s = init ? init(initialArg) : initialArg
- const queue: any = { r: reducer }
- const dispatch = (action: A) => {
- const currentState = hook.s as S
- const next = queue.r(currentState, action)
- if (!Object.is(next, currentState)) {
+ hook.s = hook.d = typeof initial === 'function' ? (initial as () => S)() : initial
+ hook.c = null
+ hook.q = (action: BasicStateAction<S>) => {
+ if (fiber.um || fiber.pd) return
+ if (ReactSharedInternals.F !== fiber && !hook.c) {
+ let next: S
+ try {
+ next = basicReducer(hook.s, action)
+ } catch {
+ hook.c = [action]
+ scheduleUpdate(fiber)
+ return
+ }
+ if (Object.is(next, hook.s)) return
hook.s = next
+ hook.c = 0
scheduleUpdate(fiber)
+ return
}
+ ;(hook.c ||= []).push(action)
+ scheduleUpdate(fiber)
}
- queue.d = dispatch
- hook.q = queue
- } else {
- hook.q.r = reducer
}
- return [hook.s, hook.q.d] as [S, (a: A) => void]
+ reducePending(hook, basicReducer, hook.d)
+ hook.d = hook.s
+ return [hook.s, hook.q]
},
- useEffect(create: () => any, deps?: ReadonlyArray<unknown>) {
+ useReducer<S, A>(reducer: (s: S, a: A) => S, initialArg: any, init?: (a: any) => S) {
const hook = nextHook()
- const fiber = getCurrentFiber()
- const prevDeps = hook.d
- if (prevDeps !== undefined && depsEqual(prevDeps, deps)) return
- hook.d = deps
- const effect: Effect = {
- t: 0,
- c: () => {
- // Run the prior cleanup INSIDE the effect run, not during the
- // dispatch/render phase. If render A → B → C all happen back-to-
- // back before the passive microtask drains, dispatch-time cleanup
- // only fires once (between A→B) and fx B + C both run fresh,
- // leaving two side-fx (e.g. two plot SVGs) in the DOM. Doing
- // it here, at effect-run time, means every new create first tears
- // down whatever cleanup is currently live on the hook.
- if (hook.c) {
- try { hook.c() } catch {}
- // The prior cleanup was also pushed onto fiber.cu; remove
- // it so unmount doesn't double-call it.
- if (fiber.cu) {
- const i = fiber.cu.indexOf(hook.c)
- if (i >= 0) fiber.cu.splice(i, 1)
- }
- hook.c = null
- }
- const c = create()
- hook.c = typeof c == 'function' ? c : null
- return hook.c
- },
- }
- enqueueEffect(fiber, effect)
+ if (hook.q === undefined) initializeReducer(hook, getCurrentFiber(), initialArg, init)
+ reducePending(hook, reducer)
+ hook.d = reducer
+ return [hook.s, hook.q] as [S, (a: A) => void]
+ },
+
+ useEffect(create: () => any, deps?: ReadonlyArray<unknown>) {
+ useEffectImpl(0, create, deps)
},
useLayoutEffect(create: () => any, deps?: ReadonlyArray<unknown>) {
- const hook = nextHook()
- const fiber = getCurrentFiber()
- const prevDeps = hook.d
- if (prevDeps !== undefined && depsEqual(prevDeps, deps)) return
- hook.d = deps
- const effect: Effect = {
- t: 1,
- c: () => {
- // Mirror useEffect: tear down the prior cleanup at run time so
- // coalesced renders don't leak side-fx.
- if (hook.c) {
- try { hook.c() } catch {}
- if (fiber.cu) {
- const i = fiber.cu.indexOf(hook.c)
- if (i >= 0) fiber.cu.splice(i, 1)
- }
- hook.c = null
- }
- const c = create()
- hook.c = typeof c == 'function' ? c : null
- return hook.c
- },
- }
- enqueueEffect(fiber, effect)
+ useEffectImpl(1, create, deps)
},
useInsertionEffect(create: () => any, deps?: ReadonlyArray<unknown>) {
- return this.useLayoutEffect(create, deps)
+ useEffectImpl(2, create, deps)
},
useRef<T>(initial: T) {
@@ -190,14 +245,16 @@ function makeDispatcherImpl() {
},
useImperativeHandle<T>(ref: any, factory: () => T, deps?: ReadonlyArray<unknown>) {
- const hook = nextHook()
- if (hook.d !== undefined && depsEqual(hook.d, deps)) return
- hook.d = deps
- const value = factory()
- if (ref) {
- if (typeof ref == 'function') ref(value)
- else ref.current = value
- }
+ useEffectImpl(1, () => {
+ if (!ref) return
+ const value = factory()
+ if (typeof ref === 'function') {
+ const cleanup = ref(value)
+ return typeof cleanup === 'function' ? cleanup : () => ref(null)
+ }
+ ref.current = value
+ return () => { ref.current = null }
+ }, deps == null ? undefined : [...deps, ref])
},
useDebugValue<T>(_value: T, _formatter?: (v: T) => any): void {
@@ -217,13 +274,19 @@ function makeDispatcherImpl() {
},
useTransition(): [boolean, (fn: () => void) => void] {
- return [false, (fn: () => void) => fn()]
+ return [false, startTransition]
},
useDeferredValue<T>(v: T): T {
return v
},
+ useCacheRefresh(): () => void {
+ // There is no client cache to invalidate. Preserve hook identity and
+ // leave state and scheduling alone, as with the uncached client cache().
+ return this.useCallback(() => {}, [])
+ },
+
useSyncExternalStore<T>(
subscribe: (cb: () => void) => () => void,
getSnapshot: () => T,
@@ -251,26 +314,19 @@ function makeDispatcherImpl() {
const isHydrating = Boolean(root?.h)
const value =
isHydrating && getServerSnapshot ? getServerSnapshot() : getSnapshot()
+ if (!Object.is(hook.s, value)) hookFlags |= 1
hook.s = value
const deps = [subscribe]
- if (hook.d === undefined || !depsEqual(hook.d, deps)) {
+ const changed = hook.d === undefined || !depsEqual(hook.d, deps)
+ if (changed || fiber.root?.a) {
+ const previous = hook.d
hook.d = deps
const effect: Effect = {
t: 1,
+ s: true,
c: () => {
- if (hook.c) {
- try {
- hook.c()
- } catch {
- // ignore cleanup failures
- }
- if (fiber.cu) {
- const i = fiber.cu.indexOf(hook.c)
- if (i >= 0) fiber.cu.splice(i, 1)
- }
- hook.c = null
- }
+ cleanupEffect(hook, fiber)
let unsubscribed = false
const cleanup = () => {
@@ -293,7 +349,6 @@ function makeDispatcherImpl() {
}
if (!Object.is(hook.s, next)) {
- hook.s = next
scheduleUpdate(fiber)
}
}
@@ -311,12 +366,13 @@ function makeDispatcherImpl() {
return cleanup
},
}
- enqueueEffect(fiber, effect)
+ ;(hookEffects ||= []).push(hook, previous, effect, changed)
}
return value
},
use<T>(resource: any): T {
+ if (resource?.$$typeof === REACT_RECOVERABLE_TYPE) return undefined as T
if (resource == null) {
if (process.env.NODE_ENV !== 'production') {
throw new Error('use() received null or undefined')
@@ -372,7 +428,7 @@ let idCounter = 0
function findRootFromFiber(fiber: Fiber): FiberRoot | null {
let f: Fiber | null = fiber
while (f) {
- if (f.root) return f.root
+ if (f.root) return fiber.root = f.root
f = f.parent
}
return null
diff --git a/dom/dom.ts b/dom/dom.ts
index 2140001..f4737b3 100644
--- a/dom/dom.ts
+++ b/dom/dom.ts
@@ -9,6 +9,7 @@ const BOOLEAN_ATTRS = new Set([
'autoplay',
'checked',
'controls',
+ 'credentialless',
'default',
'defer',
'disabled',
@@ -51,6 +52,54 @@ export function isSvgElement(el: Element): boolean {
return (el as any).ownerSVGElement !== undefined || el.tagName === 'svg'
}
+export function syncInputValue(el: HTMLInputElement, props: any, prev?: any): void {
+ if (!prev) {
+ el.checked = el.defaultChecked = !!(props.checked ?? props.defaultChecked)
+ } else if (props.checked != null) {
+ el.checked = !!props.checked
+ } else if (props.defaultChecked != null) {
+ el.defaultChecked = !!props.defaultChecked
+ }
+ const value = props.value
+ const fallback = props.defaultValue
+ if (!prev) {
+ if (value == null && (el.type === 'submit' || el.type === 'reset')) return
+ if (value != null || fallback != null) {
+ const initial = '' + (value ?? fallback)
+ if (el.value !== initial) el.value = initial
+ el.defaultValue = initial
+ }
+ return
+ }
+ if (value != null) {
+ // Number inputs keep equivalent user spelling, including trailing zeroes.
+ if (el.type === 'number' ? (value === 0 && el.value === '') || el.value != value : el.value !== '' + value) {
+ el.value = '' + value
+ }
+ const nextDefault = el.type === 'number' && el.value == value ? el.value : '' + value
+ if (el.defaultValue !== nextDefault) el.defaultValue = nextDefault
+ } else if (fallback != null) {
+ if (el.defaultValue !== '' + fallback) el.defaultValue = '' + fallback
+ } else if (prev.defaultValue != null || el.type === 'submit' || el.type === 'reset') {
+ el.removeAttribute('value')
+ }
+}
+
+export function syncTextareaValue(el: HTMLTextAreaElement, props: any, mounting = false): void {
+ if (mounting) {
+ const children = props.children
+ const initial = props.value ?? props.defaultValue ?? (Array.isArray(children) ? children[0] : children) ?? ''
+ el.defaultValue = initial
+ // The strict check also preserves React's clean numeric-default state.
+ if (initial !== '' && el.textContent === initial) el.value = initial
+ return
+ }
+ const value = props.value
+ if (value != null && el.value !== '' + value) el.value = '' + value
+ const fallback = props.defaultValue ?? value ?? ''
+ if (el.defaultValue !== '' + fallback) el.defaultValue = '' + fallback
+}
+
export function setProp(
el: Element,
name: string,
@@ -59,6 +108,14 @@ export function setProp(
isSvg: boolean,
): void {
if (name === 'children' || name === 'key' || name === 'ref') return
+ // These names need no alias or boolean-attribute normalization.
+ if (name.length > 5 && (name.charCodeAt(0) === 97 || name.charCodeAt(0) === 100)) {
+ if (name.startsWith('aria-') || name.startsWith('data-')) {
+ if (next == null) el.removeAttribute(name)
+ else el.setAttribute(name, '' + next)
+ return
+ }
+ }
const attr = attributeName(name, isSvg)
// defaultValue / defaultChecked are IDL-property-only — they seed the
@@ -76,19 +133,8 @@ export function setProp(
return
}
- if (name === 'className') {
- if (isSvg) {
- if (next == null) el.removeAttribute('class')
- else el.setAttribute('class', '' + next)
- } else {
- ;(el as HTMLElement).className = next == null ? '' : '' + next
- }
- return
- }
-
- if (name === 'class') {
- if (next == null) el.removeAttribute('class')
- else el.setAttribute('class', '' + next)
+ if (name === 'className' && !isSvg) {
+ ;(el as HTMLElement).className = next == null ? '' : '' + next
return
}
@@ -105,17 +151,11 @@ export function setProp(
}
if (name[0] === 'o' && name[1] === 'n') {
- setEventHandler(el, name, next, prev)
+ setEventHandler(el, name, next)
return
}
- if (name === 'htmlFor') {
- if (next == null) el.removeAttribute('for')
- else el.setAttribute('for', '' + next)
- return
- }
-
- if (STRING_BOOLEAN_ATTRS.has(attr)) {
+ if (name === 'className' || name === 'class' || name === 'htmlFor' || STRING_BOOLEAN_ATTRS.has(attr)) {
if (next == null) el.removeAttribute(attr)
else el.setAttribute(attr, '' + next)
return
@@ -128,32 +168,12 @@ export function setProp(
} catch {}
}
- if (BOOLEAN_ATTRS.has(name.toLowerCase())) {
- if (next) el.setAttribute(attr, '')
- else el.removeAttribute(attr)
- return
- }
-
- // aria-* and data-* attributes stringify booleans to `"true"`/`"false"`
- // rather than using the HTML boolean-attribute presence/absence semantics.
- // This matches React and the ARIA spec (aria-hidden="false" is meaningful).
- if (name.length > 5 && (name.charCodeAt(0) === 97 /* a */ || name.charCodeAt(0) === 100 /* d */)) {
- if (name.startsWith('aria-') || name.startsWith('data-')) {
- if (next == null) {
- el.removeAttribute(attr)
- } else {
- el.setAttribute(attr, '' + next)
- }
- return
- }
- }
+ if (BOOLEAN_ATTRS.has(attr)) next = !!next
if (next == null || next === false) {
el.removeAttribute(attr)
- } else if (next === true) {
- el.setAttribute(attr, '')
} else {
- el.setAttribute(attr, '' + next)
+ el.setAttribute(attr, next === true ? '' : next)
}
}
@@ -241,7 +261,7 @@ export interface SyntheticEvent extends Event {
currentTarget: EventTarget & Element
}
-function setEventHandler(el: Element, name: string, next: any, prev: any): void {
+function setEventHandler(el: Element, name: string, next: any): void {
// Only function handlers are accepted. Reject strings/objects/etc — the
// legacy `onclick="..."` HTML attribute (string handler) is a known XSS
// vector if a parent spreads untrusted props onto a host element. React
@@ -256,13 +276,11 @@ function setEventHandler(el: Element, name: string, next: any, prev: any): void
// `onInput` on the same text input — which both dispatch from the native
// `input` event — can coexist without clobbering each other's handlers.
const handlers = ((el as any).__handlers ||= Object.create(null))
- const key = name
-
- const existing = handlers[key]
+ const existing = handlers[name]
if (existing && !next) {
- el.removeEventListener(existing.event, existing.listener, existing.capture)
- handlers[key] = null
+ el.removeEventListener(existing.event, existing.listener, capture)
+ handlers[name] = null
return
}
@@ -271,7 +289,6 @@ function setEventHandler(el: Element, name: string, next: any, prev: any): void
current: next as Function,
listener: null as any,
event: eventName,
- capture,
}
entry.listener = (e: Event) => {
// React hands handlers a SyntheticEvent that carries `.nativeEvent`.