clear-react-router 2.4.1 → 2.4.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 CHANGED
@@ -127,7 +127,9 @@ Component for client-side navigation with prefetch support, active state detecti
127
127
 
128
128
  | Prop | Type | Default | Description |
129
129
  |------|------|---------|-------------|
130
- | `to` | `string` | required | Target path |
130
+ | `to` | `string` | required (unless `path` is set) | Target path as a raw URL. Mutually exclusive with `path` |
131
+ | `path` | `string` (route pattern) | required (unless `to` is set) | Route pattern with `:segments`, e.g. `/product/:productId`. Segments are filled from `params` |
132
+ | `params` | `Record<string, string \| number>` | required if `path` has `:segments` | Values for the pattern segments (URL-encoded). A missing param throws at runtime |
131
133
  | `search` | `string \| Record<string, string \| number \| boolean \| null \| undefined> \| undefined` | `undefined` | Query string or object appended to the target path |
132
134
  | `state` | `unknown` | `undefined` | Arbitrary value attached to the navigation entry |
133
135
  | `as` | `(props: ElementProps<T>, state: { isActive: boolean; isPending: boolean }) => ReactElement` | renders `<a>` | Render function for using a custom element/component instead of the default <a>. Receives the props to spread onto your element (href, ref, event handlers, className, style, children) as the first argument, and `{ isActive, isPending }` as a separate second argument — kept separate so these values are never accidentally forwarded to the DOM |
@@ -232,9 +234,44 @@ import { Button } from '@mui/material';
232
234
  To about page
233
235
  </Link>
234
236
  ```
237
+ ### Styling link states with CSS
238
+
239
+ Before reaching for `as`, check whether CSS is enough: active and loading states are already
240
+ in the DOM — `Link` sets `aria-current="page"` on the active link (plus your `activeClassName`)
241
+ and `aria-busy="true"` while the target is loading. Attribute selectors cover most custom
242
+ designs with zero JS, keeping the native `<a>` semantics (keyboard focus, right-click,
243
+ screen readers) intact:
244
+
245
+ ```tsx
246
+ <Link to="/playground/settings" aria-label="Settings" className="gear-link">
247
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
248
+ <path d="..." />
249
+ </svg>
250
+ </Link>
251
+ ```
252
+
253
+ ```css
254
+ /* Active page — no state plumbing needed */
255
+ .gear-link[aria-current='page'] {
256
+ color: steelblue;
257
+ }
258
+ /* CSS beats SVG presentation attributes (fill="none"), so this fills the icon: */
259
+ .gear-link[aria-current='page'] svg {
260
+ fill: steelblue;
261
+ stroke: steelblue;
262
+ }
263
+ /* Target is loading: */
264
+ .gear-link[aria-busy='true'] {
265
+ opacity: 0.6;
266
+ }
267
+ ```
268
+
269
+ Reach for `as` only when the element itself must change (a `<button>`, a UI-kit component)
270
+ — for looks alone, attributes + CSS are simpler and accessible by default.
271
+
235
272
  ```tsx
236
273
  // Global prefetch: hover with 100ms delay
237
- <Router routes={routes} defaultPrefetchh="hover" defaultHoverPrefetchDelay={100} />
274
+ <Router routes={routes} defaultPrefetch="hover" defaultHoverPrefetchDelay={100} />
238
275
 
239
276
  // Override for a specific link
240
277
  <Link to="/heavy-page" prefetch="viewport">
@@ -578,6 +615,93 @@ const params = useParams<{ userId: string }>();
578
615
  // URL: /user/123 → params.userId === '123'
