@solidjs/router 1.0.0-next.8 → 1.0.0

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 (58) hide show
  1. package/README.md +715 -531
  2. package/dist/components.d.ts +31 -0
  3. package/dist/components.jsx +40 -0
  4. package/dist/data/action.d.ts +11 -40
  5. package/dist/data/action.js +100 -274
  6. package/dist/data/createAsync.d.ts +32 -0
  7. package/dist/data/createAsync.js +96 -0
  8. package/dist/data/events.d.ts +0 -8
  9. package/dist/data/events.js +23 -24
  10. package/dist/data/index.d.ts +4 -2
  11. package/dist/data/index.js +4 -2
  12. package/dist/data/query.d.ts +3 -1
  13. package/dist/data/query.js +22 -39
  14. package/dist/data/response.d.ts +4 -0
  15. package/dist/data/response.js +42 -0
  16. package/dist/index.d.ts +3 -5
  17. package/dist/index.js +1024 -1578
  18. package/dist/index.jsx +2 -2
  19. package/dist/lifecycle.d.ts +4 -29
  20. package/dist/lifecycle.js +37 -40
  21. package/dist/routers/HashRouter.d.ts +9 -0
  22. package/dist/routers/HashRouter.js +41 -0
  23. package/dist/routers/MemoryRouter.d.ts +24 -0
  24. package/dist/routers/MemoryRouter.js +57 -0
  25. package/dist/routers/Router.d.ts +17 -0
  26. package/dist/routers/Router.js +59 -0
  27. package/dist/routers/StaticRouter.d.ts +6 -0
  28. package/dist/routers/StaticRouter.js +15 -0
  29. package/dist/routers/components.d.ts +26 -12
  30. package/dist/routers/components.jsx +54 -68
  31. package/dist/routers/createRouter.d.ts +10 -0
  32. package/dist/routers/createRouter.js +41 -0
  33. package/dist/routers/index.d.ts +11 -4
  34. package/dist/routers/index.js +6 -2
  35. package/dist/routers/scrollRestoration.d.ts +32 -0
  36. package/dist/routers/scrollRestoration.js +96 -0
  37. package/dist/routing.d.ts +52 -88
  38. package/dist/routing.js +166 -381
  39. package/dist/types.d.ts +33 -83
  40. package/dist/utils.d.ts +0 -2
  41. package/dist/utils.js +0 -2
  42. package/package.json +7 -11
  43. package/dist/claims.d.ts +0 -21
  44. package/dist/claims.js +0 -115
  45. package/dist/data/flash.d.ts +0 -21
  46. package/dist/data/flash.js +0 -78
  47. package/dist/data/flashCookie.d.ts +0 -7
  48. package/dist/data/flashCookie.js +0 -20
  49. package/dist/data/serverForms.d.ts +0 -1
  50. package/dist/data/serverForms.js +0 -5
  51. package/dist/paths.d.ts +0 -117
  52. package/dist/paths.js +0 -41
  53. package/dist/routers/factory.d.ts +0 -45
  54. package/dist/routers/factory.jsx +0 -143
  55. package/dist/routers/history.d.ts +0 -24
  56. package/dist/routers/history.js +0 -180
  57. package/dist/server.d.ts +0 -75
  58. package/dist/server.js +0 -264
