@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
@@ -0,0 +1,411 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { createEffect, createSignal, disposeAll } from './signal.js';
3
+ import { __krateOwn, __krateOwner, __krateCondPre, __krateCondPost, __krateOnError } from './boundary.js';
4
+ import { __krateClass } from './class-component.js';
5
+ // Lets the effect flush, the render phase and the commit phase run.
6
+ const settle = () => new Promise((r) => setTimeout(r, 0));
7
+ afterEach(() => {
8
+ disposeAll();
9
+ });
10
+ // Simulates the hydration scope the compiler emits for a lowered class: a
11
+ // committed-state signal, the instance, and the render bindings.
12
+ function classScope(props, initial, spec, render) {
13
+ const [state, setState] = createSignal(initial);
14
+ const inst = __krateClass(props, state, setState, spec);
15
+ if (render)
16
+ render(state, props);
17
+ return { inst, state };
18
+ }
19
+ describe('class lifecycles', () => {
20
+ it('mounts children before parents and updates child before parent', async () => {
21
+ const log = [];
22
+ let parent;
23
+ const text = { p: '', c: '' };
24
+ const childProps = {};
25
+ __krateOwn('P', { n: 'Parent' }, () => {
26
+ parent = classScope({}, { n: 1 }, {
27
+ componentDidMount: () => log.push('P didMount'),
28
+ componentDidUpdate: (pp, ps) => log.push('P didUpdate ' + ps.n + '>' + parent.inst.state.n),
29
+ }, (st) => {
30
+ Object.defineProperty(childProps, 'n', { get: () => st().n, enumerable: true, configurable: true });
31
+ createEffect(() => {
32
+ text.p = String(st().n);
33
+ });
34
+ });
35
+ });
36
+ __krateOwn('C', { p: 'P', n: 'Child', k: 'P' }, () => {
37
+ const c = classScope(childProps, {}, {
38
+ componentDidMount: () => log.push('C didMount ' + c.inst.props.n),
39
+ componentDidUpdate: (pp) => log.push('C didUpdate ' + pp.n + '>' + c.inst.props.n + ' dom=' + text.c),
40
+ }, (_st, props) => {
41
+ createEffect(() => {
42
+ text.c = String(props.n);
43
+ });
44
+ });
45
+ });
46
+ await settle();
47
+ expect(log).toEqual(['C didMount 1', 'P didMount']);
48
+ log.length = 0;
49
+ parent.inst.setState({ n: 2 });
50
+ await settle();
51
+ expect(log).toEqual(['C didUpdate 1>2 dom=2', 'P didUpdate 1>2']);
52
+ expect(text).toEqual({ p: '2', c: '2' });
53
+ });
54
+ it('re-renders child classes when the creator re-renders with equal props', async () => {
55
+ const log = [];
56
+ let parent;
57
+ __krateOwn('P', { n: 'Parent' }, () => {
58
+ parent = classScope({}, { n: 1, other: 0 }, { componentDidUpdate: () => log.push('P') });
59
+ });
60
+ __krateOwn('C', { p: 'P', n: 'Child', k: 'P' }, () => {
61
+ classScope({ label: 'x' }, {}, { componentDidUpdate: () => log.push('C') });
62
+ });
63
+ __krateOwn('Pure', { p: 'P', n: 'Pure', k: 'P' }, () => {
64
+ classScope({ label: 'x' }, {}, { pure: true, componentDidUpdate: () => log.push('Pure') });
65
+ });
66
+ // Passed as children from outside: not re-rendered by P.
67
+ __krateOwn('Passed', { p: 'P', n: 'Passed' }, () => {
68
+ classScope({}, {}, { componentDidUpdate: () => log.push('Passed') });
69
+ });
70
+ await settle();
71
+ parent.inst.setState({ other: 1 });
72
+ await settle();
73
+ expect(log).toEqual(['C', 'P']);
74
+ });
75
+ it('batches setState, applies updaters in order and runs callbacks after didUpdate', async () => {
76
+ const log = [];
77
+ let c;
78
+ __krateOwn('A', { n: 'A' }, () => {
79
+ c = classScope({}, { n: 0 }, {
80
+ componentDidUpdate: (_pp, ps) => log.push('didUpdate ' + ps.n + '>' + c.inst.state.n),
81
+ });
82
+ });
83
+ await settle();
84
+ c.inst.setState((s) => ({ n: s.n + 1 }), () => log.push('cb1 ' + c.inst.state.n));
85
+ c.inst.setState((s) => ({ n: s.n + 1 }), () => log.push('cb2'));
86
+ c.inst.setState({ extra: true });
87
+ // setState is asynchronous: this.state is unchanged until the update runs.
88
+ expect(c.inst.state.n).toBe(0);
89
+ await settle();
90
+ expect(log).toEqual(['didUpdate 0>2', 'cb1 2', 'cb2']);
91
+ expect(c.state()).toEqual({ n: 2, extra: true });
92
+ });
93
+ it('shouldComponentUpdate false skips the render and didUpdate but updates the instance', async () => {
94
+ const log = [];
95
+ let c;
96
+ let dom = '';
97
+ __krateOwn('A', { n: 'A' }, () => {
98
+ c = classScope({}, { n: 0 }, {
99
+ shouldComponentUpdate: (_np, ns) => ns.n % 2 === 0,
100
+ componentDidUpdate: () => log.push('didUpdate ' + c.inst.state.n),
101
+ }, (st) => {
102
+ createEffect(() => {
103
+ dom = String(st().n);
104
+ });
105
+ });
106
+ });
107
+ await settle();
108
+ c.inst.setState({ n: 1 }, () => log.push('cb ' + c.inst.state.n));
109
+ await settle();
110
+ expect(dom).toBe('0');
111
+ expect(c.inst.state.n).toBe(1);
112
+ expect(log).toEqual(['cb 1']);
113
+ c.inst.setState({ n: 2 });
114
+ await settle();
115
+ expect(dom).toBe('2');
116
+ expect(log).toEqual(['cb 1', 'didUpdate 2']);
117
+ // forceUpdate bypasses shouldComponentUpdate.
118
+ c.inst.setState({ n: 3 });
119
+ await settle();
120
+ expect(dom).toBe('2');
121
+ c.inst.forceUpdate(() => log.push('forced'));
122
+ await settle();
123
+ expect(dom).toBe('3');
124
+ expect(log.slice(-2)).toEqual(['didUpdate 3', 'forced']);
125
+ });
126
+ it('PureComponent skips shallow-equal updates', async () => {
127
+ const log = [];
128
+ let c;
129
+ __krateOwn('A', { n: 'A' }, () => {
130
+ c = classScope({}, { n: 0 }, { pure: true, componentDidUpdate: () => log.push('u') });
131
+ });
132
+ await settle();
133
+ c.inst.setState({ n: 0 });
134
+ await settle();
135
+ expect(log).toEqual([]);
136
+ c.inst.setState({ n: 1 });
137
+ await settle();
138
+ expect(log).toEqual(['u']);
139
+ });
140
+ it('runs getDerivedStateFromProps on prop changes and passes the snapshot to didUpdate', async () => {
141
+ const log = [];
142
+ const [x, setX] = createSignal(1);
143
+ const props = {};
144
+ Object.defineProperty(props, 'x', { get: () => x(), enumerable: true, configurable: true });
145
+ let dom = '';
146
+ __krateOwn('A', { n: 'A' }, () => {
147
+ classScope(props, { doubled: 2 }, {
148
+ getDerivedStateFromProps: (p, s) => {
149
+ log.push('gDSFP ' + p.x + ' ' + s.doubled);
150
+ return { doubled: p.x * 2 };
151
+ },
152
+ getSnapshotBeforeUpdate: (pp) => {
153
+ log.push('snapshot dom=' + dom + ' prev=' + pp.x);
154
+ return 'snap';
155
+ },
156
+ componentDidUpdate: (pp, ps, snap) => log.push('didUpdate ' + pp.x + ' ' + ps.doubled + ' ' + snap + ' dom=' + dom),
157
+ }, (st, p) => {
158
+ createEffect(() => {
159
+ dom = p.x + ':' + st().doubled;
160
+ });
161
+ });
162
+ });
163
+ await settle();
164
+ expect(dom).toBe('1:2');
165
+ setX(5);
166
+ await settle();
167
+ expect(log).toEqual(['gDSFP 5 2', 'snapshot dom=1:2 prev=1', 'didUpdate 1 2 snap dom=5:10']);
168
+ });
169
+ it('applies defaultProps to this.props and gated reads', async () => {
170
+ let c;
171
+ const props = { given: 'g' };
172
+ __krateOwn('A', { n: 'A' }, () => {
173
+ c = classScope(props, {}, { defaultProps: { color: 'blue', given: 'no' } });
174
+ });
175
+ await settle();
176
+ expect(c.inst.props).toEqual({ given: 'g', color: 'blue' });
177
+ expect(props.color).toBe('blue');
178
+ });
179
+ it('runs componentWillUnmount parent-first when a branch is hidden and remounts fresh state', async () => {
180
+ const log = [];
181
+ let setups = 0;
182
+ __krateOwn('Page', { n: 'Page' }, () => {
183
+ __krateCondPost('5', true);
184
+ });
185
+ __krateOwn('P', { p: 'Page', n: 'P', c: '5', b: 'c' }, () => {
186
+ setups++;
187
+ classScope({}, {}, {
188
+ componentDidMount: () => log.push('P mount'),
189
+ componentWillUnmount: () => log.push('P unmount'),
190
+ });
191
+ });
192
+ __krateOwn('C', { p: 'P', n: 'C' }, () => {
193
+ classScope({}, {}, {
194
+ componentDidMount: () => log.push('C mount'),
195
+ componentWillUnmount: () => log.push('C unmount'),
196
+ });
197
+ });
198
+ await settle();
199
+ expect(log).toEqual(['C mount', 'P mount']);
200
+ __krateCondPre('5', false);
201
+ __krateCondPost('5', false);
202
+ expect(log.slice(2)).toEqual(['P unmount', 'C unmount']);
203
+ expect(__krateOwner('P').state).toBe('dormant');
204
+ __krateCondPre('5', true);
205
+ __krateCondPost('5', true);
206
+ await settle();
207
+ expect(setups).toBe(2);
208
+ expect(log.slice(4)).toEqual(['C mount', 'P mount']);
209
+ });
210
+ it('attaches the instance to a ref after mount and detaches it before unmount', async () => {
211
+ const log = [];
212
+ const ref = { current: null };
213
+ __krateOwn('Page', { n: 'Page' }, () => {
214
+ __krateCondPost('9', true);
215
+ });
216
+ __krateOwn('Fancy', { p: 'Page', n: 'Fancy', c: '9', b: 'c' }, () => {
217
+ const focus = () => log.push('focus');
218
+ classScope({ ref, label: 'x' }, {}, {
219
+ expose: () => ({ focus }),
220
+ componentDidMount: () => log.push('mount ref=' + (ref.current === null ? 'null' : 'set')),
221
+ componentWillUnmount: () => log.push('unmount ref=' + (ref.current === null ? 'null' : 'set')),
222
+ });
223
+ });
224
+ await settle();
225
+ ref.current.focus();
226
+ expect(ref.current.props).toEqual({ label: 'x' });
227
+ __krateCondPre('9', false);
228
+ __krateCondPost('9', false);
229
+ expect(ref.current).toBeNull();
230
+ expect(log).toEqual(['mount ref=null', 'focus', 'unmount ref=null']);
231
+ });
232
+ it('keeps components in an initially hidden branch dormant', async () => {
233
+ let setups = 0;
234
+ __krateOwn('Page', { n: 'Page' }, () => {
235
+ __krateCondPost('7', false);
236
+ });
237
+ __krateOwn('X', { p: 'Page', n: 'X', c: '7', b: 'c' }, () => {
238
+ setups++;
239
+ });
240
+ expect(setups).toBe(0);
241
+ __krateCondPost('7', true);
242
+ expect(setups).toBe(1);
243
+ });
244
+ });
245
+ describe('runtime class components (react.ts Component)', () => {
246
+ it('re-renders on setState and runs lifecycles through the controller', async () => {
247
+ const { Component, createElement } = await import('./react.js');
248
+ const log = [];
249
+ let counter;
250
+ class Counter extends Component {
251
+ constructor() {
252
+ super(...arguments);
253
+ this.state = { n: 0 };
254
+ }
255
+ componentDidMount() {
256
+ log.push('mount');
257
+ }
258
+ componentDidUpdate(_pp, ps) {
259
+ log.push('update ' + ps.n + '>' + this.state.n);
260
+ }
261
+ render() {
262
+ counter = this;
263
+ return createElement('b', null, 'n=' + String(this.state.n) + ' ' + String(this.props.label));
264
+ }
265
+ }
266
+ const host = createElement(Counter, { label: 'x' });
267
+ expect(host.textContent).toBe('n=0 x');
268
+ await settle();
269
+ expect(log).toEqual(['mount']);
270
+ counter.setState({ n: 1 });
271
+ // Batched: the DOM changes once the update commits.
272
+ expect(host.textContent).toBe('n=0 x');
273
+ await settle();
274
+ expect(host.textContent).toBe('n=1 x');
275
+ expect(log).toEqual(['mount', 'update 0>1']);
276
+ });
277
+ });
278
+ describe('error boundaries', () => {
279
+ function boundary(id, meta, log, name = 'Boundary') {
280
+ let b;
281
+ __krateOwn(id, { n: name, ...meta }, () => {
282
+ b = classScope({}, { error: null }, {
283
+ name,
284
+ getDerivedStateFromError: (error) => {
285
+ log.push(name + ' gDSFE ' + error.message);
286
+ return { error: error.message };
287
+ },
288
+ componentDidCatch: (error, info) => log.push(name + ' didCatch ' + error.message + info.componentStack),
289
+ });
290
+ });
291
+ return { get: () => b };
292
+ }
293
+ it('catches a descendant setup error, unmounts the subtree and recovers on reset', async () => {
294
+ const log = [];
295
+ const b = boundary('B', {}, log);
296
+ let attempts = 0;
297
+ let shouldThrow = true;
298
+ __krateOwn('Ok', { p: 'B', n: 'Ok' }, () => {
299
+ classScope({}, {}, {
300
+ componentDidMount: () => log.push('Ok mount'),
301
+ componentWillUnmount: () => log.push('Ok unmount'),
302
+ });
303
+ });
304
+ __krateOwn('Buggy', { p: 'B', n: 'Buggy' }, () => {
305
+ attempts++;
306
+ if (shouldThrow)
307
+ throw new Error('boom');
308
+ });
309
+ __krateOwn('Later', { p: 'B', n: 'Later' }, () => {
310
+ log.push('Later setup');
311
+ });
312
+ await settle();
313
+ expect(log).toEqual(['Boundary gDSFE boom', 'Boundary didCatch boom\n at Buggy\n at Boundary']);
314
+ expect(b.get().state()).toEqual({ error: 'boom' });
315
+ expect(__krateOwner('Ok').state).toBe('dormant');
316
+ expect(__krateOwner('Later').state).toBe('dormant');
317
+ log.length = 0;
318
+ shouldThrow = false;
319
+ b.get().inst.setState({ error: null });
320
+ await settle();
321
+ expect(attempts).toBe(2);
322
+ expect(log).toEqual(['Later setup', 'Ok mount']);
323
+ expect(__krateOwner('Buggy').state).toBe('mounted');
324
+ });
325
+ it('catches errors in reactive re-runs and lifecycles, not in event handlers', async () => {
326
+ const log = [];
327
+ boundary('B', {}, log);
328
+ const [n, setN] = createSignal(0);
329
+ let handler;
330
+ __krateOwn('Child', { p: 'B', n: 'Child' }, () => {
331
+ createEffect(() => {
332
+ if (n() === 2)
333
+ throw new Error('render ' + n());
334
+ });
335
+ handler = () => {
336
+ throw new Error('handler');
337
+ };
338
+ });
339
+ await settle();
340
+ expect(() => handler()).toThrow('handler');
341
+ expect(log).toEqual([]);
342
+ setN(2);
343
+ await settle();
344
+ expect(log[0]).toBe('Boundary gDSFE render 2');
345
+ expect(__krateOwner('Child').state).toBe('dormant');
346
+ const log2 = [];
347
+ disposeAll();
348
+ boundary('B2', {}, log2);
349
+ __krateOwn('Life', { p: 'B2', n: 'Life' }, () => {
350
+ classScope({}, {}, {
351
+ componentDidMount: () => {
352
+ throw new Error('mount');
353
+ },
354
+ });
355
+ });
356
+ await settle();
357
+ expect(log2[0]).toBe('Boundary gDSFE mount');
358
+ });
359
+ it('lets the innermost boundary catch and sends fallback errors to the next one', async () => {
360
+ const log = [];
361
+ boundary('Outer', {}, log, 'Outer');
362
+ boundary('Inner', { p: 'Outer' }, log, 'Inner');
363
+ __krateOwn('Leaf', { p: 'Inner', n: 'Leaf' }, () => {
364
+ throw new Error('leaf');
365
+ });
366
+ await settle();
367
+ expect(log.filter((l) => l.includes('gDSFE'))).toEqual(['Inner gDSFE leaf']);
368
+ // An error thrown by the boundary's own render goes to the boundary above.
369
+ const log2 = [];
370
+ disposeAll();
371
+ boundary('O', {}, log2, 'O');
372
+ __krateOwn('I', { p: 'O', n: 'I' }, () => {
373
+ const [st, setSt] = createSignal({ error: null });
374
+ __krateClass({}, st, setSt, {
375
+ getDerivedStateFromError: () => ({ error: 'x' }),
376
+ });
377
+ createEffect(() => {
378
+ if (st().error)
379
+ throw new Error('fallback broke');
380
+ });
381
+ });
382
+ __krateOwn('Deep', { p: 'I', n: 'Deep' }, () => {
383
+ throw new Error('deep');
384
+ });
385
+ await settle();
386
+ expect(log2.filter((l) => l.includes('gDSFE'))).toEqual(['O gDSFE fallback broke']);
387
+ });
388
+ it('reports uncaught errors and unmounts only the failing component', async () => {
389
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => { });
390
+ let siblingRan = false;
391
+ __krateOwn('Root', { n: 'Root' }, () => { });
392
+ __krateOwn('Bad', { p: 'Root', n: 'Bad' }, () => {
393
+ throw new Error('nobody catches');
394
+ });
395
+ __krateOwn('Fine', { p: 'Root', n: 'Fine' }, () => {
396
+ siblingRan = true;
397
+ });
398
+ expect(siblingRan).toBe(true);
399
+ expect(__krateOwner('Bad').state).toBe('dormant');
400
+ expect(spy.mock.calls.some((c) => String(c[0]).includes('The above error occurred in the <Bad> component'))).toBe(true);
401
+ spy.mockRestore();
402
+ });
403
+ it('ignores errors from bindings outside the document', () => {
404
+ const detached = document.createElement('div');
405
+ let routed = false;
406
+ __krateOwn('Root', { n: 'Root' }, () => {
407
+ routed = __krateOnError(new Error('hidden'), detached);
408
+ });
409
+ expect(routed).toBe(false);
410
+ });
411
+ });
package/dist/context.d.ts CHANGED
@@ -1,11 +1,24 @@
1
1
  import type { CSSScope, CSSFlagsScope } from './signal.js';
