@renr/parcel-rsc-router 0.1.0-alpha.1 → 1.0.0-alpha.3
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/README.md +212 -3
- package/dist/esm/Link.d.ts +2 -4
- package/dist/esm/Link.d.ts.map +1 -1
- package/dist/esm/Link.js +4 -6
- package/dist/esm/Link.js.map +1 -1
- package/dist/esm/Router.d.ts +25 -0
- package/dist/esm/Router.d.ts.map +1 -0
- package/dist/esm/Router.js +88 -0
- package/dist/esm/Router.js.map +1 -0
- package/dist/esm/history.js +42 -0
- package/dist/esm/history.js.map +1 -0
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/rsc.js +1 -3
- package/dist/esm/rsc.js.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +6 -0
package/README.md
CHANGED
|
@@ -1,5 +1,214 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @renr/parcel-rsc-router
|
|
2
2
|
|
|
3
|
-
A router for
|
|
3
|
+
A client-side router designed for React Server Components (RSC) applications built with Parcel's `react-static` packager.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
⚠️ This package is an alpha / work in progress.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Client-side navigation:** Navigate between pages using the `<Link>` component.
|
|
10
|
+
- **Type safety:** Type-safe route definitions via `@renr/parcel-reporter-rsc-router` (the Link's `to` prop is typed).
|
|
11
|
+
- **Programmatic navigation:** Control navigation programmatically using the `useRouter` hook.
|
|
12
|
+
- **Location access:** Access the current URL and its properties with the `useLocation` hook.
|
|
13
|
+
- **Route data access:** Retrieve data associated with the current route using the `useCurrentRoute` hook.
|
|
14
|
+
- **Automatic scroll restoration:** Remembers and restores scroll positions when navigating back and forth.
|
|
15
|
+
- **Hash scrolling:** Automatically scrolls to elements identified by URL hash.
|
|
16
|
+
- **RSC integration:** Navigations fetch the rsc payload for the target route and update the UI without a full page reload.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
For the initial Parcel static RSC site setup see https://parceljs.org/recipes/rsc/#static-rendering, or check out the example app [here](https://github.com/renrizzolo/parcel-rsc-react/tree/main/apps/my-static-site).
|
|
21
|
+
|
|
22
|
+
Install the package using your preferred package manager:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pnpm add @renr/parcel-rsc-router
|
|
26
|
+
# or
|
|
27
|
+
npm install @renr/parcel-rsc-router
|
|
28
|
+
# or
|
|
29
|
+
yarn add @renr/parcel-rsc-router
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Install the required peer dependency:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pnpm add @renr/parcel-reporter-rsc-router
|
|
36
|
+
# or
|
|
37
|
+
npm install @renr/parcel-reporter-rsc-router
|
|
38
|
+
# or
|
|
39
|
+
yarn add @renr/parcel-reporter-rsc-router
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### 1. Wrapping your Application
|
|
45
|
+
|
|
46
|
+
Wrap your main application component with the `RouterProvider` and pass your routes. This component should be a client component.
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
// src/appProvider.tsx (example)
|
|
50
|
+
"use client";
|
|
51
|
+
import { RouterProvider } from "@renr/parcel-rsc-router";
|
|
52
|
+
import { flatRoutes } from "./routes";
|
|
53
|
+
|
|
54
|
+
export function AppProvider({ children }: { children: React.ReactNode }) {
|
|
55
|
+
return <RouterProvider routes={flatRoutes}>{children}</RouterProvider>;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 2. Navigation
|
|
60
|
+
|
|
61
|
+
#### Declarative Navigation with `<Link>`
|
|
62
|
+
|
|
63
|
+
Use the `<Link>` component for client-side navigation. It behaves like a standard `<a>` tag but intercepts clicks to use the router's navigation logic.
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
import { Link } from "@renr/parcel-rsc-router";
|
|
67
|
+
|
|
68
|
+
function NavigationMenu() {
|
|
69
|
+
return (
|
|
70
|
+
<nav>
|
|
71
|
+
<Link to="/">Home</Link>
|
|
72
|
+
<Link to="/about">About</Link>
|
|
73
|
+
<Link to="/blog/first-post" className="nav-item">
|
|
74
|
+
First Blog Post
|
|
75
|
+
</Link>
|
|
76
|
+
<Link to="/contact" hash="form-section">
|
|
77
|
+
Contact (scroll to form)
|
|
78
|
+
</Link>
|
|
79
|
+
<Link to="/products" search={{ category: "electronics" }}>
|
|
80
|
+
Electronics
|
|
81
|
+
</Link>
|
|
82
|
+
</nav>
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
#### Programmatic Navigation with `useRouter`
|
|
88
|
+
|
|
89
|
+
For more complex navigation scenarios, use the `useRouter` hook to get access to the `navigate` function.
|
|
90
|
+
|
|
91
|
+
```tsx
|
|
92
|
+
import { useRouter } from "@renr/parcel-rsc-router";
|
|
93
|
+
|
|
94
|
+
function LoginForm() {
|
|
95
|
+
const { navigate } = useRouter();
|
|
96
|
+
|
|
97
|
+
const handleSubmit = (event: React.FormEvent) => {
|
|
98
|
+
event.preventDefault();
|
|
99
|
+
// ... form submission logic
|
|
100
|
+
navigate("/dashboard"); // Navigate after successful login
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
return (
|
|
104
|
+
<form onSubmit={handleSubmit}>
|
|
105
|
+
{/* ... form fields */}
|
|
106
|
+
<button type="submit">Login</button>
|
|
107
|
+
</form>
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### 4. Accessing Route Information
|
|
113
|
+
|
|
114
|
+
#### `useLocation()`
|
|
115
|
+
|
|
116
|
+
The `useLocation` hook provides access to the browser's `Location` object, giving you details about the current URL.
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
import { useLocation } from "@renr/parcel-rsc-router";
|
|
120
|
+
|
|
121
|
+
function CurrentPathDisplay() {
|
|
122
|
+
const location = useLocation();
|
|
123
|
+
return (
|
|
124
|
+
<div>
|
|
125
|
+
<p>Current Pathname: {location.pathname}</p>
|
|
126
|
+
<p>Current Search Params: {location.search}</p>
|
|
127
|
+
<p>Current Hash: {location.hash}</p>
|
|
128
|
+
</div>
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
#### `useCurrentRoute()`
|
|
134
|
+
|
|
135
|
+
The `useCurrentRoute` hook returns the `RouteData` object for the currently matched route, allowing you to access any custom data associated with it.
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
import { useCurrentRoute } from "@renr/parcel-rsc-router";
|
|
139
|
+
|
|
140
|
+
function PageTitle() {
|
|
141
|
+
const currentRoute = useCurrentRoute();
|
|
142
|
+
const title = currentRoute?.data?.title || "Page Not Found";
|
|
143
|
+
|
|
144
|
+
return <h1>{title}</h1>;
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## API Reference
|
|
149
|
+
|
|
150
|
+
### Components
|
|
151
|
+
|
|
152
|
+
#### `RouterProvider`
|
|
153
|
+
|
|
154
|
+
The main component that provides the routing context to your application.
|
|
155
|
+
|
|
156
|
+
```tsx
|
|
157
|
+
<RouterProvider routes={RouteData[]} children={React.ReactNode} />
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
- `routes`: An array of `RouteData` objects defining your application's routes.
|
|
161
|
+
- `children`: The React nodes to be rendered within the router's context.
|
|
162
|
+
|
|
163
|
+
#### `Link`
|
|
164
|
+
|
|
165
|
+
A component for declarative client-side navigation.
|
|
166
|
+
|
|
167
|
+
```tsx
|
|
168
|
+
<Link
|
|
169
|
+
to={RoutePath}
|
|
170
|
+
hash?: string
|
|
171
|
+
search?: Record<string, string>
|
|
172
|
+
children={React.ReactNode}
|
|
173
|
+
onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void
|
|
174
|
+
target?: HTMLAttributeAnchorTarget
|
|
175
|
+
{...restProps: React.AnchorHTMLAttributes<HTMLAnchorElement>}
|
|
176
|
+
/>
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
- `to`: The target path for the link (e.g., `"/dashboard"`).
|
|
180
|
+
- `hash`: Optional hash segment for the URL (e.g., `"form-section"`).
|
|
181
|
+
- `search`: Optional object of query parameters (e.g., `{ category: "electronics" }`).
|
|
182
|
+
- `children`: The content to render inside the link.
|
|
183
|
+
- `onClick`: Optional click handler.
|
|
184
|
+
- `target`: Standard `target` attribute for `<a>` tags (e.g., `"_blank"`).
|
|
185
|
+
- `{...restProps}`: Any other standard HTML `<a>` tag attributes.
|
|
186
|
+
|
|
187
|
+
### Hooks
|
|
188
|
+
|
|
189
|
+
#### `useRouter()`
|
|
190
|
+
|
|
191
|
+
Returns an object with methods for programmatic navigation.
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
const { navigate } = useRouter();
|
|
195
|
+
navigate(to: string); // Navigates to the specified path.
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
#### `useLocation()`
|
|
199
|
+
|
|
200
|
+
Returns the browser's `Location` object for the current URL.
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
const location: Location = useLocation();
|
|
204
|
+
// location.pathname, location.search, location.hash, etc.
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
#### `useCurrentRoute()`
|
|
208
|
+
|
|
209
|
+
Returns the `RouteData` object for the currently matched route.
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
const currentRoute: RouteData | undefined = useCurrentRoute();
|
|
213
|
+
// currentRoute?.path, currentRoute?.data, etc.
|
|
214
|
+
```
|
package/dist/esm/Link.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RoutePath } from "./types.js";
|
|
2
2
|
import React, { HTMLAttributeAnchorTarget } from "react";
|
|
3
3
|
|
|
4
4
|
//#region src/Link.d.ts
|
|
@@ -6,10 +6,9 @@ declare function Link({
|
|
|
6
6
|
to,
|
|
7
7
|
children,
|
|
8
8
|
hash,
|
|
9
|
-
onClick,
|
|
10
9
|
target,
|
|
11
10
|
search,
|
|
12
|
-
|
|
11
|
+
onClick,
|
|
13
12
|
...props
|
|
14
13
|
}: {
|
|
15
14
|
to: RoutePath;
|
|
@@ -18,7 +17,6 @@ declare function Link({
|
|
|
18
17
|
children: React.ReactNode;
|
|
19
18
|
onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;
|
|
20
19
|
target?: HTMLAttributeAnchorTarget;
|
|
21
|
-
routes: RouteData[];
|
|
22
20
|
} & React.AnchorHTMLAttributes<HTMLAnchorElement>): React.JSX.Element;
|
|
23
21
|
//#endregion
|
|
24
22
|
export { Link };
|
package/dist/esm/Link.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Link.d.ts","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":[],"mappings":";;;;iBAMgB,IAAA
|
|
1
|
+
{"version":3,"file":"Link.d.ts","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":[],"mappings":";;;;iBAMgB,IAAA;;;;;;;;AAKd;MAII;EATU,IAAA,CAAA,EAAI,MAAA;EAClB,MAAA,CAAA,EAUS,MAVT,CAAA,MAAA,EAAA,MAAA,CAAA;EACA,QAAA,EAUU,KAAA,CAAM,SAVhB;EACA,OAAA,CAAA,EAAA,CAAA,CAAA,EAUc,KAAA,CAAM,UAVpB,CAU+B,iBAV/B,CAAA,EAAA,GAAA,IAAA;EACA,MAAA,CAAA,EAUS,yBAVT;CACA,GAUE,KAAA,CAAM,oBAVR,CAU6B,iBAV7B,CAAA,CAAA,EAU+C,KAAA,CAAA,GAAA,CAAA,OAV/C"}
|
package/dist/esm/Link.js
CHANGED
|
@@ -1,22 +1,20 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { useRouter } from "./Router.js";
|
|
5
5
|
import React from "react";
|
|
6
6
|
|
|
7
7
|
//#region src/Link.tsx
|
|
8
|
-
function Link({ to, children, hash,
|
|
8
|
+
function Link({ to, children, hash, target, search, onClick,...props }) {
|
|
9
|
+
const { navigate } = useRouter();
|
|
9
10
|
const href = `${to}${hash ? `#${hash}` : ""}${search ? `?${new URLSearchParams(search)}` : ""}`;
|
|
10
|
-
console.log("Link href", href);
|
|
11
11
|
return /* @__PURE__ */ React.createElement("a", {
|
|
12
12
|
href,
|
|
13
13
|
onClick: (e) => {
|
|
14
14
|
if (onClick) onClick(e);
|
|
15
15
|
if ((!target || target === "_self") && e.button === 0 && !e.metaKey && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.defaultPrevented) {
|
|
16
16
|
e.preventDefault();
|
|
17
|
-
navigate(href
|
|
18
|
-
window.history.pushState(null, "", href);
|
|
19
|
-
});
|
|
17
|
+
navigate(href);
|
|
20
18
|
}
|
|
21
19
|
},
|
|
22
20
|
...props
|
package/dist/esm/Link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Link.js","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport {
|
|
1
|
+
{"version":3,"file":"Link.js","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport { RoutePath } from \"./types.js\";\nimport { useRouter } from \"./Router.js\";\n\nexport function Link({\n to,\n children,\n hash,\n target,\n search,\n onClick,\n ...props\n}: {\n to: RoutePath;\n hash?: string;\n search?: Record<string, string>;\n children: React.ReactNode;\n onClick?: (e: React.MouseEvent<HTMLAnchorElement>) => void;\n target?: HTMLAttributeAnchorTarget;\n} & React.AnchorHTMLAttributes<HTMLAnchorElement>) {\n const { navigate } = useRouter();\n const href = `${to}${hash ? `#${hash}` : \"\"}${search ? `?${new URLSearchParams(search)}` : \"\"}`;\n\n return (\n <a\n href={href}\n onClick={(e) => {\n if (onClick) {\n onClick(e);\n }\n\n if (\n (!target || target === \"_self\") &&\n e.button === 0 && // left clicks only\n !e.metaKey && // open in new tab (mac)\n !e.ctrlKey && // open in new tab (windows)\n !e.altKey && // download\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n // Intercept link clicks to perform RSC navigation.\n e.preventDefault();\n navigate(href);\n }\n }}\n {...props}\n >\n {children}\n </a>\n );\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,KAAK,EACnB,IACA,UACA,MACA,QACA,QACA,QACA,GAAG,SAQ8C;CACjD,MAAM,EAAE,aAAa,WAAW;CAChC,MAAM,OAAO,GAAG,KAAK,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,gBAAgB,OAAO,KAAK;AAE3F,QACE,oCAAC;EACO;EACN,UAAU,MAAM;AACd,OAAI,QACF,SAAQ,EAAE;AAGZ,QACG,CAAC,UAAU,WAAW,YACvB,EAAE,WAAW,KACb,CAAC,EAAE,WACH,CAAC,EAAE,WACH,CAAC,EAAE,UACH,CAAC,EAAE,YACH,CAAC,EAAE,kBACH;AAEA,MAAE,gBAAgB;AAClB,aAAS,KAAK;;;EAGlB,GAAI;IAEH,SACC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { RouteData, RoutePath } from "./types.js";
|
|
2
|
+
import * as React$1 from "react";
|
|
3
|
+
|
|
4
|
+
//#region src/Router.d.ts
|
|
5
|
+
declare function useRouter(): {
|
|
6
|
+
navigate: (to: string) => void;
|
|
7
|
+
};
|
|
8
|
+
declare function useLocation(): Location;
|
|
9
|
+
declare function useCurrentRoute(): {
|
|
10
|
+
rsc: `${string}.rsc`;
|
|
11
|
+
url: string;
|
|
12
|
+
path: RoutePath;
|
|
13
|
+
slug: string;
|
|
14
|
+
html: `${string}.html`;
|
|
15
|
+
} | null;
|
|
16
|
+
declare const RouterProvider: ({
|
|
17
|
+
children,
|
|
18
|
+
routes
|
|
19
|
+
}: {
|
|
20
|
+
children: React$1.ReactNode;
|
|
21
|
+
routes: RouteData[];
|
|
22
|
+
}) => React$1.JSX.Element;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { RouterProvider, useCurrentRoute, useLocation, useRouter };
|
|
25
|
+
//# sourceMappingURL=Router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Router.d.ts","names":[],"sources":["../../src/Router.tsx"],"sourcesContent":[],"mappings":";;;;iBAuBgB,SAAA,CAAA;EAAA,QAAA,EAAA,CAAA,EAAS,EAAA,MAAA,EAAA,GAAA,IAAA;AAUzB,CAAA;AAQgB,iBARA,WAAA,CAAA,CAQe,EARJ,QAQI;AAelB,iBAfG,eAAA,CAAA,CAuGf,EAAA;EAxF8B,GAAA,EAAA,GAAA,MAAA,MAAA;EAAA,GAAA,EAAA,MAAA;EAInB,IAAA,EAnBmB,SAmBb;EACR,IAAA,EAAA,MAAA;EACT,IAAA,EAAA,GAAA,MAAA,OAAA;CAkFA,GAAA,IAAA;cAxFY;;;;YAID,OAAA,CAAM;UACR;MACT,OAAA,CAAA,GAAA,CAAA"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import { createHistory } from "./history.js";
|
|
5
|
+
import { getPathData } from "./util.js";
|
|
6
|
+
import { navigate } from "./rsc.js";
|
|
7
|
+
import * as React$1 from "react";
|
|
8
|
+
import { useSyncExternalStore } from "react";
|
|
9
|
+
|
|
10
|
+
//#region src/Router.tsx
|
|
11
|
+
const RoutesContext = React$1.createContext(null);
|
|
12
|
+
const useRoutes = () => {
|
|
13
|
+
const routes = React$1.useContext(RoutesContext);
|
|
14
|
+
if (routes === null) throw new Error("useRoutes must be used within a RouterProvider");
|
|
15
|
+
return routes;
|
|
16
|
+
};
|
|
17
|
+
const RouterContext = React$1.createContext(null);
|
|
18
|
+
function useRouter() {
|
|
19
|
+
const context = React$1.useContext(RouterContext);
|
|
20
|
+
if (context === null) throw new Error("useRouter must be used within a RouterProvider");
|
|
21
|
+
return context;
|
|
22
|
+
}
|
|
23
|
+
const LocationContext = React$1.createContext(null);
|
|
24
|
+
function useLocation() {
|
|
25
|
+
const context = React$1.useContext(LocationContext);
|
|
26
|
+
if (context === null) throw new Error("useLocation must be used within a RouterProvider");
|
|
27
|
+
return context;
|
|
28
|
+
}
|
|
29
|
+
function useCurrentRoute() {
|
|
30
|
+
const location = useLocation();
|
|
31
|
+
const routes = useRoutes();
|
|
32
|
+
return getPathData(location.pathname, routes);
|
|
33
|
+
}
|
|
34
|
+
const history = createHistory();
|
|
35
|
+
const ssrSnapshot = {
|
|
36
|
+
location: null,
|
|
37
|
+
state: null
|
|
38
|
+
};
|
|
39
|
+
const getSsrSnapshot = () => ssrSnapshot;
|
|
40
|
+
const RouterProvider = ({ children, routes }) => {
|
|
41
|
+
const { location, state } = useSyncExternalStore(history.subscribe, history.getSnapshot, getSsrSnapshot);
|
|
42
|
+
const navigate$1 = React$1.useCallback((to) => {
|
|
43
|
+
var _history$snapshot$sta, _history$snapshot$sta2;
|
|
44
|
+
if (!(location === null || location === void 0 ? void 0 : location.href)) throw new Error("Location is not available");
|
|
45
|
+
if (location.href === new URL(to, location.href).href) return;
|
|
46
|
+
history.replace(location.href, {
|
|
47
|
+
...history.snapshot.state,
|
|
48
|
+
key: (_history$snapshot$sta = (_history$snapshot$sta2 = history.snapshot.state) === null || _history$snapshot$sta2 === void 0 ? void 0 : _history$snapshot$sta2.key) !== null && _history$snapshot$sta !== void 0 ? _history$snapshot$sta : Math.random().toString(36).slice(2),
|
|
49
|
+
scrollX: window.scrollX,
|
|
50
|
+
scrollY: window.scrollY
|
|
51
|
+
});
|
|
52
|
+
navigate(to, routes, (url) => {
|
|
53
|
+
history.push(url, {
|
|
54
|
+
key: Math.random().toString(36).slice(2),
|
|
55
|
+
scrollX: 0,
|
|
56
|
+
scrollY: 0
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}, [routes, location === null || location === void 0 ? void 0 : location.href]);
|
|
60
|
+
const routerContextValue = React$1.useMemo(() => ({ navigate: navigate$1 }), [navigate$1]);
|
|
61
|
+
React$1.useEffect(() => {
|
|
62
|
+
const handlePopState = () => {
|
|
63
|
+
navigate(window.location.pathname, routes, () => {}, { push: false });
|
|
64
|
+
};
|
|
65
|
+
window.addEventListener("popstate", handlePopState);
|
|
66
|
+
return () => window.removeEventListener("popstate", handlePopState);
|
|
67
|
+
}, [routes]);
|
|
68
|
+
React$1.useLayoutEffect(() => {
|
|
69
|
+
if (location === null || location === void 0 ? void 0 : location.hash) {
|
|
70
|
+
const element = document.querySelector(location.hash);
|
|
71
|
+
if (element) {
|
|
72
|
+
element.scrollIntoView();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if ((state === null || state === void 0 ? void 0 : state.scrollY) !== void 0) window.scrollTo(state.scrollX, state.scrollY);
|
|
77
|
+
else window.scrollTo(0, 0);
|
|
78
|
+
}, [
|
|
79
|
+
location === null || location === void 0 ? void 0 : location.pathname,
|
|
80
|
+
location === null || location === void 0 ? void 0 : location.hash,
|
|
81
|
+
state
|
|
82
|
+
]);
|
|
83
|
+
return /* @__PURE__ */ React$1.createElement(RoutesContext.Provider, { value: routes }, /* @__PURE__ */ React$1.createElement(LocationContext.Provider, { value: location }, /* @__PURE__ */ React$1.createElement(RouterContext.Provider, { value: routerContextValue }, children)));
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
//#endregion
|
|
87
|
+
export { RouterProvider, useCurrentRoute, useLocation, useRouter };
|
|
88
|
+
//# sourceMappingURL=Router.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Router.js","names":["React","navigate","rscNavigate"],"sources":["../../src/Router.tsx"],"sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport { useSyncExternalStore } from \"react\";\nimport { createHistory } from \"./history.js\";\nimport { navigate as rscNavigate } from \"./rsc.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\nconst RoutesContext = React.createContext<RouteData[] | null>(null);\n\nexport const useRoutes = () => {\n const routes = React.useContext(RoutesContext);\n if (routes === null) {\n throw new Error(\"useRoutes must be used within a RouterProvider\");\n }\n return routes;\n};\n\nconst RouterContext = React.createContext<{\n navigate: (to: string) => void;\n} | null>(null);\n\nexport function useRouter() {\n const context = React.useContext(RouterContext);\n if (context === null) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n return context;\n}\n\nconst LocationContext = React.createContext<Location | null>(null);\n\nexport function useLocation() {\n const context = React.useContext(LocationContext);\n if (context === null) {\n throw new Error(\"useLocation must be used within a RouterProvider\");\n }\n return context;\n}\n\nexport function useCurrentRoute() {\n const location = useLocation();\n const routes = useRoutes();\n return getPathData(location.pathname, routes);\n}\n\nconst history = createHistory();\n\nconst ssrSnapshot = {\n location: null,\n state: null,\n};\n\nconst getSsrSnapshot = () => ssrSnapshot;\n\nexport const RouterProvider = ({\n children,\n routes,\n}: {\n children: React.ReactNode;\n routes: RouteData[];\n}) => {\n // subscribe to history changes\n const { location, state } = useSyncExternalStore(\n history.subscribe,\n history.getSnapshot,\n getSsrSnapshot\n );\n\n const navigate = React.useCallback(\n (to: string) => {\n if (!location?.href) {\n throw new Error(\"Location is not available\");\n }\n\n if (location.href === new URL(to, location.href).href) {\n return;\n }\n\n // save scroll position for the current entry\n history.replace(location.href, {\n ...history.snapshot.state,\n key: history.snapshot.state?.key ?? Math.random().toString(36).slice(2),\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n });\n\n void rscNavigate(to, routes, (url) => {\n history.push(url, {\n key: Math.random().toString(36).slice(2),\n scrollX: 0,\n scrollY: 0,\n });\n });\n },\n [routes, location?.href]\n );\n\n const routerContextValue = React.useMemo(() => ({ navigate }), [navigate]);\n\n React.useEffect(() => {\n const handlePopState = () => {\n void rscNavigate(\n window.location.pathname,\n routes,\n () => {\n // noop, history is already updated\n },\n { push: false }\n );\n };\n\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [routes]);\n\n React.useLayoutEffect(() => {\n // hash scrolling takes priority\n if (location?.hash) {\n const element = document.querySelector(location.hash);\n if (element) {\n element.scrollIntoView();\n return;\n }\n }\n\n // otherwise use saved scroll position\n if (state?.scrollY !== undefined) {\n window.scrollTo(state.scrollX, state.scrollY);\n } else {\n window.scrollTo(0, 0);\n }\n }, [location?.pathname, location?.hash, state]);\n\n return (\n <RoutesContext.Provider value={routes}>\n <LocationContext.Provider value={location}>\n <RouterContext.Provider value={routerContextValue}>\n {children}\n </RouterContext.Provider>\n </LocationContext.Provider>\n </RoutesContext.Provider>\n );\n};\n"],"mappings":";;;;;;;;;;AASA,MAAM,gBAAgBA,QAAM,cAAkC,KAAK;AAEnE,MAAa,kBAAkB;CAC7B,MAAM,SAASA,QAAM,WAAW,cAAc;AAC9C,KAAI,WAAW,KACb,OAAM,IAAI,MAAM,iDAAiD;AAEnE,QAAO;;AAGT,MAAM,gBAAgBA,QAAM,cAElB,KAAK;AAEf,SAAgB,YAAY;CAC1B,MAAM,UAAUA,QAAM,WAAW,cAAc;AAC/C,KAAI,YAAY,KACd,OAAM,IAAI,MAAM,iDAAiD;AAEnE,QAAO;;AAGT,MAAM,kBAAkBA,QAAM,cAA+B,KAAK;AAElE,SAAgB,cAAc;CAC5B,MAAM,UAAUA,QAAM,WAAW,gBAAgB;AACjD,KAAI,YAAY,KACd,OAAM,IAAI,MAAM,mDAAmD;AAErE,QAAO;;AAGT,SAAgB,kBAAkB;CAChC,MAAM,WAAW,aAAa;CAC9B,MAAM,SAAS,WAAW;AAC1B,QAAO,YAAY,SAAS,UAAU,OAAO;;AAG/C,MAAM,UAAU,eAAe;AAE/B,MAAM,cAAc;CAClB,UAAU;CACV,OAAO;CACR;AAED,MAAM,uBAAuB;AAE7B,MAAa,kBAAkB,EAC7B,UACA,aAII;CAEJ,MAAM,EAAE,UAAU,UAAU,qBAC1B,QAAQ,WACR,QAAQ,aACR,eACD;CAED,MAAMC,aAAWD,QAAM,aACpB,OAAe;;AACd,MAAI,sDAAC,SAAU,MACb,OAAM,IAAI,MAAM,4BAA4B;AAG9C,MAAI,SAAS,SAAS,IAAI,IAAI,IAAI,SAAS,KAAK,CAAC,KAC/C;AAIF,UAAQ,QAAQ,SAAS,MAAM;GAC7B,GAAG,QAAQ,SAAS;GACpB,wDAAK,QAAQ,SAAS,uFAAO,4EAAO,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE;GACvE,SAAS,OAAO;GAChB,SAAS,OAAO;GACjB,CAAC;AAEF,EAAKE,SAAY,IAAI,SAAS,QAAQ;AACpC,WAAQ,KAAK,KAAK;IAChB,KAAK,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE;IACxC,SAAS;IACT,SAAS;IACV,CAAC;IACF;IAEJ,CAAC,4DAAQ,SAAU,KAAK,CACzB;CAED,MAAM,qBAAqBF,QAAM,eAAe,EAAE,sBAAU,GAAG,CAACC,WAAS,CAAC;AAE1E,SAAM,gBAAgB;EACpB,MAAM,uBAAuB;AAC3B,GAAKC,SACH,OAAO,SAAS,UAChB,cACM,IAGN,EAAE,MAAM,OAAO,CAChB;;AAGH,SAAO,iBAAiB,YAAY,eAAe;AACnD,eAAa,OAAO,oBAAoB,YAAY,eAAe;IAClE,CAAC,OAAO,CAAC;AAEZ,SAAM,sBAAsB;AAE1B,0DAAI,SAAU,MAAM;GAClB,MAAM,UAAU,SAAS,cAAc,SAAS,KAAK;AACrD,OAAI,SAAS;AACX,YAAQ,gBAAgB;AACxB;;;AAKJ,qDAAI,MAAO,aAAY,OACrB,QAAO,SAAS,MAAM,SAAS,MAAM,QAAQ;MAE7C,QAAO,SAAS,GAAG,EAAE;IAEtB;sDAAC,SAAU;sDAAU,SAAU;EAAM;EAAM,CAAC;AAE/C,QACE,sCAAC,cAAc,YAAS,OAAO,UAC7B,sCAAC,gBAAgB,YAAS,OAAO,YAC/B,sCAAC,cAAc,YAAS,OAAO,sBAC5B,SACsB,CACA,CACJ"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
//#region src/history.ts
|
|
5
|
+
function createHistory() {
|
|
6
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7
|
+
let currentSnapshot;
|
|
8
|
+
const getSnapshot = () => {
|
|
9
|
+
const newSnapshot = {
|
|
10
|
+
location: window.location,
|
|
11
|
+
state: window.history.state
|
|
12
|
+
};
|
|
13
|
+
if (!currentSnapshot || currentSnapshot.location !== newSnapshot.location || currentSnapshot.state !== newSnapshot.state) currentSnapshot = newSnapshot;
|
|
14
|
+
return currentSnapshot;
|
|
15
|
+
};
|
|
16
|
+
if (typeof window !== "undefined") window.addEventListener("popstate", () => {
|
|
17
|
+
queueMicrotask(() => listeners.forEach((listener) => listener()));
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
get snapshot() {
|
|
21
|
+
return getSnapshot();
|
|
22
|
+
},
|
|
23
|
+
getSnapshot,
|
|
24
|
+
subscribe(listener) {
|
|
25
|
+
listeners.add(listener);
|
|
26
|
+
return () => {
|
|
27
|
+
listeners.delete(listener);
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
push(url, state) {
|
|
31
|
+
window.history.pushState(state, "", url);
|
|
32
|
+
queueMicrotask(() => listeners.forEach((listener) => listener()));
|
|
33
|
+
},
|
|
34
|
+
replace(url, state) {
|
|
35
|
+
window.history.replaceState(state, "", url);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
//#endregion
|
|
41
|
+
export { createHistory };
|
|
42
|
+
//# sourceMappingURL=history.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.js","names":["currentSnapshot: {\n location: Location | null;\n state: HistoryState | null;\n }"],"sources":["../../src/history.ts"],"sourcesContent":["\"use client\";\n\n// basic history management\n\nexport type HistoryState = {\n key: string;\n scrollX: number;\n scrollY: number;\n};\n\nexport function createHistory() {\n const listeners = new Set<() => void>();\n let currentSnapshot: {\n location: Location | null;\n state: HistoryState | null;\n };\n\n const getSnapshot = () => {\n const newSnapshot = {\n location: window.location,\n state: window.history.state as HistoryState | null,\n };\n // Only update currentSnapshot if something actually changed to prevent infinite loops\n if (\n !currentSnapshot ||\n currentSnapshot.location !== newSnapshot.location ||\n currentSnapshot.state !== newSnapshot.state\n ) {\n currentSnapshot = newSnapshot;\n }\n return currentSnapshot;\n };\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"popstate\", () => {\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n });\n }\n\n return {\n get snapshot() {\n return getSnapshot();\n },\n\n getSnapshot,\n\n subscribe(this: void, listener: () => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n\n push(url: string, state: HistoryState) {\n window.history.pushState(state, \"\", url);\n // notify listeners - do it in a microtask to avoid scheduling react updates\n queueMicrotask(() => listeners.forEach((listener) => listener()));\n },\n\n replace(url: string, state: HistoryState) {\n window.history.replaceState(state, \"\", url);\n // don't notify listeners on replace, as it's for non-navigation changes\n },\n };\n}\n\nexport type BrowserHistory = ReturnType<typeof createHistory>;\n"],"mappings":";;;;AAUA,SAAgB,gBAAgB;CAC9B,MAAM,4BAAY,IAAI,KAAiB;CACvC,IAAIA;CAKJ,MAAM,oBAAoB;EACxB,MAAM,cAAc;GAClB,UAAU,OAAO;GACjB,OAAO,OAAO,QAAQ;GACvB;AAED,MACE,CAAC,mBACD,gBAAgB,aAAa,YAAY,YACzC,gBAAgB,UAAU,YAAY,MAEtC,mBAAkB;AAEpB,SAAO;;AAGT,KAAI,OAAO,WAAW,YACpB,QAAO,iBAAiB,kBAAkB;AAExC,uBAAqB,UAAU,SAAS,aAAa,UAAU,CAAC,CAAC;GACjE;AAGJ,QAAO;EACL,IAAI,WAAW;AACb,UAAO,aAAa;;EAGtB;EAEA,UAAsB,UAAsB;AAC1C,aAAU,IAAI,SAAS;AACvB,gBAAa;AACX,cAAU,OAAO,SAAS;;;EAI9B,KAAK,KAAa,OAAqB;AACrC,UAAO,QAAQ,UAAU,OAAO,IAAI,IAAI;AAExC,wBAAqB,UAAU,SAAS,aAAa,UAAU,CAAC,CAAC;;EAGnE,QAAQ,KAAa,OAAqB;AACxC,UAAO,QAAQ,aAAa,OAAO,IAAI,IAAI;;EAG9C"}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import { App, RouteData, RouteNode, RoutePath } from "./types.js";
|
|
2
2
|
import { Link } from "./Link.js";
|
|
3
|
-
|
|
3
|
+
import { RouterProvider, useCurrentRoute, useLocation, useRouter } from "./Router.js";
|
|
4
|
+
export { type App, Link, type RouteData, type RouteNode, type RoutePath, RouterProvider, useCurrentRoute, useLocation, useRouter };
|
package/dist/esm/index.js
CHANGED
package/dist/esm/rsc.js
CHANGED
|
@@ -3,12 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
import { updateRoot } from "./client-entry.js";
|
|
5
5
|
import { getPathData } from "./util.js";
|
|
6
|
-
import { createElement } from "react";
|
|
7
6
|
import { fetchRSC } from "@parcel/rsc/client";
|
|
8
7
|
|
|
9
8
|
//#region src/rsc.ts
|
|
10
9
|
async function navigate(pathname, routes, onPush, { push = true } = {}) {
|
|
11
|
-
console.
|
|
10
|
+
console.debug("client navigating to:", pathname);
|
|
12
11
|
let shouldPush = push;
|
|
13
12
|
const path = getPathData(pathname, routes);
|
|
14
13
|
if (!path) {
|
|
@@ -16,7 +15,6 @@ async function navigate(pathname, routes, onPush, { push = true } = {}) {
|
|
|
16
15
|
if (routes.some((r) => r.path === "/404")) navigate("/404", routes, () => {
|
|
17
16
|
onPush(pathname);
|
|
18
17
|
});
|
|
19
|
-
else updateRoot(createElement("h1", null, "404 Not Found"));
|
|
20
18
|
return;
|
|
21
19
|
}
|
|
22
20
|
if (path.url === location.pathname) shouldPush = false;
|
package/dist/esm/rsc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsc.js","names":[],"sources":["../../src/rsc.ts"],"sourcesContent":["\"use client\";\n\nimport { type RSCRequestInit, fetchRSC } from \"@parcel/rsc/client\";\nimport { type ReactNode
|
|
1
|
+
{"version":3,"file":"rsc.js","names":[],"sources":["../../src/rsc.ts"],"sourcesContent":["\"use client\";\n\nimport { type RSCRequestInit, fetchRSC } from \"@parcel/rsc/client\";\nimport { type ReactNode } from \"react\";\nimport { updateRoot } from \"./client-entry.js\";\nimport { RouteData } from \"./types.js\";\nimport { getPathData } from \"./util.js\";\n\n// fetch and push an rsc route\nexport async function navigate(\n pathname: string,\n routes: RouteData[],\n /** callback for a successful navigation (use this to update the history) */\n onPush: (url: string) => void,\n { push = true }: { push?: boolean } = {}\n) {\n console.debug(\"client navigating to:\", pathname);\n\n let shouldPush = push;\n\n const path = getPathData(pathname, routes);\n\n if (!path) {\n console.warn(`No route found for ${pathname}`);\n\n if (routes.some((r) => r.path === \"/404\")) {\n // we have a 404 page, navigate there\n void navigate(\"/404\", routes, () => {\n // show the original not found path (rather than 404) in the URL\n onPush(pathname);\n });\n }\n\n return;\n }\n\n // Don't add to history if we're already on this page\n if (path.url === location.pathname) {\n shouldPush = false;\n }\n\n try {\n const root = await fetchRSCWithPreloadCache<ReactNode>(path.rsc);\n\n updateRoot(root, () => {\n if (shouldPush) {\n onPush(path.url);\n }\n });\n\n // after a successful navigation, we can clear the cache\n // note everything is static currently, we don't need to clear the cache\n // fetchCache.clear();\n } catch (e) {\n console.log(`Error fetching ${path.path} RSC`, e);\n }\n}\n\nasync function fetchRSCWithPreloadCache<T>(\n url: string | URL | Request,\n options?: RSCRequestInit\n): Promise<T> {\n if (fetchCache.has(url)) {\n console.log(\"Cache hit\", url);\n\n return fetchCache.get(url) as Promise<T>;\n }\n\n const promise = fetchRSC<T>(url, options);\n\n fetchCache.set(url, promise);\n\n // keep the cache small, removing the oldest entries\n while (fetchCache.size > 5) {\n const firstKey = fetchCache.keys().next().value;\n\n if (!firstKey) {\n break;\n }\n\n fetchCache.delete(firstKey);\n }\n\n return promise\n .then((data) => {\n return data;\n })\n .catch((error) => {\n fetchCache.delete(url);\n\n throw error;\n });\n}\n\nexport const fetchCache = new Map<string | URL | Request, Promise<unknown>>();\n\nexport async function prefetch(\n pathname: string,\n routes: RouteData[],\n signal?: AbortSignal\n) {\n const path = getPathData(pathname, routes);\n\n if (!path) {\n return;\n }\n\n try {\n await fetchRSCWithPreloadCache<ReactNode>(path.rsc, { signal });\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error fetching ${pathname} RSC`, error);\n\n return;\n }\n\n // don't throw if the signal is aborted - this is expected\n if (signal?.aborted) {\n console.log(signal.reason);\n\n return;\n }\n }\n}\n"],"mappings":";;;;;;;;AASA,eAAsB,SACpB,UACA,QAEA,QACA,EAAE,OAAO,SAA6B,EAAE,EACxC;AACA,SAAQ,MAAM,yBAAyB,SAAS;CAEhD,IAAI,aAAa;CAEjB,MAAM,OAAO,YAAY,UAAU,OAAO;AAE1C,KAAI,CAAC,MAAM;AACT,UAAQ,KAAK,sBAAsB,WAAW;AAE9C,MAAI,OAAO,MAAM,MAAM,EAAE,SAAS,OAAO,CAEvC,CAAK,SAAS,QAAQ,cAAc;AAElC,UAAO,SAAS;IAChB;AAGJ;;AAIF,KAAI,KAAK,QAAQ,SAAS,SACxB,cAAa;AAGf,KAAI;AAGF,aAFa,MAAM,yBAAoC,KAAK,IAAI,QAEzC;AACrB,OAAI,WACF,QAAO,KAAK,IAAI;IAElB;UAKK,GAAG;AACV,UAAQ,IAAI,kBAAkB,KAAK,KAAK,OAAO,EAAE;;;AAIrD,eAAe,yBACb,KACA,SACY;AACZ,KAAI,WAAW,IAAI,IAAI,EAAE;AACvB,UAAQ,IAAI,aAAa,IAAI;AAE7B,SAAO,WAAW,IAAI,IAAI;;CAG5B,MAAM,UAAU,SAAY,KAAK,QAAQ;AAEzC,YAAW,IAAI,KAAK,QAAQ;AAG5B,QAAO,WAAW,OAAO,GAAG;EAC1B,MAAM,WAAW,WAAW,MAAM,CAAC,MAAM,CAAC;AAE1C,MAAI,CAAC,SACH;AAGF,aAAW,OAAO,SAAS;;AAG7B,QAAO,QACJ,MAAM,SAAS;AACd,SAAO;GACP,CACD,OAAO,UAAU;AAChB,aAAW,OAAO,IAAI;AAEtB,QAAM;GACN;;AAGN,MAAa,6BAAa,IAAI,KAA+C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@renr/parcel-rsc-router",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.0-alpha.3",
|
|
4
4
|
"author": "Ren Rizzolo",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "Parcel rsc router",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
27
|
"react": "^19",
|
|
28
|
-
"@parcel/rsc": "^2"
|
|
28
|
+
"@parcel/rsc": "^2",
|
|
29
|
+
"react-server-dom-parcel": "^19"
|
|
29
30
|
},
|
|
30
31
|
"devDependencies": {
|
|
31
32
|
"react": "^19.2.0",
|