@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.4

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 (105) hide show
  1. package/dist/action-context.d.ts +56 -0
  2. package/dist/action-context.js +73 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +550 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +417 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/cache-scope.d.ts +118 -0
  12. package/dist/cache-scope.js +311 -0
  13. package/dist/cache.d.ts +55 -0
  14. package/dist/cache.js +155 -0
  15. package/dist/cache.test.d.ts +1 -0
  16. package/dist/cache.test.js +217 -0
  17. package/dist/class-component.d.ts +66 -0
  18. package/dist/class-component.js +633 -0
  19. package/dist/class-component.test.d.ts +1 -0
  20. package/dist/class-component.test.js +411 -0
  21. package/dist/context.d.ts +13 -0
  22. package/dist/context.js +58 -32
  23. package/dist/context.test.d.ts +1 -0
  24. package/dist/context.test.js +57 -0
  25. package/dist/derived.test.d.ts +1 -0
  26. package/dist/derived.test.js +140 -0
  27. package/dist/discrete.test.d.ts +1 -0
  28. package/dist/discrete.test.js +100 -0
  29. package/dist/dom.d.ts +55 -0
  30. package/dist/dom.js +414 -63
  31. package/dist/effects.d.ts +88 -0
  32. package/dist/effects.js +790 -0
  33. package/dist/effects.test.d.ts +1 -0
  34. package/dist/effects.test.js +485 -0
  35. package/dist/events.d.ts +58 -0
  36. package/dist/events.js +503 -0
  37. package/dist/events.test.d.ts +1 -0
  38. package/dist/events.test.js +447 -0
  39. package/dist/index.d.ts +14 -4
  40. package/dist/index.js +9 -3
  41. package/dist/jsx-types.d.ts +2 -0
  42. package/dist/krate-hydrate-lite.js +7 -1
  43. package/dist/krate-hydrate.js +7 -1
  44. package/dist/krate-runtime.js +7 -1
  45. package/dist/krate-suspense.js +2 -0
  46. package/dist/lanes.test.d.ts +1 -0
  47. package/dist/lanes.test.js +59 -0
  48. package/dist/list.d.ts +20 -0
  49. package/dist/list.js +466 -0
  50. package/dist/list.test.d.ts +1 -0
  51. package/dist/list.test.js +344 -0
  52. package/dist/optimistic-lanes.test.d.ts +1 -0
  53. package/dist/optimistic-lanes.test.js +45 -0
  54. package/dist/portal.d.ts +47 -0
  55. package/dist/portal.js +189 -0
  56. package/dist/portal.test.d.ts +1 -0
  57. package/dist/portal.test.js +99 -0
  58. package/dist/react-effects.test.d.ts +1 -0
  59. package/dist/react-effects.test.js +96 -0
  60. package/dist/react-suspense.test.d.ts +1 -0
  61. package/dist/react-suspense.test.js +194 -0
  62. package/dist/react.d.ts +132 -32
  63. package/dist/react.js +335 -81
  64. package/dist/react.test.js +12 -2
  65. package/dist/reconcile.js +13 -0
  66. package/dist/refs.d.ts +33 -0
  67. package/dist/refs.js +142 -0
  68. package/dist/refs.test.d.ts +1 -0
  69. package/dist/refs.test.js +257 -0
  70. package/dist/request-context.d.ts +62 -0
  71. package/dist/request-context.js +107 -0
  72. package/dist/resource.js +20 -1
  73. package/dist/router-layout.test.d.ts +1 -0
  74. package/dist/router-layout.test.js +179 -0
  75. package/dist/router-lite.d.ts +25 -0
  76. package/dist/router-lite.js +73 -0
  77. package/dist/router-nav.test.d.ts +1 -0
  78. package/dist/router-nav.test.js +399 -0
  79. package/dist/router-slots.test.d.ts +1 -0
  80. package/dist/router-slots.test.js +144 -0
  81. package/dist/router.d.ts +66 -2
  82. package/dist/router.js +1535 -650
  83. package/dist/server-async.test.d.ts +1 -0
  84. package/dist/server-async.test.js +174 -0
  85. package/dist/server-renderer.js +494 -119
  86. package/dist/server.d.ts +27 -1
  87. package/dist/server.js +187 -1
  88. package/dist/server.test.js +20 -0
  89. package/dist/signal-lanes.test.d.ts +1 -0
  90. package/dist/signal-lanes.test.js +32 -0
  91. package/dist/signal.d.ts +186 -1
  92. package/dist/signal.js +896 -66
  93. package/dist/slots.d.ts +22 -0
  94. package/dist/slots.js +134 -0
  95. package/dist/slots.test.d.ts +1 -0
  96. package/dist/slots.test.js +169 -0
  97. package/dist/snapshots.test.d.ts +1 -0
  98. package/dist/snapshots.test.js +208 -0
  99. package/dist/suspense-actions.test.d.ts +1 -0
  100. package/dist/suspense-actions.test.js +72 -0
  101. package/dist/suspense.d.ts +220 -0
  102. package/dist/suspense.js +901 -0
  103. package/dist/suspense.test.d.ts +1 -0
  104. package/dist/suspense.test.js +518 -0
  105. package/package.json +5 -1