2
+ /** Marks Krate context objects so `use(x)` can tell them from promises. */
3
+ export declare const KRATE_CONTEXT: unique symbol;
2
4
  export interface Context<T> {
5
+ /** Context marker (see {@link KRATE_CONTEXT}). */
6
+ $$typeof?: typeof KRATE_CONTEXT;
7
+ /** React 19: the context itself renders as its provider (`<Ctx value>`). */
8
+ (props: {
9
+ value: T;
10
+ children?: any;
11
+ }): Node;
3
12
  id: number;
4
13
  defaultValue: T;
5
14
  Provider: (props: {
6
15
  value: T;
7
16
  children?: any;
8
17
  }) => Node;
18
+ /** Renders `children(value)` with the nearest provider value. */
19
+ Consumer: (props: {
20
+ children?: any;
21
+ }) => Node;
9
22
  useContext: () => T;
10
23
  /** Alias for {@link Context.useContext}. */
11
24
  use: () => T;
package/dist/context.js CHANGED
@@ -1,4 +1,19 @@
1
1
  let contextId = 0;
2
+ /** Marks Krate context objects so `use(x)` can tell them from promises. */
3
+ export const KRATE_CONTEXT = Symbol.for('krate.context');
4
+ function toNode(v) {
5
+ if (v instanceof Node)
6
+ return v;
7
+ const frag = document.createDocumentFragment();
8
+ if (Array.isArray(v)) {
9
+ for (const item of v)
10
+ frag.appendChild(toNode(item));
11
+ }
12
+ else if (v != null && v !== false && v !== true) {
13
+ frag.appendChild(document.createTextNode(String(v)));
14
+ }
15
+ return frag;
16
+ }
2
17
  const contextStack = new Map();
3
18
  // Reset all context stacks to their default values.
4
19
  // Called during SPA navigation to prevent stale context leaking across pages.
@@ -38,39 +53,50 @@ export function createContext(defaultValue) {
38
53
  }
39
54
  return defaultValue;
40
55
  };