@@ -1,4 +1,11 @@
1
- export { createRouter, defineRoutes } from "./factory.jsx";
2
- export type { RouterConfig, RouterInstance } from "./factory.jsx";
3
- export { browserHistory, hashHistory, memoryHistory } from "./history.js";
4
- export type { RouterHistory, MemoryHistoryAdapter } from "./history.js";
1
+ export { Route } from "./components.jsx";
2
+ export type { BaseRouterProps, RouteProps } from "./components.jsx";
3
+ export { createRouter } from "./createRouter.js";
4
+ export { Router } from "./Router.js";
5
+ export type { RouterProps } from "./Router.js";
6
+ export { HashRouter } from "./HashRouter.js";
7
+ export type { HashRouterProps } from "./HashRouter.js";
8
+ export { MemoryRouter, createMemoryHistory } from "./MemoryRouter.js";
9
+ export type { MemoryRouterProps, MemoryHistory } from "./MemoryRouter.js";
10
+ export { StaticRouter } from "./StaticRouter.js";
11
+ export type { StaticRouterProps } from "./StaticRouter.js";
@@ -1,2 +1,6 @@
1
- export { createRouter, defineRoutes } from "./factory.jsx";
2
- export { browserHistory, hashHistory, memoryHistory } from "./history.js";
1
+ export { Route } from "./components.jsx";
2
+ export { createRouter } from "./createRouter.js";
3
+ export { Router } from "./Router.js";
4
+ export { HashRouter } from "./HashRouter.js";
5
+ export { MemoryRouter, createMemoryHistory } from "./MemoryRouter.js";
6
+ export { StaticRouter } from "./StaticRouter.js";
@@ -0,0 +1,32 @@
1
+ import type { RouterContext } from "../types.js";
2
+ /**
3
+ * Explicit scroll restoration for back/forward navigation. The browser's
4
+ * native same-document heuristic is unreliable for suspense-driven rendering:
5
+ * if the destination route forces a layout while the document is still short,
6
+ * the saved offset for the previous entry is clamped and lost (#577).
7
+ *
8
+ * Positions are captured continuously from the scroll event, keyed by the
9
+ * `_depth` the router already stamps on every history entry — capturing at
10
+ * scroll time (rather than at exit) stays correct through `useBeforeLeave`
11
+ * blocked/reverted traversals. The map persists to sessionStorage on pagehide
12
+ * so restoration survives reloads, which `scrollRestoration = "manual"`
13
+ * otherwise disables.
14
+ *
15
+ * Restoration is a single scroll once routing settles — the same strategy
16
+ * SvelteKit, TanStack Router and React Router use. Settling after the
17
+ * transition commits is what makes the offset reachable; chasing a still-
18
+ * growing document afterwards (a ResizeObserver re-asserting the offset as
19
+ * content arrives) was tried and removed: no peer router does it, an
20
+ * unbounded observer re-clamps the viewport to the bottom when the target is
21
+ * never reachable (a list that is genuinely shorter now), and scroll-induced
22
+ * layout changes can feed it back into itself. Content that commits after the
23
+ * transition settles — an image without reserved space, a boundary below the
24
+ * fold — keeps whatever offset the document can hold.
25
+ */
26
+ export declare function createScrollRestoration(): {
27
+ /** Before the router reacts to a popstate: mark the traversal target. */
28
+ onPop(): void;
29
+ /** After a push: forward entries died, and this depth may be reused. */
30
+ onPush(): void;
31
+ create(router: RouterContext): void;
32
+ };
@@ -0,0 +1,96 @@
1
+ import { createEffect, on, onCleanup } from "solid-js";
2
+ import { saveCurrentDepth } from "../lifecycle.js";
3
+ import { bindEvent } from "./createRouter.js";
4
+ const STORAGE_KEY = "solid-router:scroll";
5
+ /**
6
+ * Explicit scroll restoration for back/forward navigation. The browser's
7
+ * native same-document heuristic is unreliable for suspense-driven rendering:
8
+ * if the destination route forces a layout while the document is still short,
9
+ * the saved offset for the previous entry is clamped and lost (#577).
10
+ *
11
+ * Positions are captured continuously from the scroll event, keyed by the
12
+ * `_depth` the router already stamps on every history entry — capturing at
13
+ * scroll time (rather than at exit) stays correct through `useBeforeLeave`
14
+ * blocked/reverted traversals. The map persists to sessionStorage on pagehide
15
+ * so restoration survives reloads, which `scrollRestoration = "manual"`
16
+ * otherwise disables.
17
+ *
18
+ * Restoration is a single scroll once routing settles — the same strategy
19
+ * SvelteKit, TanStack Router and React Router use. Settling after the
20
+ * transition commits is what makes the offset reachable; chasing a still-
21
+ * growing document afterwards (a ResizeObserver re-asserting the offset as
22
+ * content arrives) was tried and removed: no peer router does it, an
23
+ * unbounded observer re-clamps the viewport to the bottom when the target is
24
+ * never reachable (a list that is genuinely shorter now), and scroll-induced
25
+ * layout changes can feed it back into itself. Content that commits after the
26
+ * transition settles — an image without reserved space, a boundary below the
27
+ * fold — keeps whatever offset the document can hold.
28
+ */
29
+ export function createScrollRestoration() {
30
+ window.history.scrollRestoration = "manual";
31
+ // the current entry needs its depth stamp for captures to have a key, even
32
+ // if something replaced history.state after the lifecycle module loaded
33
+ saveCurrentDepth();
34
+ let positions = {};
35
+ try {
36
+ positions = JSON.parse(sessionStorage.getItem(STORAGE_KEY)) || {};
37
+ }
38
+ catch { }
39
+ const depth = () => window.history.state && window.history.state._depth;
40
+ let programmatic = false;
41
+ let pending;
42
+ const unbind = [
43
+ bindEvent(window, "scroll", () => {
44
+ const d = depth();
45
+ if (d != null)
46
+ positions[d] = window.scrollY;
47
+ // the user took over — a pending restore would yank them
48
+ if (!programmatic)
49
+ pending = undefined;
50
+ }),
51
+ bindEvent(window, "pagehide", () => {
52
+ try {
53
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify(positions));
54
+ }
55
+ catch { }
56
+ })
57
+ ];
58
+ const restore = () => {
59
+ if (pending == null)
60
+ return;
61
+ const y = positions[pending];
62
+ pending = undefined;
63
+ if (y == null)
64
+ return;
65
+ // flagged so the resulting scroll event is not mistaken for the user
66
+ // taking over (which cancels a pending restore)
67
+ programmatic = true;
68
+ window.scrollTo(0, y);
69
+ programmatic = false;
70
+ };
71
+ return {
72
+ /** Before the router reacts to a popstate: mark the traversal target. */
73
+ onPop() {
74
+ pending = depth();
75
+ },
76
+ /** After a push: forward entries died, and this depth may be reused. */
77
+ onPush() {
78
+ const d = depth();
79
+ if (d != null)
80
+ for (const k in positions)
81
+ +k >= d && delete positions[k];
82
+ },
83
+ create(router) {
84
+ createEffect(on(router.isRouting, routing => routing || restore(), { defer: true }));
85
+ onCleanup(() => unbind.forEach(u => u()));
86
+ // reload/back_forward document loads land on an existing entry; a fresh
87
+ // navigation starts a new one and belongs at the top
88
+ const [nav] = (performance.getEntriesByType &&
89
+ performance.getEntriesByType("navigation"));
90
+ if (nav && nav.type !== "navigate") {
91
+ pending = depth();
92
+ restore();
93
+ }
94
+ }
95
+ };
96
+ }
package/dist/routing.d.ts CHANGED
@@ -1,15 +1,11 @@
1
- import type { JSX } from "@solidjs/web";
2
- import type { Branch, Intent, LazyBoundary, Location, MatchFilters, NavigateOptions, Navigator, Params, RouteDescription, RouteContext, RouteDefinition, RouteMatch, RouterContext, RouterIntegration, SearchParams, SetSearchParams, TypedPath, TypedSearchPath } from "./types.js";
3
- import type { FlashSubmission } from "./data/flash.js";
1
+ import { JSX, Accessor } from "solid-js";
2
+ import type { BeforeLeaveEventArgs, Branch, Intent, Location, MatchFilters, NavigateOptions, Navigator, Params, RouteDescription, RouteContext, RouteDefinition, RouteMatch, RouterContext, RouterIntegration, SearchParams, SetSearchParams } from "./types.js";
4
3
  /** Consider this API opaque and internal. It is likely to change in the future. */
