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/a11y.js CHANGED
@@ -1,25 +1,35 @@
1
1
  // What Framework - Accessibility Utilities
2
2
  // Focus management, ARIA helpers, screen reader announcements
3
3
 
4
- import { signal, effect } from './reactive.js';
4
+ import { signal, effect, onCleanup } from './reactive.js';
5
5
  import { h } from './h.js';
6
- import { getCurrentComponent } from './dom.js';
7
6
  import { getServerContext } from './server-context.js';
8
7
 
9
8
  // --- Focus Management ---
10
9
 
11
- // Track currently focused element
12
- const focusedElement = signal(null);
13
-
14
- if (typeof document !== 'undefined') {
15
- document.addEventListener('focusin', (e) => {
16
- focusedElement.set(e.target);
17
- });
10
+ // The focused element, tracked from the first useFocus() call on. Until then
11
+ // nothing listens, so a program that never asks pays nothing.
12
+ /** @type {any} */
13
+ let focusedElement = null;
14
+
15
+ function trackFocus() {
16
+ if (focusedElement === null) {
17
+ const active = typeof document !== 'undefined' ? document.activeElement : null;
18
+ focusedElement = signal(active && active !== document.body ? active : null);
19
+ if (typeof document !== 'undefined') {
20
+ // focusout clears it and the next focusin, if focus moves on, sets it:
21
+ // focus that leaves for nothing (the body) is no element.
22
+ document.addEventListener('focusin', (e) => focusedElement.set(e.target));
23
+ document.addEventListener('focusout', () => focusedElement.set(null));
24
+ }
25
+ }
26
+ return focusedElement;
18
27
  }
19
28
 
20
29
  export function useFocus() {
30
+ const focused = trackFocus();
21
31
  return {
22
- current: () => focusedElement(),
32
+ current: () => focused(),
23
33
  focus: (element) => element?.focus(),
24
34
  blur: () => /** @type {HTMLElement | null} */ (document.activeElement)?.blur(),
25
35
  };
@@ -71,27 +81,24 @@ export function useFocusTrap(containerRef) {
71
81
  // Focus first element
72
82
  focusables[0].focus();
73
83
 
74
- // Handle Tab key
84
+ // Tab and Shift+Tab move focus through the trap's own list, in document
85
+ // order, wrapping at both ends. The trap makes every move itself because
86
+ // browsers disagree on what Tab reaches: Safari by default skips buttons
87
+ // and links, so from the last field it reaches the browser would carry
88
+ // focus out of the container.
75
89
  function handleKeydown(e) {
76
90
  if (e.key !== 'Tab') return;
77
91
 
78
92
  const focusables = getFocusableElements(container);
79
- const first = focusables[0];
80
- const last = focusables[focusables.length - 1];
81
-
82
- if (e.shiftKey) {
83
- // Shift+Tab: if on first, go to last
84
- if (document.activeElement === first) {
85
- e.preventDefault();
86
- last.focus();
87
- }
88
- } else {
89
- // Tab: if on last, go to first
90
- if (document.activeElement === last) {
91
- e.preventDefault();
92
- first.focus();
93
- }
94
- }
93
+ e.preventDefault();
94
+ if (focusables.length === 0) return;
95
+
96
+ const at = focusables.indexOf(/** @type {HTMLElement} */ (document.activeElement));
97
+ const last = focusables.length - 1;
98
+ const next = e.shiftKey
99
+ ? focusables[at <= 0 ? last : at - 1]
100
+ : focusables[at === -1 || at === last ? 0 : at + 1];
101
+ next.focus();
95
102
  }
96
103
 
97
104
  container.addEventListener('keydown', handleKeydown);
@@ -128,7 +135,11 @@ function getFocusableElements(container) {
128
135
  // --- Focus Scope ---
129
136
  // Component wrapper that traps focus
130
137
 
131
- export function FocusTrap({ children, active = true }) {
138
+ // These place their children in an element of their own, so compiled
139
+ // children arrive unbuilt (`_deferChildren`, dom.js _installLazyChildren)
140
+ // and are built there: while hydrating, children built while the component
141
+ // runs would claim the server's nodes before its element does.
142
+ export const FocusTrap = /* @__PURE__ */ Object.assign(function FocusTrap({ children, active = true }) {
132
143
  const containerRef = { current: null };
133
144
  const refVersion = signal(0);
134
145
  const trap = useFocusTrap(containerRef);
@@ -140,8 +151,8 @@ export function FocusTrap({ children, active = true }) {
140
151
  refVersion.set(v => v + 1);
141
152
  };
142
153
 
143
- // Scope the effect to the component lifecycle so it disposes on unmount
144
- const dispose = effect(() => {
154
+ // The effect belongs to the component and is disposed on unmount.
155
+ effect(() => {
145
156
  // Re-run activation after the ref element is attached/updated.
146
157
  refVersion();
147
158
 
@@ -161,20 +172,14 @@ export function FocusTrap({ children, active = true }) {
161
172
  }
162
173
  });
163
174
 
164
- // Register cleanup on component context
165
- const ctx = getCurrentComponent?.();
166
- if (ctx) {
167
- ctx._cleanupCallbacks = ctx._cleanupCallbacks || [];
168
- ctx._cleanupCallbacks.push(() => {
169
- dispose();
170
- trapCleanup?.();
171
- trapCleanup = null;
172
- trap.deactivate();
173
- });
174
- }
175
+ onCleanup(() => {
176
+ trapCleanup?.();
177
+ trapCleanup = null;
178
+ trap.deactivate();
179
+ });
175
180
 
176
181
  return h('div', { ref: setRef }, children);
177
- }
182
+ }, { _deferChildren: true });
178
183
 
179
184
  // --- Screen Reader Announcements ---
180
185
 
@@ -238,7 +243,7 @@ export function announceAssertive(message) {
238
243
  // --- Skip Link ---
239
244
  // Accessible skip navigation
240
245
 
241
- export function SkipLink({ href = '#main', children = 'Skip to content' }) {
246
+ export const SkipLink = /* @__PURE__ */ Object.assign(function SkipLink({ href = '#main', children = 'Skip to content' }) {
242
247
  return h('a', {
243
248
  href,
244
249
  class: 'what-skip-link',
@@ -267,7 +272,7 @@ export function SkipLink({ href = '#main', children = 'Skip to content' }) {
267
272
  e.target.style.top = '-40px';
268
273
  },
269
274
  }, children);
270
- }
275
+ }, { _deferChildren: true });
271
276
 
272
277
  // --- ARIA Helpers ---
273
278
 
@@ -408,7 +413,7 @@ export function useRovingTabIndex(itemCountOrSignal, options = {}) {
408
413
  // accept an object and only two accept a function: render.js spread() treats
409
414
  // any function-valued prop as a reactive accessor and would CALL a callback
410
415
  // ref with no arguments. An object is assigned `.current` by dom.js
411
- // applyProps (h()), render.js setProp() (compiled spread) and
416
+ // createElementFromVNode (h()), render.js setProp() (compiled spread) and
412
417
  // hydrateElementProps() (SSR) alike, and renderToString() skips `ref`
413
418
  // entirely, so nothing lands in the HTML and there is no hydration mismatch
414
419
  // to have.
@@ -500,9 +505,9 @@ export function useRovingTabIndex(itemCountOrSignal, options = {}) {
500
505
  }
501
506
 
502
507
  // Out-of-range indexes handed in from application code are REFUSED rather
503
- // than clamped. focusItem(99) used to write 99 into the signal and return
504
- // null: no item matched, so every item went to tabindex="-1" and the widget
505
- // dropped out of the tab order entirely. Clamping instead would move focus
508
+ // than clamped. Writing focusItem(99) into the signal would match no item,
509
+ // so every item would go to tabindex="-1" and the widget would drop out of
510
+ // the tab order entirely. Clamping instead would move focus
506
511
  // somewhere the caller never asked for, which is a worse surprise than
507
512
  // ignoring an index that does not exist.
508
513
  function isValidIndex(i) {
@@ -588,7 +593,7 @@ export function useRovingTabIndex(itemCountOrSignal, options = {}) {
588
593
  // --- Visually Hidden ---
589
594
  // Hide content visually but keep accessible to screen readers
590
595
 
591
- export function VisuallyHidden({ children, as = 'span' }) {
596
+ export const VisuallyHidden = /* @__PURE__ */ Object.assign(function VisuallyHidden({ children, as = 'span' }) {
592
597
  return h(as, {
593
598
  style: {
594
599
  position: 'absolute',
@@ -602,16 +607,16 @@ export function VisuallyHidden({ children, as = 'span' }) {
602
607
  border: '0',
603
608
  },
604
609
  }, children);
605
- }
610
+ }, { _deferChildren: true });
606
611
 
607
612
  // --- Live Region Component ---
608
613
 
609
- export function LiveRegion({ children, priority = 'polite', atomic = true }) {
614
+ export const LiveRegion = /* @__PURE__ */ Object.assign(function LiveRegion({ children, priority = 'polite', atomic = true }) {
610
615
  return h('div', {
611
616
  'aria-live': priority,
612
617
  'aria-atomic': atomic,
613
618
  }, children);
614
- }
619
+ }, { _deferChildren: true });
615
620
 
616
621
  // --- ID Generator ---
617
622
  // Generate unique IDs for ARIA attributes
@@ -649,9 +654,9 @@ export function __resetIdCounter() {
649
654
  idCounter = 0;
650
655
  }
651
656
 
657
+ // A string, as in React: the component runs once, so the id never changes.
652
658
  export function useId(prefix = 'what') {
653
- const id = `${prefix}-${nextIdSuffix()}`;
654
- return () => id;
659
+ return `${prefix}-${nextIdSuffix()}`;
655
660
  }
656
661
 
657
662
  export function useIds(count, prefix = 'what') {
@@ -671,14 +676,14 @@ export function useDescribedBy(description) {
671
676
  return {
672
677
  descriptionId: id,
673
678
  descriptionProps: () => ({
674
- id: id(),
679
+ id,
675
680
  style: { display: 'none' },
676
681
  }),
677
682
  describedByProps: () => ({
678
- 'aria-describedby': id(),
683
+ 'aria-describedby': id,
679
684
  }),
680
685
  Description: () => h('div', {
681
- id: id(),
686
+ id,
682
687
  style: { display: 'none' },
683
688
  }, description),
684
689
  };
@@ -692,10 +697,10 @@ export function useLabelledBy(_label) {
692
697
  return {
693
698
  labelId: id,
694
699
  labelProps: () => ({
695
- id: id(),
700
+ id,
696
701
  }),
697
702
  labelledByProps: () => ({
698
- 'aria-labelledby': id(),
703
+ 'aria-labelledby': id,
699
704
  }),
700
705
  };
701
706
  }
package/src/actions.js ADDED
@@ -0,0 +1,226 @@
1
+ // What Framework - Actions: React 19's useActionState and useFormStatus, on
2
+ // the engine's transitions (docs/DATA.md).
3
+ //
4
+ // An action is an async function run inside a transition: everything its
5
+ // writes and refetches reach on screen commits together once it has finished
6
+ // and what it made fetch again has landed, and the optimistic overlays added
7
+ // in it drop in that same flush. A server action called from one (what-server
8
+ // action()) revalidates inside it, so the screen goes from the old data to
9
+ // the new in one commit.
10
+
11
+ import { signal, getOwner, onCleanup, _startTransition, _onCommit, _handleError, HANDLED } from './reactive.js';
12
+ import { createContext, useContext } from './hooks.js';
13
+
14
+ /**
15
+ * React 19's useActionState: `[state, dispatch, isPending]`. `dispatch(payload)`
16
+ * runs `action(previousState, payload)` inside a transition; dispatches queue,
17
+ * each receiving the state the previous one returned. The new state commits
18
+ * with the transition: in the same flush as the data its action revalidated.
19
+ * `state` and `isPending` are accessors. An action that throws reaches the
20
+ * nearest <ErrorBoundary>, and the dispatches queued behind it are dropped.
21
+ * `permalink` is the URL a <Form> posts to before JavaScript has loaded; by
22
+ * default the page's own. The dispatch of a server action (what-server
23
+ * action()) carries its id and this hook's key: posted to the page, the
24
+ * action runs there, and the page comes back with its result for this hook
25
+ * alone (what-server actions.js formState).
26
+ */
27
+ export function useActionState(action, initialState, permalink) {
28
+ // A server action (what-server action()) knows this hook's key, and the
29
+ // state its form came back with when it was posted without JavaScript, for
30
+ // this render and its hydration.
31
+ const id = action != null ? action._actionId : undefined;
32
+ const form = id !== undefined && action._formState ? action._formState() : null;
33
+ const start = form !== null && 'state' in form ? form.state : initialState;
34
+ const state = signal(start);
35
+ const open = signal(0);
36
+ const owner = getOwner();
37
+ /** @type {Set<any>} the transition calls of the dispatches still running */
38
+ const calls = new Set();
39
+ /** @type {Set<() => void>} how to stop waiting for each action still running */
40
+ const waits = new Set();
41
+ let latest = start;
42
+ /** @type {Promise<void> | null} the last dispatch still running, if any */
43
+ let queue = null;
44
+ let generation = 0;
45
+ // Once the owner is gone, every dispatch stops waiting: none of them
46
+ // commits, the queued ones never run, and an action's promise that stays
47
+ // pending holds nothing of the hook.
48
+ if (owner !== null) {
49
+ onCleanup(() => {
50
+ generation++;
51
+ for (const call of calls) call.abandon();
52
+ for (const leave of waits) leave();
53
+ });
54
+ }
55
+
56
+ const dispatch = (payload) => {
57
+ const gen = generation;
58
+ /** @type {any} */
59
+ let tx = null;
60
+ const before = queue;
61
+ /** @type {() => void} */
62
+ let done = () => {};
63
+ const mine = queue = new Promise((resolve) => { done = resolve; });
64
+ _startTransition(async () => {
65
+ try {
66
+ // With nothing queued the action starts at once, inside the
67
+ // transition: an addOptimistic() before its first await belongs to it.
68
+ if (before !== null) await before;
69
+ if (gen !== generation) {
70
+ failedIn.add(tx);
71
+ return;
72
+ }
73
+ const [settled, leave] = untilLeft(action(latest, payload));
74
+ waits.add(leave);
75
+ let next;
76
+ try {
77
+ next = await settled;
78
+ } finally {
79
+ // On every way out, a rejection included: `leave` reaches the
80
+ // settled wait, and so what it settled with.
81
+ waits.delete(leave);
82
+ }
83
+ if (gen !== generation) {
84
+ failedIn.add(tx);
85
+ return;
86
+ }
87
+ latest = next;
88
+ _onCommit(tx, () => state(next));
89
+ } catch (err) {
90
+ generation++;
91
+ failedIn.add(tx);
92
+ const left = _handleError(owner, err);
93
+ if (left !== HANDLED) throw left;
94
+ } finally {
95
+ if (queue === mine) queue = null;
96
+ done();
97
+ }
98
+ }, (t, call) => {
99
+ tx = t;
100
+ open((n) => n + 1);
101
+ calls.add(call);
102
+ _onCommit(t, () => {
103
+ open((n) => n - 1);
104
+ calls.delete(call);
105
+ });
106
+ }).catch((err) => {
107
+ try { console.error('[what] Uncaught error in action:', err); } catch { /* no console */ }
108
+ });
109
+ };
110
+ if (permalink !== undefined) dispatch.permalink = permalink;
111
+ if (id !== undefined) {
112
+ dispatch._actionId = id;
113
+ dispatch._key = form !== null ? form.key : null;
114
+ dispatch._state = () => state();
115
+ }
116
+
117
+ return [() => state(), dispatch, () => open() > 0];
118
+ }
119
+
120
+ // What `value` settles to, and how to stop waiting for it: `leave()` settles
121
+ // the wait at once, and from then on the callbacks `value` holds reach
122
+ // nothing (they hold `wait`, which leave empties), so a promise that never
123
+ // settles keeps nothing of the dispatch waiting for it.
124
+ /** @returns {[Promise<any>, () => void]} */
125
+ function untilLeft(value) {
126
+ const wait = { resolve: (_v) => {}, reject: (_e) => {} };
127
+ const settled = new Promise((resolve, reject) => {
128
+ wait.resolve = resolve;
129
+ wait.reject = reject;
130
+ });
131
+ Promise.resolve(value).then((v) => wait.resolve(v), (err) => wait.reject(err));
132
+ const leave = () => {
133
+ const resolve = wait.resolve;
134
+ wait.resolve = wait.reject = () => {};
135
+ resolve(undefined);
136
+ };
137
+ return [settled, leave];
138
+ }
139
+
140
+ // The transitions a dispatch did not succeed in: its action threw, or was
141
+ // dropped behind one that did. A <Form> it ran in is not reset at the commit.
142
+ const failedIn = new WeakSet();
143
+
144
+ // What useFormStatus() answers outside a <Form>.
145
+ const NO_FORM = /* @__PURE__ */ Object.freeze({
146
+ pending: () => false,
147
+ data: () => null,
148
+ method: null,
149
+ action: null,
150
+ });
151
+
152
+ /** @type {any} */
153
+ let formContext = null;
154
+
155
+ /** @internal The context a <Form> (what-server) provides its status in. */
156
+ export function _formStatusContext() {
157
+ return formContext || (formContext = createContext(NO_FORM));
158
+ }
159
+
160
+ /**
161
+ * React 19's useFormStatus: the submission of the <Form> this component is
162
+ * rendered in. `pending()` is true from a submit until its transition
163
+ * commits; `data()` is the FormData of the latest submission still pending
164
+ * (null when none is); `method` and `action` are the form's. Outside a
165
+ * <Form>, `pending()` is false and the rest null.
166
+ */
167
+ export function useFormStatus() {
168
+ return formContext === null ? NO_FORM : useContext(formContext);
169
+ }
170
+
171
+ /**
172
+ * @internal A <Form>'s status: what useFormStatus() inside it reads (`action`
173
+ * is the form's action function, or null for a URL or an action id, as in
174
+ * React), and `submit(formData, run, reset)`, which runs `run(formData)` for
175
+ * one submission as a transition the status shows. As React 19 does for an
176
+ * uncontrolled form, `reset()` runs when that transition has committed (after
177
+ * the effects of its commit), if what ran in it succeeded: `run` did not
178
+ * reject and no useActionState dispatch in it failed. `run` returns what the action returns (a promise for an async one),
179
+ * without awaiting it. Once the form's owner is disposed, the submissions still
180
+ * running stop waiting and the form is not reset. Returns the transition's
181
+ * promise.
182
+ */
183
+ export function _formStatus(method, action) {
184
+ // The FormData of each submission still pending, oldest first.
185
+ const pending = signal(/** @type {FormData[]} */ ([]));
186
+ /** @type {Set<any>} the transition calls of the submissions still running */
187
+ const calls = new Set();
188
+ let mounted = true;
189
+ // Once the form is gone, no submission waits for its action any more: a
190
+ // promise that stays pending holds nothing of the form or its data, and
191
+ // nothing resets the unmounted form.
192
+ if (getOwner() !== null) {
193
+ onCleanup(() => {
194
+ mounted = false;
195
+ for (const call of calls) call.abandon();
196
+ });
197
+ }
198
+ return {
199
+ pending: () => pending().length > 0,
200
+ data: () => pending().at(-1) ?? null,
201
+ method,
202
+ action: typeof action === 'function' ? action : null,
203
+ submit(formData, run, reset) {
204
+ // `run` returns the action's promise rather than awaiting it: an async
205
+ // frame would hold the submission across a promise the action owns.
206
+ return _startTransition(() => {
207
+ try {
208
+ return run(formData);
209
+ } catch (error) {
210
+ return Promise.reject(error);
211
+ }
212
+ }, (t, call) => {
213
+ calls.add(call);
214
+ pending((list) => [...list, formData]);
215
+ _onCommit(t, () => {
216
+ calls.delete(call);
217
+ pending((list) => list.filter((entry) => entry !== formData));
218
+ // Once the commit has run its effects: the defaults a reset
219
+ // restores are those the committed state gives (a useActionState
220
+ // form's `defaultValue={() => state()?.fields?.title}`).
221
+ if (mounted && !call.failed && !failedIn.has(t)) queueMicrotask(() => mounted && reset());
222
+ });
223
+ });
224
+ },
225
+ };
226
+ }