@kasperrt/smolter 0.0.0-stage → 0.0.1-rc.1

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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +470 -2
  3. package/dist/client.d.ts +2 -0
  4. package/dist/client.js +2 -0
  5. package/dist/core.d.ts +2 -0
  6. package/dist/core.js +2 -0
  7. package/dist/files.d.ts +2 -0
  8. package/dist/files.js +2 -0
  9. package/dist/internal/client/deserialize.d.ts +3 -0
  10. package/dist/internal/client/deserialize.js +11 -0
  11. package/dist/internal/client/index.d.ts +23 -0
  12. package/dist/internal/client/index.js +44 -0
  13. package/dist/internal/core/errors.d.ts +3 -0
  14. package/dist/internal/core/errors.js +6 -0
  15. package/dist/internal/core/index.d.ts +6 -0
  16. package/dist/internal/core/index.js +6 -0
  17. package/dist/internal/core/match.d.ts +5 -0
  18. package/dist/internal/core/match.js +27 -0
  19. package/dist/internal/core/router.d.ts +3 -0
  20. package/dist/internal/core/router.js +189 -0
  21. package/dist/internal/core/types.d.ts +119 -0
  22. package/dist/internal/core/types.js +5 -0
  23. package/dist/internal/core/url.d.ts +2 -0
  24. package/dist/internal/core/url.js +6 -0
  25. package/dist/internal/files/index.d.ts +11 -0
  26. package/dist/internal/files/index.js +77 -0
  27. package/dist/internal/preact/context.d.ts +18 -0
  28. package/dist/internal/preact/context.js +20 -0
  29. package/dist/internal/preact/fetcher.d.ts +22 -0
  30. package/dist/internal/preact/fetcher.js +28 -0
  31. package/dist/internal/preact/form.d.ts +17 -0
  32. package/dist/internal/preact/form.js +41 -0
  33. package/dist/internal/preact/hooks.d.ts +21 -0
  34. package/dist/internal/preact/hooks.js +35 -0
  35. package/dist/internal/preact/index.d.ts +9 -0
  36. package/dist/internal/preact/index.js +7 -0
  37. package/dist/internal/preact/link.d.ts +12 -0
  38. package/dist/internal/preact/link.js +28 -0
  39. package/dist/internal/preact/routes.d.ts +22 -0
  40. package/dist/internal/preact/routes.js +22 -0
  41. package/dist/internal/preact/runtime.d.ts +2 -0
  42. package/dist/internal/preact/runtime.js +1 -0
  43. package/dist/internal/react/context.d.ts +18 -0
  44. package/dist/internal/react/context.js +20 -0
  45. package/dist/internal/react/fetcher.d.ts +22 -0
  46. package/dist/internal/react/fetcher.js +28 -0
  47. package/dist/internal/react/form.d.ts +17 -0
  48. package/dist/internal/react/form.js +41 -0
  49. package/dist/internal/react/hooks.d.ts +21 -0
  50. package/dist/internal/react/hooks.js +35 -0
  51. package/dist/internal/react/index.d.ts +9 -0
  52. package/dist/internal/react/index.js +7 -0
  53. package/dist/internal/react/link.d.ts +12 -0
  54. package/dist/internal/react/link.js +28 -0
  55. package/dist/internal/react/routes.d.ts +22 -0
  56. package/dist/internal/react/routes.js +22 -0
  57. package/dist/internal/react/runtime.d.ts +2 -0
  58. package/dist/internal/react/runtime.js +2 -0
  59. package/dist/internal/server/index.d.ts +11 -0
  60. package/dist/internal/server/index.js +81 -0
  61. package/dist/internal/vite/index.d.ts +10 -0
  62. package/dist/internal/vite/index.js +132 -0
  63. package/dist/internal/vite/transport.d.ts +2 -0
  64. package/dist/internal/vite/transport.js +42 -0
  65. package/dist/preact.d.ts +2 -0
  66. package/dist/preact.js +2 -0
  67. package/dist/react.d.ts +2 -0
  68. package/dist/react.js +2 -0
  69. package/dist/server.d.ts +2 -0
  70. package/dist/server.js +2 -0
  71. package/dist/vite.d.ts +2 -0
  72. package/dist/vite.js +2 -0
  73. package/jsr.json +26 -0
  74. package/package.json +94 -4
  75. package/src/client.ts +2 -0
  76. package/src/core.ts +2 -0
  77. package/src/files.ts +2 -0
  78. package/src/internal/client/deserialize.ts +15 -0
  79. package/src/internal/client/index.ts +84 -0
  80. package/src/internal/core/errors.ts +13 -0
  81. package/src/internal/core/index.ts +7 -0
  82. package/src/internal/core/match.ts +45 -0
  83. package/src/internal/core/router.ts +251 -0
  84. package/src/internal/core/types.ts +151 -0
  85. package/src/internal/core/url.ts +6 -0
  86. package/src/internal/files/index.ts +112 -0
  87. package/src/internal/preact/context.ts +46 -0
  88. package/src/internal/preact/fetcher.ts +83 -0
  89. package/src/internal/preact/form.ts +79 -0
  90. package/src/internal/preact/hooks.ts +72 -0
  91. package/src/internal/preact/index.ts +13 -0
  92. package/src/internal/preact/link.ts +46 -0
  93. package/src/internal/preact/routes.ts +50 -0
  94. package/src/internal/preact/runtime.ts +15 -0
  95. package/src/internal/react/context.ts +46 -0
  96. package/src/internal/react/fetcher.ts +83 -0
  97. package/src/internal/react/form.ts +79 -0
  98. package/src/internal/react/hooks.ts +72 -0
  99. package/src/internal/react/index.ts +13 -0
  100. package/src/internal/react/link.ts +46 -0
  101. package/src/internal/react/routes.ts +50 -0
  102. package/src/internal/react/runtime.ts +18 -0
  103. package/src/internal/server/index.ts +120 -0
  104. package/src/internal/vite/index.ts +208 -0
  105. package/src/internal/vite/transport.ts +60 -0
  106. package/src/preact.ts +2 -0
  107. package/src/react.ts +2 -0
  108. package/src/server.ts +2 -0
  109. package/src/vite.ts +2 -0
