@argon-router/react 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("react"),r=require("effector-react"),o=t.createContext(null);function n(){const e=t.useContext(o);if(!e)throw new Error("[useRouter] Router not found. Add RouterProvider in app root");return e}const u=t.forwardRef((t,o)=>{const{to:u,params:s,onClick:i,...a}=t,{mappedRoutes:c}=n(),l=c.find(({route:e})=>e===u),{onOpen:p}=r.useUnit(u);if(!l)throw new Error(`[Link] Route with path "${u.path}" not found. Maybe it is not passed into createRouter?`);return e.jsx("a",{...a,ref:o,href:l.build(s??void 0),onClick:e=>{null==i||i(e),e.defaultPrevented||a.target&&"_self"!==a.target||e.metaKey||e.altKey||e.ctrlKey||e.shiftKey||(e.preventDefault(),p({params:s||{}}))}})});exports.Link=u,exports.RouterProvider=t=>e.jsx(o.Provider,{value:t.router,children:t.children}),exports.createLazyRouteView=function(r){r.route.internal.setAsyncImport(r.view);const o=t.lazy(r.view),{layout:n,fallback:u=()=>e.jsx(e.Fragment,{})}=r,s=n?()=>e.jsx(n,{children:e.jsx(t.Suspense,{fallback:e.jsx(u,{}),children:e.jsx(o,{})})}):()=>e.jsx(t.Suspense,{fallback:e.jsx(u,{}),children:e.jsx(o,{})});return{route:r.route,view:s}},exports.createRouteView=function(t){const{layout:r,view:o}=t,n=r?()=>e.jsx(r,{children:e.jsx(o,{})}):()=>e.jsx(o,{});return{route:t.route,view:n}},exports.createRoutesView=o=>{const{routes:n,otherwise:u}=o;return()=>{const o=r.useUnit(n.map(e=>e.route.$isOpened)),s=t.useMemo(()=>{const e=n.filter((e,t)=>o[t]);return e.reduce((e,t)=>e.filter(e=>e.route!==t.route.parent),e)},[o]).at(-1);return s?t.createElement(s.view):u?e.jsx(u,{}):null}},exports.useRouter=function(){return r.useUnit(n())},exports.useRouterContext=n,exports.withLayout=function(r,o){const n=r;return o.map(({route:r,view:o})=>({route:r,view:()=>e.jsx(n,{children:t.createElement(o)})}))};
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),t=require("react"),r=require("effector-react"),n=require("@argon-router/core"),o=require("effector"),u=t.createContext(null),s=t.createContext(null);function i(){const e=t.useContext(u);if(!e)throw new Error("[useRouter] Router not found. Add RouterProvider in app root");return e}function c(e,t){const{knownRoutes:n}=i(),o=n.find(({route:t})=>t===e),{onOpen:u}=r.useUnit(e);if(!o)throw new Error(`[useLink] Route "${e}" not found. Maybe it is not passed into createRouter?`);return{path:o.build(t??void 0),onOpen:u}}const a=t.forwardRef((t,r)=>{const{to:n,params:o,onClick:u,replace:s,query:i,...a}=t,{path:l,onOpen:p}=c(n,o);return e.jsx("a",{...a,ref:r,href:l,onClick:e=>{null==u||u(e),e.defaultPrevented||a.target&&"_self"!==a.target||e.metaKey||e.altKey||e.ctrlKey||e.shiftKey||(e.preventDefault(),p({params:o||{},replace:s,query:i}))}})});function l(e,t){return t?t.getState(e):e.getState()}function p(e){const u=r.useProvidedScope(),[s,i]=t.useState(function(e,t){return e.map(e=>n.is.router(e.route)?l(e.route.$activeRoutes,t).length>0:l(e.route.$isOpened,t))}(e,u));return t.useEffect(()=>{const t=[];for(const[r,s]of e.entries())if(n.is.router(s.route)){const e=s.route,n=o.createWatch({unit:e.$activeRoutes,scope:u??void 0,fn:e=>{i(t=>{const n=[...t];return n[r]=e.length>0,n})}});t.push(n)}else t.push(o.createWatch({unit:s.route.$isOpened,scope:u??void 0,fn:e=>{i(t=>{const n=[...t];return n[r]=e,n})}}));return()=>{for(const e of t)e.unsubscribe()}},[e,u]),t.useMemo(()=>{const t=e.filter((e,t)=>s[t]);return t.reduce((e,t)=>e.filter(e=>e.route!==t.route.parent),t)},[e,s])}exports.Link=a,exports.Outlet=()=>{const{children:e}=t.useContext(s)??{children:[]},r=p(e).at(-1);return r?t.createElement(r.view):null},exports.RouterProvider=t=>e.jsx(u.Provider,{value:t.router,children:t.children}),exports.createLazyRouteView=function(r){r.route.internal.setAsyncImport(r.view);const n=t.lazy(r.view),{layout:o,fallback:u=()=>e.jsx(e.Fragment,{})}=r,s=o?()=>e.jsx(o,{children:e.jsx(t.Suspense,{fallback:e.jsx(u,{}),children:e.jsx(n,{})})}):()=>e.jsx(t.Suspense,{fallback:e.jsx(u,{}),children:e.jsx(n,{})});return{route:r.route,view:s}},exports.createRouteView=function(t){const{layout:r,view:n}=t,o=r?()=>e.jsx(r,{children:e.jsx(n,{})}):()=>e.jsx(n,{});return{route:t.route,view:o}},exports.createRoutesView=r=>{const{routes:n,otherwise:o}=r;return()=>{const r=p(n).at(-1);return r?e.jsx(s.Provider,{value:{children:r.children??[]},children:t.createElement(r.view)}):o?e.jsx(o,{}):null}},exports.useIsOpened=function(e){return n.is.router(e)?r.useUnit(e.$activeRoutes).length>0:r.useUnit(e.$isOpened)},exports.useLink=c,exports.useOpenedViews=p,exports.useRouter=function(){return r.useUnit(i())},exports.useRouterContext=i,exports.withLayout=function(r,n){const o=r;return n.map(({route:r,view:n})=>({route:r,view:()=>e.jsx(o,{children:t.createElement(n)})}))};
package/dist/index.d.ts CHANGED
@@ -1,26 +1,31 @@
1
1
  import { AnchorHTMLAttributes } from 'react';