package/dist/react.js CHANGED
@@ -9,15 +9,30 @@
9
9
  * Krate components run once and update through signals, so hooks here are
10
10
  * signal-backed rather than re-render based. Pure APIs (`createElement`,
11
11
  * `Children`, `cloneElement`, `isValidElement`, `createRef`, `createContext`)
12
- * behave as expected; scheduling APIs (`useTransition`, `startTransition`,
13
- * `useDeferredValue`) are best-effort. Class components are intentionally
12
+ * behave as expected. `Suspense`, `lazy` and `use` suspend through the
13
+ * Suspense runtime (see suspense.ts): a component that reads a pending promise
14
+ * renders a placeholder that is replaced once the promise settles, and the
15
+ * nearest `<Suspense>` shows its fallback until all of its placeholders
16
+ * resolved. `useTransition`/`startTransition` support async actions and
17
+ * `useDeferredValue` defers getter values. Class components are intentionally
14
18
  * minimal.
15
19
  */
16
- import { h } from './dom.js';
17
- import { createSignal, createEffect } from './signal.js';
20
+ import { h, krateTrackNode } from './dom.js';
21
+ import { getOwner, handleError } from './boundary.js';
22
+ import { createSignal, createReducer, isSignalGetter } from './signal.js';
23
+ import { createEffectDeps } from './effects.js';
24
+ import { krateSetRef } from './refs.js';
25
+ import { krateEventRoot } from './events.js';
18
26
  import { createContext as krateCreateContext } from './context.js';
19
27
  import { cloneElement as krateCloneElement } from './class-helpers.js';
20
28
  import { jsx as krateJsx } from './jsx-runtime.js';
29
+ import { mountClassElement } from './class-component.js';
30
+ import { createBoundary, createDeferredValue, createExternalStore, isSuspenseSignal, readValue, reportSuspenseError, startTransition as krateStartTransition, trackThenable, useTransition as krateUseTransition, withReplayScope, connectActionTransitions, connectErrorBoundaries, } from './suspense.js';
31
+ import { __krateActionState, __krateBeginAction, __krateOptimistic, requestFormReset as krateRequestFormReset, setActionTransitionRunner, } from './actions.js';
32
+ // Actions, useActionState and useTransition share one transition scope.
33
+ connectActionTransitions({ setActionTransitionRunner, __krateBeginAction });
34
+ // Errors from suspended work go to the nearest error boundary.
35
+ connectErrorBoundaries({ getOwner, handleError: (e, o) => handleError(e, o) });
21
36
  /** React's `Fragment` marker; `createElement(Fragment, ...)` yields a fragment. */
22
37
  export const Fragment = Symbol.for('krate.react.fragment');