@@ -0,0 +1,3 @@
1
+ import type { Route, Router, RouterOptions } from "./types.ts";
2
+ /** Create an isolated router. Use browser: true for browser history, or loadRouter for SSR. */
3
+ export declare function createRouter(routes: readonly Route[], options?: RouterOptions): Router;
@@ -0,0 +1,189 @@
1
+ import { safeWrapAsync } from "./errors.js";
2
+ import { matchRoutes } from "./match.js";
3
+ import { internalURL } from "./url.js";
4
+ /** Create an isolated router. Use browser: true for browser history, or loadRouter for SSR. */
5
+ export function createRouter(routes, options = {}) {
6
+ const browser = options.browser && typeof window !== "undefined";
7
+ let initialized = options.hydrationData?.state === "idle";
8
+ const initial = {
9
+ loaded: initialized,
10
+ ...(options.hydrationData ?? {
11
+ url: new URL(options.url ?? (browser ? location.href : "/"), "http://localhost").href,
12
+ params: {},
13
+ state: "idle",
14
+ }),
15
+ };
16
+ const disposers = new Set();
17
+ const channel = (initial, local = false) => {
18
+ let snapshot = initial;
19
+ let controller;
20
+ const listeners = new Set();
21
+ const dispose = () => {
22
+ disposers.delete(dispose);
23
+ controller?.abort();
24
+ listeners.clear();
25
+ };
26
+ const emit = (next) => {
27
+ snapshot = { ...snapshot, ...next };
28
+ for (const listener of listeners)
29
+ listener();
30
+ };
31
+ const run = async (href, body, operation = {},
32
+ // true pushes history; false handles popstate; undefined is a data request.
33
+ navigation) => {
34
+ controller?.abort();
35
+ controller = new AbortController();
36
+ const { signal } = controller;
37
+ disposers.add(dispose);
38
+ const previous = snapshot;
39
+ const url = internalURL(main.getSnapshot().url, href);
40
+ const match = url && matchRoutes(routes, url.pathname);
41
+ const commit = () => {
42
+ if (local || !url)
43
+ return;
44
+ const changed = snapshot.url !== url.href;
45
+ if (!changed && snapshot.path !== undefined)
46
+ return;
47
+ if (browser && (navigation || body) && changed)
48
+ history[operation.replace ? "replaceState" : "pushState"](null, "", url);
49
+ const sameRoute = snapshot.path === match?.route.path;
50
+ snapshot = {
51
+ ...snapshot,
52
+ url: url.href,
53
+ path: match?.route.path,
54
+ params: match?.params ?? {},
55
+ actionData: undefined,
56
+ data: sameRoute ? snapshot.data : undefined,
57
+ loaded: sameRoute && snapshot.loaded,
58
+ };
59
+ };
60
+ if (!body)
61
+ commit();
62
+ emit({ state: body ? "submitting" : "loading", error: undefined });
63
+ const result = await safeWrapAsync(() => {
64
+ if (!match)
65
+ return new Error(url ? "No route" : "External URL");
66
+ if (navigation !== undefined &&
67
+ !body &&
68
+ previous.loaded &&
69
+ !previous.error &&
70
+ previous.path === match.route.path &&
71
+ match.route.shouldRevalidate?.({
72
+ url,
73
+ currentUrl: new URL(previous.url),
74
+ nextUrl: url,
75
+ defaultShouldRevalidate: true,
76
+ reason: "navigation",
77
+ }) === false)
78
+ return previous.data;
79
+ const fn = match.route[body ? "clientAction" : "clientLoader"] ||
80
+ match.route[body ? "action" : "loader"];
81
+ if (!fn)
82
+ return body && new Error("No action");
83
+ return fn({
84
+ request: new Request(url, {
85
+ signal,
86
+ method: body && (operation.method ?? "POST"),
87
+ body,
88
+ }),
89
+ params: match.params,
90
+ signal,
91
+ });
92
+ });
93
+ if (signal.aborted)
94
+ return result;
95
+ const redirectTo = result.data instanceof Response && result.data.headers.get("Location");
96
+ if (redirectTo && (operation.hops ?? 0) < 10) {
97
+ await main.load(new URL(redirectTo, url).href, undefined, {
98
+ replace: true,
99
+ hops: (operation.hops ?? 0) + 1,
100
+ }, true);
101
+ if (!signal.aborted)
102
+ emit({ state: "idle" });
103
+ return result;
104
+ }
105
+ if (redirectTo)
106
+ result.error = new Error("Redirect loop");
107
+ if (body && !result.error)
108
+ commit();
109
+ emit({
110
+ [body && !local ? "actionData" : "data"]: result.data,
111
+ error: result.error,
112
+ loaded: body ? snapshot.loaded : !result.error,
113
+ state: body && !result.error ? "loading" : "idle",
114
+ });
115
+ if (body && !result.error) {
116
+ await router.revalidate("action", {
117
+ formMethod: operation.method ?? "POST",
118
+ formAction: url.href,
119
+ formData: body,
120
+ actionResult: result.data,
121
+ });
122
+ if (!signal.aborted)
123
+ emit({ state: "idle" });
124
+ }
125
+ return result;
126
+ };
127
+ return {
128
+ getSnapshot: () => snapshot,
129
+ subscribe(listener) {
130
+ listeners.add(listener);
131
+ return () => {
132
+ listeners.delete(listener);
133
+ };
134
+ },
135
+ load: run,
136
+ submit: run,
137
+ dispose,
138
+ };
139
+ };
140
+ const main = channel(initial);
141
+ let started = 0;
142
+ const pop = () => {
143
+ void main.load(location.href, undefined, undefined, false);
144
+ };
145
+ const router = {
146
+ ...main,
147
+ routes,
148
+ start() {
149
+ if (!started++ && browser)
150
+ addEventListener("popstate", pop);
151
+ if (!initialized) {
152
+ initialized = true;
153
+ void main.load(initial.url);
154
+ }
155
+ return () => {
156
+ if (!--started && browser)
157
+ removeEventListener("popstate", pop);
158
+ };
159
+ },
160
+ async navigate(url, operation) {
161
+ initialized = true;
162
+ await main.load(url, undefined, operation, true);
163
+ },
164
+ async revalidate(reason = "manual", context = {}) {
165
+ const url = new URL(main.getSnapshot().url);
166
+ if (matchRoutes(routes, url.pathname)?.route.shouldRevalidate?.({
167
+ ...context,
168
+ url,
169
+ currentUrl: url,
170
+ nextUrl: url,
171
+ defaultShouldRevalidate: true,
172
+ reason,
173
+ }) === false)
174
+ return;
175
+ await main.load(url.href);
176
+ },
177
+ createFetcher() {
178
+ return channel({ state: "idle" }, true);
179
+ },
180
+ dispose() {
181
+ main.dispose();
182
+ for (const dispose of disposers)
183
+ dispose();
184
+ if (browser)
185
+ removeEventListener("popstate", pop);
186
+ },
187
+ };
188
+ return router;
189
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Framework-independent route matching, data requests, and state.
3
+ * @module
4
+ */
5
+ /** Framework-independent data routing. No global request state. */
6
+ export type Params = Record<string, string>;
7
+ /** Request, path parameters, and cancellation signal passed to a data handler. */
8
+ export interface DataArgs {
9
+ request: Request;
10
+ params: Params;
11
+ signal: AbortSignal;
12
+ }
13
+ /** A loader or action that returns data, a Response, or an Error value. */
14
+ export type DataFunction = (args: DataArgs) => unknown;
15
+ /** A handler signature used to infer data from specialized loader and action arguments. */
16
+ export type AnyDataFunction = (...args: never[]) => unknown;
17
+ /** Client loader arguments, including a typed call to the server loader. */
18
+ export interface ClientLoaderArgs<L extends AnyDataFunction = DataFunction> extends DataArgs {
19
+ serverLoader: () => Promise<DataOf<L>>;
20
+ }
21
+ /** Client action arguments, including a typed call to the server action. */
22
+ export interface ClientActionArgs<A extends AnyDataFunction = DataFunction> extends DataArgs {
23
+ serverAction: () => Promise<DataOf<A>>;
24
+ }
25
+ /** The resolved data returned by a handler, excluding Error values. */
26
+ export type DataOf<F> = F extends AnyDataFunction ? Exclude<Awaited<ReturnType<F>>, Error> : undefined;
27
+ /** Mutation details supplied when deciding whether to reload route data. */
28
+ export interface RevalidationContext {
29
+ formMethod?: string;
30
+ formAction?: string;
31
+ formData?: FormData;
32
+ actionResult?: unknown;
33
+ }
34
+ /** Current URL, mutation result, and reason passed to shouldRevalidate. */
35
+ export interface RevalidationArgs extends RevalidationContext {
36
+ currentUrl: URL;
37
+ nextUrl: URL;
38
+ defaultShouldRevalidate: boolean;
39
+ url: URL;
40
+ reason: "manual" | "action" | "navigation";
41
+ }
42
+ /** A route component and its optional server and client data handlers. */
43
+ export interface RouteModule {
44
+ default?: unknown;
45
+ HydrateFallback?: unknown;
46
+ ErrorBoundary?: unknown;
47
+ loader?: DataFunction;
48
+ action?: DataFunction;
49
+ clientLoader?(args: ClientLoaderArgs): unknown;
50
+ clientAction?(args: ClientActionArgs): unknown;
51
+ shouldRevalidate?: (args: RevalidationArgs) => boolean;
52
+ }
53
+ /** A route module associated with an explicit URL pattern. */
54
+ export type Route<M extends RouteModule = RouteModule> = M & {
55
+ path: string;
56
+ };
57
+ /** The first matching route and its decoded path parameters. */
58
+ export interface Match {
59
+ route: Route;
60
+ params: Params;
61
+ }
62
+ /** Immutable current route state observed by framework hooks. */
63
+ export interface Snapshot {
64
+ url: string;
65
+ path?: string;
66
+ params: Params;
67
+ data?: unknown;
68
+ /** Whether this route has completed a loader, including an undefined result. */
69
+ loaded?: boolean;
70
+ actionData?: unknown;
71
+ error?: Error;
72
+ state: "idle" | "loading" | "submitting";
73
+ }
74
+ /** Initial URL, browser history, and hydration configuration. */
75
+ export interface RouterOptions {
76
+ url?: string;
77
+ /** Explicitly opt into browser history; leave off for SSR and tests. */
78
+ browser?: boolean;
79
+ hydrationData?: Snapshot;
80
+ }
81
+ /** Options for replacing rather than appending a browser history entry. */
82
+ export interface NavigateOptions {
83
+ replace?: boolean;
84
+ }
85
+ /** HTTP method for a route action submission; defaults to POST. */
86
+ export interface SubmitOptions {
87
+ method?: "POST" | "PUT" | "PATCH" | "DELETE";
88
+ }
89
+ /** A resolved operation result, with either data or a normalized Error. */
90
+ export interface Result<T = unknown> {
91
+ data?: T;
92
+ error?: Error;
93
+ }
94
+ /** Independent fetcher data, error, and pending state. */
95
+ export interface FetcherSnapshot extends Result {
96
+ state: Snapshot["state"];
97
+ }
98
+ /** An independent loader/action channel that does not navigate the page. */
99
+ export interface Fetcher {
100
+ getSnapshot: () => FetcherSnapshot;
101
+ subscribe: (listener: () => void) => () => void;
102
+ load: (url: string) => Promise<Result>;
103
+ submit: (url: string, body: FormData, options?: SubmitOptions) => Promise<Result>;
104
+ /** Abort work and release subscriptions when this imperative fetcher is no longer used. */
105
+ dispose: () => void;
106
+ }
107
+ /** Route navigation, subscriptions, fetchers, and loader revalidation. */
108
+ export interface Router {
109
+ routes: readonly Route[];
110
+ getSnapshot: () => Snapshot;
111
+ subscribe: (listener: () => void) => () => void;
112
+ start: () => () => void;
113
+ navigate: (url: string, options?: NavigateOptions) => Promise<void>;
114
+ revalidate: (reason?: RevalidationArgs["reason"], context?: RevalidationContext) => Promise<void>;
115
+ submit: (url: string, body: FormData, options?: SubmitOptions) => Promise<Result>;
116
+ /** Create an independent fetcher. Framework useFetcher hooks manage disposal automatically. */
117
+ createFetcher: () => Fetcher;
118
+ dispose: () => void;
119
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Framework-independent route matching, data requests, and state.
3
+ * @module
4
+ */
5
+ export {};
@@ -0,0 +1,2 @@
1
+ /** Resolve an internal URL; external links remain the browser's responsibility. */
2
+ export declare function internalURL(base: string, href?: string): URL | undefined;
@@ -0,0 +1,6 @@
1
+ /** Resolve an internal URL; external links remain the browser's responsibility. */
2
+ export function internalURL(base, href = base) {
3
+ const url = new URL(href, base);
4
+ if (url.origin === new URL(base).origin)
5
+ return url;
6
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Build-time discovery of flat file routes.
3
+ * @module
4
+ */
5
+ /** A discovered flat route pattern and its module file path. */
6
+ export interface RouteFile {
7
+ path: string;
8
+ file: string;
9
+ }
10
+ /** Read only flat files and immediate route folders. Colocated helpers are ignored. */
11
+ export declare function flatRoutes(directory: string): Promise<RouteFile[] | Error>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Build-time discovery of flat file routes.
3
+ * @module
4
+ */
5
+ import { readdir } from "node:fs/promises";
6
+ import { resolve } from "node:path";
7
+ import { safeWrapAsync } from "../core/index.js";
8
+ const routeFile = /^route\.[jt]sx?$/;
9
+ const flatFile = /\.[jt]sx?$/;
10
+ /** Read only flat files and immediate route folders. Colocated helpers are ignored. */
11
+ export async function flatRoutes(directory) {
12
+ const result = await safeWrapAsync(async () => {
13
+ const entries = await readdir(directory, { withFileTypes: true });
14
+ const routes = [];
15
+ const patterns = new Set();
16
+ for (const entry of entries) {
17
+ let name = entry.name;
18
+ let file = resolve(directory, name);
19
+ if (entry.isDirectory()) {
20
+ const candidates = (await readdir(file)).filter((name) => routeFile.test(name));
21
+ if (candidates.length > 1)
22
+ return new Error(`Multiple route files in ${file}`);
23
+ if (!candidates.length)
24
+ continue;
25
+ file = resolve(file, candidates[0]);
26
+ }
27
+ else {
28
+ if (!entry.isFile() || !flatFile.test(name) || name.endsWith(".d.ts"))
29
+ continue;
30
+ name = name.replace(flatFile, "");
31
+ }
32
+ if (/[()[\]:*?]/.test(name))
33
+ return new Error(`Unsupported flat route name: ${name}`);
34
+ const segments = name.split(".");
35
+ const parts = [];
36
+ for (const [index, segment] of segments.entries()) {
37
+ if (!segment)
38
+ return new Error(`Empty route segment: ${name}`);
39
+ if (segment === "_index" && index !== segments.length - 1)
40
+ return new Error(`_index must be last: ${name}`);
41
+ if (segment === "$" && index !== segments.length - 1)
42
+ return new Error(`Splat must be last: ${name}`);
43
+ if (segment.startsWith("_"))
44
+ continue;
45
+ const part = segment.replace(/_$/, "");
46
+ parts.push(part === "$" ? "*" : part.replace(/^\$/, ":"));
47
+ }
48
+ // Pathless grouping modules are not nested layouts in a flat router.
49
+ if (segments.at(-1)?.startsWith("_") && segments.at(-1) !== "_index")
50
+ continue;
51
+ const path = `/${parts.join("/")}`;
52
+ const pattern = path.replace(/:[^/]+/g, ":");
53
+ if (patterns.has(pattern))
54
+ return new Error(`Conflicting flat route: ${path}`);
55
+ patterns.add(pattern);
56
+ routes.push({ path, file });
57
+ }
58
+ return routes.sort((a, b) => {
59
+ const left = a.path.split("/");
60
+ const right = b.path.split("/");
61
+ const rank = (part) => part === "*"
62
+ ? 0
63
+ : part?.startsWith(":")
64
+ ? 1
65
+ : part === undefined
66
+ ? 2
67
+ : 3;
68
+ for (let index = 0; index < Math.max(left.length, right.length); index++) {
69
+ const difference = rank(right[index]) - rank(left[index]);
70
+ if (difference)
71
+ return difference;
72
+ }
73
+ return a.path.localeCompare(b.path);
74
+ });
75
+ });
76
+ return result.error ?? result.data;
77
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import type { Router, Snapshot } from "../core/index.ts";
6
+ import type { ReactNode } from "./runtime.ts";
7
+ /** Router instance and children rendered within its context. */
8
+ export interface RouterProviderProps {
9
+ router: Router;
10
+ children?: ReactNode;
11
+ }
12
+ /** Provide a router to descendant hooks and connect its browser lifecycle. */
13
+ export declare function RouterProvider({ router, children, }: RouterProviderProps): ReactNode;
14
+ /** Hooks require a RouterProvider. */
15
+ export declare function useRouter(): Router;
16
+ type SnapshotSelector<T> = (snapshot: Snapshot) => T;
17
+ export declare function useSnapshot<T>(select: SnapshotSelector<T>): T;
18
+ export {};
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import { createContext, createElement, useContext, useEffect, useSyncExternalStore, } from "./runtime.js";
6
+ const RouterContext = createContext(undefined);
7
+ /** Provide a router to descendant hooks and connect its browser lifecycle. */
8
+ export function RouterProvider({ router, children, }) {
9
+ useEffect(router.start, [router]);
10
+ return createElement(RouterContext.Provider, { value: router }, children);
11
+ }
12
+ /** Hooks require a RouterProvider. */
13
+ export function useRouter() {
14
+ return useContext(RouterContext);
15
+ }
16
+ export function useSnapshot(select) {
17
+ const router = useRouter();
18
+ const getSnapshot = () => select(router.getSnapshot());
19
+ return useSyncExternalStore(router.subscribe, getSnapshot, getSnapshot);
20
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import type { AnyDataFunction, DataFunction, DataOf, FetcherSnapshot, Result, Route as RouteDefinition, RouteModule, SubmitOptions } from "../core/index.ts";
6
+ import { type FormProps } from "./form.ts";
7
+ import type { ComponentType } from "./runtime.ts";
8
+ /** Action method and optional explicit route URL for a fetcher submission. */
9
+ export interface FetcherSubmitOptions extends SubmitOptions {
10
+ action?: string;
11
+ }
12
+ /** Typed independent request state, methods, and a bound Form component. */
13
+ export interface TypedFetcher<T> extends Omit<FetcherSnapshot, "data"> {
14
+ data?: T;
15
+ Form: ComponentType<FormProps>;
16
+ load: (url?: string) => Promise<Result>;
17
+ submit: (body: FormData, options?: FetcherSubmitOptions) => Promise<Result>;
18
+ }
19
+ /** Create a fetcher for independent route reads and mutations; its data stays local. */
20
+ export declare function useFetcher<T extends RouteModule>(route: RouteDefinition<T>): TypedFetcher<DataOf<Extract<T["action"] | T["clientAction"], AnyDataFunction>> | DataOf<Extract<T["loader"] | T["clientLoader"], AnyDataFunction>>>;
21
+ /** Create a fetcher for independent route reads and mutations; its data stays local. */
22
+ export declare function useFetcher<T extends AnyDataFunction = DataFunction>(): TypedFetcher<DataOf<T>>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import { useRouter } from "./context.js";
6
+ import { Form } from "./form.js";
7
+ import { createElement, useEffect, useMemo, useSyncExternalStore, } from "./runtime.js";
8
+ /** Create a fetcher for independent route reads and mutations; its data stays local. */
9
+ export function useFetcher(route) {
10
+ const router = useRouter();
11
+ const path = route?.path;
12
+ const fetcher = useMemo(() => {
13
+ const store = router.createFetcher();
14
+ const target = () => {
15
+ const snapshot = router.getSnapshot();
16
+ return path === undefined || path === snapshot.path ? snapshot.url : path;
17
+ };
18
+ return {
19
+ ...store,
20
+ Form: (props) => createElement(Form, { action: target(), ...props, fetcher: store }),
21
+ load: (url) => store.load(url ?? target()),
22
+ submit: (body, options) => store.submit(options?.action ?? target(), body, options),
23
+ };
24
+ }, [router, path]);
25
+ useEffect(() => fetcher.dispose, [fetcher]);
26
+ const state = useSyncExternalStore(fetcher.subscribe, fetcher.getSnapshot, fetcher.getSnapshot);
27
+ return { ...fetcher, ...state };
28
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import type { Fetcher } from "../core/index.ts";
6
+ import type { FormHTMLAttributes, ReactNode } from "./runtime.ts";
7
+ /** Form attributes with GET loader requests or POST, PUT, PATCH, and DELETE actions. */
8
+ export interface FormProps extends Omit<FormHTMLAttributes<HTMLFormElement>, "action" | "method"> {
9
+ action?: string;
10
+ method?: "get" | "post" | "put" | "patch" | "delete";
11
+ }
12
+ interface InternalFormProps extends FormProps {
13
+ fetcher?: Fetcher;
14
+ }
15
+ /** Submit form data to a registered route without a document reload. */
16
+ export declare function Form({ action, method, fetcher, onSubmit, ...props }: InternalFormProps): ReactNode;
17
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import { internalURL } from "../core/index.js";
6
+ import { useRouter } from "./context.js";
7
+ import { createElement } from "./runtime.js";
8
+ /** Submit form data to a registered route without a document reload. */
9
+ export function Form({ action, method = "post", fetcher, onSubmit, ...props }) {
10
+ const router = useRouter();
11
+ const submit = (event) => {
12
+ onSubmit?.(event);
13
+ if (event.defaultPrevented)
14
+ return;
15
+ const submitter = event.submitter;
16
+ const target = internalURL(router.getSnapshot().url, submitter?.getAttribute("formaction") ?? action);
17
+ if (!target)
18
+ return;
19
+ event.preventDefault();
20
+ const data = new FormData(event.currentTarget, submitter);
21
+ const verb = (submitter?.getAttribute("formmethod") ?? method).toUpperCase();
22
+ if (verb === "GET") {
23
+ const search = new URLSearchParams();
24
+ for (const [key, value] of data)
25
+ search.append(key, typeof value === "string" ? value : value.name);
26
+ target.search = String(search);
27
+ void (fetcher ? fetcher.load : router.navigate)(target.href);
28
+ return;
29
+ }
30
+ const options = {
31
+ method: verb,
32
+ };
33
+ void (fetcher ?? router).submit(target.href, data, options);
34
+ };
35
+ return createElement("form", {
36
+ ...props,
37
+ action,
38
+ method: method === "get" ? "get" : "post",
39
+ onSubmit: submit,
40
+ });
41
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import type { AnyDataFunction, DataOf, RouteModule, Router, Snapshot } from "../core/index.ts";
6
+ /** A route module or loader function used for data inference. */
7
+ export type LoaderSource = RouteModule | AnyDataFunction;
8
+ /** Infer server and client loader data from a route module or function. */
9
+ export type LoaderData<T> = T extends AnyDataFunction ? DataOf<T> : T extends RouteModule ? DataOf<Extract<T["loader"] | T["clientLoader"], AnyDataFunction>> : unknown;
10
+ /** Infer server and client action data from a route module or function. */
11
+ export type ActionData<T> = T extends AnyDataFunction ? DataOf<T> : T extends RouteModule ? DataOf<Extract<T["action"] | T["clientAction"], AnyDataFunction>> : unknown;
12
+ /** Pass a route for inference, or use useLoaderData<typeof loader>() in its module. */
13
+ export declare function useLoaderData<T extends LoaderSource = RouteModule>(route?: T): LoaderData<T> | undefined;
14
+ /** Read the last page action result, optionally inferring its type from a route. */
15
+ export declare function useActionData<T extends LoaderSource = RouteModule>(route?: T): ActionData<T> | undefined;
16
+ /** Read path parameters for the active route. */
17
+ export declare function useParams(): Snapshot["params"];
18
+ /** Read the current path, search, and hash together with the navigate function. */
19
+ export declare function useLocation(): readonly [string, Router["navigate"]];
20
+ /** Get the function that revalidates the current loader subject to shouldRevalidate. */
21
+ export declare function useRevalidator(): Router["revalidate"];
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import { useRouter, useSnapshot } from "./context.js";
6
+ function useData(key, route) {
7
+ const path = route?.path;
8
+ return useSnapshot((snapshot) => {
9
+ if (path !== undefined && path !== snapshot.path)
10
+ return undefined;
11
+ return snapshot[key];
12
+ });
13
+ }
14
+ /** Pass a route for inference, or use useLoaderData<typeof loader>() in its module. */
15
+ export function useLoaderData(route) {
16
+ return useData("data", route);
17
+ }
18
+ /** Read the last page action result, optionally inferring its type from a route. */
19
+ export function useActionData(route) {
20
+ return useData("actionData", route);
21
+ }
22
+ /** Read path parameters for the active route. */
23
+ export function useParams() {
24
+ return useSnapshot((snapshot) => snapshot.params);
25
+ }
26
+ /** Read the current path, search, and hash together with the navigate function. */
27
+ export function useLocation() {
28
+ const router = useRouter();
29
+ const url = useSnapshot((snapshot) => snapshot.url);
30
+ return [url.replace(/^\w+:\/\/[^/]+/, ""), router.navigate];
31
+ }
32
+ /** Get the function that revalidates the current loader subject to shouldRevalidate. */
33
+ export function useRevalidator() {
34
+ return useRouter().revalidate;
35
+ }
@@ -0,0 +1,9 @@
1
+ /** Framework components and typed data hooks. @module */
2
+ export type * from "../core/index.ts";
3
+ export { createRouter, defineRoute } from "../core/index.ts";
4
+ export { RouterProvider, type RouterProviderProps, useRouter, } from "./context.ts";
5
+ export * from "./fetcher.ts";
6
+ export * from "./form.ts";
7
+ export * from "./hooks.ts";
8
+ export * from "./link.ts";
9
+ export * from "./routes.ts";
@@ -0,0 +1,7 @@
1
+ export { createRouter, defineRoute } from "../core/index.js";
2
+ export { RouterProvider, useRouter, } from "./context.js";
3
+ export * from "./fetcher.js";
4
+ export * from "./form.js";
5
+ export * from "./hooks.js";
6
+ export * from "./link.js";
7
+ export * from "./routes.js";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Preact components and typed data hooks. Import from smolter/preact.
3
+ * @module
4
+ */
5
+ import type { AnchorHTMLAttributes, ReactNode } from "./runtime.ts";
6
+ /** Anchor attributes with internal navigation and optional history replacement. */
7
+ export interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
8
+ href: string;
9
+ replace?: boolean;
10
+ }
11
+ /** Render an anchor that handles internal navigation and preserves native modified clicks. */
12
+ export declare function Link({ href, replace, onClick, ...props }: LinkProps): ReactNode;