@renr/parcel-rsc-router 0.1.0-alpha.1 → 1.0.0-alpha.2

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.
@@ -1,4 +1,4 @@
1
- import { RouteData, RoutePath } from "./types.js";
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
- routes,
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 };
@@ -1 +1 @@
1
- {"version":3,"file":"Link.d.ts","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":[],"mappings":";;;;iBAMgB,IAAA;;;;;;;;;AAMd;MAII;EAVU,IAAA,CAAA,EAAI,MAAA;EAClB,MAAA,CAAA,EAWS,MAXT,CAAA,MAAA,EAAA,MAAA,CAAA;EACA,QAAA,EAWU,KAAA,CAAM,SAXhB;EACA,OAAA,CAAA,EAAA,CAAA,CAAA,EAWc,KAAA,CAAM,UAXpB,CAW+B,iBAX/B,CAAA,EAAA,GAAA,IAAA;EACA,MAAA,CAAA,EAWS,yBAXT;EACA,MAAA,EAYQ,SAZR,EAAA;CACA,GAYE,KAAA,CAAM,oBAZR,CAY6B,iBAZ7B,CAAA,CAAA,EAY+C,KAAA,CAAA,GAAA,CAAA,OAZ/C"}
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 { navigate } from "./rsc.js";
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, onClick, target, search, routes,...props }) {
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, routes, () => {
18
- window.history.pushState(null, "", href);
19
- });
17
+ navigate(href);
20
18
  }
21
19
  },
22
20
  ...props
@@ -1 +1 @@
1
- {"version":3,"file":"Link.js","names":[],"sources":["../../src/Link.tsx"],"sourcesContent":["\"use client\";\n\nimport React, { type HTMLAttributeAnchorTarget } from \"react\";\nimport { RouteData, RoutePath } from \"./types.js\";\nimport { navigate } from \"./rsc.js\";\n\nexport function Link({\n to,\n children,\n hash,\n onClick,\n target,\n search,\n routes,\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 // TODO we will get routes from context, but for now we pass it in\n routes: RouteData[];\n} & React.AnchorHTMLAttributes<HTMLAnchorElement>) {\n const href = `${to}${hash ? `#${hash}` : \"\"}${search ? `?${new URLSearchParams(search)}` : \"\"}`;\n console.log(\"Link href\", href);\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\n void navigate(href, routes, () => {\n // add to history on a successful navigation\n window.history.pushState(null, \"\", href);\n });\n }\n }}\n {...props}\n >\n {children}\n </a>\n );\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,KAAK,EACnB,IACA,UACA,MACA,SACA,QACA,QACA,OACA,GAAG,SAU8C;CACjD,MAAM,OAAO,GAAG,KAAK,OAAO,IAAI,SAAS,KAAK,SAAS,IAAI,IAAI,gBAAgB,OAAO,KAAK;AAC3F,SAAQ,IAAI,aAAa,KAAK;AAC9B,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;AAElB,IAAK,SAAS,MAAM,cAAc;AAEhC,YAAO,QAAQ,UAAU,MAAM,IAAI,KAAK;MACxC;;;EAGN,GAAI;IAEH,SACC"}
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"}
@@ -1,3 +1,4 @@
1
1
  import { App, RouteData, RouteNode, RoutePath } from "./types.js";
2
2
  import { Link } from "./Link.js";
3
- export { type App, Link, type RouteData, type RouteNode, type RoutePath };
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
@@ -1,3 +1,4 @@
1
+ import { RouterProvider, useCurrentRoute, useLocation, useRouter } from "./Router.js";
1
2
  import { Link } from "./Link.js";
2
3
 
3
- export { Link };
4
+ export { Link, RouterProvider, useCurrentRoute, useLocation, useRouter };
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.log("client navigating to:", pathname);
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;
@@ -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, createElement } from \"react\";\nimport { updateRoot } from \"./client-entry.js\";\nimport { getPathData } from \"./util.js\";\nimport { RouteData } from \"./types.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.log(\"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 } else {\n // render a fallback 404\n updateRoot(createElement(\"h1\", null, \"404 Not Found\"));\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,IAAI,yBAAyB,SAAS;CAE9C,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;MAGF,YAAW,cAAc,MAAM,MAAM,gBAAgB,CAAC;AAExD;;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"}
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": "0.1.0-alpha.1",
3
+ "version": "1.0.0-alpha.2",
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",
package/src/index.ts CHANGED
@@ -1,2 +1,8 @@
1
1
  export type { RouteNode, RouteData, RoutePath, App } from "./types.js";
2
2
  export { Link } from "./Link.js";
3
+ export {
4
+ RouterProvider,
5
+ useRouter,
6
+ useLocation,
7
+ useCurrentRoute,
8
+ } from "./Router.js";