579
616
  ```
580
617
 
618
+ Pass a path pattern instead of a shape to infer it — no manual type needed:
619
+
620
+ ```tsx
621
+ const { productId } = useParams<'/product/:productId'>();
622
+ // productId: string
623
+ ```
624
+
625
+ ### Typed paths with `path` + `params`
626
+
627
+ `Link` and `useNavigate` accept raw URLs via `to` / `pathname` as usual. For type-checked
628
+ navigation, pass a route pattern via `path` with matching `params` instead — the router
629
+ interpolates the segments (values are URL-encoded, a missing param throws):
630
+
631
+ ```tsx
632
+ <Link path="/product/:productId" params={{ productId: '7' }} />
633
+ navigate({ path: '/product/:productId', params: { productId: '7' } });
634
+ ```
635
+
636
+ Parameter names and presence are checked from the literal itself: a missing `params`
637
+ or a wrong param name is a compile error. `params` values accept `string | number`.
638
+
639
+ Declarative and imperative forms are equivalent — this link:
640
+
641
+ ```tsx
642
+ <Link path="/nest/:nestId/item/:itemId" params={{ nestId, itemId }}>
643
+ {itemId}
644
+ </Link>
645
+ ```
646
+
647
+ does the same as this button:
648
+
649
+ ```tsx
650
+ const navigate = useNavigate();
651
+
652
+ <button onClick={() => navigate({ path: '/nest/:nestId/item/:itemId', params: { nestId, itemId } })}>
653
+ {itemId}
654
+ </button>
655
+ ```
656
+
657
+ Same type-checking, same interpolation. Use links for navigation, buttons with `navigate`
658
+ for actions that end in navigation (submit-then-go, confirm dialogs).
659
+
660
+ The library's part ends here: generic types (`LinkProps<T, TPath>`, `NavigatePathArg`,
661
+ `ParamsFor`) that pick up whatever union you give them. Everything above that is a
662
+ userland pattern — adopt it ladder-style, each rung optional:
663
+
664
+ - **Rung 0 — nothing.** Plain `<Link to="...">` works exactly as before, no unions,
665
+ no imports, no files. Proven by the library's own suite, which has no union anywhere.
666
+ - **Rung 1 — `path` + `params` on plain `Link`.** No union, no wrapper, no setup:
667
+ TypeScript infers the pattern from the `path` literal itself and checks `params`
668
+ against it:
669
+ ```tsx
670
+ <Link path="/product/:productId" params={{ productId: '7' }} /> // ok
671
+ <Link path="/product/:productId" /> // error: params missing
672
+ <Link path="/product/:productId" params={{ id: '7' }} /> // error: wrong param name
673
+ ```
674
+ But path *existence* is unchecked — there is no list to check against, so this
675
+ compiles silently:
676
+ ```tsx
677
+ <Link path="/playgroud/cache" /> // typo, no error (no union knows the routes)
678
+ ```
679
+ In other words: rung 1 checks internal consistency (`path` ↔ `params`), not the
680
+ outside world (path ↔ app routes). That half needs a union — rung 3.
681
+ - **Rung 2 — thin wrapper, no union.** Gives the pattern a name without any type file:
682
+ ```tsx
683
+ import { Link, type LinkProps } from 'clear-react-router';
684
+
685
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T>) => (
686
+ <Link {...props} />
687
+ );
688
+ ```
689
+ - **Rung 3 — wrapper + union.** Binds one union for existence checking:
690
+ ```tsx
691
+ type AppPaths = '/cache' | '/product/:productId';
692
+
693
+ export const AppLink = <T extends HTMLElement = HTMLAnchorElement>(props: LinkProps<T, AppPaths>) => (
694
+ <Link {...props} />
695
+ );
696
+
697
+ <AppLink path="/product/:productId" params={{ productId: '7' }} /> // ok
698
+ <AppLink path="/playgroud/cache" /> // error: not in AppPaths
699
+ ```
700
+
701
+ The union is generated by script or hand-written.
702
+ Keep it next to the routes so drift is visible in review; a forgotten path fails
703
+ compilation at usage (fail-closed), a leftover entry is harmless.
704
+
581
705
  ### `useLocation()`
582
706
 
583
707
  Returns current location `{ pathname, search, state }`.
@@ -1,5 +1,5 @@
1
1
  import { type CSSProperties, ReactNode, MouseEvent, ReactElement, Ref } from 'react';
2
- import { RouterProps, SearchObject } from '../types';
2
+ import { LinkDestination, RouterProps, SearchObject } from '../types';
3
3
  type ElementState = {
4
4
  isActive: boolean;
5
5
  isPending: boolean;
@@ -16,8 +16,7 @@ export type ElementProps<T extends HTMLElement = HTMLElement> = {
16
16
  'aria-current'?: 'page';
17
17
  'aria-busy'?: boolean;
18
18
  } & Record<`data-${string}` | `aria-${string}`, unknown>;
19
- type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
20
- to: string;
19
+ export type LinkProps<T extends HTMLElement = HTMLAnchorElement, TPath extends string = string> = {
21
20
  search?: string | SearchObject;
22
21
  state?: unknown;
23
22
  children?: ReactNode;
@@ -30,6 +29,6 @@ type LinkProps<T extends HTMLElement = HTMLAnchorElement> = {
30
29
  beforeNavigate?(): Promise<void>;
31
30
  style?: CSSProperties | ((arg: ElementState) => CSSProperties);
32
31
  exact?: boolean;
33
- } & Record<`data-${string}` | `aria-${string}`, unknown>;
34
- export declare const Link: <T extends HTMLElement = HTMLAnchorElement>({ children, to, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, ...rest }: LinkProps<T>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
32
+ } & LinkDestination<TPath> & Record<`data-${string}` | `aria-${string}`, unknown>;
33
+ export declare const Link: <T extends HTMLElement = HTMLAnchorElement, const TPath extends string = string>({ children, to, path, params, search, state, as, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact, activeClassName, pendingClassName, ...rest }: LinkProps<T, TPath>) => ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
35
34
  export {};
@@ -1 +1,4 @@
1
- export declare const useNavigate: () => (arg: import("..").NavigationLocation | string | -1) => Promise<void>;
1
+ export declare const useNavigate: () => {
2
+ (arg: import("..").NavigationLocation | string | -1): Promise<void>;
3
+ <const TPath extends string>(arg: import("..").NavigatePathArg<TPath>): Promise<void>;
4
+ };
@@ -1 +1,9 @@
1
- export declare const useParams: <T>() => T;
1
+ import type { ParamsFor } from '../types';
2
+ /**
3
+ * Route params of the current location.
4
+ *
5
+ * - `useParams()` — plain record, convenient but key typos are NOT caught.
6
+ * - `useParams<'/post/:postId'>()` — infers `{ postId: string }` from the pattern; typos are compile errors.
7
+ * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
8
+ */
9
+ export declare const useParams: <T = Record<string, string>>() => T extends string ? ParamsFor<T> : T;
package/dist/index.d.ts CHANGED
@@ -14,5 +14,5 @@ export { useSubmitAction } from './hooks/useSubmitAction';
14
14
  export { useRestoreScroll } from './hooks/useRestoreScroll';
15
15
  export { createRouter } from './creators/createRouter';
16
16
  export { lazy } from './utils/lazy';
17
- export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation, Status } from './types';
18
- export type { ElementProps } from './components/Link';
17
+ export type { RouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, } from './types';
18
+ export type { ElementProps, LinkProps } from './components/Link';
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ var EMPTY_LOADER_STATE = {};
46
46
  var WINDOW_TOP = "__window_top__";
47
47
  var WINDOW_LEFT = "__window_left__";
48
48
  //#endregion
49
- //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
49
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/typeof.js
50
50
  function _typeof(o) {
51
51
  "@babel/helpers - typeof";
52
52
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -56,7 +56,7 @@ function _typeof(o) {
56
56
  }, _typeof(o);
57
57
  }
58
58
  //#endregion
59
- //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
59
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPrimitive.js
60
60
  function toPrimitive(t, r) {
61
61
  if ("object" != _typeof(t) || !t) return t;
62
62
  var e = t[Symbol.toPrimitive];
@@ -68,13 +68,13 @@ function toPrimitive(t, r) {
68
68
  return ("string" === r ? String : Number)(t);
69
69
  }
70
70
  //#endregion
71
- //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
71
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPropertyKey.js
72
72
  function toPropertyKey(t) {
73
73
  var i = toPrimitive(t, "string");
74
74
  return "symbol" == _typeof(i) ? i : i + "";
75
75
  }
76
76
  //#endregion
77
- //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
77
+ //#region \0@oxc-project+runtime@0.152.0/helpers/esm/defineProperty.js
78
78
  function _defineProperty(e, r, t) {
79
79
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
80
80
  value: t,
@@ -188,6 +188,11 @@ var updateScrollMap = (routeDataState, scrollMapState) => {
188
188
  };
189
189
  });
190
190
  };
191
+ var interpolatePath = (pattern, params = {}) => pattern.replace(/:([^/]+)/g, (_, name) => {
192
+ const value = params[name];
193
+ if (value === void 0) throw new Error(`Missing param "${name}" for path "${pattern}"`);
194
+ return encodeURIComponent(String(value));
195
+ });
191
196
  var formatSearchObject = (searchObject) => {
192
197
  const params = new URLSearchParams();
193
198
  Object.entries(searchObject).forEach(([key, value]) => {
@@ -662,12 +667,25 @@ var createRouterInstance = (synchronizer) => {
662
667
  });
663
668
  return;
664
669
  }
665
- const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
666
- await navigate({
667
- ...arg,
668
- search,
669
- prevLocation
670
- });
670
+ if (typeof arg === "object" && arg !== null && "path" in arg && arg.path !== void 0) {
671
+ const { path, params, ...rest } = arg;
672
+ const search = typeof rest.search === "object" ? formatSearchObject(rest.search) : rest.search ?? "";
673
+ await navigate({
674
+ ...rest,
675
+ pathname: interpolatePath(path, params ?? {}),
676
+ search,
677
+ prevLocation
678
+ });
679
+ return;
680
+ }
681
+ if (typeof arg === "object" && arg !== null && !("path" in arg)) {
682
+ const search = typeof arg.search === "object" ? formatSearchObject(arg.search) : arg.search;
683
+ await navigate({
684
+ ...arg,
685
+ search,
686
+ prevLocation
687
+ });
688
+ }
671
689
  },
672
690
  useAction: (action, options = {}) => {
673
691
  return async (input) => {
@@ -873,24 +891,25 @@ var useNavigate = router.hooks.useNavigate;
873
891
  //#region components/Link.tsx
874
892
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
875
893
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
876
- var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
894
+ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
895
+ const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
877
896
  const { useRouteDataSelector } = router.hooks;
878
- const isPending = useRouteDataSelector(({ location: { pathname }, status }) => pathname === to && status === "pending");
897
+ const isPending = useRouteDataSelector(({ location: { pathname: currentPathname }, status }) => currentPathname === pathname && status === "pending");
879
898
  const navigate = useNavigate();
880
- const isActive = useRouteDataSelector(({ location: { pathname } }) => comparator(to, pathname, exact));
899
+ const isActive = useRouteDataSelector(({ location: { pathname: currentPathname } }) => comparator(pathname, currentPathname, exact));
881
900
  const timeout = useRef(0);
882
901
  const elementRef = useRef(null);
883
902
  const getPrefetchStrategy = useCallback(() => linkPrefetch || routerConfig.defaultPrefetch, [linkPrefetch]);
884
903
  const getPrefetchDelay = useCallback(() => hoverPrefetchDelay ?? routerConfig.defaultHoverPrefetchDelay, [hoverPrefetchDelay]);
885
904
  const searchString = typeof search === "object" ? formatSearchObject(search) : search;
886
905
  const location = useMemo(() => ({
887
- pathname: to,
906
+ pathname,
888
907
  search: searchString,
889
908
  state
890
909
  }), [
891
910
  searchString,
892
911
  state,
893
- to
912
+ pathname
894
913
  ]);
895
914
  const onMouseEnter = useCallback(() => {
896
915
  const prefetchDelay = getPrefetchDelay();
@@ -954,7 +973,7 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
954
973
  "style": normalizedStyle,
955
974
  "className": resultClassName,
956
975
  "onClick": clickHandler,
957
- href: `${to}${searchString}`,
976
+ href: `${pathname}${searchString}`,
958
977
  onMouseEnter,
959
978
  onMouseLeave,
960
979
  children,
@@ -968,7 +987,14 @@ var Link = ({ children, to, search = "", state, as = defaultAs, prefetch: linkPr
968
987
  };
969
988
  //#endregion
970
989
  //#region hooks/useParams.ts
971
- var useParams = router.hooks.useParams;
990
+ /**
991
+ * Route params of the current location.
992
+ *
993
+ * - `useParams()` — plain record, convenient but key typos are NOT caught.
994
+ * - `useParams<'/post/:postId'>()` — infers `{ postId: string }` from the pattern; typos are compile errors.
995
+ * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
996
+ */
997
+ var useParams = () => router.hooks.useParams();
972
998
  //#endregion
973
999
  //#region hooks/useLocation.ts
974
1000
  var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
@@ -1071,8 +1097,10 @@ var useSearchParams = () => {
1071
1097
  currentParams.delete(param);
1072
1098
  (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1073
1099
  navigateWithSearchParams(currentParams);
1074
- } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1075
- else throw new Error("useSearchParams first argument must be either function or string");
1100
+ } else if (typeof param === "function") {
1101
+ const newParams = param(currentParams);
1102
+ navigateWithSearchParams(newParams);
1103
+ } else throw new Error("useSearchParams first argument must be either function or string");
1076
1104
  }, [navigateWithSearchParams, searchRef])
1077
1105
  };
1078
1106
  };
package/dist/types.d.ts CHANGED
@@ -139,7 +139,10 @@ export type RouterType = {
139
139
  useContextState(): ReturnType<typeof useGlobalState<Record<string, unknown>>>;
140
140
  useBlockedTargetState(): ReturnType<typeof useGlobalState<Location | null>>;
141
141
  useParams<T>(): T;
142
- useNavigate(): (arg: NavigationLocation | string | -1) => Promise<void>;
142
+ useNavigate(): {
143
+ (arg: NavigationLocation | string | -1): Promise<void>;
144
+ <const TPath extends string>(arg: NavigatePathArg<TPath>): Promise<void>;
145
+ };
143
146
  useAction(action: string, options?: Options): (arg: Record<string, unknown>) => Promise<{
144
147
  data: unknown;
145
148
  error: Error | null;
@@ -168,5 +171,58 @@ export type SearchObject = Record<string, string | number | boolean | null | und
168
171
  export type NavigationLocation = Omit<Location, 'search'> & {
169
172
  search?: string | SearchObject;
170
173
  };
174
+ export type PathParams = Record<string, string | number>;
175
+ export type ParamsFor<TPath extends string> = TPath extends `${string}:${infer Param}/${infer Rest}` ? {
176
+ [K in Param | keyof ParamsFor<Rest> as K & string]: string;
177
+ } : TPath extends `${string}:${infer Param}` ? {
178
+ [K in Param]: string;
179
+ } : Record<string, never>;
180
+ export type ParamsInput<TPath extends string> = {
181
+ [K in keyof ParamsFor<TPath>]: string | number;
182
+ };
183
+ export type HasPathSegments<TPath extends string> = TPath extends `${string}:${string}` ? true : false;
184
+ type StrictLinkDestination<TPath extends string> = TPath extends unknown ? HasPathSegments<TPath> extends true ? {
185
+ to?: never;
186
+ path: TPath;
187
+ params: ParamsInput<TPath>;
188
+ } : {
189
+ to?: never;
190
+ path: TPath;
191
+ params?: never;
192
+ } : never;
193
+ export type LinkDestination<TPath extends string> = {
194
+ to: string;
195
+ path?: never;
196
+ params?: never;
197
+ } | (string extends TPath ? {
198
+ to?: never;
199
+ path: string;
200
+ params?: PathParams;
201
+ } : StrictLinkDestination<TPath>);
202
+ type StrictNavigateArg<TPath extends string> = TPath extends unknown ? HasPathSegments<TPath> extends true ? {
203
+ path: TPath;
204
+ params: ParamsInput<TPath>;
205
+ pathname?: never;
206
+ search?: string | SearchObject;
207
+ state?: unknown;
208
+ } : {
209
+ path: TPath;
210
+ params?: never;
211
+ pathname?: never;
212
+ search?: string | SearchObject;
213
+ state?: unknown;
214
+ } : never;
215
+ export type NavigatePathArg<TPath extends string> = string extends TPath ? {
216
+ path: string;
217
+ params?: PathParams;
218
+ search?: string | SearchObject;
219
+ state?: unknown;
220
+ } : StrictNavigateArg<TPath>;
221
+ export type NavigatePathInput = {
222
+ path: string;
223
+ params?: PathParams;
224
+ search?: string | SearchObject;
225
+ state?: unknown;
226
+ };
171
227
  export type Synchronizer = <T>(subscribe: (updater: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
172
228
  export {};
@@ -14,4 +14,5 @@ export declare const getPartialLoaderArgs: (contextState: RouterState["contextSt
14
14
  };
15
15
  export declare const isVerticalScroll: (el: Element | null) => boolean;
16
16
  export declare const updateScrollMap: (routeDataState: Store<RouteData>, scrollMapState: Store<ScrollMap>) => void;
17
+ export declare const interpolatePath: (pattern: string, params?: Record<string, string | number>) => string;
17
18
  export declare const formatSearchObject: (searchObject: SearchObject) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.1",
3
+ "version": "2.4.3",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {