@krate/runtime 0.5.0-rc.5 → 0.5.0-rc.7
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/actions.js +10 -1
- package/dist/cache-scope.d.ts +2 -0
- package/dist/cache-scope.js +6 -1
- package/dist/context.d.ts +5 -0
- package/dist/context.js +28 -17
- package/dist/flight-props.d.ts +7 -0
- package/dist/flight-props.js +105 -0
- package/dist/handler-routing.d.ts +2 -23
- package/dist/handler-routing.js +4 -188
- package/dist/head-tags.js +5 -2
- package/dist/highlight.d.ts +3 -2
- package/dist/highlight.js +12 -6
- package/dist/hints.d.ts +25 -2
- package/dist/hints.js +148 -74
- package/dist/index.d.ts +1 -0
- package/dist/island-swap.d.ts +45 -0
- package/dist/island-swap.js +608 -0
- package/dist/jsx-types.d.ts +7 -2
- package/dist/krate-core.js +1 -1
- package/dist/krate-f-actions.js +1 -1
- package/dist/krate-f-list.js +1 -1
- package/dist/krate-f-navigation.js +1 -1
- package/dist/krate-f-router-lite.js +1 -1
- package/dist/krate-f-router.js +1 -1
- package/dist/krate-features.json +452 -0
- package/dist/krate-hydrate-lite.js +5 -5
- package/dist/krate-hydrate.js +5 -5
- package/dist/krate-island-swap.js +1 -0
- package/dist/krate-runtime.js +5 -5
- package/dist/list.d.ts +14 -4
- package/dist/list.js +4 -5
- package/dist/navigation-react.d.ts +13 -0
- package/dist/navigation-react.js +86 -0
- package/dist/navigation.d.ts +19 -0
- package/dist/navigation.js +35 -0
- package/dist/react-compat.d.ts +39 -0
- package/dist/react-compat.js +359 -0
- package/dist/request-extras.d.ts +4 -0
- package/dist/request-extras.js +51 -0
- package/dist/route-source.d.ts +39 -0
- package/dist/route-source.js +532 -0
- package/dist/router.js +293 -23
- package/dist/server-handler.d.ts +20 -1
- package/dist/server-handler.js +208 -92
- package/dist/server.d.ts +24 -17
- package/dist/server.js +435 -101
- package/dist/site-config.d.ts +2 -0
- package/dist/testing.d.ts +4 -1
- package/dist/testing.js +3 -1
- package/package.json +15 -2
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -75
- package/dist/after.test.d.ts +0 -1
- package/dist/after.test.js +0 -58
- package/dist/builtin-tags.test.d.ts +0 -1
- package/dist/builtin-tags.test.js +0 -12
- package/dist/cache-adapter.test.d.ts +0 -1
- package/dist/cache-adapter.test.js +0 -45
- package/dist/cache.test.d.ts +0 -1
- package/dist/cache.test.js +0 -37
- package/dist/events.test.d.ts +0 -1
- package/dist/events.test.js +0 -42
- package/dist/handler-html.test.d.ts +0 -1
- package/dist/handler-html.test.js +0 -55
- package/dist/handler-segments.test.d.ts +0 -1
- package/dist/handler-segments.test.js +0 -25
- package/dist/head-tags.test.d.ts +0 -1
- package/dist/head-tags.test.js +0 -24
- package/dist/inline-action-token.test.d.ts +0 -1
- package/dist/inline-action-token.test.js +0 -31
- package/dist/jsx-svg-types.test.d.ts +0 -1
- package/dist/jsx-svg-types.test.js +0 -58
- package/dist/link-base-path.test.d.ts +0 -1
- package/dist/link-base-path.test.js +0 -28
- package/dist/node-server.test.d.ts +0 -1
- package/dist/node-server.test.js +0 -138
- package/dist/platform.test.d.ts +0 -1
- package/dist/platform.test.js +0 -44
- package/dist/router-nav.test.d.ts +0 -1
- package/dist/router-nav.test.js +0 -130
- package/dist/server-handler.test.d.ts +0 -1
- package/dist/server-handler.test.js +0 -338
- package/dist/server-renderer.test.d.ts +0 -1
- package/dist/server-renderer.test.js +0 -162
- package/dist/server.test.d.ts +0 -1
- package/dist/server.test.js +0 -91
- package/dist/sha256.test.d.ts +0 -1
- package/dist/sha256.test.js +0 -13
- package/dist/signal.test.d.ts +0 -1
- package/dist/signal.test.js +0 -68
- package/dist/site-config.test.d.ts +0 -1
- package/dist/site-config.test.js +0 -30
- package/dist/slot.test.d.ts +0 -1
- package/dist/slot.test.js +0 -25
- package/dist/ssr-core-behavior.test.d.ts +0 -1
- package/dist/ssr-core-behavior.test.js +0 -108
- package/dist/testing.test.d.ts +0 -1
- package/dist/testing.test.js +0 -73
package/dist/list.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type KrateAdoptable } from './dom.js';
|
|
2
|
-
type KeyFn = ((item: unknown, index: number) => unknown) | null;
|
|
3
|
-
type RenderFn = (item: unknown, index: unknown) => unknown;
|
|
2
|
+
export type KeyFn = ((item: unknown, index: number) => unknown) | null;
|
|
3
|
+
export type RenderFn = (item: unknown, index: unknown) => unknown;
|
|
4
4
|
/**
|
|
5
5
|
* Indices (into `seq`) of a longest strictly increasing subsequence of the
|
|
6
6
|
* non-negative entries. O(n log n).
|
|
@@ -16,5 +16,15 @@ export declare function krateBindList(start: Comment, getItems: () => unknown, k
|
|
|
16
16
|
* mounts as a fragment with its own markers, or adopts a server-rendered list
|
|
17
17
|
* at the hydration cursor.
|
|
18
18
|
*/
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* The value krateList returns. Besides mounting itself as DOM it carries its
|
|
21
|
+
* arguments, so a custom renderer (a renderer component's children) can
|
|
22
|
+
* reconcile the list itself.
|
|
23
|
+
*/
|
|
24
|
+
export interface KrateListValue extends KrateAdoptable {
|
|
25
|
+
items: () => unknown;
|
|
26
|
+
key: KeyFn;
|
|
27
|
+
render: RenderFn;
|
|
28
|
+
mode: number;
|
|
29
|
+
}
|
|
30
|
+
export declare function krateList(getItems: () => unknown, keyFn: KeyFn, render: RenderFn, mode: number): KrateListValue;
|
package/dist/list.js
CHANGED
|
@@ -436,14 +436,13 @@ export function krateBindList(start, getItems, keyFn, render, mode) {
|
|
|
436
436
|
}
|
|
437
437
|
run(newState(start, end, keyFn, render, mode), getItems, true);
|
|
438
438
|
}
|
|
439
|
-
/**
|
|
440
|
-
* A list nested in rendered JSX (a `.map()` inside a row or component). It
|
|
441
|
-
* mounts as a fragment with its own markers, or adopts a server-rendered list
|
|
442
|
-
* at the hydration cursor.
|
|
443
|
-
*/
|
|
444
439
|
export function krateList(getItems, keyFn, render, mode) {
|
|
445
440
|
return {
|
|
446
441
|
__ka: 1,
|
|
442
|
+
items: getItems,
|
|
443
|
+
key: keyFn,
|
|
444
|
+
render,
|
|
445
|
+
mode,
|
|
447
446
|
mount() {
|
|
448
447
|
const frag = document.createDocumentFragment();
|
|
449
448
|
const start = document.createComment('');
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AppRouterInstance } from './navigation.js';
|
|
2
|
+
type ParamValue = string | string[];
|
|
3
|
+
type UseSyncExternalStore = <T>(subscribe: (cb: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
|
|
4
|
+
export interface ValueNavigationHooks {
|
|
5
|
+
usePathname(): string;
|
|
6
|
+
useSearchParams(): URLSearchParams;
|
|
7
|
+
useParams<T extends Record<string, ParamValue> = Record<string, ParamValue>>(): T;
|
|
8
|
+
useRouter(): AppRouterInstance;
|
|
9
|
+
useSelectedLayoutSegments(parallelRouteKey?: string, depth?: number): string[];
|
|
10
|
+
useSelectedLayoutSegment(parallelRouteKey?: string, depth?: number): string | null;
|
|
11
|
+
}
|
|
12
|
+
export declare function createValueNavigationHooks(useSyncExternalStore: UseSyncExternalStore): ValueNavigationHooks;
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Router hooks for React-model components: modules that run on Preact compat
|
|
2
|
+
// or on real React (a "use client" module under a server component, an island
|
|
3
|
+
// that uses an npm React library). They read hook results as plain values, so
|
|
4
|
+
// each hook returns a value and the component re-renders when the URL changes.
|
|
5
|
+
// Krate-compiled components use the getter-returning hooks of navigation.ts.
|
|
6
|
+
//
|
|
7
|
+
// The compiler's island builds replace the router hooks of `@krate/runtime`
|
|
8
|
+
// with createValueNavigationHooks(useSyncExternalStore) of their React.
|
|
9
|
+
import { getRequestContext } from './request-context.js';
|
|
10
|
+
import * as serverNav from './navigation-server.js';
|
|
11
|
+
import { krateRouter } from './router.js';
|
|
12
|
+
import { krateRouteStore, krateMatchParams, krateLayoutSegments } from './navigation.js';
|
|
13
|
+
const routerInstance = {
|
|
14
|
+
push: (href, options) => void krateRouter.push(href, options),
|
|
15
|
+
replace: (href, options) => void krateRouter.replace(href, options),
|
|
16
|
+
back: () => krateRouter.back(),
|
|
17
|
+
forward: () => krateRouter.forward(),
|
|
18
|
+
refresh: () => void krateRouter.refresh(),
|
|
19
|
+
prefetch: (href) => void krateRouter.prefetch(href),
|
|
20
|
+
};
|
|
21
|
+
export function createValueNavigationHooks(useSyncExternalStore) {
|
|
22
|
+
const store = krateRouteStore();
|
|
23
|
+
const route = () => useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
|
|
24
|
+
// Values derived from the snapshot are cached so they keep their identity
|
|
25
|
+
// between renders of the same URL, as React's hooks do.
|
|
26
|
+
let paramsKey = '';
|
|
27
|
+
let paramsVal = new URLSearchParams();
|
|
28
|
+
let routeKey = '';
|
|
29
|
+
let routeVal = {};
|
|
30
|
+
let segKey = '';
|
|
31
|
+
let segVal = [];
|
|
32
|
+
const segments = (depth) => {
|
|
33
|
+
const s = route();
|
|
34
|
+
const key = s.pathname + '\0' + (depth ?? '');
|
|
35
|
+
if (key !== segKey) {
|
|
36
|
+
segKey = key;
|
|
37
|
+
segVal = krateLayoutSegments(s.pathname, depth);
|
|
38
|
+
}
|
|
39
|
+
return segVal;
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
usePathname() {
|
|
43
|
+
if (getRequestContext())
|
|
44
|
+
return serverNav.usePathname();
|
|
45
|
+
return route().pathname;
|
|
46
|
+
},
|
|
47
|
+
useSearchParams() {
|
|
48
|
+
if (getRequestContext())
|
|
49
|
+
return serverNav.useSearchParams();
|
|
50
|
+
const s = route();
|
|
51
|
+
if (s.search !== paramsKey) {
|
|
52
|
+
paramsKey = s.search;
|
|
53
|
+
paramsVal = new URLSearchParams(s.search);
|
|
54
|
+
}
|
|
55
|
+
return paramsVal;
|
|
56
|
+
},
|
|
57
|
+
useParams() {
|
|
58
|
+
if (getRequestContext())
|
|
59
|
+
return serverNav.useParams();
|
|
60
|
+
const s = route();
|
|
61
|
+
const key = s.route + '\0' + s.pathname;
|
|
62
|
+
if (key !== routeKey) {
|
|
63
|
+
routeKey = key;
|
|
64
|
+
routeVal = krateMatchParams(s.route, s.pathname);
|
|
65
|
+
}
|
|
66
|
+
return routeVal;
|
|
67
|
+
},
|
|
68
|
+
useRouter() {
|
|
69
|
+
if (getRequestContext())
|
|
70
|
+
return serverNav.useRouter();
|
|
71
|
+
return routerInstance;
|
|
72
|
+
},
|
|
73
|
+
useSelectedLayoutSegments(parallelRouteKey, depth) {
|
|
74
|
+
if (getRequestContext())
|
|
75
|
+
return serverNav.useSelectedLayoutSegments(parallelRouteKey, depth);
|
|
76
|
+
return segments(depth);
|
|
77
|
+
},
|
|
78
|
+
useSelectedLayoutSegment(parallelRouteKey, depth) {
|
|
79
|
+
if (getRequestContext())
|
|
80
|
+
return serverNav.useSelectedLayoutSegment(parallelRouteKey, depth);
|
|
81
|
+
const at = typeof depth === 'number' ? depth : 0;
|
|
82
|
+
const parts = krateLayoutSegments(route().pathname);
|
|
83
|
+
return parts.length > at ? parts[at] : null;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
package/dist/navigation.d.ts
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
interface RouteSnapshot {
|
|
2
|
+
pathname: string;
|
|
3
|
+
search: string;
|
|
4
|
+
/** The route pattern of the current document ("/blog/[slug]"), "" for a static route. */
|
|
5
|
+
route: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* An external store of the route for React-model components (Preact compat and
|
|
9
|
+
* real React islands), which read hook results as plain values and re-render
|
|
10
|
+
* when the URL changes. The snapshot object only changes with the route.
|
|
11
|
+
*/
|
|
12
|
+
export declare function krateRouteStore(): {
|
|
13
|
+
subscribe: (cb: () => void) => () => void;
|
|
14
|
+
getSnapshot: () => RouteSnapshot;
|
|
15
|
+
};
|
|
16
|
+
/** The params a route pattern matches in a pathname (see useParams). */
|
|
17
|
+
export declare function krateMatchParams(route: string, pathname: string): Record<string, string | string[]>;
|
|
18
|
+
/** The path segments below depth (see useSelectedLayoutSegments). */
|
|
19
|
+
export declare function krateLayoutSegments(pathname: string, depth?: number): string[];
|
|
1
20
|
/** Test hook: forgets the shared snapshot so the next hook call reads the URL again. */
|
|
2
21
|
export declare function krateResetNavigation(): void;
|
|
3
22
|
/** The current URL path without the base path and the query ("/blog/hello"). */
|
package/dist/navigation.js
CHANGED
|
@@ -58,6 +58,41 @@ function routeState() {
|
|
|
58
58
|
}
|
|
59
59
|
return read;
|
|
60
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* An external store of the route for React-model components (Preact compat and
|
|
63
|
+
* real React islands), which read hook results as plain values and re-render
|
|
64
|
+
* when the URL changes. The snapshot object only changes with the route.
|
|
65
|
+
*/
|
|
66
|
+
export function krateRouteStore() {
|
|
67
|
+
let last = null;
|
|
68
|
+
const getSnapshot = () => {
|
|
69
|
+
const next = snapshot();
|
|
70
|
+
if (last && last.pathname === next.pathname && last.search === next.search && last.route === next.route)
|
|
71
|
+
return last;
|
|
72
|
+
last = next;
|
|
73
|
+
return next;
|
|
74
|
+
};
|
|
75
|
+
const subscribe = (cb) => {
|
|
76
|
+
const off = subscribeNavigation(cb);
|
|
77
|
+
// The router swaps the document before it emits the final status.
|
|
78
|
+
if (typeof window !== 'undefined')
|
|
79
|
+
window.addEventListener('krate:navigate-end', cb);
|
|
80
|
+
return () => {
|
|
81
|
+
off();
|
|
82
|
+
if (typeof window !== 'undefined')
|
|
83
|
+
window.removeEventListener('krate:navigate-end', cb);
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
return { subscribe, getSnapshot };
|
|
87
|
+
}
|
|
88
|
+
/** The params a route pattern matches in a pathname (see useParams). */
|
|
89
|
+
export function krateMatchParams(route, pathname) {
|
|
90
|
+
return matchRouteParams(route, pathname);
|
|
91
|
+
}
|
|
92
|
+
/** The path segments below depth (see useSelectedLayoutSegments). */
|
|
93
|
+
export function krateLayoutSegments(pathname, depth) {
|
|
94
|
+
return pathname.split('/').filter(Boolean).map(safeDecode).slice(typeof depth === 'number' ? depth : 0);
|
|
95
|
+
}
|
|
61
96
|
/** Test hook: forgets the shared snapshot so the next hook call reads the URL again. */
|
|
62
97
|
export function krateResetNavigation() {
|
|
63
98
|
state = null;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
type AnyFn = (...args: any[]) => any;
|
|
2
|
+
export interface FormStatus {
|
|
3
|
+
pending: boolean;
|
|
4
|
+
data: FormData | null;
|
|
5
|
+
method: string | null;
|
|
6
|
+
action: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface ReactCompatExtras {
|
|
9
|
+
useOptimistic: AnyFn;
|
|
10
|
+
useActionState: AnyFn;
|
|
11
|
+
useFormState: AnyFn;
|
|
12
|
+
useFormStatus: () => FormStatus;
|
|
13
|
+
requestFormReset: (form: HTMLFormElement) => void;
|
|
14
|
+
use: AnyFn;
|
|
15
|
+
cache: AnyFn;
|
|
16
|
+
useEffectEvent: AnyFn;
|
|
17
|
+
startTransition: AnyFn;
|
|
18
|
+
useTransition: AnyFn;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Builds the additions once per Preact instance: the `react` and `react-dom`
|
|
22
|
+
* modules of a bundle (and of every island chunk) share one action scope and
|
|
23
|
+
* one form-status context.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createReactCompatExtras(c: any, options: any): ReactCompatExtras;
|
|
26
|
+
/**
|
|
27
|
+
* React 18 flushes the passive effects of a render caused by a discrete event
|
|
28
|
+
* (a click, a key press, typing) synchronously at the end of its commit, and
|
|
29
|
+
* renders the updates those effects make in the same task. Preact runs them
|
|
30
|
+
* after the next frame, so a quick second event could render a component with
|
|
31
|
+
* a new prop and a state update from its previous effects at once: react-colorful
|
|
32
|
+
* then took its own color prop for user input and called onChange with a
|
|
33
|
+
* stale colour. While a discrete event's task runs, this flushes Preact's
|
|
34
|
+
* effect queue after every commit (Preact's render loop picks up the updates
|
|
35
|
+
* they make); otherwise effects keep running after paint. The compiler's
|
|
36
|
+
* client builds call it from their `react` module, once per Preact instance.
|
|
37
|
+
*/
|
|
38
|
+
export declare function installDiscreteEffects(options: any): void;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
// React 19 APIs that preact/compat lacks, for React-model code that runs on
|
|
2
|
+
// Preact: a "use client" module, an island, an npm React library. The
|
|
3
|
+
// compiler's island builds re-export these next to everything preact/compat
|
|
4
|
+
// provides, as `react` (and `useFormStatus` as `react-dom`).
|
|
5
|
+
//
|
|
6
|
+
// The module takes the bundle's own compat namespace and Preact `options`, so
|
|
7
|
+
// it never imports Preact and stays on the project's single Preact instance.
|
|
8
|
+
const IDLE = Object.freeze({ pending: false, data: null, method: null, action: null });
|
|
9
|
+
const EMPTY = Object.freeze([]);
|
|
10
|
+
function isThenable(v) {
|
|
11
|
+
return !!v && typeof v.then === 'function';
|
|
12
|
+
}
|
|
13
|
+
function reportError(err) {
|
|
14
|
+
const g = globalThis;
|
|
15
|
+
if (typeof g.reportError === 'function')
|
|
16
|
+
g.reportError(err);
|
|
17
|
+
else
|
|
18
|
+
console.error(err);
|
|
19
|
+
}
|
|
20
|
+
const SHARED = '__krateReactCompat';
|
|
21
|
+
/**
|
|
22
|
+
* Builds the additions once per Preact instance: the `react` and `react-dom`
|
|
23
|
+
* modules of a bundle (and of every island chunk) share one action scope and
|
|
24
|
+
* one form-status context.
|
|
25
|
+
*/
|
|
26
|
+
export function createReactCompatExtras(c, options) {
|
|
27
|
+
if (options[SHARED])
|
|
28
|
+
return options[SHARED];
|
|
29
|
+
const extras = build(c, options);
|
|
30
|
+
options[SHARED] = extras;
|
|
31
|
+
return extras;
|
|
32
|
+
}
|
|
33
|
+
function build(c, options) {
|
|
34
|
+
const { useState, useRef, useEffect, useCallback, useContext, createContext, createElement } = c;
|
|
35
|
+
// Action scope: optimistic updates stay applied while any transition or
|
|
36
|
+
// form action is pending and are dropped when the last one settles.
|
|
37
|
+
let open = 0;
|
|
38
|
+
const settled = new Set();
|
|
39
|
+
const begin = () => {
|
|
40
|
+
open++;
|
|
41
|
+
let done = false;
|
|
42
|
+
return () => {
|
|
43
|
+
if (done)
|
|
44
|
+
return;
|
|
45
|
+
done = true;
|
|
46
|
+
if (--open === 0)
|
|
47
|
+
for (const fn of Array.from(settled))
|
|
48
|
+
fn();
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
function startTransition(fn) {
|
|
52
|
+
const end = begin();
|
|
53
|
+
let r;
|
|
54
|
+
try {
|
|
55
|
+
r = fn();
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
end();
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
if (isThenable(r))
|
|
62
|
+
r.then(end, (err) => { end(); reportError(err); });
|
|
63
|
+
else
|
|
64
|
+
end();
|
|
65
|
+
}
|
|
66
|
+
function useTransition() {
|
|
67
|
+
const [pending, setPending] = useState(false);
|
|
68
|
+
const start = useCallback((fn) => {
|
|
69
|
+
const end = begin();
|
|
70
|
+
let r;
|
|
71
|
+
try {
|
|
72
|
+
r = fn();
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
end();
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
if (!isThenable(r)) {
|
|
79
|
+
end();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
setPending(true);
|
|
83
|
+
const finish = () => { setPending(false); end(); };
|
|
84
|
+
r.then(finish, (err) => { finish(); reportError(err); });
|
|
85
|
+
}, []);
|
|
86
|
+
return [pending, start];
|
|
87
|
+
}
|
|
88
|
+
function useOptimistic(passthrough, reducer) {
|
|
89
|
+
const [updates, setUpdates] = useState(EMPTY);
|
|
90
|
+
useEffect(() => {
|
|
91
|
+
const revert = () => setUpdates(EMPTY);
|
|
92
|
+
settled.add(revert);
|
|
93
|
+
return () => { settled.delete(revert); };
|
|
94
|
+
}, []);
|
|
95
|
+
let value = passthrough;
|
|
96
|
+
for (const a of updates)
|
|
97
|
+
value = reducer ? reducer(value, a) : a;
|
|
98
|
+
const add = useCallback((action) => {
|
|
99
|
+
setUpdates((u) => u.concat([action]));
|
|
100
|
+
// An update made outside any transition is dropped right away.
|
|
101
|
+
if (open === 0) {
|
|
102
|
+
Promise.resolve().then(() => { if (open === 0)
|
|
103
|
+
setUpdates(EMPTY); });
|
|
104
|
+
}
|
|
105
|
+
}, []);
|
|
106
|
+
return [value, add];
|
|
107
|
+
}
|
|
108
|
+
const StatusCtx = createContext(IDLE);
|
|
109
|
+
function FormScope(props) {
|
|
110
|
+
const [status, setStatus] = useState(IDLE);
|
|
111
|
+
props.box.set = setStatus;
|
|
112
|
+
return createElement(StatusCtx.Provider, { value: status }, props.children);
|
|
113
|
+
}
|
|
114
|
+
const isPlainAction = (f) => typeof f === 'function' && typeof f.$$krateAction !== 'string';
|
|
115
|
+
function withRef(vnode, attach) {
|
|
116
|
+
const orig = vnode.ref;
|
|
117
|
+
vnode.ref = (el) => {
|
|
118
|
+
if (el)
|
|
119
|
+
attach(el);
|
|
120
|
+
if (typeof orig === 'function')
|
|
121
|
+
orig(el);
|
|
122
|
+
else if (orig && typeof orig === 'object')
|
|
123
|
+
orig.current = el;
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function onSubmit(e) {
|
|
127
|
+
const form = e.target;
|
|
128
|
+
if (!form || form.tagName !== 'FORM' || e.defaultPrevented)
|
|
129
|
+
return;
|
|
130
|
+
const submitter = e.submitter || null;
|
|
131
|
+
const box = form.__krateForm;
|
|
132
|
+
const fn = (submitter && submitter.__krateFormAction) || (box && box.fn);
|
|
133
|
+
if (typeof fn !== 'function')
|
|
134
|
+
return;
|
|
135
|
+
e.preventDefault();
|
|
136
|
+
let data;
|
|
137
|
+
try {
|
|
138
|
+
data = submitter ? new FormData(form, submitter) : new FormData(form);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
data = new FormData(form);
|
|
142
|
+
}
|
|
143
|
+
const end = begin();
|
|
144
|
+
if (box && box.set)
|
|
145
|
+
box.set({ pending: true, data, method: 'post', action: fn });
|
|
146
|
+
let ok = false;
|
|
147
|
+
Promise.resolve()
|
|
148
|
+
.then(() => fn(data))
|
|
149
|
+
.then(() => { ok = true; }, reportError)
|
|
150
|
+
.then(() => {
|
|
151
|
+
if (box && box.set)
|
|
152
|
+
box.set(IDLE);
|
|
153
|
+
end();
|
|
154
|
+
if (ok && form.isConnected)
|
|
155
|
+
form.reset();
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
{
|
|
159
|
+
const prev = options.vnode;
|
|
160
|
+
options.vnode = (vnode) => {
|
|
161
|
+
const p = vnode.props;
|
|
162
|
+
const t = vnode.type;
|
|
163
|
+
if (p && vnode.ref != null && typeof t === 'function' && !t._forwarded && !(t.prototype && t.prototype.render) && t !== c.Fragment) {
|
|
164
|
+
// React 19: a function component receives ref as an ordinary prop.
|
|
165
|
+
p.ref = vnode.ref;
|
|
166
|
+
vnode.ref = null;
|
|
167
|
+
}
|
|
168
|
+
if (p && typeof vnode.type === 'string') {
|
|
169
|
+
if (vnode.type === 'form' && isPlainAction(p.action)) {
|
|
170
|
+
const box = { fn: p.action };
|
|
171
|
+
p.action = undefined;
|
|
172
|
+
withRef(vnode, (el) => { el.__krateForm = box; });
|
|
173
|
+
p.children = createElement(FormScope, { box }, p.children);
|
|
174
|
+
}
|
|
175
|
+
else if (isPlainAction(p.formAction)) {
|
|
176
|
+
const fn = p.formAction;
|
|
177
|
+
p.formAction = undefined;
|
|
178
|
+
withRef(vnode, (el) => { el.__krateFormAction = fn; });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (prev)
|
|
182
|
+
prev(vnode);
|
|
183
|
+
};
|
|
184
|
+
if (typeof document !== 'undefined')
|
|
185
|
+
document.addEventListener('submit', onSubmit, false);
|
|
186
|
+
}
|
|
187
|
+
function useFormStatus() {
|
|
188
|
+
return useContext(StatusCtx);
|
|
189
|
+
}
|
|
190
|
+
function requestFormReset(form) {
|
|
191
|
+
form.reset();
|
|
192
|
+
}
|
|
193
|
+
function useActionState(action, initialState, _permalink) {
|
|
194
|
+
const [state, setState] = useState(initialState);
|
|
195
|
+
const [pending, setPending] = useState(false);
|
|
196
|
+
const [failure, setFailure] = useState(null);
|
|
197
|
+
const live = useRef(null);
|
|
198
|
+
if (!live.current)
|
|
199
|
+
live.current = { state, action, queued: 0, chain: Promise.resolve(), cancelled: false };
|
|
200
|
+
const l = live.current;
|
|
201
|
+
l.action = action;
|
|
202
|
+
l.state = state;
|
|
203
|
+
const dispatch = useCallback((payload) => {
|
|
204
|
+
l.queued++;
|
|
205
|
+
setPending(true);
|
|
206
|
+
const end = begin();
|
|
207
|
+
const run = l.chain.then(async () => {
|
|
208
|
+
if (l.cancelled)
|
|
209
|
+
return;
|
|
210
|
+
const next = await l.action(l.state, payload);
|
|
211
|
+
l.state = next;
|
|
212
|
+
setState(() => next);
|
|
213
|
+
});
|
|
214
|
+
l.chain = run.then(undefined, (error) => {
|
|
215
|
+
// An error cancels the queued calls and surfaces at the nearest error boundary.
|
|
216
|
+
l.cancelled = true;
|
|
217
|
+
setFailure({ error });
|
|
218
|
+
});
|
|
219
|
+
return l.chain.then(() => {
|
|
220
|
+
if (--l.queued === 0) {
|
|
221
|
+
l.cancelled = false;
|
|
222
|
+
setPending(false);
|
|
223
|
+
}
|
|
224
|
+
end();
|
|
225
|
+
});
|
|
226
|
+
}, []);
|
|
227
|
+
if (failure)
|
|
228
|
+
throw failure.error;
|
|
229
|
+
return [state, dispatch, pending];
|
|
230
|
+
}
|
|
231
|
+
function use(usable) {
|
|
232
|
+
if (isThenable(usable)) {
|
|
233
|
+
const p = usable;
|
|
234
|
+
if (p.status === 'fulfilled')
|
|
235
|
+
return p.value;
|
|
236
|
+
if (p.status === 'rejected')
|
|
237
|
+
throw p.reason;
|
|
238
|
+
if (p.status !== 'pending') {
|
|
239
|
+
p.status = 'pending';
|
|
240
|
+
p.then((v) => { p.status = 'fulfilled'; p.value = v; }, (e) => { p.status = 'rejected'; p.reason = e; });
|
|
241
|
+
}
|
|
242
|
+
// preact/compat's Suspense catches a thrown promise and re-renders when it settles.
|
|
243
|
+
throw p;
|
|
244
|
+
}
|
|
245
|
+
// Preact's createContext returns a function carrying Provider and Consumer.
|
|
246
|
+
if (usable && (typeof usable === 'object' || typeof usable === 'function') && 'Provider' in usable)
|
|
247
|
+
return useContext(usable);
|
|
248
|
+
throw new Error('use() received something that is neither a promise nor a context.');
|
|
249
|
+
}
|
|
250
|
+
function cache(fn) {
|
|
251
|
+
const root = new Map();
|
|
252
|
+
const result = Symbol('result');
|
|
253
|
+
return function (...args) {
|
|
254
|
+
let node = root;
|
|
255
|
+
for (const a of args) {
|
|
256
|
+
let next = node.get(a);
|
|
257
|
+
if (!next)
|
|
258
|
+
node.set(a, (next = new Map()));
|
|
259
|
+
node = next;
|
|
260
|
+
}
|
|
261
|
+
if (!node.has(result)) {
|
|
262
|
+
try {
|
|
263
|
+
node.set(result, { value: fn.apply(this, args) });
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
node.set(result, { error, failed: true });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const r = node.get(result);
|
|
270
|
+
if (r.failed)
|
|
271
|
+
throw r.error;
|
|
272
|
+
return r.value;
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
function useEffectEvent(fn) {
|
|
276
|
+
const ref = useRef(fn);
|
|
277
|
+
ref.current = fn;
|
|
278
|
+
return useCallback((...args) => ref.current(...args), []);
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
useOptimistic,
|
|
282
|
+
useActionState,
|
|
283
|
+
useFormState: useActionState,
|
|
284
|
+
useFormStatus,
|
|
285
|
+
requestFormReset,
|
|
286
|
+
use,
|
|
287
|
+
cache,
|
|
288
|
+
useEffectEvent,
|
|
289
|
+
startTransition,
|
|
290
|
+
useTransition,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
// Events React treats as discrete: the effects of a render they cause are
|
|
294
|
+
// flushed at the end of its commit, not after paint.
|
|
295
|
+
const DISCRETE_EVENTS = [
|
|
296
|
+
'beforeinput', 'blur', 'change', 'click', 'compositionend', 'compositionstart', 'contextmenu', 'copy', 'cut',
|
|
297
|
+
'dblclick', 'dragend', 'dragstart', 'drop', 'focusin', 'focusout', 'input', 'keydown', 'keypress', 'keyup',
|
|
298
|
+
'mousedown', 'mouseup', 'paste', 'pointercancel', 'pointerdown', 'pointerup', 'reset', 'submit',
|
|
299
|
+
'touchcancel', 'touchend', 'touchstart',
|
|
300
|
+
];
|
|
301
|
+
/**
|
|
302
|
+
* React 18 flushes the passive effects of a render caused by a discrete event
|
|
303
|
+
* (a click, a key press, typing) synchronously at the end of its commit, and
|
|
304
|
+
* renders the updates those effects make in the same task. Preact runs them
|
|
305
|
+
* after the next frame, so a quick second event could render a component with
|
|
306
|
+
* a new prop and a state update from its previous effects at once: react-colorful
|
|
307
|
+
* then took its own color prop for user input and called onChange with a
|
|
308
|
+
* stale colour. While a discrete event's task runs, this flushes Preact's
|
|
309
|
+
* effect queue after every commit (Preact's render loop picks up the updates
|
|
310
|
+
* they make); otherwise effects keep running after paint. The compiler's
|
|
311
|
+
* client builds call it from their `react` module, once per Preact instance.
|
|
312
|
+
*/
|
|
313
|
+
export function installDiscreteEffects(options) {
|
|
314
|
+
if (typeof window === 'undefined' || typeof document === 'undefined' || options.__krateDiscrete)
|
|
315
|
+
return;
|
|
316
|
+
options.__krateDiscrete = true;
|
|
317
|
+
let discrete = false;
|
|
318
|
+
let clearing = false;
|
|
319
|
+
let flushEffects = null;
|
|
320
|
+
const onEvent = () => {
|
|
321
|
+
discrete = true;
|
|
322
|
+
if (clearing)
|
|
323
|
+
return;
|
|
324
|
+
clearing = true;
|
|
325
|
+
setTimeout(() => {
|
|
326
|
+
discrete = false;
|
|
327
|
+
clearing = false;
|
|
328
|
+
}, 0);
|
|
329
|
+
};
|
|
330
|
+
for (const type of DISCRETE_EVENTS)
|
|
331
|
+
window.addEventListener(type, onEvent, true);
|
|
332
|
+
// Preact's default afterNextFrame, used outside discrete events. The flush
|
|
333
|
+
// function preact/hooks hands over is always the same one, so it is kept.
|
|
334
|
+
const prevRaf = options.requestAnimationFrame;
|
|
335
|
+
options.requestAnimationFrame = (cb) => {
|
|
336
|
+
flushEffects = cb;
|
|
337
|
+
if (prevRaf)
|
|
338
|
+
return prevRaf(cb);
|
|
339
|
+
let raf = 0;
|
|
340
|
+
const done = () => {
|
|
341
|
+
clearTimeout(timeout);
|
|
342
|
+
if (typeof cancelAnimationFrame === 'function')
|
|
343
|
+
cancelAnimationFrame(raf);
|
|
344
|
+
setTimeout(cb);
|
|
345
|
+
};
|
|
346
|
+
const timeout = setTimeout(done, 100);
|
|
347
|
+
if (typeof requestAnimationFrame === 'function')
|
|
348
|
+
raf = requestAnimationFrame(done);
|
|
349
|
+
};
|
|
350
|
+
// options._commit (mangled __c) runs after refs and, through preact/hooks'
|
|
351
|
+
// own wrapper, after layout effects.
|
|
352
|
+
const prevCommit = options.__c;
|
|
353
|
+
options.__c = (vnode, queue) => {
|
|
354
|
+
if (prevCommit)
|
|
355
|
+
prevCommit(vnode, queue);
|
|
356
|
+
if (discrete && flushEffects)
|
|
357
|
+
flushEffects();
|
|
358
|
+
};
|
|
359
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function requestCookiesOf(headers: Headers): Map<string, string>;
|
|
2
|
+
export declare function attachCookies(request: Request, basePath?: string): Request;
|
|
3
|
+
/** A URL carrying Next's NextURL extras: basePath (pathname never includes it) and clone(). */
|
|
4
|
+
export declare function makeNextUrl(href: string, basePath: string): URL;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Next's request extras on a route handler's Request: a read-only
|
|
2
|
+
// request.cookies and request.nextUrl. Shared by the server handler and
|
|
3
|
+
// @krate/runtime/testing so tests see what the server passes.
|
|
4
|
+
export function requestCookiesOf(headers) {
|
|
5
|
+
const jar = new Map();
|
|
6
|
+
for (const part of String(headers.get("cookie") || "").split(";")) {
|
|
7
|
+
const i = part.indexOf("=");
|
|
8
|
+
if (i <= 0)
|
|
9
|
+
continue;
|
|
10
|
+
const name = part.slice(0, i).trim();
|
|
11
|
+
if (!name || jar.has(name))
|
|
12
|
+
continue;
|
|
13
|
+
// Same parsing as the action context and the Node sidecar: unquote, then percent-decode.
|
|
14
|
+
let value = part.slice(i + 1).trim();
|
|
15
|
+
if (value.startsWith('"') && value.endsWith('"'))
|
|
16
|
+
value = value.slice(1, -1);
|
|
17
|
+
try {
|
|
18
|
+
value = decodeURIComponent(value);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// keep the raw value
|
|
22
|
+
}
|
|
23
|
+
jar.set(name, value);
|
|
24
|
+
}
|
|
25
|
+
return jar;
|
|
26
|
+
}
|
|
27
|
+
export function attachCookies(request, basePath = "") {
|
|
28
|
+
try {
|
|
29
|
+
const jar = requestCookiesOf(request.headers);
|
|
30
|
+
Object.defineProperty(request, "cookies", {
|
|
31
|
+
value: {
|
|
32
|
+
get: (n) => (jar.has(String(n)) ? { name: String(n), value: jar.get(String(n)) } : undefined),
|
|
33
|
+
getAll: (n) => [...jar].filter(([k]) => n === undefined || k === String(n)).map(([name, value]) => ({ name, value })),
|
|
34
|
+
has: (n) => jar.has(String(n)),
|
|
35
|
+
},
|
|
36
|
+
enumerable: false,
|
|
37
|
+
});
|
|
38
|
+
Object.defineProperty(request, "nextUrl", { value: makeNextUrl(request.url, basePath), enumerable: false });
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// frozen request objects keep working without the cookies accessor
|
|
42
|
+
}
|
|
43
|
+
return request;
|
|
44
|
+
}
|
|
45
|
+
/** A URL carrying Next's NextURL extras: basePath (pathname never includes it) and clone(). */
|
|
46
|
+
export function makeNextUrl(href, basePath) {
|
|
47
|
+
const u = new URL(href);
|
|
48
|
+
Object.defineProperty(u, "basePath", { value: basePath, enumerable: false });
|
|
49
|
+
Object.defineProperty(u, "clone", { value: () => makeNextUrl(u.href, basePath), enumerable: false });
|
|
50
|
+
return u;
|
|
51
|
+
}
|