Repository navigation
Expand file tree
/
Copy pathcommit-error-parity.patch
More file actions
5282 lines (5095 loc) · 196 KB
/
Copy pathcommit-error-parity.patch
File metadata and controls
5282 lines (5095 loc) · 196 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..37d09b3 100644
--- a/core/internal.ts
+++ b/core/internal.ts
@@ -14,6 +14,7 @@ export const enum FiberTag {
Lazy = 10,
Suspense = 11,
Root = 12,
+ Activity = 13,
}
export interface Hook {
@@ -21,12 +22,12 @@ 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
}
export interface Fiber {
@@ -42,24 +43,35 @@ 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
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 }) => void
+
export interface FiberRoot {
c: Element | DocumentFragment
r: Fiber
p: Set<Fiber>
s: boolean
- re?: ((err: unknown) => void) | undefined
+ u?: (() => void) | undefined
+ eb?: boolean
+ re?: RecoverableErrorHandler | undefined
ce?: ((err: unknown) => void) | undefined
ue?: ((err: unknown) => void) | 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/dom/commit.ts b/dom/commit.ts
new file mode 100644
index 0000000..fa16e45
--- /dev/null
+++ b/dom/commit.ts
@@ -0,0 +1,160 @@
+import { FiberTag, type Fiber } 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
+ for (const work of plan.q[4]!) work()
+ 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()
+}
+
+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
+ const hooks = fiber.hooks?.map(hook => [hook, { ...hook }, hook.q && typeof hook.q === 'object' ? { ...hook.q } : null] as const)
+ 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) {
+ for (const [hook, snapshot, queue] of hooks) {
+ Object.assign(hook, snapshot)
+ if (queue) Object.assign(hook.q, queue)
+ }
+ fiber.hooks = hooks.map(([hook]) => hook)
+ }
+ 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..99bdf6d 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 { ReactSharedInternals, REACT_CONTEXT_TYPE, startTransition } from '../react'
+import { scheduleUpdate, enqueueEffect, readContext, rememberActivityEffect } 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,6 +37,57 @@ function depsEqual(
type BasicStateAction<S> = S | ((p: S) => S)
+function initialState<S>(initial: S | (() => S)): S {
+ return typeof initial === 'function' ? (initial as () => S)() : initial
+}
+
+function initializeReducer(hook: Hook, fiber: Fiber, initialArg: any, init?: (arg: any) => any): void {
+ hook.s = init ? init(initialArg) : initialArg
+ hook.q = (action: any) => {
+ const currentState = hook.s
+ const next = hook.d(currentState, action)
+ if (!Object.is(next, currentState)) {
+ hook.s = next
+ scheduleUpdate(fiber)
+ }
+ }
+}
+
+function cleanupEffect(hook: Hook, fiber: Fiber): void {
+ if (!hook.c) return
+ try { hook.c() } catch {}
+ if (fiber.cu) {
+ const index = fiber.cu.indexOf(hook.c)
+ if (index >= 0) fiber.cu.splice(index, 1)
+ }
+ hook.c = null
+}
+
+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) return
+ 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) {
+ if (!deferTransitionPassive(cleanup)) queueCommitEffects(cleanup)
+ } else cleanup()
+ } : null
+ return hook.c
+ },
+ }
+ if (type === 1) effect.d = () => cleanupEffect(hook, fiber)
+ rememberActivityEffect(fiber, hook, effect)
+ if (changed) enqueueEffect(fiber, effect)
+}
+
// 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-
@@ -72,95 +103,28 @@ function makeDispatcherImpl() {
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,
+ initial,
+ initialState,
)
},
useReducer<S, A>(reducer: (s: S, a: A) => S, initialArg: any, init?: (a: any) => S) {
const hook = nextHook()
- const 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 = next
- scheduleUpdate(fiber)
- }
- }
- queue.d = dispatch
- hook.q = queue
- } else {
- hook.q.r = reducer
- }
- return [hook.s, hook.q.d] as [S, (a: A) => void]
+ if (hook.q === undefined) initializeReducer(hook, getCurrentFiber(), initialArg, init)
+ hook.d = reducer
+ return [hook.s, hook.q] as [S, (a: A) => void]
},
useEffect(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: 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)
+ 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 +154,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 +183,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,
@@ -254,7 +226,8 @@ function makeDispatcherImpl() {
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) {
hook.d = deps
const effect: Effect = {
t: 1,
@@ -311,12 +284,14 @@ function makeDispatcherImpl() {
return cleanup
},
}
- enqueueEffect(fiber, effect)
+ rememberActivityEffect(fiber, hook, effect)
+ if (changed) enqueueEffect(fiber, effect)
}
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 +347,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..e980703 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`.
@@ -282,7 +299,7 @@ function setEventHandler(el: Element, name: string, next: any, prev: any): void
if ((e as any).nativeEvent === undefined) (e as any).nativeEvent = e
entry.current(e)
}
- handlers[key] = entry
+ handlers[name] = entry
el.addEventListener(eventName, entry.listener, capture)
return
}
@@ -291,10 +308,9 @@ function setEventHandler(el: Element, name: string, next: any, prev: any): void
// Re-bind if the effective DOM event changed (e.g. <input> whose `type`
// flipped from "text" to "checkbox" — onChange should now follow `change`
// instead of `input`). This is rare but keeps semantics correct.
- if (existing.event !== eventName || existing.capture !== capture) {
- el.removeEventListener(existing.event, existing.listener, existing.capture)
+ if (existing.event !== eventName) {
+ el.removeEventListener(existing.event, existing.listener, capture)
existing.event = eventName
- existing.capture = capture
el.addEventListener(eventName, existing.listener, capture)
}
existing.current = next
diff --git b/dom/features/activity/full.ts b/dom/features/activity/full.ts
new file mode 100644
index 0000000..0159c1c
--- /dev/null
+++ b/dom/features/activity/full.ts
@@ -0,0 +1,187 @@
+import { FiberTag, type Fiber, type Hook, type Effect } from '../../../core'
+import { REACT_ACTIVITY_TYPE } from '../../../react/activity'
+import { onCommitRollback, queueMutation } from '../../commit'
+import {
+ attachRef,
+ childrenToArray,
+ detachRef,
+ enqueueEffect,
+ findRoot,
+ flushFiberCommits,
+ getCurrentRoot,
+ installCapability,
+ reconcileChildren,
+ registerRenderer,
+ registerTypeMatcher,
+ scheduleLifecycle,
+ scheduleUpdate,
+} from '../../reconcile'
+
+// Retain effect descriptions, not subscriptions, while a subtree is hidden.
+// Weak keys keep this bookkeeping out of fibers that do not use Activity.
+const effects = new WeakMap<Fiber, Map<Hook, Effect>>()
+const disconnected = new WeakSet<Fiber>()
+const hiddenDoms = new WeakSet<Fiber>()
+
+function setMembership(set: WeakSet<Fiber>, fiber: Fiber, present: boolean): boolean {
+ const previous = set.has(fiber)
+ if (previous === present) return previous
+ onCommitRollback(() => { if (previous) set.add(fiber); else set.delete(fiber) })
+ if (present) set.add(fiber)
+ else set.delete(fiber)
+ return previous
+}
+
+function isHidden(fiber: Fiber): boolean {
+ if (!(fiber.root ?? findRoot(fiber))?.a) return false
+ for (let parent: Fiber | null = fiber; parent; parent = parent.parent) {
+ if (parent.tag === FiberTag.Activity && parent.pp?.mode === 'hidden') return true
+ }
+ return false
+}
+
+function rememberEffect(fiber: Fiber, hook: Hook, effect: Effect): void {
+ if (!(fiber.root ?? findRoot(fiber))?.a) return
+ let entries = effects.get(fiber)
+ if (!entries) {
+ effects.set(fiber, entries = new Map())
+ onCommitRollback(() => { effects.delete(fiber) })
+ }
+ const previous = entries.get(hook)
+ const target = entries
+ onCommitRollback(() => { if (previous) target.set(hook, previous); else target.delete(hook) })
+ entries.set(hook, effect)
+}
+
+function report(fiber: Fiber, fn: () => void): void {
+ try { fn() } catch (error) { (fiber.root ?? findRoot(fiber))?.ce?.(error) }
+}
+
+function disconnect(fiber: Fiber): void {
+ if (disconnected.has(fiber)) return
+ setMembership(disconnected, fiber, true)
+ queueMutation(() => {
+ // Insertion effects remain connected, just as they do in React.
+ const insertion = new Set<() => void>()
+ for (const [hook, effect] of effects.get(fiber) ?? []) {
+ if (effect.t === 2 && hook.c) insertion.add(hook.c)
+ }
+ if (fiber.cu) {
+ const keep = fiber.cu.filter(cleanup => insertion.has(cleanup))
+ for (const cleanup of fiber.cu) {
+ if (!insertion.has(cleanup)) report(fiber, cleanup)
+ }
+ fiber.cu = keep.length ? keep : null
+ }
+ for (const [hook, effect] of effects.get(fiber) ?? []) {
+ if (effect.t !== 2) hook.c = null
+ }
+ detachRef(fiber.cr ?? fiber.ref)
+ fiber.cr = null
+ fiber.rc = null
+ if (fiber.tag === FiberTag.Class && fiber.sn?.componentWillUnmount) {
+ report(fiber, () => fiber.sn.componentWillUnmount())
+ }
+ })
+}
+
+function walk(fiber: Fiber, visit: (fiber: Fiber) => void, postorder = false): void {
+ if (!postorder) visit(fiber)
+ for (let child = fiber.child; child; child = child.sibling) walk(child, visit, postorder)
+ if (fiber.tag === FiberTag.Suspense && fiber.ms?.f) walk(fiber.ms.f, visit, postorder)
+ if (postorder) visit(fiber)
+}
+
+function prepare(fiber: Fiber): void {
+ if (!isHidden(fiber) || disconnected.has(fiber)) return
+ if (fiber.mp == null) setMembership(disconnected, fiber, true)
+ else disconnect(fiber)
+}
+
+function needsHiddenDom(fiber: Fiber): boolean {
+ for (let parent = fiber.parent; parent; parent = parent.parent) {
+ if (parent.tag === FiberTag.Activity && parent.pp?.mode === 'hidden') return true
+ if (parent.tag === FiberTag.Host) return false
+ // A portal starts a new DOM tree, but keeps the parent's Activity state.
+ if (parent.tag === FiberTag.Portal) return isHidden(parent)
+ }
+ return false
+}
+
+function syncDom(fiber: Fiber): void {
+ if (!(fiber.root ?? findRoot(fiber))?.a) return
+ if (!fiber.dom || (fiber.tag !== FiberTag.Host && fiber.tag !== FiberTag.Text)) return
+ if (needsHiddenDom(fiber)) {
+ setMembership(hiddenDoms, fiber, true)
+ queueMutation(() => {
+ if (fiber.tag === FiberTag.Text) fiber.dom!.nodeValue = ''
+ else (fiber.dom as HTMLElement).style.setProperty('display', 'none', 'important')
+ })
+ } else if (setMembership(hiddenDoms, fiber, false)) {
+ // A Suspense fallback can remain active after its Activity is revealed.
+ // Its preserved primary DOM must stay hidden until that boundary resumes.
+ for (let parent = fiber.parent; parent; parent = parent.parent) {
+ if (parent.tag === FiberTag.Suspense && parent.ms?.d?.some(([node]: [Node, string]) => node === fiber.dom)) return
+ }
+ const props = fiber.pp
+ queueMutation(() => {
+ if (fiber.tag === FiberTag.Text) fiber.dom!.nodeValue = props
+ else {
+ const display = props?.style?.display
+ ;(fiber.dom as HTMLElement).style.display = display == null || typeof display === 'boolean' ? '' : ('' + display).trim()
+ }
+ })
+ }
+}
+
+function reconnect(fiber: Fiber): void {
+ syncDom(fiber)
+ if (isHidden(fiber) || inSuspensePrimary(fiber) || !setMembership(disconnected, fiber, false)) return
+ if (fiber.tag === FiberTag.Host) attachRef(fiber, fiber.dom)
+ else if (fiber.tag === FiberTag.Class || fiber.tag === FiberTag.Fragment) attachRef(fiber, fiber.sn)
+ for (const effect of effects.get(fiber)?.values() ?? []) {
+ if (effect.t !== 2) enqueueEffect(fiber, effect)
+ }
+ if (fiber.tag === FiberTag.Class && fiber.sn?.componentDidMount) {
+ scheduleLifecycle(fiber, () => fiber.sn.componentDidMount())
+ }
+ flushFiberCommits(fiber)
+}
+
+function inSuspensePrimary(fiber: Fiber): boolean {
+ for (let child = fiber, parent = fiber.parent; parent; child = parent, parent = parent.parent) {
+ if (parent.tag === FiberTag.Suspense && parent.ms?.d && parent.ms.f !== child) return true
+ }
+ return false
+}
+
+function finish(fiber: Fiber): void {
+ if (fiber.tag === FiberTag.Suspense && (fiber.root ?? findRoot(fiber))?.a) walk(fiber, reconnect, true)
+ else syncDom(fiber)
+}
+
+function renderActivity(fiber: Fiber, domParent: Node, anchor: Node | null): void {
+ const root = fiber.root ?? findRoot(fiber)
+ if (root) root.a = true
+ const props = fiber.pp ?? {}
+ // Hidden content is absent from server HTML. Mount it after hydration so it
+ // cannot consume a following visible sibling's hydration cursor.
+ if (getCurrentRoot()?.h && props.mode === 'hidden' && !fiber.mp) {
+ fiber.mp = props
+ queueMicrotask(() => scheduleUpdate(fiber))
+ return
+ }
+ if (isHidden(fiber)) walk(fiber, prepare)
+ else walk(fiber, syncDom)
+ reconcileChildren(fiber, childrenToArray(props.children), domParent, anchor)
+ walk(fiber, reconnect, true)
+ fiber.mp = props
+}
+
+installCapability('isActivityHidden', isHidden)
+installCapability('activityIsDisconnected', fiber => disconnected.has(fiber))
+installCapability('rememberActivityEffect', rememberEffect)
+installCapability('prepareActivityFiber', prepare)
+installCapability('syncActivity', finish)
+registerTypeMatcher(type => type === REACT_ACTIVITY_TYPE ? FiberTag.Activity : null)
+registerRenderer(FiberTag.Activity, renderActivity)
diff --git b/dom/features/activity/index.ts b/dom/features/activity/index.ts
new file mode 100644
index 0000000..007f15d
--- /dev/null
+++ b/dom/features/activity/index.ts
@@ -0,0 +1 @@
+export * from './full'
diff --git b/dom/features/activity/stub.ts b/dom/features/activity/stub.ts
new file mode 100644
index 0000000..0c507dd
--- /dev/null
+++ b/dom/features/activity/stub.ts
@@ -0,0 +1,14 @@
+import { FiberTag, type Fiber } from '../../../core'
+import { REACT_ACTIVITY_TYPE } from '../../../react/activity'