5
- export declare const RouterContextObj: import("solid-js").Context<RouterContext>;
6
- export declare const RouteContextObj: import("solid-js").Context<RouteContext>;
7
- export declare function useOptionalContext<T>(context: {
8
- defaultValue?: T;
9
- }): T | undefined;
4
+ export declare const RouterContextObj: import("solid-js").Context<RouterContext | undefined>;
5
+ export declare const RouteContextObj: import("solid-js").Context<RouteContext | undefined>;
10
6
  export declare const useRouter: () => RouterContext;
11
7
  export declare const useRoute: () => RouteContext;
12
- export declare const useResolvedPath: (path: () => string) => import("solid-js").SourceAccessor<string | undefined>;
8
+ export declare const useResolvedPath: (path: () => string) => Accessor<string | undefined>;
13
9
  export declare const useHref: <T extends string | undefined>(to: () => T) => () => string | T;
14
10
  /**
15
11
  * Retrieves method to do navigation. The method accepts a path to navigate to and an optional object with the following options:
@@ -43,8 +39,8 @@ export declare const useNavigate: () => Navigator;
43
39
  */
44
40
  export declare const useLocation: <S = unknown>() => Location<S>;
45
41
  /**
46
- * Retrieves a signal that indicates whether the router is currently processing a navigation.
47
- * Useful for showing pending navigation state while the next route and its data settle.
42
+ * Retrieves signal that indicates whether the route is currently in a *Transition*.
43
+ * Useful for showing stale/pending state when the route resolution is *Suspended* during concurrent rendering.
48
44
  *
49
45
  * @example
50
46
  * ```js
@@ -59,47 +55,43 @@ export declare const useLocation: <S = unknown>() => Location<S>;
59
55
  */
