@@ -1,67 +1,20 @@
1−import React, {
2− createContext,
3− forwardRef,
4− useContext,
5− useState,
6− useEffect,
7−} from 'react';
8−import { last, includes } from 'lodash';
1+import React, { createContext, forwardRef, useContext } from 'react';
92
10−import { BRIDGE_ERROR } from '../lib/error';
11−import { ROUTE_NAMES } from '../lib/routeNames';
3+import useRouter from 'lib/useRouter';
124
13−export const HistoryContext = createContext(null);
14−
15−function _useHistory(initialRoutes = []) {
16− const [history, setHistory] = useState(initialRoutes);
17−
18− const value = {
19− routes: history,
20− push: (name, data) => {
21− if (!includes(ROUTE_NAMES, name)) {
22− throw BRIDGE_ERROR.INVALID_ROUTE;
23− }
24−
25− setHistory(history => [...history, { name, data }]);
26− },
27− popAndPush: (name, data = {}) =>
28− setHistory(history => [
29− ...history.slice(0, history.length - 1),
30− { name, data },
31− ]),
32− pop: (count = 1) =>
33− setHistory(history => [...history.slice(0, history.length - count)]),
34− peek: () => last(history),
35− size: history.length,
36− includes: name => includes(history.map(r => r.name), name),
37− data: last(history).data,
38− };
39−
40− // Scroll to top of page with each route transition.
41− useEffect(() => window.scrollTo(0, 0), [history]);
5+/**
6+ * `useHistory` is just a global `useRouter`
7+ * and we call it `history` to distinguish it within a local router.
8+ * (see Invite.js for an example)
9+ */
4210
43− // set up handlers
44− useEffect(() => {
45− window.history.pushState(null, null, null);
46−
47− window.onpopstate = e => {
48− window.history.pushState(null, null, null);
49− value.pop();
50− };
51−
52− // TODO: disposer functon
53− });
54−
55− return value;
56−}
11+export const HistoryContext = createContext(null);
5712
58−export function HistoryProvider({ initialRoutes, children }) {
59− const history = _useHistory(initialRoutes);
13+export function HistoryProvider({ names, views, initialRoutes, children }) {
14+ const router = useRouter({ names, views, initialRoutes, primary: true });
6015
6116 return (
62− <HistoryContext.Provider value={history}>
63− {children}
64− </HistoryContext.Provider>
17+ <HistoryContext.Provider value={router}>{children}</HistoryContext.Provider>
6518 );
6619}
6720
@@ -74,6 +27,6 @@ export function useHistory() {
7427export const withHistory = Component =>
7528 forwardRef((props, ref) => (
7629 <HistoryContext.Consumer>
77− {history => <Component ref={ref} history={history} {...props} />}
30+ {router => <Component ref={ref} history={router} {...props} />}
7831 </HistoryContext.Consumer>
7932 ));