what-core 0.13.11 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -38
  3. package/a11y.d.ts +128 -0
  4. package/data.d.ts +294 -0
  5. package/dist/a11y.js +510 -0
  6. package/dist/a11y.min.js +413 -0
  7. package/dist/actions.js +158 -0
  8. package/dist/actions.min.js +112 -0
  9. package/dist/animation.js +481 -0
  10. package/dist/animation.min.js +295 -0
  11. package/dist/async.js +180 -0
  12. package/dist/async.min.js +134 -0
  13. package/dist/components.js +577 -0
  14. package/dist/components.min.js +413 -0
  15. package/dist/data.js +1212 -0
  16. package/dist/data.min.js +918 -0
  17. package/dist/diagnostics.js +187 -0
  18. package/dist/diagnostics.min.js +134 -0
  19. package/dist/dom.js +796 -0
  20. package/dist/dom.min.js +603 -0
  21. package/dist/entries/a11y.js +43 -0
  22. package/dist/entries/a11y.min.js +43 -0
  23. package/dist/entries/data.js +29 -0
  24. package/dist/entries/data.min.js +29 -0
  25. package/dist/entries/dom.js +45 -0
  26. package/dist/entries/dom.min.js +45 -0
  27. package/dist/entries/form.js +31 -0
  28. package/dist/entries/form.min.js +31 -0
  29. package/dist/entries/internal.js +123 -0
  30. package/dist/entries/internal.min.js +123 -0
  31. package/dist/entries/motion.js +23 -0
  32. package/dist/entries/motion.min.js +23 -0
  33. package/dist/entries/ui.js +25 -0
  34. package/dist/entries/ui.min.js +25 -0
  35. package/dist/env.js +5 -0
  36. package/dist/env.min.js +5 -0
  37. package/dist/errors.js +1518 -0
  38. package/dist/errors.min.js +548 -0
  39. package/dist/form.js +936 -0
  40. package/dist/form.min.js +703 -0
  41. package/dist/guardrails.js +84 -0
  42. package/dist/guardrails.min.js +55 -0
  43. package/dist/h.js +232 -0
  44. package/dist/h.min.js +171 -0
  45. package/dist/head.js +241 -0
  46. package/dist/head.min.js +207 -0
  47. package/dist/helpers.js +126 -0
  48. package/dist/helpers.min.js +98 -0
  49. package/dist/hooks.js +255 -0
  50. package/dist/hooks.min.js +153 -0
  51. package/dist/hot.js +215 -0
  52. package/dist/hot.min.js +24 -0
  53. package/dist/hydration-data.js +495 -0
  54. package/dist/hydration-data.min.js +371 -0
  55. package/dist/import-changes.js +273 -0
  56. package/dist/import-changes.min.js +272 -0
  57. package/dist/index.js +95 -0
  58. package/dist/index.min.js +95 -227
  59. package/dist/jsx-dev-runtime.js +10 -0
  60. package/dist/jsx-dev-runtime.min.js +10 -1
  61. package/dist/jsx-runtime.js +27 -0
  62. package/dist/jsx-runtime.min.js +15 -1
  63. package/dist/live.js +54 -0
  64. package/dist/live.min.js +49 -0
  65. package/dist/markup-rules.js +250 -0
  66. package/dist/markup-rules.min.js +213 -0
  67. package/dist/reactive.js +3334 -0
  68. package/dist/reactive.min.js +2033 -0
  69. package/dist/render.js +4746 -0
  70. package/dist/render.min.js +2797 -1
  71. package/dist/scheduler.js +225 -0
  72. package/dist/scheduler.min.js +162 -0
  73. package/dist/selector.js +11 -0
  74. package/dist/selector.min.js +10 -0
  75. package/dist/server-context.js +148 -0
  76. package/dist/server-context.min.js +121 -0
  77. package/dist/skeleton.js +342 -0
  78. package/dist/skeleton.min.js +310 -0
  79. package/dist/store.js +72 -0
  80. package/dist/store.min.js +50 -0
  81. package/dist/testing.js +720 -0
  82. package/dist/testing.min.js +458 -1
  83. package/dist/vnode-adoption.js +19 -0
  84. package/dist/vnode-adoption.min.js +19 -0
  85. package/dist/vnode-renderer.js +61 -0
  86. package/dist/vnode-renderer.min.js +47 -0
  87. package/dom.d.ts +44 -0
  88. package/form.d.ts +218 -0
  89. package/hot.d.ts +35 -0
  90. package/index.d.ts +421 -736
  91. package/internal.d.ts +284 -0
  92. package/jsx-runtime.d.ts +160 -137
  93. package/markup-rules.d.ts +83 -0
  94. package/motion.d.ts +156 -0
  95. package/package.json +117 -3
  96. package/render.d.ts +278 -29
  97. package/src/a11y.js +64 -59
  98. package/src/actions.js +226 -0
  99. package/src/animation.js +105 -57
  100. package/src/async.js +259 -0
  101. package/src/components.js +495 -144
  102. package/src/data.js +1410 -1159
  103. package/src/diagnostics.js +263 -0
  104. package/src/dom.js +1159 -872
  105. package/src/entries/a11y.js +24 -0
  106. package/src/entries/data.js +17 -0
  107. package/src/entries/dom.js +29 -0
  108. package/src/entries/form.js +16 -0
  109. package/src/entries/internal.js +63 -0
  110. package/src/entries/motion.js +13 -0
  111. package/src/entries/ui.js +13 -0
  112. package/src/env-development.js +12 -0
  113. package/src/env.js +33 -0
  114. package/src/errors.js +1144 -168
  115. package/src/form.js +723 -225
  116. package/src/guardrails.js +38 -126
  117. package/src/h.js +227 -152
  118. package/src/head.js +189 -19
  119. package/src/helpers.js +47 -75
  120. package/src/hooks.js +233 -248
  121. package/src/hot.js +316 -0
  122. package/src/hydration-data.js +859 -16
  123. package/src/import-changes.js +156 -0
  124. package/src/index.js +38 -188
  125. package/src/jsx-dev-runtime.js +7 -14
  126. package/src/jsx-runtime.js +25 -9
  127. package/src/live.js +80 -0
  128. package/src/markup-rules.js +387 -0
  129. package/src/reactive.js +4400 -862
  130. package/src/render.js +6502 -2570
  131. package/src/scheduler.js +56 -21
  132. package/src/selector.js +31 -0
  133. package/src/server-context.js +252 -22
  134. package/src/skeleton.js +22 -12
  135. package/src/store.js +17 -31
  136. package/src/testing.js +389 -63
  137. package/src/vnode-adoption.js +48 -0
  138. package/src/vnode-renderer.js +114 -0
  139. package/testing.d.ts +81 -1
  140. package/ui.d.ts +20 -0
  141. package/dist/chunk-6YOUZ6T4.min.js +0 -1
  142. package/dist/chunk-FN6HXME3.min.js +0 -11
  143. package/dist/chunk-VKZY7JPN.min.js +0 -1
  144. package/src/agent-context.js +0 -127
  145. package/src/warnings.js +0 -193