60
56
  export declare const useIsRouting: () => () => boolean;
61
57
  /**
62
- * `useMatch` takes an accessor that returns the path and creates a `Memo` that returns match information if the current path matches the provided path.
63
- * Useful for determining if a given path matches the current route.
58
+ * usePreloadRoute returns a function that can be used to preload a route manual.
59
+ * This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.
64
60
  *
65
61
  * @example
66
62
  * ```js
67
- * const match = useMatch(() => props.href);
63
+ * const preload = usePreloadRoute();
68
64
  *
69
- * return <div classList={{ active: Boolean(match()) }} />;
65
+ * preload(`/users/settings`, { preloadData: true });
70
66
  * ```
71
67
  */
72
- export declare const useMatch: <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => import("solid-js").SourceAccessor<import("./types.js").PathMatch | undefined>;
68
+ export declare const usePreloadRoute: () => (url: string | URL, options?: {
69
+ preloadData?: boolean;
70
+ }) => void;
73
71
  /**
74
- * `useRouteMatches` returns an accessor of the router's resolved matches for
75
- * the current location — the chain of route definitions producing the current
76
- * render, outermost first. Useful for reading `info` metadata off the matched
77
- * chain. Unlike `useMatch`, which tests a path pattern you supply against the
78
- * location, this reflects the route tree itself.
72
+ * `useMatch` takes an accessor that returns the path and creates a `Memo` that returns match information if the current path matches the provided path.
73
+ * Useful for determining if a given path matches the current route.
79
74
  *
80
75
  * @example
81
76
  * ```js
82
- * const matches = useRouteMatches();
77
+ * const match = useMatch(() => props.href);
83
78
  *
84
- * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb));
79
+ * return <div classList={{ active: Boolean(match()) }} />;
85
80
  * ```
86
81
  */
