Skip to content

Commit 32628df

Browse files
committed
fix(packages): fix useRouter type
1 parent d78613c commit 32628df

File tree

5 files changed

+40
-52
lines changed

5 files changed

+40
-52
lines changed

packages/simple-router/src/hooks/useRouter/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createContext, useContext } from 'react';
2+
import type { Router } from '../../router';
23

3-
export const RouterContext = createContext<any>({});
4+
export const RouterContext = createContext<Router>({} as Router);
45
export function useRouter() {
56
const router = useContext(RouterContext);
67
if (!router) {
Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,13 @@
1-
import { createRouter } from './router';
21
import { useRouter } from './hooks/useRouter';
32
import RouterProvider from './Component';
43
import type { RouteRecordNormalized } from './matcher/types';
54

6-
export { useRouter, createRouter, RouterProvider };
5+
export { useRouter, RouterProvider };
6+
7+
export { createRouter } from './router';
8+
9+
export type { Mode, Options, RouterOptions, Router } from './router';
710

811
export type { RouteRecordNormalized };
912

10-
export type {
11-
LocationQueryValueRaw,
12-
RouteLocationNamedRaw,
13-
AfterEach,
14-
BeforeEach,
15-
RouteLocationNormalizedLoaded,
16-
Route
17-
} from './types';
13+
export * from './types';

packages/simple-router/src/router.ts

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { createBrowserRouter, createHashRouter, createMemoryRouter } from 'react
22
import type { Location, RouteObject } from 'react-router-dom';
33
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
44
import type { BlockerFunction, RouterState } from '@remix-run/router';
5-
import type { RouteLocationNamedRaw, RouteLocationNormalizedLoaded } from './types';
5+
import type { AfterEach, BeforeEach, Init, RouteLocationNamedRaw, RouteLocationNormalizedLoaded } from './types';
66
import CreateRouterMatcher from './matcher';
77
import { cleanParams, findParentNames, getFullPath, removeElement } from './utils/auxi';
88
import { START_LOCATION_NORMALIZED } from './location';
@@ -18,18 +18,18 @@ const historyCreatorMap = {
1818

1919
type HistoryCreator = typeof historyCreatorMap;
2020

21-
type Mode = keyof HistoryCreator;
21+
export type Mode = keyof HistoryCreator;
2222

23-
type Options = Parameters<HistoryCreator[Mode]>[1];
23+
export type Options = Parameters<HistoryCreator[Mode]>[1];
2424

2525
export interface RouterOptions {
2626
mode: Mode;
2727
initRoutes: ElegantConstRoute[];
2828
opt: Options;
2929
getReactRoutes: (route: ElegantConstRoute) => RouteObject;
30-
init: () => Promise<void>;
31-
afterEach: any;
32-
beforeEach: any;
30+
init: Init;
31+
afterEach: AfterEach;
32+
beforeEach: BeforeEach;
3333
}
3434

3535
export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes, init, afterEach }: RouterOptions) {
@@ -43,13 +43,12 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
4343

4444
let currentRoute = START_LOCATION_NORMALIZED;
4545

46-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
47-
let listeners: any;
48-
49-
reactRouter.subscribe(afterRouteChange);
46+
let listeners: (() => void)[] = [];
5047

5148
reactRouter.getBlocker('beforeGuard', onBeforeRouteChange);
5249

50+
reactRouter.subscribe(afterRouteChange);
51+
5352
/**
5453
* Adds React routes to the router.
5554
*
@@ -91,8 +90,6 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
9190
return true;
9291
}
9392

94-
if (nextLocation.state === 'reload') return false;
95-
9693
if (to.redirect) {
9794
if (to.redirect.startsWith('/')) {
9895
if (to.redirect === currentRoute.fullPath) {
@@ -107,10 +104,10 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
107104
}
108105
}
109106

110-
return beforeEach(to, currentRoute, next);
107+
return beforeEach(to, currentRoute, blockerOrJump);
111108
}
112109

113-
function next(param?: boolean | string | Location | RouteLocationNamedRaw) {
110+
function blockerOrJump(param?: undefined | null | boolean | string | Location | RouteLocationNamedRaw) {
114111
if (!param) return false;
115112
if (typeof param === 'string') {
116113
reactRouter.navigate(param);
@@ -207,10 +204,14 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
207204

208205
async function initReady(): Promise<boolean> {
209206
return new Promise((resolved, reject) => {
210-
init()
211-
.then(() => {
212-
reactRouter.initialize();
213-
resolved(true);
207+
init(resolve(reactRouter.state.location), blockerOrJump)
208+
.then(res => {
209+
if (!res) {
210+
reactRouter.initialize();
211+
resolved(true);
212+
} else {
213+
reject(new Error('init failed'));
214+
}
214215
})
215216
.catch(e => {
216217
reject(e);
@@ -279,12 +280,13 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
279280
function resetRoute() {
280281
// Resets the route matcher so it can begin matching new routes again.
281282
matcher.resetMatcher();
283+
reactRouter._internalSetRoutes(initReactRoutes);
282284
}
283285

284286
function subscribe(listener: () => void) {
285-
listeners = [listener];
287+
listeners = [...listeners, listener];
286288
return () => {
287-
listeners = [];
289+
listeners = listeners.filter(l => l !== listener);
288290
};
289291
}
290292

@@ -328,3 +330,5 @@ export function createRouter({ beforeEach, initRoutes, mode, opt, getReactRoutes
328330

329331
return router;
330332
}
333+
334+
export type Router = ReturnType<typeof createRouter>;

packages/simple-router/src/types/router.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
2-
import type { RouteObject } from 'react-router-dom';
2+
import type { Location, RouteObject } from 'react-router-dom';
33
import type { Router as RemixRouter } from '@remix-run/router';
44
import type { RouteRecordNormalized } from '../matcher/types';
55
import type { RouteLocationNormalizedLoaded } from './route';
6-
76
export interface RouterOptions {
87
initRoutes: ElegantConstRoute[];
98
history: 'hash' | 'history' | 'memory';
@@ -36,9 +35,14 @@ export interface Router {
3635
export type BeforeEach = (
3736
to: RouteLocationNormalizedLoaded,
3837
from: RouteLocationNormalizedLoaded,
39-
next: (param?: boolean | undefined | string) => boolean
38+
next: (param?: boolean | undefined | null | string | Location | RouteLocationNamedRaw) => boolean
4039
) => boolean;
4140

41+
export type Init = (
42+
current: RouteLocationNormalizedLoaded,
43+
next: (param?: boolean | undefined | null | string | Location | RouteLocationNamedRaw) => boolean
44+
) => Promise<boolean>;
45+
4246
export type AfterEach = (to: RouteLocationNormalizedLoaded, from: RouteLocationNormalizedLoaded) => void;
4347

4448
export type HistoryStateArray = Array<HistoryStateValue>;

src/router/index.ts

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
import type { ElegantConstRoute } from '@ohh-889/react-auto-route';
22
import { createRouter } from '@sa/simple-router';
3-
import { localStg } from '@/utils/storage';
4-
import { store } from '@/store';
5-
import { initAuthRoute, initConstantRoute } from '@/store/slice/route';
6-
// import { initTabStore } from '@/store/slice/tab';
73
import { layouts, pages } from './elegant/imports';
84
import { transformElegantRouteToReactRoute } from './elegant/transform';
9-
import { afterEach, createRouteGuard } from './guard';
5+
import { afterEach, createRouteGuard, init } from './guard';
106
import { builtinRoutes } from './routes/builtin';
117

128
const { VITE_ROUTER_HISTORY_MODE = 'history', VITE_BASE_URL } = import.meta.env;
@@ -20,19 +16,6 @@ function getReactRoutes(route: ElegantConstRoute) {
2016
return transformElegantRouteToReactRoute(route, layouts, pages);
2117
}
2218

23-
async function init() {
24-
await store.dispatch(initConstantRoute());
25-
const isLogin = Boolean(localStg.get('token'));
26-
if (!isLogin) {
27-
return;
28-
}
29-
await store.dispatch(initAuthRoute());
30-
}
31-
32-
// function initBeforeRoute(allNames: string[]) {
33-
// store.dispatch(initTabStore(allNames));
34-
// }
35-
3619
export const router = createRouter({
3720
initRoutes: builtinRoutes,
3821
mode: VITE_ROUTER_HISTORY_MODE,

0 commit comments

Comments
 (0)