@solidjs/router 0.17.0-next.6 → 1.0.0-next.8

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 (48) hide show
  1. package/README.md +526 -716
  2. package/dist/claims.d.ts +21 -0
  3. package/dist/claims.js +115 -0
  4. package/dist/data/action.d.ts +15 -0
  5. package/dist/data/action.js +127 -12
  6. package/dist/data/events.d.ts +8 -0
  7. package/dist/data/events.js +23 -22
  8. package/dist/data/flash.d.ts +1 -5
  9. package/dist/data/flash.js +10 -18
  10. package/dist/data/flashCookie.d.ts +7 -0
  11. package/dist/data/flashCookie.js +20 -0
  12. package/dist/data/serverForms.d.ts +1 -0
  13. package/dist/data/serverForms.js +5 -0
  14. package/dist/index.d.ts +5 -3
  15. package/dist/index.js +1736 -1157
  16. package/dist/index.jsx +2 -2
  17. package/dist/lifecycle.d.ts +29 -4
  18. package/dist/lifecycle.js +40 -37
  19. package/dist/paths.d.ts +117 -0
  20. package/dist/paths.js +41 -0
  21. package/dist/routers/components.d.ts +10 -21
  22. package/dist/routers/components.jsx +29 -51
  23. package/dist/routers/factory.d.ts +45 -0
  24. package/dist/routers/factory.jsx +143 -0
  25. package/dist/routers/history.d.ts +24 -0
  26. package/dist/routers/history.js +180 -0
  27. package/dist/routers/index.d.ts +4 -11
  28. package/dist/routers/index.js +2 -6
  29. package/dist/routing.d.ts +79 -52
  30. package/dist/routing.js +296 -127
  31. package/dist/server.d.ts +25 -15
  32. package/dist/server.js +43 -7
  33. package/dist/types.d.ts +74 -5
  34. package/dist/utils.d.ts +2 -0
  35. package/dist/utils.js +2 -0
  36. package/package.json +6 -6
  37. package/dist/components.d.ts +0 -31
  38. package/dist/components.jsx +0 -46
  39. package/dist/routers/HashRouter.d.ts +0 -9
  40. package/dist/routers/HashRouter.js +0 -41
  41. package/dist/routers/MemoryRouter.d.ts +0 -24
  42. package/dist/routers/MemoryRouter.js +0 -57
  43. package/dist/routers/Router.d.ts +0 -9
  44. package/dist/routers/Router.js +0 -45
  45. package/dist/routers/StaticRouter.d.ts +0 -6
  46. package/dist/routers/StaticRouter.js +0 -15
  47. package/dist/routers/createRouter.d.ts +0 -10
  48. package/dist/routers/createRouter.js +0 -40