87
- export declare const useRouteMatches: () => () => RouteMatch[];
82
+ export declare const useMatch: <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => Accessor<import("./types.js").PathMatch | undefined>;
88
83
  /**
89
- * `usePreloadRoute` returns a function for warming a route by hand — the same
90
- * work link hover/focus intent triggers automatically: the matched routes'
91
- * lazy components load, and with `preloadData` their `preload` functions run.
84
+ * `useCurrentMatches` returns all the matches for the current matched route.
85
+ * Useful for getting all the route information.
92
86
  *
93
87
  * @example
94
88
  * ```js
95
- * const preload = usePreloadRoute();
89
+ * const matches = useCurrentMatches();
96
90
  *
97
- * preload(paths.users(2).settings, { preloadData: true });
91
+ * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))
98
92
  * ```
99
93
  */
100
- export declare const usePreloadRoute: () => (url: string | URL | TypedPath, options?: {
101
- preloadData?: boolean;
102
- }) => void;
94
+ export declare const useCurrentMatches: () => () => RouteMatch[];
103
95
  /**
104
96
  * Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
105
97
  *
@@ -108,13 +100,10 @@ export declare const usePreloadRoute: () => (url: string | URL | TypedPath, opti
108
100
  * const params = useParams();
109
101
  *
110
102
  * // fetch user based on the id path parameter
111
- * const getUser = query(() => fetchUser(params.id), "user");
103
+ * const [user] = createResource(() => params.id, fetchUser);
112
104
  * ```
113
105
  */
114
- export declare function useParams<T extends Params>(): T;
115
- export declare function useParams<P extends Params>(path: TypedPath<P>): {
116
- [K in keyof P]: P[K];
117
- };
106
+ export declare const useParams: <T extends Params>() => T;
118
107
  /**
119
108
  * Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them.
120
109
  * The object is a proxy so you must access properties to subscribe to reactive updates.
@@ -142,64 +131,39 @@ export declare function useParams<P extends Params>(path: TypedPath<P>): {
142
131
  * );
143
132
  * ```
144
133
  */
145
- export declare function useSearchParams<In, Out>(path: TypedSearchPath<In, Out>): [Out, (params: Partial<In>, options?: Partial<NavigateOptions>) => void];
146
- export declare function useSearchParams<T extends SearchParams>(): [
147
- Partial<T>,
148
- (params: SetSearchParams, options?: Partial<NavigateOptions>) => void
149
- ];
150
- export interface LinkState {
151
- /** The location matches this link or lives under it (exact-only when `end`). Styling: `data-active`. */
152
- active: () => boolean;
153
- /** The location matches this link exactly — what `aria-current="page"` reflects. */
154
- current: () => boolean;
155
- /** This link is the target of an in-flight navigation. Styling: `data-pending`. */
156
- pending: () => boolean;
157
- }
134
+ export declare const useSearchParams: <T extends SearchParams>() => [Partial<T>, (params: SetSearchParams, options?: Partial<NavigateOptions>) => void];
158
135
  /**
159
- * Reactive link state for custom link components — the programmatic
160
- * counterpart of the attribute vocabulary plain anchors receive
161
- * (`aria-current`, `data-active`, `data-pending`).
136
+ * useBeforeLeave takes a function that will be called prior to leaving a route.
137
+ * The function will be called with:
138
+ *
139
+ * - from (*Location*): current location (before change).
140
+ * - to (*string | number*): path passed to `navigate`.
141
+ * - options (*NavigateOptions*): options passed to navigate.
142
+ * - preventDefault (*function*): call to block the route change.
143
+ * - defaultPrevented (*readonly boolean*): `true` if any previously called leave handlers called `preventDefault`.
144
+ * - retry (*function*, force?: boolean ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (i.e. force navigate without confirming).
162
145
  *
163
146
  * @example
164
- * ```tsx
165
- * function TabLink(props: { href: string; children: JSX.Element }) {
166
- * const link = useLinkState(() => props.href);
167
- * return (
168
- * <a href={props.href} class="tab" data-selected={link.active() || undefined}>
169
- * {props.children}
170
- * </a>
171
- * );
172
- * }
147
+ * ```js
148
+ * useBeforeLeave((e: BeforeLeaveEventArgs) => {
149
+ * if (form.isDirty && !e.defaultPrevented) {
150
+ * // preventDefault to block immediately and prompt user async
151
+ * e.preventDefault();
152
+ * setTimeout(() => {
153
+ * if (window.confirm("Discard unsaved changes - are you sure?")) {
154
+ * // user wants to proceed anyway so retry with force=true
155
+ * e.retry(true);
156
+ * }
157
+ * }, 100);
158
+ * }
159
+ * });
173
160
  * ```
174
161
  */
