Skip to content

Commit 5be5fb8

Browse files
committed
feat: Add createRouteView & createRoutesView
1 parent 3dc2f4e commit 5be5fb8

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

src/create-route-view.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import React from 'react';
2+
import { combine } from 'effector';
3+
import { useStore } from 'effector-react';
4+
import { RouteInstance } from 'atomic-router';
5+
6+
export const createRouteView = <Props,>(
7+
route: RouteInstance<any> | RouteInstance<any>[],
8+
View: React.FC<Props>
9+
) => {
10+
const $isOpened = Array.isArray(route)
11+
? combine(combine(route.map((r) => r.$isOpened)), (isOpened) =>
12+
isOpened.includes(true)
13+
)
14+
: route.$isOpened;
15+
16+
return (props: Props) => {
17+
const isOpened = useStore($isOpened);
18+
19+
if (isOpened) {
20+
return <View {...props} />;
21+
}
22+
23+
return null;
24+
};
25+
};

src/create-routes-view.tsx

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { combine } from 'effector';
2+
import { useStore } from 'effector-react';
3+
import React, { FC } from 'react';
4+
import { RouteInstance } from 'atomic-router';
5+
import { createRouteView } from './create-route-view';
6+
7+
export const createRoutesView = (config: {
8+
routes: { route: RouteInstance<any> | RouteInstance<any>[]; view: FC<any> }[];
9+
notFound?: FC<any>;
10+
}) => {
11+
const views = config.routes.map(({ route, view }) =>
12+
createRouteView(route, view)
13+
);
14+
const $isSomeOpened = combine(
15+
...config.routes
16+
.map(({ route }) => route)
17+
.flat()
18+
.map((route) => route.$isOpened),
19+
// @ts-expect-error
20+
(...isOpened) => isOpened.some(Boolean)
21+
);
22+
23+
const NotFound = config.notFound;
24+
25+
return () => {
26+
const isSomeOpened = useStore($isSomeOpened);
27+
28+
if (!isSomeOpened && NotFound) {
29+
return <NotFound />;
30+
}
31+
return (
32+
<>
33+
{views.map((View, idx) => (
34+
<View key={idx} />
35+
))}
36+
</>
37+
);
38+
};
39+
};

src/index.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
export * from './link';
22
export * from './route';
33
export * from './router-provider';
4+
export * from './create-route-view';
5+
export * from './create-routes-view';

0 commit comments

Comments
 (0)