@@ -0,0 +1,24 @@
1
+ import type { LocationChange, RouterUtils } from "../types.js";
2
+ /**
3
+ * A history adapter: the source of truth for the current URL and how
4
+ * navigations write back to it. Adapters are plain imported values so
5
+ * unused ones never enter the bundle — `createRouter` defaults to browser
6
+ * history on the client and the request URL on the server.
7
+ */
8
+ export interface RouterHistory {
9
+ get: () => string | LocationChange;
10
+ set: (next: LocationChange) => void;
11
+ init?: (notify: (value?: string | LocationChange) => void) => () => void;
12
+ utils?: Partial<RouterUtils>;
13
+ }
14
+ export declare function browserHistory(): RouterHistory;
15
+ export declare function hashParser(str: string): string;
16
+ export declare function hashHistory(): RouterHistory;
17
+ export interface MemoryHistoryAdapter extends RouterHistory {
18
+ get: () => string;
19
+ go: (delta: number) => void;
20
+ back: () => void;
21
+ forward: () => void;
22
+ listen: (listener: (value: string) => void) => () => void;
23
+ }
24
+ export declare function memoryHistory(initial?: string): MemoryHistoryAdapter;
@@ -0,0 +1,180 @@
1
+ import { isServer } from "@solidjs/web";
2
+ function bindEvent(target, type, handler) {
3
+ target.addEventListener(type, handler);
4
+ return () => target.removeEventListener(type, handler);
5
+ }
6
+ // Depth stamping supports blocking browser-initiated navigation (back/forward)
7
+ // for `useBeforeLeave`. It stays always-on — a couple of history.state writes —
8
+ // so blocking stays exact no matter when the first guard subscribes, while the
9
+ // guard machinery itself lives behind the lazy `beforeLeave` slot.
10
+ let depth;
11
+ function saveCurrentDepth() {
12
+ if (!window.history.state || window.history.state._depth == null) {
13
+ window.history.replaceState({ ...window.history.state, _depth: window.history.length - 1 }, "");
14
+ }
15
+ depth = window.history.state._depth;
16
+ }
17
+ function keepDepth(state) {
18
+ return {
19
+ ...state,
20
+ _depth: window.history.state && window.history.state._depth
21
+ };
22
+ }
23
+ function notifyIfNotBlocked(notify, block) {
24
+ let ignore = false;
25
+ return () => {
26
+ const prevDepth = depth;
27
+ saveCurrentDepth();
28
+ const delta = prevDepth == null ? null : depth - prevDepth;
29
+ if (ignore) {
30
+ ignore = false;
31
+ return;
32
+ }
33
+ if (delta && block(delta)) {
34
+ ignore = true;
35
+ window.history.go(-delta);
36
+ }
37
+ else {
38
+ notify();
39
+ }
40
+ };
41
+ }
42
+ function scrollToHash(hash, fallbackTop) {
43
+ const el = hash && document.getElementById(hash);
44
+ if (el) {
45
+ el.scrollIntoView();
46
+ }
47
+ else if (fallbackTop) {
48
+ window.scrollTo(0, 0);
49
+ }
50
+ }
51
+ export function browserHistory() {
52
+ const getSource = () => {
53
+ const url = window.location.pathname + window.location.search;
54
+ const state = window.history.state &&
55
+ window.history.state._depth &&
56
+ Object.keys(window.history.state).length === 1
57
+ ? undefined
58
+ : window.history.state;
59
+ return {
60
+ value: url + window.location.hash,
61
+ state
62
+ };
63
+ };
64
+ const beforeLeave = {};
65
+ if (!isServer)
66
+ saveCurrentDepth();
67
+ return {
68
+ get: getSource,
69
+ set({ value, replace, scroll, state }) {
70
+ if (replace) {
71
+ window.history.replaceState(keepDepth(state), "", value);
72
+ }
73
+ else {
74
+ window.history.pushState(state, "", value);
75
+ }
76
+ scrollToHash(decodeURIComponent(window.location.hash.slice(1)), scroll);
77
+ saveCurrentDepth();
78
+ },
79
+ init: notify => bindEvent(window, "popstate", notifyIfNotBlocked(notify, delta => {
80
+ const guard = beforeLeave.current;
81
+ if (!guard)
82
+ return false;
83
+ if (delta) {
84
+ return !guard.confirm(delta);
85
+ }
86
+ else {
87
+ const s = getSource();
88
+ return !guard.confirm(s.value, { state: s.state });
89
+ }
90
+ })),
91
+ utils: {
92
+ go: delta => window.history.go(delta),
93
+ beforeLeave
94
+ }
95
+ };
96
+ }
97
+ export function hashParser(str) {
98
+ const to = str.replace(/^.*?#/, "");
99
+ // Hash-only hrefs like `#foo` from plain anchors will come in as `/#foo` whereas a link to
100
+ // `/foo` will be `/#/foo`. Check if the to starts with a `/` and if not append it as a hash
101
+ // to the current path so we can handle these in-page anchors correctly.
102
+ if (!to.startsWith("/")) {
103
+ const [, path = "/"] = window.location.hash.split("#", 2);
104
+ return `${path}#${to}`;
105
+ }
106
+ return to;
107
+ }
108
+ export function hashHistory() {
109
+ const getSource = () => window.location.hash.slice(1);
110
+ const beforeLeave = {};
111
+ if (!isServer)
112
+ saveCurrentDepth();
113
+ return {
114
+ get: getSource,
115
+ set({ value, replace, scroll, state }) {
116
+ if (replace) {
117
+ window.history.replaceState(keepDepth(state), "", "#" + value);
118
+ }
119
+ else {
120
+ window.history.pushState(state, "", "#" + value);
121
+ }
122
+ const hashIndex = value.indexOf("#");
123
+ const hash = hashIndex >= 0 ? value.slice(hashIndex + 1) : "";
124
+ scrollToHash(hash, scroll);
125
+ saveCurrentDepth();
126
+ },
127
+ init: notify => bindEvent(window, "hashchange", notifyIfNotBlocked(notify, delta => {
128
+ const guard = beforeLeave.current;
129
+ return !!guard && !guard.confirm(delta && delta < 0 ? delta : getSource());
130
+ })),
131
+ utils: {
132
+ go: delta => window.history.go(delta),
133
+ renderPath: path => `#${path}`,
134
+ parsePath: hashParser,
135
+ beforeLeave
136
+ }
137
+ };
138
+ }
139
+ export function memoryHistory(initial = "/") {
140
+ const entries = [initial];
141
+ let index = 0;
142
+ const listeners = [];
143
+ const go = (n) => {
144
+ // https://github.com/remix-run/react-router/blob/682810ca929d0e3c64a76f8d6e465196b7a2ac58/packages/router/history.ts#L245
145
+ index = Math.max(0, Math.min(index + n, entries.length - 1));
146
+ const value = entries[index];
147
+ listeners.forEach(listener => listener(value));
148
+ };
149
+ const listen = (listener) => {
150
+ listeners.push(listener);
151
+ return () => {
152
+ const i = listeners.indexOf(listener);
153
+ listeners.splice(i, 1);
154
+ };
155
+ };
156
+ return {
157
+ get: () => entries[index],
158
+ set: ({ value, scroll, replace }) => {
159
+ if (replace) {
160
+ entries[index] = value;
161
+ }
162
+ else {
163
+ entries.splice(index + 1, entries.length - index, value);
164
+ index++;
165
+ }
166
+ listeners.forEach(listener => listener(value));
167
+ setTimeout(() => {
168
+ if (scroll) {
169
+ scrollToHash(value.split("#")[1] || "", true);
170
+ }
171
+ }, 0);
172
+ },
173
+ back: () => go(-1),
174
+ forward: () => go(1),
175
+ go,
176
+ listen,
177
+ init: listen,
178
+ utils: { go }
179
+ };
180
+ }
@@ -1,11 +1,4 @@
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
+ 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,6 +1,2 @@
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";
1
+ export { createRouter, defineRoutes } from "./factory.jsx";
2
+ export { browserHistory, hashHistory, memoryHistory } from "./history.js";
package/dist/routing.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import type { JSX } from "@solidjs/web";
2
- import type { BeforeLeaveEventArgs, Branch, Intent, Location, MatchFilters, NavigateOptions, Navigator, Params, RouteDescription, RouteContext, RouteDefinition, RouteMatch, RouterContext, RouterIntegration, SearchParams, SetSearchParams } from "./types.js";
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";
3
4
  /** Consider this API opaque and internal. It is likely to change in the future. */
4
5
  export declare const RouterContextObj: import("solid-js").Context<RouterContext>;
5
6
  export declare const RouteContextObj: import("solid-js").Context<RouteContext>;
7
+ export declare function useOptionalContext<T>(context: {
8
+ defaultValue?: T;
9
+ }): T | undefined;
6
10
  export declare const useRouter: () => RouterContext;
7
11
  export declare const useRoute: () => RouteContext;
8
12
  export declare const useResolvedPath: (path: () => string) => import("solid-js").SourceAccessor<string | undefined>;
@@ -55,43 +59,47 @@ export declare const useLocation: <S = unknown>() => Location<S>;
55
59
  */
56
60
  export declare const useIsRouting: () => () => boolean;
57
61
  /**
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.
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.
60
64
  *
61
65
  * @example
62
66
  * ```js
63
- * const preload = usePreloadRoute();
67
+ * const match = useMatch(() => props.href);
64
68
  *
65
- * preload(`/users/settings`, { preloadData: true });
69
+ * return <div classList={{ active: Boolean(match()) }} />;
66
70
  * ```
67
71
  */
68
- export declare const usePreloadRoute: () => (url: string | URL, options?: {
69
- preloadData?: boolean;
70
- }) => void;
72
+ export declare const useMatch: <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => import("solid-js").SourceAccessor<import("./types.js").PathMatch | undefined>;
71
73
  /**
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.
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.
74
79
  *
75
80
  * @example
76
81
  * ```js
77
- * const match = useMatch(() => props.href);
82
+ * const matches = useRouteMatches();
78
83
  *
79
- * return <div classList={{ active: Boolean(match()) }} />;
84
+ * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb));
80
85
  * ```
81
86
  */
82
- export declare const useMatch: <S extends string>(path: () => S, matchFilters?: MatchFilters<S>) => import("solid-js").SourceAccessor<import("./types.js").PathMatch | undefined>;
87
+ export declare const useRouteMatches: () => () => RouteMatch[];
83
88
  /**
84
- * `useCurrentMatches` returns all the matches for the current matched route.
85
- * Useful for getting all the route information.
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.
86
92
  *
87
93
  * @example
88
94
  * ```js
89
- * const matches = useCurrentMatches();
95
+ * const preload = usePreloadRoute();
90
96
  *
91
- * const breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))
97
+ * preload(paths.users(2).settings, { preloadData: true });
92
98
  * ```
93
99
  */
94
- export declare const useCurrentMatches: () => () => RouteMatch[];
100
+ export declare const usePreloadRoute: () => (url: string | URL | TypedPath, options?: {
101
+ preloadData?: boolean;
102
+ }) => void;
95
103
  /**
96
104
  * Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
97
105
  *
@@ -103,7 +111,10 @@ export declare const useCurrentMatches: () => () => RouteMatch[];
103
111
  * const getUser = query(() => fetchUser(params.id), "user");
104
112
  * ```
105
113
  */
106
- export declare const useParams: <T extends Params>() => T;
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
+ };
107
118
  /**
108
119
  * Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them.
109
120
  * The object is a proxy so you must access properties to subscribe to reactive updates.
@@ -131,48 +142,64 @@ export declare const useParams: <T extends Params>() => T;
131
142
  * );
132
143
  * ```
133
144
  */