41
- return {
42
- id,
43
- defaultValue,
44
- Provider: (props) => {
45
- const stack = contextStack.get(id) || [defaultValue];
46
- stack.push(props.value);
47
- contextStack.set(id, stack);
48
- // Create a container and render children
49
- const container = document.createElement('div');
50
- container.style.display = 'contents';
51
- if (props.children) {
52
- for (const child of props.children) {
53
- if (child instanceof Node) {
54
- container.appendChild(child);
55
- }
56
- else if (child != null) {
57
- container.appendChild(document.createTextNode(String(child)));
58
- }
56
+ const Provider = (props) => {
57
+ const stack = contextStack.get(id) || [defaultValue];
58
+ stack.push(props.value);
59
+ contextStack.set(id, stack);
60
+ // Create a container and render children
61
+ const container = document.createElement('div');
62
+ container.style.display = 'contents';
63
+ // Read once: a lazy `children` getter renders under this provider.
64
+ const children = props.children;
65
+ if (children) {
66
+ for (const child of Array.isArray(children) ? children : [children]) {
67
+ if (child instanceof Node) {
68
+ container.appendChild(child);
69
+ }
70
+ else if (child != null) {
71
+ container.appendChild(document.createTextNode(String(child)));
59
72
  }
60
73
  }
61
- // Pop the context value synchronously after rendering children.
62
- // Children are already rendered (passed as pre-built DOM nodes), so
63
- // any effects that read context have already done so during their
64
- // synchronous creation. Synchronous pop fixes the nested Provider race:
65
- // with microtask pop, code after an inner Provider but within the outer
66
- // Provider's scope would incorrectly see the inner value still on the stack.
67
- stack.pop();
68
- if (stack.length === 0) {
69
- stack.push(defaultValue);
70
- }
71
- return container;
72
- },
73
- useContext,
74
- use: useContext,
74
+ }
75
+ // Pop the context value synchronously after rendering children.
76
+ // Children are already rendered (passed as pre-built DOM nodes), so
77
+ // any effects that read context have already done so during their
78
+ // synchronous creation. Synchronous pop fixes the nested Provider race:
79
+ // with microtask pop, code after an inner Provider but within the outer
80
+ // Provider's scope would incorrectly see the inner value still on the stack.
81
+ stack.pop();
82
+ if (stack.length === 0) {
83
+ stack.push(defaultValue);
84
+ }
85
+ return container;
86
+ };
87
+ const Consumer = (props) => {
88
+ let fn = props.children;
89
+ if (Array.isArray(fn))
90
+ fn = fn.find((c) => typeof c === 'function');
91
+ return typeof fn === 'function' ? toNode(fn(useContext())) : toNode(null);
75
92
  };
93
+ const ctx = ((props) => Provider(props));
94
+ ctx.$$typeof = KRATE_CONTEXT;
95
+ ctx.id = id;
96
+ ctx.defaultValue = defaultValue;
97
+ ctx.Provider = Provider;
98
+ ctx.Consumer = Consumer;
99
+ ctx.useContext = useContext;
100
+ ctx.use = useContext;
101
+ return ctx;
76
102
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { createContext } from './context';
3
+ import { h } from './dom';
4
+ // Runtime providers push their value while their children are read; compiled
5
+ // source components resolve context at build time instead. The tests pass
6
+ // lazy children (getters) so the children render under the provider.
7
+ describe('createContext (runtime)', () => {
8
+ it('reads the default without a provider', () => {
9
+ const Theme = createContext({ color: 'black' });
10
+ expect(Theme.useContext()).toEqual({ color: 'black' });
11
+ expect(Theme.use()).toEqual({ color: 'black' });
12
+ });
13
+ it('nested providers shadow outer ones and restore on exit', () => {
14
+ const Depth = createContext(0);
15
+ const seen = [];
16
+ const read = () => {
17
+ seen.push(Depth.useContext());
18
+ return document.createTextNode(String(Depth.useContext()));
19
+ };
20
+ const outer = Depth.Provider({
21
+ value: 1,
22
+ get children() {
23
+ const first = read();
24
+ const inner = Depth.Provider({
25
+ value: 2,
26
+ get children() {
27
+ return [read()];
28
+ },
29
+ });
30
+ return [first, inner, read()];
31
+ },
32
+ });
33
+ expect(seen).toEqual([1, 2, 1]);
34
+ expect(outer.textContent).toBe('121');
35
+ expect(Depth.useContext()).toBe(0);
36
+ });
37
+ it('works as a React 19 provider and with Consumer', () => {
38
+ const Density = createContext('comfortable');
39
+ let inside = '';
40
+ const node = Density({
41
+ value: 'compact',
42
+ get children() {
43
+ inside = Density.useContext();
44
+ return [Density.Consumer({ children: (d) => h('span', null, d) })];
45
+ },
46
+ });
47
+ expect(inside).toBe('compact');
48
+ expect(node.querySelector('span').textContent).toBe('compact');
49
+ expect(Density.useContext()).toBe('comfortable');
50
+ });
51
+ it('Consumer renders text, arrays and nothing', () => {
52
+ const Name = createContext('ada');
53
+ expect(Name.Consumer({ children: (n) => 'hi ' + n }).textContent).toBe('hi ada');
54
+ expect(Name.Consumer({ children: [(n) => [n, '!']] }).textContent).toBe('ada!');
55
+ expect(Name.Consumer({ children: () => null }).textContent).toBe('');
56
+ });
57
+ });
@@ -0,0 +1 @@
1
+ export {};