package/src/animation.js CHANGED
@@ -1,18 +1,9 @@
1
1
  // What Framework - Animation Primitives
2
2
  // Springs, tweens, gestures, and transition helpers
3
3
 
4
- import { signal, effect, untrack, batch } from './reactive.js';
5
- import { getCurrentComponent } from './dom.js';
4
+ import { signal, effect, batch, onCleanup, createRoot, untrack, _userEffect } from './reactive.js';
6
5
  import { scheduleRead, scheduleWrite } from './scheduler.js';
7
6
 
8
- // Create an effect scoped to the current component's lifecycle
9
- function scopedEffect(fn) {
10
- const ctx = getCurrentComponent?.();
11
- const dispose = effect(fn);
12
- if (ctx) ctx.effects.push(dispose);
13
- return dispose;
14
- }
15
-
16
7
  // --- Spring Animation ---
17
8
  // Physics-based animation with natural feel
18
9
 
@@ -106,12 +97,8 @@ export function spring(initialValue, options = {}) {
106
97
  });
107
98
  }
108
99
 
109
- // Register stop() as cleanup if inside a component
110
- const ctx = getCurrentComponent?.();
111
- if (ctx) {
112
- ctx._cleanupCallbacks = ctx._cleanupCallbacks || [];
113
- ctx._cleanupCallbacks.push(stop);
114
- }
100
+ // Stop when the owner (the component using the spring) goes away.
101
+ onCleanup(stop);
115
102
 