134
- export declare const useSearchParams: <T extends SearchParams>() => [Partial<T>, (params: SetSearchParams, options?: Partial<NavigateOptions>) => void];
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
+ }
135
158
  /**
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).
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`).
145
162
  *
146
163
  * @example
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
- * });
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
+ * }
160
173
  * ```
161
174
  */
162
- export declare const useBeforeLeave: (listener: (e: BeforeLeaveEventArgs) => void) => void;
163
- export declare function createRoutes(routeDef: RouteDefinition, base?: string): RouteDescription[];
164
- export declare function createBranch(routes: RouteDescription[], index?: number): Branch;
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[]>;
165
189
  /**
166
- * Resolves the route tree an app hands the router — JSX `<Route>` children
167
- * (`Route` is a data-holder component, evaluating to its merged props),
168
- * config objects, arrays, or thunks producing either — into route
169
- * definitions. Shared by the `<Router>` component (which keeps the
170
- * resolution live) and the server integration's preload runner (one-shot).
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.
171
193
  */
172
- export declare function resolveRouteDefinitions(routes: JSX.Element | RouteDefinition | RouteDefinition[]): () => RouteDefinition | RouteDefinition[];
173
- export declare function createBranches(routeDef: RouteDefinition | RouteDefinition[], base?: string, stack?: RouteDescription[], branches?: Branch[]): Branch[];
194
+ export declare function unresolvedLazyMatches(matches: RouteMatch[]): LazyBoundary[];
195
+ export declare function createRoutes(routeDef: RouteDefinition, base?: string): RouteDescription[];
196
+ 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[];
174
198
  export declare function getRouteMatches(branches: Branch[], location: string): RouteMatch[];
175
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;
176
203
  export declare function getIntent(): Intent | undefined;
177
204
  export declare function getInPreloadFn(): boolean;
178
205
  export declare function setInPreloadFn(value: boolean): void;