23
38
  function fragmentChildren(children) {
@@ -46,12 +61,87 @@ export function createElement(type, config, ...children) {
46
61
  props.children = children[0];
47
62
  else if (children.length > 1)
48
63
  props.children = children;
49
- return krateJsx(type, props);
64
+ return render(type, props);
65
+ }
66
+ export function jsx(type, props, _key) {
67
+ return render(type, props);
50
68
  }
51
- export const jsx = krateJsx;
52
- export const jsxs = krateJsx;
69
+ export const jsxs = jsx;
53
70
  export function jsxDEV(type, props, _key, _isStatic, _source, _self) {
54
- return krateJsx(type, props);
71
+ return render(type, props);
72
+ }
73
+ // render creates an element, or calls a component. A component that suspends
74
+ // (a pending use() or lazy load) becomes a placeholder comment that re-renders
75
+ // the component when the promise settles; the nearest <Suspense> claims it.
76
+ function render(type, props) {
77
+ if (type === Fragment) {
78
+ const kids = props?.children;
79
+ return fragmentChildren(kids === undefined ? [] : Array.isArray(kids) ? kids : [kids]);
80
+ }
81
+ if (typeof type !== 'function' || isClassComponent(type)) {
82
+ return renderType(type, props || {});
83
+ }
84
+ const replay = { list: [], i: 0 };
85
+ const attempt = () => withReplayScope(replay, () => renderType(type, props || {}));
86
+ try {
87
+ return attempt();
88
+ }
89
+ catch (error) {
90
+ if (!isSuspenseSignal(error))
91
+ throw error;
92
+ return suspendedPlaceholder(error.thenable, attempt);
93
+ }
94
+ }
95
+ const SUSPENDED = '__krateSuspended';
96
+ function suspendedPlaceholder(thenable, attempt) {
97
+ const marker = document.createComment('krate:suspended');
98
+ const state = { boundary: null };
99
+ marker[SUSPENDED] = state;
100
+ const settle = () => {
101
+ let next;
102
+ try {
103
+ next = attempt();
104
+ }
105
+ catch (error) {
106
+ if (isSuspenseSignal(error)) {
107
+ error.thenable.then(settle, settle);
108
+ return;
109
+ }
110
+ reportSuspenseError(error, state.boundary);
111
+ next = document.createComment('krate:error');
112
+ }
113
+ if (state.boundary)
114
+ claimSuspended(next, state.boundary);
115
+ if (marker.parentNode)
116
+ marker.parentNode.replaceChild(next, marker);
117
+ marker[SUSPENDED] = undefined;
118
+ state.boundary?.release();
119
+ };
120
+ thenable.then(settle, settle);
121
+ return marker;
122
+ }
123
+ // claimSuspended attributes every unclaimed placeholder under root to the
124
+ // boundary and holds it once per placeholder. Inner boundaries render (and
125
+ // claim) first, so the innermost boundary wins.
126
+ function claimSuspended(root, boundary) {
127
+ let claimed = 0;
128
+ const visit = (node) => {
129
+ if (node.nodeType === 8) {
130
+ const state = node[SUSPENDED];
131
+ if (state && !state.boundary) {
132
+ if (boundary) {
133
+ state.boundary = boundary;
134
+ boundary.hold();
135
+ }
136
+ claimed++;
137
+ }
138
+ return;
139
+ }
140
+ for (let c = node.firstChild; c; c = c.nextSibling)
141
+ visit(c);
142
+ };
143
+ visit(root);
144
+ return claimed;
55
145
  }
56
146
  /** `React.Children` helpers over arrays and single values. */
57
147
  export const Children = {
@@ -102,17 +192,83 @@ export function forwardRef(render) {
102
192
  export function memo(component, _compare) {
103
193
  return component;
104
194
  }
195
+ /**
196
+ * `React.lazy(() => import('./X'))`. The loader runs on the first render (as
197
+ * in React); until the module resolves the component suspends to the nearest
198
+ * `<Suspense>`. The module's default export must be a component; a rejected
199
+ * import or a non-component default is reported to the nearest error
200
+ * boundary.
201
+ */
105
202
  export function lazy(loader) {
106
- // A synchronous passthrough: Krate cannot await a dynamic import at render
107
- // time. Dynamic/lazy components require the SSR/islands path.
108
- return loader;
203
+ let payload = null;
204
+ const Lazy = (props) => {
205
+ if (!payload)
206
+ payload = trackThenable(loader());
207
+ const mod = readValue(payload);
208
+ const impl = mod && typeof mod === 'object' ? mod.default : undefined;
209
+ if (typeof impl !== 'function') {
210
+ throw new Error('lazy: the module did not have a component as its default export. ' +
211
+ 'Lazy element type must resolve to a class or function; export the component with `export default`.');
212
+ }
213
+ return render(impl, props);
214
+ };
215
+ return Lazy;
109
216
  }
217
+ /** StrictMode renders its children; Krate has no double-render checks. */
110
218
  export const StrictMode = Fragment;
111
- export const Profiler = Fragment;
112
- export const Suspense = Fragment;
219
+ /**
220
+ * Profiler renders its children. `onRender` is never called: Krate does not
221
+ * re-render components, so there are no commit timings to report.
222
+ */
223
+ export function Profiler(props) {
224
+ return fragmentChildren(toArray(props.children));
225
+ }
226
+ /**
227
+ * A Suspense boundary. Children that suspend render as placeholders; while
228
+ * any placeholder under this boundary is pending the fallback is shown, and
229
+ * the content is revealed once all of them resolved (siblings together).
230
+ */
231
+ export function Suspense(props) {
232
+ const content = fragmentChildren(toArray(props.children));
233
+ const fallback = fragmentChildren(toArray(props.fallback));
234
+ const start = document.createComment('suspense');
235
+ const end = document.createComment('/suspense');
236
+ let stash;
237
+ // apply swaps the nodes between the markers with the stashed branch.
238
+ const apply = () => {
239
+ const parent = start.parentNode;
240
+ if (!parent)
241
+ return;
242
+ const taken = document.createDocumentFragment();
243
+ let n = start.nextSibling;
244
+ while (n && n !== end) {
245
+ const next = n.nextSibling;
246
+ taken.appendChild(n);
247
+ n = next;
248
+ }
249
+ parent.insertBefore(stash, end);
250
+ stash = taken;
251
+ };
252
+ const pending = claimSuspended(content, null);
253
+ const boundary = createBoundary('compat', apply, { anchor: start, initialContent: pending === 0 });
254
+ claimSuspended(content, boundary);
255
+ const out = document.createDocumentFragment();
256
+ out.appendChild(start);
257
+ if (pending === 0) {
258
+ out.appendChild(content);
259
+ stash = fallback;
260
+ }
261
+ else {
262
+ out.appendChild(fallback);
263
+ stash = content;
264
+ }
265
+ out.appendChild(end);
266
+ return out;
267
+ }
113
268
  export function createContext(defaultValue) {
114
269
  const ctx = krateCreateContext(defaultValue);
115
270
  return {
271
+ $$typeof: Symbol.for('krate.context'),
116
272
  _id: ctx.id,
117
273
  defaultValue,
118
274
  Provider: (props) => ctx.Provider(props),
@@ -129,127 +285,225 @@ export function useState(initial) {
129
285
  const value = typeof initial === 'function' ? initial() : initial;
130
286
  return createSignal(value);
131
287
  }
132
- export function useReducer(reducer, initial) {
133
- const [get, set] = createSignal(initial);
134
- const dispatch = (action) => set((prev) => reducer(prev, action));
135
- return [get, dispatch];
288
+ export function useReducer(reducer, initial, init) {
289
+ // Stable dispatch, Object.is bail-out and the lazy initializer come from
290
+ // createReducer.
291
+ return createReducer(reducer, initial, init);
136
292
  }
293
+ // Components run once, so a dependency array passed here is captured once.
294
+ // Elements that are signal getters (state from useState above) are read on
295
+ // every check, which keeps those dependencies live.
296
+ function depsThunk(deps) {
297
+ if (deps == null)
298
+ return null;
299
+ if (typeof deps === 'function')
300
+ return deps;
301
+ return () => deps.map((d) => (isSignalGetter(d) ? d() : d));
302
+ }
303
+ /**
304
+ * Memoized value. The component body runs once, so the factory runs once and
305
+ * the value is stable for the component's lifetime (React recomputes only
306
+ * when a dependency changes, which a single run cannot observe).
307
+ */
137
308
  export function useMemo(factory, _deps) {
138
309
  return factory();
139
310
  }
311
+ /** Memoized callback: one identity for the component's lifetime. */
140
312
  export function useCallback(fn, _deps) {
141
313
  return fn;
142
314
  }
143
315
  export function useRef(initial) {
144
316
  return { current: initial ?? null };
145
317
  }
146
- export function useEffect(effect, _deps) {
147
- createEffect(effect);
318
+ function effectHook(phase) {
319
+ return (effect, deps) => {
320
+ createEffectDeps(effect, depsThunk(deps), phase);
321
+ };
148
322
  }
149
- export const useLayoutEffect = useEffect;
150
- export const useInsertionEffect = useEffect;
151
- export function useImperativeHandle(ref, create) {
152
- if (!ref)
153
- return;
154
- const value = create();
155
- if (typeof ref === 'function')
156
- ref(value);
157
- else
158
- ref.current = value;
323
+ /** Passive effect: runs after paint, re-runs when a live dependency changes. */
324
+ export const useEffect = effectHook('passive');
325
+ /** Layout effect: runs synchronously after the DOM is updated, before paint. */
326
+ export const useLayoutEffect = effectHook('layout');
327
+ /** Insertion effect: runs before layout effects in the same commit. */
328
+ export const useInsertionEffect = effectHook('insertion');
329
+ export function useImperativeHandle(ref, create, deps) {
330
+ // React implements handles as layout effects: attached (object or callback
331
+ // ref, with React 19 callback cleanup) in the layout phase, re-created when
332
+ // a dependency changes, detached on cleanup.
333
+ createEffectDeps(() => (ref ? krateSetRef(ref, create()) : undefined), depsThunk(deps), 'layout');
159
334
  }
160
335
  export function useDebugValue(_value) {
161
336
  // no-op
162
337
  }
163
- export function useSyncExternalStore(subscribe, getSnapshot) {
164
- const [get, set] = createSignal(getSnapshot());
165
- createEffect(() => {
166
- const unsubscribe = subscribe(() => set(getSnapshot()));
167
- return () => unsubscribe();
168
- });
169
- return get;
338
+ /**
339
+ * `useSyncExternalStore` returning a snapshot getter. Snapshots are compared
340
+ * with Object.is, a change between the first read and the subscription is
341
+ * picked up, and the store is unsubscribed on teardown.
342
+ */
343
+ export function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
344
+ return createExternalStore(subscribe, getSnapshot, getServerSnapshot);
170
345
  }
346
+ /**
347
+ * `[isPending, startTransition]`. isPending (a getter) stays true until the
348
+ * action passed to startTransition settles, including async actions, and
349
+ * until every overlapping transition started here settled.
350
+ */
171
351
  export function useTransition() {
172
- const [pending, setPending] = createSignal(false);
173
- const start = (fn) => {
174
- setPending(true);
175
- try {
176
- fn();
177
- }
178
- finally {
179
- setPending(false);
180
- }
181
- };
182
- return [pending, start];
352
+ return krateUseTransition();
183
353
  }
184
- export function useOptimistic(initial, update) {
185
- const [state, setState] = createSignal(initial);
186
- const add = (action) => {
187
- setState((prev) => (update ? update(prev, action) : action));
188
- };
189
- return [state, add];
354
+ /**
355
+ * React 19 `useOptimistic`. `state` may be a value or a getter; optimistic
356
+ * updates apply on top of it while an action is pending and are dropped when
357
+ * the action settles.
358
+ */
359
+ export function useOptimistic(state, update) {
360
+ const base = typeof state === 'function' ? state : () => state;
361
+ const [value, setValue] = createSignal(base());
362
+ return [value, __krateOptimistic(base, (v) => setValue(() => v), update)];
190
363
  }
191
- export function useActionState(action, initial) {
364
+ /**
365
+ * React 19 `useActionState`: returns `[state, dispatch, isPending]` getters and
366
+ * a dispatch usable as a form action. Calls are queued in order and each
367
+ * receives the previous state; server actions receive it as their first
368
+ * argument over the action transport.
369
+ */
370
+ export function useActionState(action, initial, _permalink) {
192
371
  const [state, setState] = createSignal(initial);
193
372
  const [pending, setPending] = createSignal(false);
194
- const dispatch = async (payload) => {
195
- setPending(true);
196
- try {
197
- setState(await action(state(), payload));
198
- }
199
- finally {
200
- setPending(false);
201
- }
202
- };
373
+ const dispatch = __krateActionState(action, state, (v) => setState(() => v), setPending);
203
374
  return [state, dispatch, pending];
204
375
  }
376
+ /**
377
+ * React DOM `useFormStatus`. Source components are lowered by the compiler to
378
+ * a form-scoped status bound to the component's element; called from compiled
379
+ * code without an element, it reports an idle status.
380
+ */
205
381
  export function useFormStatus() {
206
382
  return { pending: false, data: null, method: null, action: null };
207
383
  }
208
- export function useDeferredValue(value) {
384
+ /** React DOM `requestFormReset(form)`. */
385
+ export const requestFormReset = krateRequestFormReset;
386
+ /**
387
+ * `useDeferredValue(value, initialValue?)`. A getter value is deferred: the
388
+ * returned getter keeps the previous value during urgent updates and catches
389
+ * up in a later task, starting from `initialValue` when given. A plain value
390
+ * cannot change without a re-render in Krate and is returned as is.
391
+ */
392
+ export function useDeferredValue(value, ...initial) {
393
+ if (typeof value === 'function')
394
+ return createDeferredValue(value, ...initial);
209
395
  return value;
210
396
  }
397
+ /** Top-level `startTransition`; async actions keep the transition pending. */
211
398
  export function startTransition(fn) {
212
- fn();
399
+ krateStartTransition(fn);
213
400
  }
401
+ /**
402
+ * React 19 `use()`: reads a context, or unwraps a promise. A pending promise
403
+ * suspends the calling component (it re-renders when the promise settles); a
404
+ * rejected one throws its reason to the nearest error boundary. The same
405
+ * promise object never suspends again once it resolved. Unlike hooks, `use`
406
+ * may be called conditionally.
407
+ */
214
408
  export function use(value) {
215
409
  const ctx = value;
216
410
  if (ctx && typeof ctx.useContext === 'function')
217
411
  return ctx.useContext();
218
- return value;
412
+ if (value && typeof value.then === 'function')
413
+ return readValue(value);
414
+ throw new Error('An unsupported type was passed to use(): ' + String(value));
219
415
  }
220
416
  export function flushSync(fn) {
221
417
  return fn();
222
418
  }
419
+ /**
420
+ * Runtime portal (content rendered by `h()` after hydration; compiled source
421
+ * components lower createPortal to an anchor instead, see portal.ts). The
422
+ * children are appended to `container`; the returned comment stands in the
423
+ * React tree: events bubble from the content through it, and disposing it
424
+ * removes the content.
425
+ */
223
426
  export function createPortal(children, container) {
224
- if (children instanceof Node)
225
- container.appendChild(children);
226
- else if (Array.isArray(children)) {
227
- for (const child of children) {
228
- if (child instanceof Node)
229
- container.appendChild(child);
230
- else if (child != null)
231
- container.appendChild(document.createTextNode(String(child)));
427
+ const anchor = document.createComment('krate-portal');
428
+ // Handlers inside a portal outside the app root still need delegation.
429
+ const root = typeof document !== 'undefined' ? document.getElementById('root') : null;
430
+ if (container.nodeType === 1 && !(root && root.contains(container)))
431
+ krateEventRoot(container);
432
+ const nodes = [];
433
+ const add = (child) => {
434
+ if (child == null || child === false || child === true)
435
+ return;
436
+ if (Array.isArray(child)) {
437
+ for (const c of child)
438
+ add(c);
439
+ return;
232
440
  }
233
- }
234
- else if (children != null) {
235
- container.appendChild(document.createTextNode(String(children)));
236
- }
237
- return container;
441
+ const node = child instanceof Node ? child : document.createTextNode(String(child));
442
+ if (node.nodeType === 11) {
443
+ for (const n of Array.from(node.childNodes))
444
+ add(n);
445
+ return;
446
+ }
447
+ node.__kpp = anchor;
448
+ nodes.push(node);
449
+ container.appendChild(node);
450
+ };
451
+ add(children);
452
+ krateTrackNode(anchor, () => {
453
+ for (const n of nodes)
454
+ if (n.parentNode)
455
+ n.parentNode.removeChild(n);
456
+ });
457
+ return anchor;
238
458
  }
239
- /** Minimal class base so compiled code that `extends React.Component` resolves. */
459
+ /**
460
+ * Class component base for React source the compiler did not lower (for
461
+ * example classes created at runtime). Rendering it with createElement/jsx
462
+ * mounts it through the same instance controller as lowered classes
463
+ * (class-component.ts): setState is batched, lifecycles run in React order,
464
+ * and each committed update re-runs render(). Compiled npm packages do not
465
+ * use this: they run on Preact in islands.
466
+ */
240
467
  export class ComponentBase {
241
468
  constructor(props) {
242
469
  this.props = props ?? {};
243
470
  this.state = {};
471
+ this.context = undefined;
244
472
  }
245
- setState(update) {
473
+ /** Replaced by the controller on mount; before that it merges synchronously. */
474
+ setState(update, _callback) {
246
475
  const next = typeof update === 'function'
247
476
  ? update(this.state, this.props)
248
477
  : update;
249
478
  this.state = { ...this.state, ...next };
250
479
  }
480
+ forceUpdate(_callback) { }
251
481
  render() {
252
482
  return null;
253
483
  }
254
484
  }
485
+ ComponentBase.prototype.isReactComponent = {};
486
+ export class Component extends ComponentBase {
487
+ }
488
+ export class PureComponent extends ComponentBase {
489
+ }
490
+ PureComponent.prototype.isPureReactComponent = true;
491
+ function isClassComponent(type) {
492
+ return typeof type === 'function' && !!type.prototype?.isReactComponent;
493
+ }
494
+ function toNode(value) {
495
+ if (value instanceof Node)
496
+ return value;
497
+ if (value == null || value === false || value === true)
498
+ return document.createTextNode('');
499
+ if (Array.isArray(value))
500
+ return fragmentChildren(value);
501
+ return document.createTextNode(String(value));
502
+ }
503
+ function renderType(type, props) {
504
+ if (isClassComponent(type)) {
505
+ return mountClassElement(type, props, toNode);
506
+ }
507
+ return krateJsx(type, props);
508
+ }
255
509
  export const reactCompat = { h, Fragment };
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { Children, Fragment, cloneElement, createContext, createElement, createRef, isValidElement, useContext, useOptimistic, useFormStatus, } from './react.js';
2
+ import { Children, Fragment, cloneElement, createContext, createElement, createRef, isValidElement, useContext, useOptimistic, useFormStatus, useActionState, } from './react.js';
3
3
  describe('react compat runtime', () => {
4
4
  it('createElement builds DOM elements with props and children', () => {
5
5
  const el = createElement('div', { class: 'x', id: 'a' }, 'hi');
@@ -38,11 +38,21 @@ describe('react compat runtime', () => {
38
38
  });
39
39
  });
40
40
  describe('react 19 compat shims', () => {
41
- it('useOptimistic updates its getter', () => {
41
+ it('useOptimistic applies an update and reverts it outside an action', async () => {
42
42
  const [state, add] = useOptimistic(1);
43
43
  expect(state()).toBe(1);
44
44
  add(2);
45
45
  expect(state()).toBe(2);
46
+ await new Promise((r) => setTimeout(r, 0));
47
+ expect(state()).toBe(1);
48
+ });
49
+ it('useActionState threads the previous state', async () => {
50
+ const [state, dispatch, pending] = useActionState(async (prev, n) => prev + n, 1);
51
+ dispatch(2);
52
+ expect(pending()).toBe(true);
53
+ await new Promise((r) => setTimeout(r, 0));
54
+ expect(state()).toBe(3);
55
+ expect(pending()).toBe(false);
46
56
  });
47
57
  it('useFormStatus exposes an idle status', () => {
48
58
  expect(useFormStatus()).toEqual({ pending: false, data: null, method: null, action: null });
package/dist/reconcile.js CHANGED
@@ -153,6 +153,9 @@ function nodeKey(n) {
153
153
  const dk = el.getAttribute('data-k');
154
154
  if (dk)
155
155
  return dk;
156
+ const kc = el.getAttribute('data-kc');
157
+ if (kc)
158
+ return 'kc:' + kc;
156
159
  const id = el.getAttribute('id');
157
160
  if (id)
158
161
  return '#' + id;
@@ -214,6 +217,16 @@ function reconcileNode(oldNode, newNode) {
214
217
  const newEl = newNode;
215
218
  if (nodeKey(oldEl) !== nodeKey(newEl))
216
219
  return replaceNode(oldEl, newEl);
220
+ // A <template>'s content is not in childNodes, so it cannot be diffed in
221
+ // place; replace it whenever its markup changed (conditional branches are
222
+ // carried in <template data-kc> elements).
223
+ if (oldEl.tagName === 'TEMPLATE') {
224
+ if (oldEl.innerHTML !== newEl.innerHTML) {
225
+ return replaceNode(oldEl, newEl);
226
+ }
227
+ syncAttributes(oldEl, newEl);
228
+ return oldEl;
229
+ }
217
230
  syncAttributes(oldEl, newEl);
218
231
  reconcileChildren(oldEl, newEl);
219
232
  return oldEl;
package/dist/refs.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ export type KrateRef = ((value: unknown) => unknown) | {
2
+ current: unknown;
3
+ } | null | undefined;
4
+ /**
5
+ * Attaches `value` (an element or an imperative handle) to `ref` and returns
6
+ * the detach function. Used by useImperativeHandle.
7
+ */
8
+ export declare function krateSetRef(ref: KrateRef, value: unknown): () => void;
9
+ /**
10
+ * Starts holding hydration refs (called at the start of a page's hydration
11
+ * script) until krateRefsFlush. Components mounted later attach at once.
12
+ */
13
+ export declare function krateRefsHold(): void;
14
+ /**
15
+ * Attaches the hydration refs queued so far whose element is in the
16
+ * document. The hydration script calls it after every component has bound its
17
+ * DOM (and before the effect commit), so a ref on server-rendered content that
18
+ * a binding replaced (a re-rendered list) is never attached, as in React.
19
+ */
20
+ export declare function krateRefsFlush(): void;
21
+ /**
22
+ * Registers an element ref. mode 'now' attaches immediately (a node built by
23
+ * h() that is about to be inserted); 'defer' queues it for krateRefsFlush
24
+ * while a hydration script holds refs (krateRefsHold); otherwise it attaches when the element is in the document. A
25
+ * ref on a detached node waits until a conditional branch holding it is
26
+ * shown. Returns the release function (detach plus unregister), safe to call
27
+ * more than once.
28
+ */
29
+ export declare function krateAttachRef(el: Element, ref: KrateRef, assign?: (v: unknown) => void, mode?: 'now' | 'defer'): () => void;
30
+ /** Detaches refs of registered elements inside `root` (a branch leaving the document). */
31
+ export declare function krateRefsLeave(root: Node): void;
32
+ /** Attaches registered refs whose element is now in the document. */
33
+ export declare function krateRefsEnter(): void;