@shuvi/router-react 0.0.1-rc.33

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/lib/Link.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import * as React from 'react';
2
+ import { State, PathRecord } from '@shuvi/router';
3
+ /**
4
+ * The public API for rendering a history-aware <a>.
5
+ */
6
+ export declare const Link: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>>;
7
+ export interface LinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
8
+ replace?: boolean;
9
+ state?: State;
10
+ to: PathRecord;
11
+ }
package/lib/Link.js ADDED
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importStar = (this && this.__importStar) || function (mod) {
14
+ if (mod && mod.__esModule) return mod;
15
+ var result = {};
16
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
17
+ result["default"] = mod;
18
+ return result;
19
+ };
20
+ var __importDefault = (this && this.__importDefault) || function (mod) {
21
+ return (mod && mod.__esModule) ? mod : { "default": mod };
22
+ };
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ const React = __importStar(require("react"));
25
+ const prop_types_1 = __importDefault(require("prop-types"));
26
+ const _1 = require(".");
27
+ const router_1 = require("@shuvi/router");
28
+ const constants_1 = require("./constants");
29
+ const hooks_1 = require("./hooks");
30
+ function isModifiedEvent(event) {
31
+ return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
32
+ }
33
+ /**
34
+ * The public API for rendering a history-aware <a>.
35
+ */
36
+ exports.Link = React.forwardRef(function LinkWithRef(_a, ref) {
37
+ var { onClick, replace: replaceProp = false, state, target, to } = _a, rest = __rest(_a, ["onClick", "replace", "state", "target", "to"]);
38
+ let href = _1.useHref(to);
39
+ let navigate = _1.useNavigate();
40
+ const location = hooks_1.useCurrentRoute();
41
+ let path = _1.useResolvedPath(to);
42
+ function handleClick(event) {
43
+ if (onClick)
44
+ onClick(event);
45
+ if (!event.defaultPrevented && // onClick prevented default
46
+ event.button === 0 && // Ignore everything but left clicks
47
+ (!target || target === '_self') && // Let browser handle "target=_blank" etc.
48
+ !isModifiedEvent(event) // Ignore clicks with modifier keys
49
+ ) {
50
+ event.preventDefault();
51
+ // If the URL hasn't changed, a regular <a> will do a replace instead of
52
+ // a push, so do the same here.
53
+ let replace = !!replaceProp || router_1.pathToString(location) === router_1.pathToString(path);
54
+ navigate(to, { replace, state });
55
+ }
56
+ }
57
+ return (
58
+ // @ts-ignore
59
+ React.createElement("a", Object.assign({}, rest, { href: href, onClick: handleClick, ref: ref, target: target })));
60
+ });
61
+ if (constants_1.__DEV__) {
62
+ exports.Link.displayName = 'Link';
63
+ exports.Link.propTypes = {
64
+ onClick: prop_types_1.default.func,
65
+ replace: prop_types_1.default.bool,
66
+ state: prop_types_1.default.object,
67
+ target: prop_types_1.default.string,
68
+ to: prop_types_1.default.oneOfType([
69
+ prop_types_1.default.string,
70
+ prop_types_1.default.shape({
71
+ pathname: prop_types_1.default.string,
72
+ search: prop_types_1.default.string,
73
+ hash: prop_types_1.default.string
74
+ })
75
+ ]).isRequired
76
+ };
77
+ }
@@ -0,0 +1,22 @@
1
+ import React from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import { IMemoryRouterProps } from './types';
4
+ /**
5
+ * A <Router> that stores all entries in memory.
6
+ */
7
+ export declare function MemoryRouter({ basename, children, routes, initialEntries, initialIndex }: IMemoryRouterProps): React.ReactElement;
8
+ export declare namespace MemoryRouter {
9
+ var displayName: string;
10
+ var propTypes: {
11
+ children: PropTypes.Requireable<PropTypes.ReactNodeLike>;
12
+ routes: PropTypes.Requireable<(object | null | undefined)[]>;
13
+ initialEntries: PropTypes.Requireable<(string | PropTypes.InferProps<{
14
+ pathname: PropTypes.Requireable<string>;
15
+ search: PropTypes.Requireable<string>;
16
+ hash: PropTypes.Requireable<string>;
17
+ state: PropTypes.Requireable<object>;
18
+ key: PropTypes.Requireable<string>;
19
+ }> | null | undefined)[]>;
20
+ initialIndex: PropTypes.Requireable<number>;
21
+ };
22
+ }
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const prop_types_1 = __importDefault(require("prop-types"));
8
+ const router_1 = require("@shuvi/router");
9
+ const Router_1 = require("./Router");
10
+ const constants_1 = require("./constants");
11
+ /**
12
+ * A <Router> that stores all entries in memory.
13
+ */
14
+ function MemoryRouter({ basename, children, routes, initialEntries, initialIndex }) {
15
+ let routerRef = react_1.default.useRef();
16
+ if (routerRef.current == null) {
17
+ routerRef.current = router_1.createRouter({
18
+ basename,
19
+ routes: routes || [],
20
+ history: router_1.createMemoryHistory({ initialEntries, initialIndex })
21
+ });
22
+ }
23
+ return react_1.default.createElement(Router_1.Router, { children: children, router: routerRef.current });
24
+ }
25
+ exports.MemoryRouter = MemoryRouter;
26
+ if (constants_1.__DEV__) {
27
+ MemoryRouter.displayName = 'MemoryRouter';
28
+ MemoryRouter.propTypes = {
29
+ children: prop_types_1.default.node,
30
+ routes: prop_types_1.default.arrayOf(prop_types_1.default.object),
31
+ initialEntries: prop_types_1.default.arrayOf(prop_types_1.default.oneOfType([
32
+ prop_types_1.default.string,
33
+ prop_types_1.default.shape({
34
+ pathname: prop_types_1.default.string,
35
+ search: prop_types_1.default.string,
36
+ hash: prop_types_1.default.string,
37
+ state: prop_types_1.default.object,
38
+ key: prop_types_1.default.string
39
+ })
40
+ ])),
41
+ initialIndex: prop_types_1.default.number
42
+ };
43
+ }
@@ -0,0 +1,19 @@
1
+ import React from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import { IRouterProps } from './types';
4
+ /**
5
+ * Provides location context for the rest of the app.
6
+ *
7
+ * Note: You usually won't render a <Router> directly. Instead, you'll render a
8
+ * router that is more specific to your environment such as a <BrowserRouter>
9
+ * in web browsers or a <StaticRouter> for server rendering.
10
+ */
11
+ export declare function Router({ children, static: staticProp, router }: IRouterProps): React.ReactElement;
12
+ export declare namespace Router {
13
+ var displayName: string;
14
+ var propTypes: {
15
+ children: PropTypes.Requireable<PropTypes.ReactNodeLike>;
16
+ router: PropTypes.Requireable<object>;
17
+ static: PropTypes.Requireable<boolean>;
18
+ };
19
+ }
package/lib/Router.js ADDED
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const react_1 = __importStar(require("react"));
14
+ const prop_types_1 = __importDefault(require("prop-types"));
15
+ const invariant_1 = __importDefault(require("@shuvi/utils/lib/invariant"));
16
+ const contexts_1 = require("./contexts");
17
+ const hooks_1 = require("./hooks");
18
+ const constants_1 = require("./constants");
19
+ const utils_1 = require("./utils");
20
+ /**
21
+ * Provides location context for the rest of the app.
22
+ *
23
+ * Note: You usually won't render a <Router> directly. Instead, you'll render a
24
+ * router that is more specific to your environment such as a <BrowserRouter>
25
+ * in web browsers or a <StaticRouter> for server rendering.
26
+ */
27
+ function Router({ children = null, static: staticProp = false, router }) {
28
+ invariant_1.default(!hooks_1.useInRouterContext(), `You cannot render a <Router> inside another <Router>.` +
29
+ ` You never need more than one.`);
30
+ const contextVal = react_1.default.useMemo(() => {
31
+ return {
32
+ static: staticProp,
33
+ router: router
34
+ };
35
+ }, [staticProp, router]);
36
+ const unmount = react_1.useRef(false);
37
+ const forceupdate = react_1.useReducer(s => s * -1, 1)[1];
38
+ utils_1.useIsomorphicEffect(() => () => (unmount.current = true), []);
39
+ utils_1.useIsomorphicEffect(() => router.listen(() => {
40
+ if (unmount.current) {
41
+ return;
42
+ }
43
+ forceupdate();
44
+ }), [router]);
45
+ return (react_1.default.createElement(contexts_1.RouterContext.Provider, { value: contextVal },
46
+ react_1.default.createElement(contexts_1.RouteContext.Provider, { children: children, value: router.current })));
47
+ }
48
+ exports.Router = Router;
49
+ if (constants_1.__DEV__) {
50
+ Router.displayName = 'Router';
51
+ Router.propTypes = {
52
+ children: prop_types_1.default.node,
53
+ router: prop_types_1.default.object,
54
+ static: prop_types_1.default.bool
55
+ };
56
+ }
@@ -0,0 +1,5 @@
1
+ import React from 'react';
2
+ export declare function RouterView(): React.ReactElement | null;
3
+ export declare namespace RouterView {
4
+ var displayName: string;
5
+ }
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const utils_1 = require("@shuvi/router/lib/utils");
8
+ const hooks_1 = require("./hooks");
9
+ const constants_1 = require("./constants");
10
+ const contexts_1 = require("./contexts");
11
+ const utils_2 = require("./utils");
12
+ const defaultElement = react_1.default.createElement(RouterView, null);
13
+ function RouterView() {
14
+ let { depth, pathname: parentPathname, params: parentParams } = react_1.default.useContext(contexts_1.MatchedRouteContext);
15
+ const { matches } = hooks_1.useCurrentRoute();
16
+ if (!matches) {
17
+ return null;
18
+ }
19
+ // Otherwise render an element.
20
+ const matched = matches[depth];
21
+ if (!matched) {
22
+ if (constants_1.__DEV__) {
23
+ utils_2.warningOnce(parentPathname, false, `Use <RouterView/> under path "${parentPathname}", but it has no children routes.` +
24
+ `\n\n` +
25
+ `Please remove the <RouterView/>.`);
26
+ }
27
+ return null;
28
+ }
29
+ const { route, params, pathname } = matched;
30
+ const element = route.component
31
+ ? react_1.default.createElement(route.component, route.props)
32
+ : defaultElement;
33
+ return (react_1.default.createElement(contexts_1.MatchedRouteContext.Provider, { children: element, value: {
34
+ depth: depth + 1,
35
+ params: utils_2.readOnly(Object.assign(Object.assign({}, parentParams), params)),
36
+ pathname: utils_1.joinPaths([parentPathname, pathname]),
37
+ route
38
+ } }));
39
+ }
40
+ exports.RouterView = RouterView;
41
+ if (constants_1.__DEV__) {
42
+ RouterView.displayName = 'RouterView';
43
+ }
@@ -0,0 +1 @@
1
+ export declare const __DEV__: boolean;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.__DEV__ = process.env.NODE_ENV !== 'production';
@@ -0,0 +1,6 @@
1
+ import React from 'react';
2
+ import { IRoute } from '@shuvi/router';
3
+ import { IRouterContextObject, IRouteContextObject } from './types';
4
+ export declare const RouterContext: React.Context<IRouterContextObject>;
5
+ export declare const RouteContext: React.Context<IRoute<import("@shuvi/router").IRouteRecord<any>>>;
6
+ export declare const MatchedRouteContext: React.Context<IRouteContextObject>;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const utils_1 = require("./utils");
8
+ const constants_1 = require("./constants");
9
+ exports.RouterContext = react_1.default.createContext(null);
10
+ if (constants_1.__DEV__) {
11
+ exports.RouterContext.displayName = 'Router';
12
+ }
13
+ exports.RouteContext = react_1.default.createContext(null);
14
+ if (constants_1.__DEV__) {
15
+ exports.RouterContext.displayName = 'Route';
16
+ }
17
+ exports.MatchedRouteContext = react_1.default.createContext({
18
+ depth: 0,
19
+ params: utils_1.readOnly({}),
20
+ pathname: '',
21
+ route: null
22
+ });
23
+ if (constants_1.__DEV__) {
24
+ exports.MatchedRouteContext.displayName = 'MatchedRoute';
25
+ }
package/lib/hooks.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { IParams, IPathMatch, Blocker, Path, PathRecord, IRouter, IPathPattern } from '@shuvi/router';
2
+ import { INavigateFunction } from './types';
3
+ export declare function useCurrentRoute(): import("@shuvi/router").IRoute<import("@shuvi/router").IRouteRecord<any>>;
4
+ /**
5
+ * Blocks all navigation attempts. This is useful for preventing the page from
6
+ * changing until some condition is met, like saving form data.
7
+ */
8
+ export declare function useBlocker(blocker: Blocker, when?: boolean): void;
9
+ /**
10
+ * Returns the full href for the given "to" value. This is useful for building
11
+ * custom links that are also accessible and preserve right-click behavior.
12
+ */
13
+ export declare function useHref(to: PathRecord): string;
14
+ /**
15
+ * Returns true if this component is a descendant of a <Router>.
16
+ */
17
+ export declare function useInRouterContext(): boolean;
18
+ /**
19
+ * Returns true if the URL for the given "to" value matches the current URL.
20
+ * This is useful for components that need to know "active" state, e.g.
21
+ * <NavLink>.
22
+ */
23
+ export declare function useMatch(pattern: IPathPattern): IPathMatch | null;
24
+ /**
25
+ * Returns an imperative method for changing the location. Used by <Link>s, but
26
+ * may also be used by other elements to change the location.
27
+ */
28
+ export declare function useNavigate(): INavigateFunction;
29
+ /**
30
+ * Returns an object of key/value pairs of the dynamic params from the current
31
+ * URL that were matched by the route path.
32
+ */
33
+ export declare function useParams(): IParams;
34
+ /**
35
+ * Resolves the pathname of the given `to` value against the current location.
36
+ */
37
+ export declare function useResolvedPath(to: PathRecord): Path;
38
+ /**
39
+ * Returns the current router object
40
+ */
41
+ export declare function useRouter(): IRouter;
package/lib/hooks.js ADDED
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ const react_1 = __importStar(require("react"));
14
+ const router_1 = require("@shuvi/router");
15
+ const invariant_1 = __importDefault(require("@shuvi/utils/lib/invariant"));
16
+ const contexts_1 = require("./contexts");
17
+ const utils_1 = require("./utils");
18
+ function useCurrentRoute() {
19
+ return react_1.useContext(contexts_1.RouteContext);
20
+ }
21
+ exports.useCurrentRoute = useCurrentRoute;
22
+ /**
23
+ * Blocks all navigation attempts. This is useful for preventing the page from
24
+ * changing until some condition is met, like saving form data.
25
+ */
26
+ function useBlocker(blocker, when = true) {
27
+ invariant_1.default(useInRouterContext(), `useBlocker() may be used only in the context of a <Router> component.`);
28
+ const { router } = react_1.useContext(contexts_1.RouterContext);
29
+ react_1.default.useEffect(() => {
30
+ if (!when)
31
+ return;
32
+ let unblock = router.block((tx) => {
33
+ let autoUnblockingTx = Object.assign(Object.assign({}, tx), { retry() {
34
+ // Automatically unblock the transition so it can play all the way
35
+ // through before retrying it. TODO: Figure out how to re-enable
36
+ // this block if the transition is cancelled for some reason.
37
+ unblock();
38
+ tx.retry();
39
+ } });
40
+ blocker(autoUnblockingTx);
41
+ });
42
+ return unblock;
43
+ }, [router, blocker, when]);
44
+ }
45
+ exports.useBlocker = useBlocker;
46
+ /**
47
+ * Returns the full href for the given "to" value. This is useful for building
48
+ * custom links that are also accessible and preserve right-click behavior.
49
+ */
50
+ function useHref(to) {
51
+ invariant_1.default(useInRouterContext(), `useHref() may be used only in the context of a <Router> component.`);
52
+ const { router } = react_1.useContext(contexts_1.RouterContext);
53
+ const path = useResolvedPath(to);
54
+ return router.resolve(path).href;
55
+ }
56
+ exports.useHref = useHref;
57
+ /**
58
+ * Returns true if this component is a descendant of a <Router>.
59
+ */
60
+ function useInRouterContext() {
61
+ return react_1.useContext(contexts_1.RouterContext) != null;
62
+ }
63
+ exports.useInRouterContext = useInRouterContext;
64
+ /**
65
+ * Returns true if the URL for the given "to" value matches the current URL.
66
+ * This is useful for components that need to know "active" state, e.g.
67
+ * <NavLink>.
68
+ */
69
+ function useMatch(pattern) {
70
+ invariant_1.default(useInRouterContext(), `useMatch() may be used only in the context of a <Router> component.`);
71
+ const { pathname } = useCurrentRoute();
72
+ return router_1.matchPathname(pattern, pathname);
73
+ }
74
+ exports.useMatch = useMatch;
75
+ /**
76
+ * Returns an imperative method for changing the location. Used by <Link>s, but
77
+ * may also be used by other elements to change the location.
78
+ */
79
+ function useNavigate() {
80
+ invariant_1.default(useInRouterContext(), `useNavigate() may be used only in the context of a <Router> component.`);
81
+ const { router } = react_1.useContext(contexts_1.RouterContext);
82
+ const { pathname } = react_1.useContext(contexts_1.MatchedRouteContext);
83
+ const activeRef = react_1.default.useRef(false);
84
+ react_1.default.useEffect(() => {
85
+ activeRef.current = true;
86
+ });
87
+ let navigate = react_1.default.useCallback((to, options = {}) => {
88
+ if (activeRef.current) {
89
+ if (typeof to === 'number') {
90
+ router.go(to);
91
+ }
92
+ else {
93
+ let { path } = router.resolve(to, pathname);
94
+ (!!options.replace ? router.replace : router.push).call(router, path, options.state);
95
+ }
96
+ }
97
+ else {
98
+ utils_1.warning(false, `You should call navigate() in a useEffect, not when ` +
99
+ `your component is first rendered.`);
100
+ }
101
+ }, [router, pathname]);
102
+ return navigate;
103
+ }
104
+ exports.useNavigate = useNavigate;
105
+ /**
106
+ * Returns an object of key/value pairs of the dynamic params from the current
107
+ * URL that were matched by the route path.
108
+ */
109
+ function useParams() {
110
+ return react_1.useContext(contexts_1.MatchedRouteContext).params;
111
+ }
112
+ exports.useParams = useParams;
113
+ /**
114
+ * Resolves the pathname of the given `to` value against the current location.
115
+ */
116
+ function useResolvedPath(to) {
117
+ const { router } = react_1.useContext(contexts_1.RouterContext);
118
+ const { pathname } = react_1.useContext(contexts_1.MatchedRouteContext);
119
+ return react_1.default.useMemo(() => router.resolve(to, pathname).path, [to, pathname]);
120
+ }
121
+ exports.useResolvedPath = useResolvedPath;
122
+ /**
123
+ * Returns the current router object
124
+ */
125
+ function useRouter() {
126
+ invariant_1.default(useInRouterContext(), `useRouter() may be used only in the context of a <Router> component.`);
127
+ return react_1.useContext(contexts_1.RouterContext).router;
128
+ }
129
+ exports.useRouter = useRouter;
package/lib/index.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { generatePath } from './utils';
2
+ export { MemoryRouter } from './MemoryRouter';
3
+ export { RouterView } from './RouterView';
4
+ export { Router } from './Router';
5
+ export { Link } from './Link';
6
+ export { withRouter } from './withRouter';
7
+ export * from './hooks';
8
+ export * from './types';
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ var utils_1 = require("./utils");
7
+ exports.generatePath = utils_1.generatePath;
8
+ var MemoryRouter_1 = require("./MemoryRouter");
9
+ exports.MemoryRouter = MemoryRouter_1.MemoryRouter;
10
+ var RouterView_1 = require("./RouterView");
11
+ exports.RouterView = RouterView_1.RouterView;
12
+ var Router_1 = require("./Router");
13
+ exports.Router = Router_1.Router;
14
+ var Link_1 = require("./Link");
15
+ exports.Link = Link_1.Link;
16
+ var withRouter_1 = require("./withRouter");
17
+ exports.withRouter = withRouter_1.withRouter;
18
+ __export(require("./hooks"));
package/lib/types.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /// <reference types="react" />
2
+ import { IParams, InitialEntry, State, PathRecord, IRouteRecord as IOriginRouteRecord, IPartialRouteRecord as IOriginalRouteRecord, IRouter } from '@shuvi/router';
3
+ export declare type IRouteRecord = IOriginRouteRecord<React.ReactNode>;
4
+ export declare type IPartialRouteRecord = IOriginalRouteRecord;
5
+ export interface IRouterContextObject {
6
+ static: boolean;
7
+ router: IRouter;
8
+ }
9
+ export interface IRouteContextObject {
10
+ depth: number;
11
+ params: IParams;
12
+ pathname: string;
13
+ route: IRouteRecord | null;
14
+ }
15
+ export interface IMemoryRouterProps {
16
+ basename?: string;
17
+ children?: React.ReactNode;
18
+ routes?: IRouteRecord[];
19
+ initialEntries?: InitialEntry[];
20
+ initialIndex?: number;
21
+ }
22
+ export interface INavigateProps {
23
+ to: PathRecord;
24
+ replace?: boolean;
25
+ state?: State;
26
+ }
27
+ export interface IOutletProps {
28
+ }
29
+ export interface IRouterProps {
30
+ children?: React.ReactNode;
31
+ static?: boolean;
32
+ router: IRouter;
33
+ }
34
+ export interface IRoutesProps {
35
+ basename?: string;
36
+ children?: React.ReactNode;
37
+ }
38
+ /**
39
+ * The interface for the navigate() function returned from useNavigate().
40
+ */
41
+ export interface INavigateFunction {
42
+ (to: PathRecord, options?: {
43
+ replace?: boolean;
44
+ state?: State;
45
+ }): void;
46
+ (delta: number): void;
47
+ }
package/lib/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/lib/utils.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { IParams } from '@shuvi/router';
2
+ export declare function useIsomorphicEffect(cb: any, deps: any): void;
3
+ export declare const readOnly: <T extends unknown>(obj: T) => T;
4
+ export declare function warning(cond: boolean, message: string): void;
5
+ export declare function warningOnce(key: string, cond: boolean, message: string): void;
6
+ /**
7
+ * Returns a path with params interpolated.
8
+ */
9
+ export declare function generatePath(path: string, params?: IParams): string;
package/lib/utils.js ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const router_1 = require("@shuvi/router");
4
+ const react_1 = require("react");
5
+ const constants_1 = require("./constants");
6
+ function useIsomorphicEffect(cb, deps) {
7
+ if (typeof window !== 'undefined') {
8
+ react_1.useLayoutEffect(cb, deps);
9
+ }
10
+ else {
11
+ react_1.useEffect(cb, deps);
12
+ }
13
+ }
14
+ exports.useIsomorphicEffect = useIsomorphicEffect;
15
+ exports.readOnly = constants_1.__DEV__
16
+ ? obj => Object.freeze(obj)
17
+ : obj => obj;
18
+ function warning(cond, message) {
19
+ if (!cond) {
20
+ if (typeof console !== 'undefined')
21
+ console.warn(message);
22
+ try {
23
+ // Welcome to debugging React Router!
24
+ //
25
+ // This error is thrown as a convenience so you can more easily
26
+ // find the source for a warning that appears in the console by
27
+ // enabling "pause on exceptions" in your JavaScript debugger.
28
+ throw new Error(message);
29
+ }
30
+ catch (e) { }
31
+ }
32
+ }
33
+ exports.warning = warning;
34
+ const alreadyWarned = {};
35
+ function warningOnce(key, cond, message) {
36
+ if (!cond && !alreadyWarned[key]) {
37
+ alreadyWarned[key] = true;
38
+ warning(false, message);
39
+ }
40
+ }
41
+ exports.warningOnce = warningOnce;
42
+ /**
43
+ * Returns a path with params interpolated.
44
+ */
45
+ function generatePath(path, params = {}) {
46
+ return router_1.matchStringify(path, params);
47
+ }
48
+ exports.generatePath = generatePath;
@@ -0,0 +1,8 @@
1
+ import { IRouter } from '@shuvi/router';
2
+ import { Runtime } from '@shuvi/service';
3
+ import React from 'react';
4
+ export declare type WithRouterProps = {
5
+ router: IRouter;
6
+ };
7
+ export declare type ExcludeRouterProps<P> = Pick<P, Exclude<keyof P, keyof WithRouterProps>>;
8
+ export declare function withRouter<P extends WithRouterProps>(ComposedComponent: Runtime.IRouteComponent<React.ComponentType<P>, any>): Runtime.IRouteComponent<React.ComponentType<ExcludeRouterProps<P>>, any>;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const react_1 = __importDefault(require("react"));
7
+ const hooks_1 = require("./hooks");
8
+ function withRouter(ComposedComponent) {
9
+ function WithRouterWrapper(props) {
10
+ return react_1.default.createElement(ComposedComponent, Object.assign({ router: hooks_1.useRouter() }, props));
11
+ }
12
+ WithRouterWrapper.getInitialProps = ComposedComponent.getInitialProps;
13
+ if (process.env.NODE_ENV !== 'production') {
14
+ const name = ComposedComponent.displayName || ComposedComponent.name || 'Unknown';
15
+ WithRouterWrapper.displayName = `withRouter(${name})`;
16
+ }
17
+ return WithRouterWrapper;
18
+ }
19
+ exports.withRouter = withRouter;
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@shuvi/router-react",
3
+ "version": "0.0.1-rc.33",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "git+https://github.com/shuvijs/shuvi.git",
7
+ "directory": "packages/router-react"
8
+ },
9
+ "author": "liximomo",
10
+ "license": "MIT",
11
+ "main": "lib/index.js",
12
+ "module": "esm/index.js",
13
+ "types": "lib/index.d.ts",
14
+ "files": [
15
+ "lib"
16
+ ],
17
+ "scripts": {
18
+ "dev": "run-p watch:*",
19
+ "watch:esm": "tsc -p tsconfig.build.esm.json -w",
20
+ "watch:cjs": "tsc -p tsconfig.build.cjs.json -w",
21
+ "prebuild": "rimraf lib esm",
22
+ "build": "run-p build:*",
23
+ "build:esm": "tsc -p tsconfig.build.esm.json",
24
+ "build:cjs": "tsc -p tsconfig.build.cjs.json"
25
+ },
26
+ "engines": {
27
+ "node": ">= 12.0.0"
28
+ },
29
+ "dependencies": {
30
+ "@shuvi/router": "^0.0.1-rc.33",
31
+ "@shuvi/service": "^0.0.1-rc.33"
32
+ },
33
+ "devDependencies": {
34
+ "@types/react": "^16.9.43",
35
+ "@types/react-test-renderer": "^16.9.2",
36
+ "react-test-renderer": "^16.13.1"
37
+ },
38
+ "peerDependencies": {
39
+ "react": ">=16.8"
40
+ },
41
+ "gitHead": "ee2abab3c102f68450cf1fb6b2c833d5a59fb0c7"
42
+ }