@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.3
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.
- package/dist/action-context.d.ts +49 -0
- package/dist/action-context.js +37 -0
- package/dist/action-context.test.d.ts +1 -0
- package/dist/action-context.test.js +47 -0
- package/dist/actions.d.ts +120 -0
- package/dist/actions.js +533 -0
- package/dist/actions.test.d.ts +1 -0
- package/dist/actions.test.js +391 -0
- package/dist/boundary.d.ts +121 -0
- package/dist/boundary.js +429 -0
- package/dist/class-component.d.ts +66 -0
- package/dist/class-component.js +633 -0
- package/dist/class-component.test.d.ts +1 -0
- package/dist/class-component.test.js +411 -0
- package/dist/context.d.ts +13 -0
- package/dist/context.js +58 -32
- package/dist/context.test.d.ts +1 -0
- package/dist/context.test.js +57 -0
- package/dist/derived.test.d.ts +1 -0
- package/dist/derived.test.js +140 -0
- package/dist/discrete.test.d.ts +1 -0
- package/dist/discrete.test.js +100 -0
- package/dist/dom.d.ts +55 -0
- package/dist/dom.js +414 -63
- package/dist/effects.d.ts +88 -0
- package/dist/effects.js +719 -0
- package/dist/effects.test.d.ts +1 -0
- package/dist/effects.test.js +485 -0
- package/dist/events.d.ts +58 -0
- package/dist/events.js +503 -0
- package/dist/events.test.d.ts +1 -0
- package/dist/events.test.js +447 -0
- package/dist/index.d.ts +12 -2
- package/dist/index.js +8 -2
- package/dist/jsx-types.d.ts +2 -0
- package/dist/krate-hydrate-lite.js +7 -1
- package/dist/krate-hydrate.js +7 -1
- package/dist/krate-runtime.js +7 -1
- package/dist/krate-suspense.js +2 -0
- package/dist/lanes.test.d.ts +1 -0
- package/dist/lanes.test.js +59 -0
- package/dist/list.d.ts +20 -0
- package/dist/list.js +466 -0
- package/dist/list.test.d.ts +1 -0
- package/dist/list.test.js +344 -0
- package/dist/optimistic-lanes.test.d.ts +1 -0
- package/dist/optimistic-lanes.test.js +45 -0
- package/dist/portal.d.ts +43 -0
- package/dist/portal.js +178 -0
- package/dist/portal.test.d.ts +1 -0
- package/dist/portal.test.js +99 -0
- package/dist/react-effects.test.d.ts +1 -0
- package/dist/react-effects.test.js +96 -0
- package/dist/react-suspense.test.d.ts +1 -0
- package/dist/react-suspense.test.js +194 -0
- package/dist/react.d.ts +132 -32
- package/dist/react.js +335 -81
- package/dist/react.test.js +12 -2
- package/dist/reconcile.js +13 -0
- package/dist/refs.d.ts +33 -0
- package/dist/refs.js +142 -0
- package/dist/refs.test.d.ts +1 -0
- package/dist/refs.test.js +257 -0
- package/dist/resource.js +20 -1
- package/dist/server-renderer.js +39 -1
- package/dist/server.d.ts +4 -1
- package/dist/server.js +30 -1
- package/dist/server.test.js +20 -0
- package/dist/signal-lanes.test.d.ts +1 -0
- package/dist/signal-lanes.test.js +32 -0
- package/dist/signal.d.ts +150 -1
- package/dist/signal.js +750 -65
- package/dist/slots.d.ts +18 -0
- package/dist/slots.js +108 -0
- package/dist/slots.test.d.ts +1 -0
- package/dist/slots.test.js +169 -0
- package/dist/snapshots.test.d.ts +1 -0
- package/dist/snapshots.test.js +208 -0
- package/dist/suspense-actions.test.d.ts +1 -0
- package/dist/suspense-actions.test.js +72 -0
- package/dist/suspense.d.ts +220 -0
- package/dist/suspense.js +901 -0
- package/dist/suspense.test.d.ts +1 -0
- package/dist/suspense.test.js +518 -0
- package/package.json +1 -1
package/dist/actions.js
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* React 19 actions on Krate's server-action transport.
|
|
3
|
+
*
|
|
4
|
+
* This module owns the client half of server actions and the action hooks the
|
|
5
|
+
* compiler lowers React source to:
|
|
6
|
+
*
|
|
7
|
+
* - `__krateAction(id)` builds the client proxy for a `"use server"` export.
|
|
8
|
+
* - A document `submit` listener runs `<form action={fn}>` and
|
|
9
|
+
* `<button formAction={fn}>` actions (server proxies or client functions)
|
|
10
|
+
* inside an async action scope, drives `useFormStatus`, and resets the form
|
|
11
|
+
* after success. Without JavaScript, forms bound to server actions still POST
|
|
12
|
+
* to the action URL.
|
|
13
|
+
* - `__krateActionState` backs `useActionState`, `__krateOptimistic` backs
|
|
14
|
+
* `useOptimistic`, and `__krateFormStatusMount` backs `useFormStatus`.
|
|
15
|
+
*
|
|
16
|
+
* Wire format (see guides/server-actions.md):
|
|
17
|
+
* request JSON {"args":[...]} every argument JSON
|
|
18
|
+
* multipart form fields + "__krate_args" last argument a FormData;
|
|
19
|
+
* (JSON array of leading args)
|
|
20
|
+
* response {"ok":true,"result":R,"redirect":"/path"?}
|
|
21
|
+
* {"ok":false,"error":{"message":M,"digest":D}}
|
|
22
|
+
*/
|
|
23
|
+
import { createEffect, onCleanup, krateRunEvent, krateTransitionWrites } from './signal.js';
|
|
24
|
+
/** Field and query parameter carrying the JSON leading arguments of a form call. */
|
|
25
|
+
export const ACTION_ARGS_FIELD = '__krate_args';
|
|
26
|
+
/** Error raised on the client when a server action fails. */
|
|
27
|
+
export class ServerActionError extends Error {
|
|
28
|
+
constructor(message, status, digest) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'ServerActionError';
|
|
31
|
+
this.status = status;
|
|
32
|
+
if (digest)
|
|
33
|
+
this.digest = digest;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function basePath() {
|
|
37
|
+
const cfg = globalThis.__KRATE_CFG__;
|
|
38
|
+
return cfg && cfg.basePath ? cfg.basePath : '';
|
|
39
|
+
}
|
|
40
|
+
/** True for a server action proxy created by `__krateAction`. */
|
|
41
|
+
export function isServerAction(value) {
|
|
42
|
+
return typeof value === 'function' && typeof value.$$krateAction === 'string';
|
|
43
|
+
}
|
|
44
|
+
function navigateTo(url) {
|
|
45
|
+
const nav = globalThis.navigate;
|
|
46
|
+
if (typeof nav === 'function')
|
|
47
|
+
nav(url);
|
|
48
|
+
else if (typeof location !== 'undefined')
|
|
49
|
+
location.assign(url);
|
|
50
|
+
}
|
|
51
|
+
function errorFrom(p, status, statusText) {
|
|
52
|
+
const e = p ? p.error : undefined;
|
|
53
|
+
if (e && typeof e === 'object') {
|
|
54
|
+
return new ServerActionError(e.message || 'Server action failed', status, e.digest);
|
|
55
|
+
}
|
|
56
|
+
const message = (p && (p.details || (typeof e === 'string' ? e : ''))) || statusText || 'Server action failed';
|
|
57
|
+
return new ServerActionError(message, status);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* POSTs one action call. A trailing FormData argument is sent as multipart
|
|
61
|
+
* with the leading arguments JSON-encoded in `__krate_args`; anything else is
|
|
62
|
+
* sent as a JSON `{args}` body. Resolves with the action's return value and
|
|
63
|
+
* follows a `redirect` from the response.
|
|
64
|
+
*/
|
|
65
|
+
export async function callServerAction(url, args) {
|
|
66
|
+
const headers = {
|
|
67
|
+
accept: 'application/json',
|
|
68
|
+
'x-krate-action': 'fetch',
|
|
69
|
+
};
|
|
70
|
+
if (typeof location !== 'undefined')
|
|
71
|
+
headers['x-krate-return'] = location.pathname + location.search;
|
|
72
|
+
let body;
|
|
73
|
+
const last = args[args.length - 1];
|
|
74
|
+
if (typeof FormData !== 'undefined' && last instanceof FormData) {
|
|
75
|
+
const fd = new FormData();
|
|
76
|
+
last.forEach((value, key) => {
|
|
77
|
+
if (key !== ACTION_ARGS_FIELD)
|
|
78
|
+
fd.append(key, value);
|
|
79
|
+
});
|
|
80
|
+
const leading = args.slice(0, -1);
|
|
81
|
+
if (leading.length > 0)
|
|
82
|
+
fd.set(ACTION_ARGS_FIELD, JSON.stringify(leading));
|
|
83
|
+
body = fd;
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
headers['content-type'] = 'application/json';
|
|
87
|
+
body = JSON.stringify({ args });
|
|
88
|
+
}
|
|
89
|
+
const res = await fetch(url, { method: 'POST', credentials: 'same-origin', headers, body });
|
|
90
|
+
let payload = null;
|
|
91
|
+
try {
|
|
92
|
+
payload = (await res.json());
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
payload = null;
|
|
96
|
+
}
|
|
97
|
+
if (!res.ok || !payload || payload.ok === false) {
|
|
98
|
+
throw errorFrom(payload, res.status, res.statusText);
|
|
99
|
+
}
|
|
100
|
+
if (typeof payload.redirect === 'string' && payload.redirect)
|
|
101
|
+
navigateTo(payload.redirect);
|
|
102
|
+
return payload.result;
|
|
103
|
+
}
|
|
104
|
+
function makeProxy(id, bound) {
|
|
105
|
+
const url = basePath() + '/__krate/action/' + id;
|
|
106
|
+
const action = function (...args) {
|
|
107
|
+
return callServerAction(url, bound.concat(args));
|
|
108
|
+
};
|
|
109
|
+
Object.defineProperty(action, 'actionUrl', { value: url });
|
|
110
|
+
Object.defineProperty(action, '$$krateAction', { value: id });
|
|
111
|
+
Object.defineProperty(action, '$$krateBound', { value: bound });
|
|
112
|
+
// React server references support `.bind(null, ...args)` to pre-fill
|
|
113
|
+
// arguments; the result is still a server action.
|
|
114
|
+
Object.defineProperty(action, 'bind', {
|
|
115
|
+
value: (_this, ...more) => makeProxy(id, bound.concat(more)),
|
|
116
|
+
});
|
|
117
|
+
action.toString = () => url;
|
|
118
|
+
return action;
|
|
119
|
+
}
|
|
120
|
+
/** Client proxy for the server action with the given id. */
|
|
121
|
+
export function __krateAction(id) {
|
|
122
|
+
return makeProxy(id, []);
|
|
123
|
+
}
|
|
124
|
+
// Action scope (async transitions)
|
|
125
|
+
let pendingActions = 0;
|
|
126
|
+
const settleListeners = new Set();
|
|
127
|
+
/**
|
|
128
|
+
* Marks the start of an action or async transition and returns its end
|
|
129
|
+
* callback. Optimistic updates stay applied while any scope is open. Exposed so
|
|
130
|
+
* `startTransition` implementations can join the same scope.
|
|
131
|
+
*/
|
|
132
|
+
export function __krateBeginAction() {
|
|
133
|
+
pendingActions++;
|
|
134
|
+
let ended = false;
|
|
135
|
+
return () => {
|
|
136
|
+
if (ended)
|
|
137
|
+
return;
|
|
138
|
+
ended = true;
|
|
139
|
+
pendingActions--;
|
|
140
|
+
if (pendingActions === 0) {
|
|
141
|
+
// Optimistic reverts land with the action's other settle updates, in
|
|
142
|
+
// the transition lane.
|
|
143
|
+
krateTransitionWrites(() => {
|
|
144
|
+
for (const listener of Array.from(settleListeners))
|
|
145
|
+
listener();
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/** True while an action or async transition is pending. */
|
|
151
|
+
export function isActionPending() {
|
|
152
|
+
return pendingActions > 0;
|
|
153
|
+
}
|
|
154
|
+
const defaultRunner = (fn) => {
|
|
155
|
+
const end = __krateBeginAction();
|
|
156
|
+
let result;
|
|
157
|
+
try {
|
|
158
|
+
result = fn();
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
end();
|
|
162
|
+
return Promise.reject(err);
|
|
163
|
+
}
|
|
164
|
+
return Promise.resolve(result).finally(end);
|
|
165
|
+
};
|
|
166
|
+
let runner = defaultRunner;
|
|
167
|
+
/**
|
|
168
|
+
* Replaces the transition runner used for form actions and `useActionState`
|
|
169
|
+
* dispatches, so a framework-wide async `startTransition` can own them. Passing
|
|
170
|
+
* null restores the built-in runner.
|
|
171
|
+
*/
|
|
172
|
+
export function setActionTransitionRunner(next) {
|
|
173
|
+
runner = next || defaultRunner;
|
|
174
|
+
}
|
|
175
|
+
/** Runs fn inside the current action transition runner. */
|
|
176
|
+
export function runActionTransition(fn) {
|
|
177
|
+
return runner(fn);
|
|
178
|
+
}
|
|
179
|
+
// Errors
|
|
180
|
+
/**
|
|
181
|
+
* Reports an action error. An error boundary integration can install
|
|
182
|
+
* `globalThis.__krateActionError(error, element)` and return true to claim the
|
|
183
|
+
* error; otherwise a bubbling `krate:action-error` event is dispatched on the
|
|
184
|
+
* element (or document) and the error is logged.
|
|
185
|
+
*/
|
|
186
|
+
export function reportActionError(error, el) {
|
|
187
|
+
const g = globalThis;
|
|
188
|
+
if (typeof g.__krateActionError === 'function') {
|
|
189
|
+
try {
|
|
190
|
+
if (g.__krateActionError(error, el) === true)
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
// A failing boundary hook must not hide the original error.
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const target = el || (typeof document !== 'undefined' ? document : null);
|
|
198
|
+
let handled = false;
|
|
199
|
+
if (target && typeof CustomEvent !== 'undefined') {
|
|
200
|
+
const ev = new CustomEvent('krate:action-error', { bubbles: true, cancelable: true, detail: { error } });
|
|
201
|
+
handled = !target.dispatchEvent(ev);
|
|
202
|
+
}
|
|
203
|
+
if (!handled)
|
|
204
|
+
console.error('krate server action:', error);
|
|
205
|
+
}
|
|
206
|
+
const IDLE = Object.freeze({ pending: false, data: null, method: null, action: null });
|
|
207
|
+
const formStates = new WeakMap();
|
|
208
|
+
function formState(form) {
|
|
209
|
+
let st = formStates.get(form);
|
|
210
|
+
if (!st) {
|
|
211
|
+
st = { status: IDLE, subs: new Set(), running: 0, resetRequested: false };
|
|
212
|
+
formStates.set(form, st);
|
|
213
|
+
}
|
|
214
|
+
return st;
|
|
215
|
+
}
|
|
216
|
+
function publish(st, status) {
|
|
217
|
+
st.status = status;
|
|
218
|
+
for (const sub of Array.from(st.subs))
|
|
219
|
+
sub(status);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Subscribes a component's `useFormStatus()` to the nearest form that contains
|
|
223
|
+
* its root element `el` (not `el` itself, matching React: a component reads the
|
|
224
|
+
* status of a parent form). Returns the unsubscribe function, used as the
|
|
225
|
+
* callback-ref cleanup when the element detaches.
|
|
226
|
+
*/
|
|
227
|
+
export function __krateFormStatusMount(el, setters) {
|
|
228
|
+
let form = null;
|
|
229
|
+
for (let n = el ? el.parentElement : null; n; n = n.parentElement) {
|
|
230
|
+
if (n.tagName === 'FORM') {
|
|
231
|
+
form = n;
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (!form)
|
|
236
|
+
return () => { };
|
|
237
|
+
const st = formState(form);
|
|
238
|
+
const sub = (s) => {
|
|
239
|
+
if (setters.status)
|
|
240
|
+
setters.status(s);
|
|
241
|
+
if (setters.pending)
|
|
242
|
+
setters.pending(s.pending);
|
|
243
|
+
if (setters.data)
|
|
244
|
+
setters.data(s.data);
|
|
245
|
+
if (setters.method)
|
|
246
|
+
setters.method(s.method);
|
|
247
|
+
if (setters.action)
|
|
248
|
+
setters.action(s.action);
|
|
249
|
+
};
|
|
250
|
+
st.subs.add(sub);
|
|
251
|
+
sub(st.status);
|
|
252
|
+
// The returned function is the callback-ref cleanup: the ref system calls
|
|
253
|
+
// it when the element detaches. Registering it with onCleanup instead would
|
|
254
|
+
// tie it to the ref binding's effect, which may re-run.
|
|
255
|
+
return () => {
|
|
256
|
+
st.subs.delete(sub);
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Assigns an element to a ref value (callback or `{ current }` object). Used
|
|
261
|
+
* when the compiler composes a component's own ref with the useFormStatus
|
|
262
|
+
* mount ref.
|
|
263
|
+
*/
|
|
264
|
+
export function __krateAssignRef(ref, el) {
|
|
265
|
+
if (typeof ref === 'function')
|
|
266
|
+
ref(el);
|
|
267
|
+
else if (ref && typeof ref === 'object')
|
|
268
|
+
ref.current = el;
|
|
269
|
+
}
|
|
270
|
+
/** Current status of a form (idle unless an action submitted from it is pending). */
|
|
271
|
+
export function getFormStatus(form) {
|
|
272
|
+
return formStates.get(form)?.status || IDLE;
|
|
273
|
+
}
|
|
274
|
+
// Form reset
|
|
275
|
+
function resetForm(form) {
|
|
276
|
+
// Controlled fields keep their signal value: snapshot and restore them
|
|
277
|
+
// around the native reset, which only affects uncontrolled fields.
|
|
278
|
+
const controlled = Array.from(form.querySelectorAll('[data-kattr-value],[data-kattr-checked]')).map((el) => ({ el, value: el.value, checked: el.checked }));
|
|
279
|
+
form.reset();
|
|
280
|
+
for (const c of controlled) {
|
|
281
|
+
if (c.el.hasAttribute('data-kattr-value'))
|
|
282
|
+
c.el.value = c.value;
|
|
283
|
+
if (c.el.hasAttribute('data-kattr-checked'))
|
|
284
|
+
c.el.checked = c.checked;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* React DOM's `requestFormReset(form)`: resets the form's uncontrolled fields
|
|
289
|
+
* once the action currently pending on it settles, or immediately when none is.
|
|
290
|
+
*/
|
|
291
|
+
export function requestFormReset(form) {
|
|
292
|
+
const st = formStates.get(form);
|
|
293
|
+
if (st && st.running > 0) {
|
|
294
|
+
st.resetRequested = true;
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
resetForm(form);
|
|
298
|
+
}
|
|
299
|
+
/** Binds a function action to a form or submit button (`action={fn}` / `formAction={fn}`). */
|
|
300
|
+
export function __krateBindFormAction(el, get) {
|
|
301
|
+
el.__krateFormAction = get;
|
|
302
|
+
// The native POST target only serves the no-JS fallback; once the function
|
|
303
|
+
// is bound the element matches React's client DOM (no action attribute).
|
|
304
|
+
if (el.tagName === 'FORM') {
|
|
305
|
+
el.removeAttribute('action');
|
|
306
|
+
el.removeAttribute('method');
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
el.removeAttribute('formaction');
|
|
310
|
+
el.removeAttribute('formmethod');
|
|
311
|
+
}
|
|
312
|
+
el.removeAttribute('data-krate-action');
|
|
313
|
+
}
|
|
314
|
+
function boundAction(el) {
|
|
315
|
+
if (!el)
|
|
316
|
+
return null;
|
|
317
|
+
const get = el.__krateFormAction;
|
|
318
|
+
if (typeof get !== 'function')
|
|
319
|
+
return null;
|
|
320
|
+
try {
|
|
321
|
+
return get();
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function resolveSubmission(form, submitter) {
|
|
328
|
+
if (submitter && submitter !== form) {
|
|
329
|
+
const fn = boundAction(submitter);
|
|
330
|
+
if (typeof fn === 'function')
|
|
331
|
+
return { fn };
|
|
332
|
+
if (submitter.hasAttribute('data-krate-action')) {
|
|
333
|
+
return { url: submitter.formAction || form.action };
|
|
334
|
+
}
|
|
335
|
+
// A plain native formaction wins over the form's action.
|
|
336
|
+
if (submitter.hasAttribute('formaction'))
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const fn = boundAction(form);
|
|
340
|
+
if (typeof fn === 'function')
|
|
341
|
+
return { fn };
|
|
342
|
+
if (form.hasAttribute('data-krate-action'))
|
|
343
|
+
return { url: form.action };
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
function formDataFor(form, submitter) {
|
|
347
|
+
let fd;
|
|
348
|
+
try {
|
|
349
|
+
fd = submitter ? new FormData(form, submitter) : new FormData(form);
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
fd = new FormData(form);
|
|
353
|
+
const s = submitter;
|
|
354
|
+
if (s && s.name)
|
|
355
|
+
fd.append(s.name, s.value);
|
|
356
|
+
}
|
|
357
|
+
return fd;
|
|
358
|
+
}
|
|
359
|
+
function stripActionURL(url) {
|
|
360
|
+
// The no-JS leading-args query is only for native posts.
|
|
361
|
+
const i = url.indexOf('?');
|
|
362
|
+
return i < 0 ? url : url.slice(0, i);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Runs a form action: sets the form status, invokes the action with the form
|
|
366
|
+
* data in an async transition, resets the form on success and reports errors.
|
|
367
|
+
* Resolves true when the action succeeded.
|
|
368
|
+
*/
|
|
369
|
+
export async function submitFormAction(form, action, data, submitter = null, url) {
|
|
370
|
+
const st = formState(form);
|
|
371
|
+
const method = ((submitter && submitter.getAttribute('formmethod')) ||
|
|
372
|
+
form.getAttribute('method') ||
|
|
373
|
+
'get').toLowerCase();
|
|
374
|
+
st.running++;
|
|
375
|
+
publish(st, { pending: true, data, method, action: action || url || null });
|
|
376
|
+
form.setAttribute('data-krate-action-pending', '1');
|
|
377
|
+
let ok = false;
|
|
378
|
+
try {
|
|
379
|
+
await runActionTransition(async () => {
|
|
380
|
+
const run = action;
|
|
381
|
+
if (run && typeof run.__krateRun === 'function') {
|
|
382
|
+
// useActionState dispatch: it queues and reports its own errors.
|
|
383
|
+
ok = await run.__krateRun(data);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (typeof run === 'function')
|
|
387
|
+
await run(data);
|
|
388
|
+
else if (url)
|
|
389
|
+
await callServerAction(stripActionURL(url), [data]);
|
|
390
|
+
ok = true;
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
reportActionError(err, form);
|
|
395
|
+
}
|
|
396
|
+
finally {
|
|
397
|
+
st.running--;
|
|
398
|
+
if (st.running === 0) {
|
|
399
|
+
form.removeAttribute('data-krate-action-pending');
|
|
400
|
+
// The settled status commits in a later task (React's transition
|
|
401
|
+
// lane), so the pending render is painted, as in React.
|
|
402
|
+
krateTransitionWrites(() => publish(st, IDLE));
|
|
403
|
+
if (ok || st.resetRequested) {
|
|
404
|
+
st.resetRequested = false;
|
|
405
|
+
if (ok && form.hasAttribute('data-krate-reload'))
|
|
406
|
+
location.reload();
|
|
407
|
+
else
|
|
408
|
+
resetForm(form);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return ok;
|
|
413
|
+
}
|
|
414
|
+
function onSubmit(e) {
|
|
415
|
+
const form = e.target;
|
|
416
|
+
if (!form || form.tagName !== 'FORM' || e.defaultPrevented)
|
|
417
|
+
return;
|
|
418
|
+
const submitter = e.submitter || null;
|
|
419
|
+
const target = resolveSubmission(form, submitter);
|
|
420
|
+
if (!target)
|
|
421
|
+
return;
|
|
422
|
+
e.preventDefault();
|
|
423
|
+
const data = formDataFor(form, submitter);
|
|
424
|
+
// submit is a discrete event: the pending status (useFormStatus,
|
|
425
|
+
// useActionState) commits before the event returns, as in React, even when
|
|
426
|
+
// the action itself settles a few microtasks later. A focused submit button
|
|
427
|
+
// disabled by that pending render loses focus like React's does.
|
|
428
|
+
krateRunEvent('submit', true, () => {
|
|
429
|
+
void submitFormAction(form, target.fn, data, submitter, target.url);
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
/** Installs the document submit listener once per window. */
|
|
433
|
+
export function installActionForms(doc = typeof document !== 'undefined' ? document : undefined) {
|
|
434
|
+
if (!doc)
|
|
435
|
+
return;
|
|
436
|
+
const w = doc.defaultView;
|
|
437
|
+
if (!w || w.__krateActionBound)
|
|
438
|
+
return;
|
|
439
|
+
w.__krateActionBound = true;
|
|
440
|
+
doc.addEventListener('submit', onSubmit, false);
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Backs `const [state, formAction, isPending] = useActionState(fn, initial)`.
|
|
444
|
+
* The returned dispatch can be a form action, a button formAction, or called
|
|
445
|
+
* directly. Calls run one at a time in dispatch order; each receives the state
|
|
446
|
+
* the previous call produced. An error cancels the queued calls and is
|
|
447
|
+
* reported to the nearest error boundary hook.
|
|
448
|
+
*/
|
|
449
|
+
export function __krateActionState(action, getState, setState, setPending) {
|
|
450
|
+
const queue = [];
|
|
451
|
+
let running = false;
|
|
452
|
+
const drain = async () => {
|
|
453
|
+
running = true;
|
|
454
|
+
while (queue.length > 0) {
|
|
455
|
+
const item = queue.shift();
|
|
456
|
+
let ok = false;
|
|
457
|
+
try {
|
|
458
|
+
const next = await runActionTransition(() => action(getState(), item.payload));
|
|
459
|
+
krateTransitionWrites(() => setState(next));
|
|
460
|
+
ok = true;
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
const cancelled = queue.splice(0);
|
|
464
|
+
for (const c of cancelled) {
|
|
465
|
+
c.end();
|
|
466
|
+
c.done(false);
|
|
467
|
+
}
|
|
468
|
+
reportActionError(err);
|
|
469
|
+
}
|
|
470
|
+
finally {
|
|
471
|
+
krateTransitionWrites(() => {
|
|
472
|
+
item.end();
|
|
473
|
+
item.done(ok);
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
running = false;
|
|
478
|
+
krateTransitionWrites(() => setPending(false));
|
|
479
|
+
};
|
|
480
|
+
const run = (payload) => new Promise((done) => {
|
|
481
|
+
queue.push({ payload, end: __krateBeginAction(), done });
|
|
482
|
+
setPending(true);
|
|
483
|
+
if (!running)
|
|
484
|
+
void drain();
|
|
485
|
+
});
|
|
486
|
+
const dispatch = ((payload) => {
|
|
487
|
+
void run(payload);
|
|
488
|
+
});
|
|
489
|
+
dispatch.__krateRun = run;
|
|
490
|
+
return dispatch;
|
|
491
|
+
}
|
|
492
|
+
// useOptimistic
|
|
493
|
+
/**
|
|
494
|
+
* Backs `const [value, addOptimistic] = useOptimistic(state, update?)`.
|
|
495
|
+
* Optimistic updates are applied on top of the latest base state while an
|
|
496
|
+
* action or async transition is pending and dropped when every pending action
|
|
497
|
+
* has settled. Updates made outside any action are dropped on the next
|
|
498
|
+
* microtask unless an action starts first.
|
|
499
|
+
*/
|
|
500
|
+
export function __krateOptimistic(base, set, update) {
|
|
501
|
+
let updates = [];
|
|
502
|
+
const apply = (b) => {
|
|
503
|
+
let v = b;
|
|
504
|
+
for (const a of updates)
|
|
505
|
+
v = update ? update(v, a) : a;
|
|
506
|
+
return v;
|
|
507
|
+
};
|
|
508
|
+
createEffect(() => {
|
|
509
|
+
set(apply(base()));
|
|
510
|
+
});
|
|
511
|
+
const revert = () => {
|
|
512
|
+
if (updates.length === 0)
|
|
513
|
+
return;
|
|
514
|
+
updates = [];
|
|
515
|
+
set(base());
|
|
516
|
+
};
|
|
517
|
+
settleListeners.add(revert);
|
|
518
|
+
onCleanup(() => {
|
|
519
|
+
settleListeners.delete(revert);
|
|
520
|
+
});
|
|
521
|
+
return (a) => {
|
|
522
|
+
updates.push(a);
|
|
523
|
+
set(apply(base()));
|
|
524
|
+
if (pendingActions === 0) {
|
|
525
|
+
queueMicrotask(() => {
|
|
526
|
+
if (pendingActions === 0)
|
|
527
|
+
revert();
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
if (typeof document !== 'undefined')
|
|
533
|
+
installActionForms(document);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|