2
2
  import { ComponentType } from 'react';
3
+ import { Equal } from 'effector-react';
3
4
  import { FC } from 'react';
4
5
  import { ForwardedRef } from 'react';
6
+ import { FunctionComponentElement } from 'react';
5
7
  import { JSX } from 'react/jsx-runtime';
6
8
  import { NavigatePayload } from '@argon-router/core';
9
+ import { OpenPayloadBase } from '@argon-router/core';
7
10
  import { Query } from '@argon-router/core';
8
11
  import { ReactNode } from 'react';
9
12
  import { Route } from '@argon-router/core';
13
+ import { RouteOpenedPayload } from '@argon-router/core';
10
14
  import { Router } from '@argon-router/core';
11
15
 
12
16
  declare type AnchorProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>;
13
17
 
14
- declare type BaseLinkProps<Params> = {
18
+ declare type BaseLinkProps<Params extends object | void = void> = {
15
19
  to: Route<Params>;
16
20
  children?: ReactNode;
17
- } & AnchorProps;
21
+ } & AnchorProps & OpenPayloadBase;
18
22
 
19
- declare interface CreateBaseRouteViewProps<T> {
20
- route: Route<T>;
23
+ declare interface CreateBaseRouteViewProps<T extends object | void = void> {
24
+ route: Route<T> | Router;
21
25
  layout?: ComponentType<{
22
26
  children: ReactNode;
23
27
  }>;
28
+ children?: CreateBaseRouteViewProps<any>[];
24
29
  }
25
30
 
26
31
  /**
@@ -47,9 +52,9 @@ declare interface CreateBaseRouteViewProps<T> {
47
52
  * });
48
53
  * ```
49
54
  */
50
- export declare function createLazyRouteView<T>(props: CreateLazyRouteViewProps<T>): RouteView;
55
+ export declare function createLazyRouteView<T extends object | void = void>(props: CreateLazyRouteViewProps<T>): RouteView;
51
56
 
52
- export declare interface CreateLazyRouteViewProps<T> extends CreateBaseRouteViewProps<T> {
57
+ export declare interface CreateLazyRouteViewProps<T extends object | void = void> extends CreateBaseRouteViewProps<T> {
53
58
  view: () => Promise<{
54
59
  default: ComponentType;
55
60
  }>;
@@ -107,13 +112,13 @@ declare interface CreateRoutesViewProps {
107
112
  * });
108
113
  * ```
109
114
  */
110
- export declare function createRouteView<T>(props: CreateRouteViewProps<T>): RouteView;
115
+ export declare function createRouteView<T extends object | void = void>(props: CreateRouteViewProps<T>): RouteView;
111
116
 
112
- export declare interface CreateRouteViewProps<T> extends CreateBaseRouteViewProps<T> {
117
+ export declare interface CreateRouteViewProps<T extends object | void = void> extends CreateBaseRouteViewProps<T> {
113
118
  view: ComponentType;
114
119
  }
115
120
 
116
- declare type ForwardedLink = <Params = void>(props: LinkProps<Params> & {
121
+ declare type ForwardedLink = <Params extends object | void = void>(props: LinkProps<Params> & {
117
122
  ref?: ForwardedRef<HTMLAnchorElement>;
118
123
  }) => ReactNode;
119
124
 
@@ -141,12 +146,41 @@ declare type ForwardedLink = <Params = void>(props: LinkProps<Params> & {
141
146
  */
142
147
  export declare const Link: ForwardedLink;
143
148
 
144
- export declare type LinkProps<Params> = Params extends Record<string, never> | void | undefined ? BaseLinkProps<Params> & {
149
+ export declare type LinkProps<Params extends object | void = void> = Params extends Record<string, never> | void | undefined ? BaseLinkProps<Params> & {
145
150
  params?: Params;
146
151
  } : BaseLinkProps<Params> & {
147
152
  params: Params;
148
153
  };
149
154
 
155
+ /**
156
+ * @description Outlet component for nested routes
157
+ * @link https://movpushmov.dev/argon-router/react/outlet.html
158
+ * @example ```ts
159
+ * export const RoutesView = createRoutesView([
160
+ * createRouteView({
161
+ * route: routes.profile,
162
+ * view: ProfileScreen,
163
+ * children: [
164
+ * createRouteView({ route: routes.settings, view: SettingsScreen }),
165
+ * ]
166
+ * }),
167
+ * ]);
168
+ *
169
+ * // profile.tsx
170
+ * export const ProfileScreen = () => {
171
+ * // will render settings screen when profile route is opened
172
+ * // and settings route is active
173
+ * return (
174
+ * <>
175
+ * <div>Profile</div>
176
+ * <Outlet />
177
+ * </>
178
+ * );
179
+ * };
180
+ * ```
181
+ */
182
+ export declare const Outlet: () => FunctionComponentElement<{}> | null;
183
+
150
184
  /**
151
185
  * @description Provides router in React tree
152
186
  * @param props Router provider config
@@ -159,10 +193,20 @@ declare interface RouterProviderProps {
159
193
  }
160
194
 
161
195
  export declare interface RouteView {
162
- route: Route<any>;
196
+ route: Route<any> | Router;
163
197
  view: FC;
198
+ children?: RouteView[];
164
199
  }
165
200
 
201
+ export declare function useIsOpened(route: Route | Router): boolean;
202
+
203
+ export declare function useLink<T extends object | void = void>(to: Route<T>, params: T): {
204
+ path: string;
205
+ onOpen: Equal<RouteOpenedPayload<T>, void> extends true ? () => void : (payload: RouteOpenedPayload<T>) => RouteOpenedPayload<T>;
206
+ };
207
+
208
+ export declare function useOpenedViews(routes: RouteView[]): RouteView[];
209
+
166
210
  /**
167
211
  * @description Use router from provider
168
212
  * @returns Router
@@ -209,8 +253,16 @@ export declare function useRouterContext(): Router;
209
253
  export declare function withLayout(layout: ComponentType<{
210
254
  children: ReactNode;
211
255
  }>, views: RouteView[]): {
212
- route: Route<any>;
256
+ route: Router | Route<any>;
213
257
  view: () => JSX.Element;
214
258
  }[];
215
259
 
216
260
  export { }
261
+
262
+
263
+ declare module 'vitest' {
264
+ interface Assertion<T = any> extends CustomMatchers<T> {
265
+ }
266
+ interface AsymmetricMatchersContaining extends CustomMatchers {
267
+ }
268
+ }
package/dist/index.js CHANGED
@@ -1,7 +1,12 @@
1
1
  import { jsx, Fragment } from "react/jsx-runtime";
2
- import { createContext, useContext, forwardRef, useMemo, createElement, lazy, Suspense } from "react";
3
- import { useUnit } from "effector-react";
2
+ import { createContext, useContext, forwardRef, useState, useEffect, useMemo, createElement, lazy, Suspense } from "react";
3
+ import { useUnit, useProvidedScope } from "effector-react";
4
+ import { is } from "@argon-router/core";
5
+ import { createWatch } from "effector";
4
6
  const RouterProviderContext = createContext(null);
7
+ const OutletContext = createContext(
8
+ null
9
+ );
5
10
  const RouterProvider = (props) => {
6
11
  return /* @__PURE__ */ jsx(RouterProviderContext.Provider, { value: props.router, children: props.children });
7
12
  };
@@ -17,22 +22,31 @@ function useRouterContext() {
17
22
  function useRouter() {
18
23
  return useUnit(useRouterContext());
19
24
  }
20
- const Link = forwardRef((props, ref) => {
21
- const { to, params, onClick, ...anchorProps } = props;
22
- const { mappedRoutes } = useRouterContext();
23
- const target = mappedRoutes.find(({ route }) => route === to);
25
+ function useLink(to, params) {
26
+ const { knownRoutes } = useRouterContext();
27
+ const target = knownRoutes.find(
28
+ ({ route }) => route === to
29
+ );
24
30
  const { onOpen } = useUnit(to);
25
31
  if (!target) {
26
32
  throw new Error(
27
- `[Link] Route with path "${to.path}" not found. Maybe it is not passed into createRouter?`
33
+ `[useLink] Route "${to}" not found. Maybe it is not passed into createRouter?`
28
34
  );
29
35
  }
36
+ return {
37
+ path: target.build(params ?? void 0),
38
+ onOpen
39
+ };
40
+ }
41
+ const Link = forwardRef((props, ref) => {
42
+ const { to, params, onClick, replace, query, ...anchorProps } = props;
43
+ const { path, onOpen } = useLink(to, params);
30
44
  return /* @__PURE__ */ jsx(
31
45
  "a",
32
46
  {
33
47
  ...anchorProps,
34
48
  ref,
35
- href: target.build(params ?? void 0),
49
+ href: path,
36
50
  onClick: (e) => {
37
51
  onClick == null ? void 0 : onClick(e);
38
52
  if (e.defaultPrevented) {
@@ -45,7 +59,11 @@ const Link = forwardRef((props, ref) => {
45
59
  return;
46
60
  }
47
61
  e.preventDefault();
48
- onOpen({ params: params || {} });
62
+ onOpen({
63
+ params: params || {},
64
+ replace,
65
+ query
66
+ });
49
67
  }
50
68
  }
51
69
  );
@@ -58,24 +76,79 @@ function createRouteView(props) {
58
76
  view
59
77
  };
60
78
  }
79
+ function getStoreValue(store, scope) {
80
+ return scope ? scope.getState(store) : store.getState();
81
+ }
82
+ function getVisibilities(routes, scope) {
83
+ return routes.map((view) => {
84
+ if (is.router(view.route)) {
85
+ return getStoreValue(view.route.$activeRoutes, scope).length > 0;
86
+ }
87
+ return getStoreValue(view.route.$isOpened, scope);
88
+ });
89
+ }
90
+ function useOpenedViews(routes) {
91
+ const scope = useProvidedScope();
92
+ const [visibilities, setVisibilities] = useState(
93
+ getVisibilities(routes, scope)
94
+ );
95
+ useEffect(() => {
96
+ const subscriptions = [];
97
+ for (const [index, view] of routes.entries()) {
98
+ if (is.router(view.route)) {
99
+ const router = view.route;
100
+ const subscription = createWatch({
101
+ unit: router.$activeRoutes,
102
+ scope: scope ?? void 0,
103
+ fn: (routes2) => {
104
+ setVisibilities((prev) => {
105
+ const newVisibilities = [...prev];
106
+ newVisibilities[index] = routes2.length > 0;
107
+ return newVisibilities;
108
+ });
109
+ }
110
+ });
111
+ subscriptions.push(subscription);
112
+ } else {
113
+ subscriptions.push(
114
+ createWatch({
115
+ unit: view.route.$isOpened,
116
+ scope: scope ?? void 0,
117
+ fn: (isOpened) => {
118
+ setVisibilities((prev) => {
119
+ const newVisibilities = [...prev];
120
+ newVisibilities[index] = isOpened;
121
+ return newVisibilities;
122
+ });
123
+ }
124
+ })
125
+ );
126
+ }
127
+ }
128
+ return () => {
129
+ for (const subscription of subscriptions) {
130
+ subscription.unsubscribe();
131
+ }
132
+ };
133
+ }, [routes, scope]);
134
+ return useMemo(() => {
135
+ const filtered = routes.filter((_, i) => visibilities[i]);
136
+ return filtered.reduce(
137
+ (filtered2, view) => filtered2.filter(
138
+ (r) => r.route !== view.route.parent
139
+ ),
140
+ filtered
141
+ );
142
+ }, [routes, visibilities]);
143
+ }
61
144
  const createRoutesView = (props) => {
62
145
  const { routes, otherwise: NotFound } = props;
63
146
  return () => {
64
- const visibilities = useUnit(routes.map((view) => view.route.$isOpened));
65
- const openedViews = useMemo(() => {
66
- const filtered = routes.filter((_, i) => visibilities[i]);
67
- return filtered.reduce(
68
- (filtered2, view) => filtered2.filter(
69
- (r) => r.route !== view.route.parent
70
- ),
71
- filtered
72
- );
73
- }, [visibilities]);
74
- const lastRoute = openedViews.at(-1);
75
- if (!lastRoute) {
147
+ const openedView = useOpenedViews(routes).at(-1);
148
+ if (!openedView) {
76
149
  return NotFound ? /* @__PURE__ */ jsx(NotFound, {}) : null;
77
150
  }
78
- return createElement(lastRoute.view);
151
+ return /* @__PURE__ */ jsx(OutletContext.Provider, { value: { children: openedView.children ?? [] }, children: createElement(openedView.view) });
79
152
  };
80
153
  };
81
154
  function createLazyRouteView(props) {
@@ -95,12 +168,27 @@ function withLayout(layout, views) {
95
168
  view: () => /* @__PURE__ */ jsx(Layout, { children: createElement(view) })
96
169
  }));
97
170
  }
171
+ const Outlet = () => {
172
+ const { children } = useContext(OutletContext) ?? { children: [] };
173
+ const openedView = useOpenedViews(children).at(-1);
174
+ if (!openedView) {
175
+ return null;
176
+ }
177
+ return createElement(openedView.view);
178
+ };
179
+ function useIsOpened(route) {
180
+ return is.router(route) ? useUnit(route.$activeRoutes).length > 0 : useUnit(route.$isOpened);
181
+ }
98
182
  export {
99
183
  Link,
184
+ Outlet,
100
185
  RouterProvider,
101
186
  createLazyRouteView,
102
187
  createRouteView,
103
188
  createRoutesView,
189
+ useIsOpened,
190
+ useLink,
191
+ useOpenedViews,
104
192
  useRouter,
105
193
  useRouterContext,
106
194
  withLayout
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "registry": "https://registry.npmjs.org/"
6
6
  },
7
7
  "private": false,
8
- "version": "0.11.1",
8
+ "version": "0.12.0",
9
9
  "description": "React bindings for argon router",
10
10
  "keywords": [
11
11
  "effector",
@@ -44,7 +44,7 @@
44
44
  "url": "https://github.com/movpushmov/argon-router/issues"
45
45
  },
46
46
  "dependencies": {
47
- "@argon-router/core": "^0.11.1"
47
+ "@argon-router/core": "^0.12.0"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@babel/preset-react": "^7.26.3",
@@ -59,5 +59,5 @@
59
59
  "effector-react": ">=23",
60
60
  "react": "18 || 19"
61
61
  },
62
- "gitHead": "3a980be012f40d741a261773efc3535f83576b1b"
62
+ "gitHead": "9832d6cd282d6abd33c26ba4d03b9a1176110fc4"
63
63
  }
package/LICENSE.MD DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Edward Gigolaev
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.