175
- export declare const useLinkState: (href: () => string | TypedPath, options?: {
176
- end?: boolean;
177
- }) => LinkState;
178
- /** Reactive read of the lazy-subtree version — recompile compiled branches when it changes. */
179
- export declare function trackLazySubtrees(): number;
180
- /** Non-reactive read, for cache-busting outside the reactive graph (server collectors). */
181
- export declare function peekLazySubtrees(): number;
182
- /**
183
- * Kicks (or joins) a boundary's resolution. Returns the resolved routes
184
- * synchronously once available, the in-flight promise otherwise. Commit is
185
- * always async — even for thunks returning arrays — so the version bump
186
- * never writes a signal from inside a render computation.
187
- */
188
- export declare function resolveLazySubtree(record: LazyBoundary): readonly RouteDefinition[] | Promise<readonly RouteDefinition[]>;
189
- /**
190
- * The unresolved boundaries in a match chain. Rendering gates on these (the
191
- * route-states memo suspends until they land — see routers/components.tsx)
192
- * and the server's flight collector awaits them before its preload pass.
193
- */
194
- export declare function unresolvedLazyMatches(matches: RouteMatch[]): LazyBoundary[];
162
+ export declare const useBeforeLeave: (listener: (e: BeforeLeaveEventArgs) => void) => void;
195
163
  export declare function createRoutes(routeDef: RouteDefinition, base?: string): RouteDescription[];
196
164
  export declare function createBranch(routes: RouteDescription[], index?: number): Branch;
197
- export declare function createBranches(routeDef: RouteDefinition | readonly RouteDefinition[], base?: string, stack?: RouteDescription[], branches?: Branch[]): Branch[];
165
+ export declare function createBranches(routeDef: RouteDefinition | RouteDefinition[], base?: string, stack?: RouteDescription[], branches?: Branch[]): Branch[];
198
166
  export declare function getRouteMatches(branches: Branch[], location: string): RouteMatch[];
199
- export declare function mergeParams(matches: RouteMatch[]): Params;
200
- export declare function registerFlightRouter(router: RouterContext): () => void;
201
- export declare function provideFlightConsumer(factory: (router: RouterContext) => () => void): void;
202
- export declare function provideFlashDecoder(decoder: (cookieHeader: string | null) => FlashSubmission | undefined): void;
203
167
  export declare function getIntent(): Intent | undefined;
204
168
  export declare function getInPreloadFn(): boolean;
205
169
  export declare function setInPreloadFn(value: boolean): void;
@@ -208,4 +172,4 @@ export declare function createRouterContext(integration: RouterIntegration, bran
208
172
  singleFlight?: boolean;
209
173
  transformUrl?: (url: string) => string;
210
174
  }): RouterContext;
211
- export declare function createRouteContext(router: RouterContext, parent: RouteContext, outlet: () => JSX.Element, match: () => RouteMatch, matches?: () => RouteMatch[]): RouteContext;
175
+ export declare function createRouteContext(router: RouterContext, parent: RouteContext, outlet: () => JSX.Element, match: () => RouteMatch): RouteContext;