116
103
  return {
117
104
  current: () => current(),
@@ -150,7 +137,8 @@ export function tween(from, to, options = {}) {
150
137
  const t0 = /** @type {number} */ (startTime);
151
138
 
152
139
  const elapsed = time - t0;
153
- const t = Math.min(elapsed / duration, 1);
140
+ // A zero duration ends on the first frame (0 / 0 would be NaN).
141
+ const t = duration > 0 ? Math.min(elapsed / duration, 1) : 1;
154
142
  const easedT = easing(t);
155
143
  const currentValue = from + (to - from) * easedT;
156
144
 
@@ -171,14 +159,19 @@ export function tween(from, to, options = {}) {
171
159
 
172
160
  rafId = requestAnimationFrame(tick);
173
161
 
162
+ function cancel() {
163
+ if (rafId) cancelAnimationFrame(rafId);
164
+ isAnimating.set(false);
165
+ }
166
+ // Stop when the owner (the component using the tween) goes away, as a
167
+ // spring does.
168
+ onCleanup(cancel);
169
+
174
170
  return {
175
171
  progress: () => progress(),
176
172
  value: () => value(),
177
173
  isAnimating: () => isAnimating(),
178
- cancel: () => {
179
- if (rafId) cancelAnimationFrame(rafId);
180
- isAnimating.set(false);
181
- },
174
+ cancel,
182
175
  subscribe: value.subscribe,
183
176
  };
184
177
  }
@@ -205,37 +198,55 @@ export const easings = {
205
198
  },
206
199
  };
207
200
 
208
- // --- useTransition Hook ---
209
- // Animate between states
201
+ // --- useTween ---
202
+ // Progress from 0 to 1 over `duration`, eased, as a signal. One run at a
203
+ // time: start() stops the run in flight (its promise resolves, its callback
204
+ // does not run), and the owner going away stops it.
210
205
 
211
- export function useTransition(options = {}) {
206
+ export function useTween(options = {}) {
212
207
  const { duration = 300, easing = easings.easeOutQuad } = options;
213
208
 
214
209
  const isTransitioning = signal(false);
215
210
  const progress = signal(0);
211
+ /** @type {{ frame: number, resolve: () => void } | null} */
212
+ let run = null;
213
+
214
+ const stopRun = () => {
215
+ const stopped = run;
216
+ if (stopped === null) return;
217
+ run = null;
218
+ cancelAnimationFrame(stopped.frame);
219
+ stopped.resolve();
220
+ };
221
+ onCleanup(stopRun);
216
222
 
217
223
  async function start(callback) {
224
+ stopRun();
218
225
  isTransitioning.set(true);
219
226
  progress.set(0);
220
227
 
221
228
  return /** @type {Promise<void>} */ (new Promise((resolve) => {
222
229
  const startTime = performance.now();
230
+ const own = { frame: 0, resolve };
231
+ run = own;
223
232
 
224
233
  function tick(time) {
234
+ if (run !== own) return;
225
235
  const elapsed = time - startTime;
226
236
  const t = Math.min(elapsed / duration, 1);
227
237
  progress.set(easing(t));
228
238
 
229
239
  if (t < 1) {
230
- requestAnimationFrame(tick);
240
+ own.frame = requestAnimationFrame(tick);
231
241
  } else {
242
+ run = null;
232
243
  isTransitioning.set(false);
233
244
  if (callback) callback();
234
245
  resolve();
235
246
  }
236
247
  }
237
248
 
238
- requestAnimationFrame(tick);
249
+ own.frame = requestAnimationFrame(tick);
239
250
  }));
240
251
  }
241
252
 
@@ -276,6 +287,9 @@ export function useGesture(element, handlers = {}) {
276
287
  let lastY = 0;
277
288
  /** @type {ReturnType<typeof setTimeout> | null} */
278
289
  let longPressTimer = null;
290
+ // Whether this gesture was reported as a long press, which is then not
291
+ // also a tap.
292
+ let longPressed = false;
279
293
 
280
294
  function handleStart(e) {
281
295
  const touch = e.touches ? e.touches[0] : e;
@@ -284,14 +298,26 @@ export function useGesture(element, handlers = {}) {
284
298
  lastX = touch.clientX;
285
299
  lastY = touch.clientY;
286
300
  lastTime = performance.now();
301
+ // A new gesture starts from rest: the last one's travel and velocity
302
+ // would read as this one's (a tap after a swipe, swiping again).
303
+ batch(() => {
304
+ state.currentX.set(touch.clientX);
305
+ state.currentY.set(touch.clientY);
306
+ state.deltaX.set(0);
307
+ state.deltaY.set(0);
308
+ state.velocity.set({ x: 0, y: 0 });
309
+ });
287
310
 
288
311
  state.isDragging.set(true);
289
312
  if (onDragStart) onDragStart({ x: state.startX, y: state.startY });
290
313
 
291
314
  // Long press detection
315
+ longPressed = false;
292
316
  if (onLongPress) {
293
317
  longPressTimer = setTimeout(() => {
318
+ longPressTimer = null;
294
319
  if (state.isDragging.peek()) {
320
+ longPressed = true;
295
321
  onLongPress({ x: lastX, y: lastY });
296
322
  }
297
323
  }, 500);
@@ -359,7 +385,7 @@ export function useGesture(element, handlers = {}) {
359
385
  const distance = Math.sqrt(deltaX ** 2 + deltaY ** 2);
360
386
 
361
387
  // Tap detection
362
- if (distance < 10 && onTap) {
388
+ if (distance < 10 && onTap && !longPressed) {
363
389
  onTap({ x: state.startX, y: state.startY });
364
390
  }
365
391
 
@@ -411,23 +437,18 @@ export function useGesture(element, handlers = {}) {
411
437
  initialPinchDistance = null;
412
438
  }
413
439
 
414
- // Attach listeners
415
- if (typeof element === 'function') {
416
- // Ref function
417
- scopedEffect(() => {
418
- const el = untrack(element);
419
- if (!el) return;
420
- return attachListeners(el);
421
- });
422
- } else if (element?.current !== undefined) {
423
- // Ref object
424
- scopedEffect(() => {
425
- const el = element.current;
440
+ // Attach listeners. A ref (an object's `current`, or a function that
441
+ // returns the element) is read once the component's output is in place, as
442
+ // useEffect runs: the component body runs before its element exists. A
443
+ // function that reads a signal attaches again when the signal changes.
444
+ if (typeof element === 'function' || element?.current !== undefined) {
445
+ _userEffect(() => {
446
+ const el = typeof element === 'function' ? element() : element.current;
426
447
  if (!el) return;
427
448
  return attachListeners(el);
428
449
  });
429
450
  } else if (element) {
430
- attachListeners(element);
451
+ onCleanup(attachListeners(element));
431
452
  }
432
453
 
433
454
  function attachListeners(el) {
@@ -456,10 +477,37 @@ export function useGesture(element, handlers = {}) {
456
477
  }
457
478
 
458
479
  // --- useAnimatedValue Hook ---
459
- // Like React Native's Animated.Value
480
+ // Like React Native's Animated.Value. One animation is in flight at a time:
481
+ // spring() and timing() stop the one before, so the value ends on the newest
482
+ // target, and the owner going away stops it. Each animation lives in a root
483
+ // of its own, which a spring disposes once it has settled.
460
484
 
461
485
  export function useAnimatedValue(initialValue) {
462
486
  const value = signal(initialValue);
487
+ /** @type {(() => void) | null} */
488
+ let running = null;
489
+ const stopRunning = () => {
490
+ const stop = running;
491
+ running = null;
492
+ if (stop !== null) stop();
493
+ };
494
+ onCleanup(stopRunning);
495
+
496
+ // Runs `start` in a root that stopping the animation disposes; `start`
497
+ // gets the function that ends it.
498
+ const animate = (start) => {
499
+ stopRunning();
500
+ const stop = createRoot((dispose) => {
501
+ const end = () => {
502
+ if (running === end) running = null;
503
+ dispose();
504
+ };
505
+ untrack(() => start(end));
506
+ return end;
507
+ });
508
+ running = stop;
509
+ return { stop: () => { if (running === stop) stopRunning(); } };
510
+ };
463
511
 
464
512
  return {
465
513
  value: () => value(),
@@ -467,28 +515,28 @@ export function useAnimatedValue(initialValue) {
467
515
 
468
516
  // Spring to target
469
517
  spring(toValue, config = {}) {
470
- const s = spring(value.peek(), config);
471
- s.set(toValue);
472
-
473
- const dispose = effect(() => {
474
- value.set(s.current());
518
+ return animate((end) => {
519
+ const s = spring(value.peek(), config);
520
+ s.set(toValue);
521
+ effect(() => {
522
+ value.set(s.current());
523
+ if (!s.isAnimating()) end();
524
+ });
475
525
  });
476
-
477
- return {
478
- stop: () => { s.stop(); dispose(); },
479
- };
480
526
  },
481
527
 
482
528
  // Tween to target
483
529
  timing(toValue, config = {}) {
484
- const t = tween(value.peek(), toValue, {
485
- ...config,
486
- onUpdate: (v) => value.set(v),
530
+ return animate((end) => {
531
+ tween(value.peek(), toValue, {
532
+ ...config,
533
+ onUpdate: (v) => value.set(v),
534
+ onComplete: () => {
535
+ end();
536
+ if (config.onComplete) config.onComplete();
537
+ },
538
+ });
487
539
  });
488
-
489
- return {
490
- stop: () => t.cancel(),
491
- };
492
540
  },
493
541
 
494
542
  // Interpolate value
package/src/async.js ADDED
@@ -0,0 +1,259 @@
1
+ // What Framework - Async values
2
+ //
3
+ // The async surface of the root entry, on the engine's async computeds and
4
+ // transitions (reactive.js):
5
+ //
6
+ // computed(fn) a computed whose function may return a promise or an
7
+ // async iterable: an async value in the graph
8
+ // refresh(c) fetch it again
9
+ // isPending(fn) is a value fn reads being fetched again?
10
+ // startTransition(fn) commit what fn's writes cause in one step, once the
11
+ // async work they started has landed
12
+ // useTransition() [isPending, startTransition]
13
+ // useOptimistic(s, fn) [optimistic state, addOptimistic]
14
+ // use(x) read a promise, a context or an accessor
15
+ // settled() resolves when nothing is queued, fetching or open
16
+ //
17
+ // docs/ASYNC.md describes the model and what it guarantees.
18
+
19
+ import {
20
+ _asyncComputed,
21
+ _devCallSite,
22
+ _refresh,
23
+ _isPending,
24
+ _startTransition,
25
+ _currentTransition,
26
+ _onCommit,
27
+ _urgent,
28
+ _latestComputed,
29
+ _runHeldReaders,
30
+ _busy,
31
+ _onQuiet,
32
+ _currentComponent,
33
+ signal,
34
+ untrack,
35
+ getOwner,
36
+ onCleanup,
37
+ __DEV__,
38
+ __devtools,
39
+ } from './reactive.js';
40
+ import { _seedFor } from './hydration-data.js';
41
+ import { _enableSuspense } from './render.js';
42
+ import { useContext } from './hooks.js';
43
+ import { report, recordObservation, _thrownMessage } from './diagnostics.js';
44
+
45
+ /**
46
+ * A computed. Its function may return a promise, a thenable or an async
47
+ * iterable: the computed is then an async value. It keeps its last value while
48
+ * a newer run is in flight, supersedes and aborts older runs, and a function
49
+ * that takes an argument gets `{ signal }`, the run's AbortSignal. A tracked
50
+ * read of a value that has not landed holds the reader (see docs/ASYNC.md).
51
+ */
52
+ export function computed(fn) {
53
+ _enableSuspense();
54
+ if (__DEV__) return /** @type {any} */ (_asyncComputed)(fn, _seedFor(null, true), _devCallSite(arguments[1] || fn.name, computed));
55
+ return _asyncComputed(fn, _seedFor(null, true));
56
+ }
57
+
58
+ /**
59
+ * Run an async computed again now. Its readers see it as pending (once it has
60
+ * a value) until the new value lands. Resolves with the value when it lands,
61
+ * rejects with its error.
62
+ */
63
+ export function refresh(c) {
64
+ return _refresh(c);
65
+ }
66
+
67
+ /**
68
+ * Whether an async computed that `fn` reads, directly or through computeds,
69
+ * has a value and is fetching a new one. False on first load, before any value
70
+ * has landed. Tracked like a read: a binding re-runs when the answer changes.
71
+ */
72
+ export function isPending(fn) {
73
+ return _isPending(fn);
74
+ }
75
+
76
+ /**
77
+ * Hold everything the writes inside `fn` reach until the async work they
78
+ * started has landed, then commit it in one flush. Writes outside `fn` commit
79
+ * as usual. Returns a promise that resolves when the transition commits and
80
+ * rejects with an async `fn`'s rejection. Writes `fn` makes after an `await`
81
+ * are ordinary writes, as in React.
82
+ */
83
+ export function startTransition(fn) {
84
+ return _startTransition(fn);
85
+ }
86
+
87
+ /**
88
+ * React's useTransition: `[isPending, startTransition]`. `isPending` is an
89
+ * accessor, `isPending()`, true from the moment `startTransition` is called
90
+ * until the transition commits. Leaving the component stops waiting for the
91
+ * async part of its transitions. A rejection goes to the error boundary above
92
+ * the component, as in React 19; the returned promise rejects too.
93
+ */
94
+ export function useTransition() {
95
+ const open = signal(0);
96
+ /** @type {Set<any>} */
97
+ const calls = new Set();
98
+ const owner = getOwner();
99
+ if (owner !== null) onCleanup(() => { for (const call of calls) call.abandon(); });
100
+ const isPending = () => open() > 0;
101
+ const start = (fn) => _startTransition(fn, (t, call) => {
102
+ open((n) => n + 1);
103
+ call.owner = owner;
104
+ calls.add(call);
105
+ _onCommit(t, () => {
106
+ open((n) => n - 1);
107
+ calls.delete(call);
108
+ });
109
+ });
110
+ return [isPending, start];
111
+ }
112
+
113
+ /**
114
+ * React 19's useOptimistic. Returns `[optimistic, addOptimistic]`:
115
+ * `optimistic()` is `state` (an accessor, or a plain value) with every overlay
116
+ * added by `addOptimistic(value)` applied through `update(current, value)`
117
+ * (or replacing it, without `update`). An overlay lives as long as the
118
+ * transition it was added in: it shows at once and drops when that transition
119
+ * commits, in the same flush that shows the real result, so neither the
120
+ * confirmation nor the rollback of a failed action flickers. Call
121
+ * `addOptimistic` synchronously inside `startTransition`.
122
+ */
123
+ export function useOptimistic(state, update) {
124
+ const overlays = signal(/** @type {Array<{ value: any }>} */ ([]));
125
+ const base = typeof state === 'function' ? state : () => state;
126
+ const optimistic = _latestComputed(() => {
127
+ let value = base();
128
+ for (const o of overlays()) value = update === undefined ? o.value : update(value, o.value);
129
+ return value;
130
+ });
131
+ const addOptimistic = (value) => {
132
+ const overlay = { value };
133
+ const place = (t) => {
134
+ if (__DEV__) recordObservation(__devtools, 'optimistic:add', overlay, { transition: t, owner: getOwner() });
135
+ // Urgent, also where a transition holds a reader of the view.
136
+ _urgent(() => {
137
+ overlays((list) => [...list, overlay]);
138
+ _runHeldReaders(optimistic);
139
+ });
140
+ _onCommit(t, () => overlays((list) => (
141
+ __DEV__ && recordObservation(__devtools, 'optimistic:drop', overlay, { transition: t }),
142
+ list.filter((o) => o !== overlay)
143
+ )));
144
+ };
145
+ const t = _currentTransition();
146
+ if (t !== null) {
147
+ place(t);
148
+ return;
149
+ }
150
+ // Outside a transition the overlay has nothing to last for: it shows, and
151
+ // drops once the current flush is over, as in React.
152
+ if (__DEV__) report('ERR_OPTIMISTIC_OUTSIDE_TRANSITION');
153
+ _startTransition(noop, place);
154
+ };
155
+ return [optimistic, addOptimistic];
156
+ }
157
+
158
+ function noop() {}
159
+
160
+ // What use() knows about each promise it has seen.
161
+ /** @type {WeakMap<object, { status: 'pending' | 'fulfilled' | 'rejected', value?: any, reason?: any }>} */
162
+ const promises = new WeakMap();
163
+
164
+ /**
165
+ * React 19's use(). A context reads like useContext. A promise returns its
166
+ * value once it has settled (or throws its error); until then the component
167
+ * suspends and is rendered again when it settles, so the promise must outlive
168
+ * the component (made outside it, or passed in): one made in the body is new
169
+ * on every attempt. An accessor (an async computed) is read untracked, which
170
+ * suspends the component the same way while it has no value.
171
+ */
172
+ export function use(x) {
173
+ _enableSuspense();
174
+ if (typeof x === 'function') return x.Provider === x ? useContext(x) : untrack(x);
175
+ if (x != null && typeof x.then === 'function') {
176
+ let entry = promises.get(x);
177
+ if (entry === undefined) {
178
+ const fresh = { status: /** @type {'pending' | 'fulfilled' | 'rejected'} */ ('pending'), value: undefined, reason: undefined };
179
+ promises.set(x, entry = fresh);
180
+ x.then((value) => { fresh.status = 'fulfilled'; fresh.value = value; }, (reason) => { fresh.status = 'rejected'; fresh.reason = reason; });
181
+ }
182
+ if (entry.status === 'fulfilled') {
183
+ readSettled(x);
184
+ return entry.value;
185
+ }
186
+ if (entry.status === 'rejected') throw entry.reason;
187
+ suspendOn(x);
188
+ throw x;
189
+ }
190
+ throw new TypeError(__DEV__
191
+ ? '[what] use(x) reads a promise, a context or an accessor; it was given ' + (x === null ? 'null' : typeof x) + '.'
192
+ : '[what] use: unsupported value');
193
+ }
194
+
195
+ // A component that keeps suspending on a promise it has never seen, after the
196
+ // one it suspended on before has settled and was not read again, makes a new
197
+ // promise every time it runs: it would never finish, and a promise that is
198
+ // already resolved retries at once, so the page would never get to paint. The
199
+ // third such suspension in a row is an error instead. The count is per
200
+ // instance: a component rendered again in place keeps its props object.
201
+ /** @type {WeakMap<object, { last: any, strikes: number }>} */
202
+ const suspensions = new WeakMap();
203
+
204
+ function suspensionsOf() {
205
+ const frame = _currentComponent();
206
+ if (frame === null) return null;
207
+ const instance = frame.props !== undefined ? frame.props : frame.Component;
208
+ let d = suspensions.get(instance);
209
+ if (d === undefined) suspensions.set(instance, d = { last: null, strikes: 0 });
210
+ return d;
211
+ }
212
+
213
+ function readSettled(x) {
214
+ const d = suspensionsOf();
215
+ if (d !== null && d.last === x) d.strikes = 0;
216
+ }
217
+
218
+ function suspendOn(x) {
219
+ const d = suspensionsOf();
220
+ if (d === null) return;
221
+ const prior = d.last !== null ? promises.get(d.last) : undefined;
222
+ if (prior !== undefined && d.last !== x && prior.status !== 'pending' && ++d.strikes >= 3) {
223
+ d.last = null;
224
+ d.strikes = 0;
225
+ const frame = /** @type {any} */ (_currentComponent());
226
+ const component = frame.Component.displayName || frame.Component.name || 'Anonymous';
227
+ if (__DEV__) report('ERR_USE_UNCACHED_PROMISE', { data: { component } });
228
+ throw Object.assign(new Error(__DEV__
229
+ ? _thrownMessage('ERR_USE_UNCACHED_PROMISE', `Component "${component}" keeps suspending on a new promise: use() received a promise made in the component body. Make it outside the component, or use computed().`)
230
+ : '[what] use: a new promise on every run'), { code: 'ERR_USE_UNCACHED_PROMISE' });
231
+ }
232
+ d.last = x;
233
+ }
234
+
235
+ /**
236
+ * A promise that resolves once the graph is quiet: no effect is queued to
237
+ * run, no async computed is fetching, no transition is open, and no
238
+ * <Suspense> waits on a promise. For tests and agents: act, then
239
+ * `await settled()`, then read the DOM. It never resolves while something
240
+ * keeps fetching (polling, a promise that never settles).
241
+ */
242
+ export function settled() {
243
+ return new Promise((resolve) => {
244
+ let stop = noop;
245
+ // Async work tells the quiet hook when it ends; queued effects run in a
246
+ // flush that is on its way, so they are looked at again after it.
247
+ const check = () => {
248
+ const busy = _busy();
249
+ if (busy === 0) {
250
+ stop();
251
+ resolve(undefined);
252
+ } else if (busy === 1) {
253
+ queueMicrotask(check);
254
+ }
255
+ };
256
+ stop = _onQuiet(check);
257
+ check();
258
+ });
259
+ }