1import { useCallback, useMemo, useState, useRef, useEffect } from 'react';
2import { last, includes as _includes, findIndex, get } from 'lodash';
7 * @param names map of string to view key, used for consumer references
8 * @param views map of view keys to react component views
9 * @param initialRoutes initial set of routes following the { key, data } format
11export default function useRouter({
16 const [routes, setRoutes] = useState(initialRoutes);
18 const oldPopState = useRef();
20 const size = routes.length;
21 const push = useCallback(
25 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
30 setRoutes(routes => [...routes, { key, data }]);
34 const popAndPush = useCallback(
38 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
45 ...routes.slice(0, routes.length - 1),
51 const pop = useCallback(
54 // if we are at the root, pass this event to our parent
55 if (oldPopState.current) {
56 oldPopState.current();
61 // on pop, tell the browser of a new state to avoid giving the user
62 // the ability to go forward
63 // TODO: allow the user to go forward by storing our data in history
64 // and using the url for other state
65 // (or just importing an actually good router lib)
66 window.history.pushState(null, null, null);
69 return setRoutes(routes => [...routes.slice(0, routes.length - count)]);
71 [size, setRoutes, oldPopState]
73 const popTo = useCallback(
75 const index = findIndex(routes, route => route.key === name);
76 return pop(routes.length - 1 - index);
80 const peek = useCallback(() => last(routes), [routes]);
81 const replaceWith = useCallback(routes => setRoutes(() => routes), [
84 const reset = useCallback(() => setRoutes(initialRoutes), [
88 const includes = useCallback(
91 routes.map(r => r.key),
96 const data = useMemo(() => {
97 return get(last(routes), 'data', NULL_DATA);
99 const Route = useMemo(() => views[peek().key], [views, peek]);
101 // Scroll to top of page with each route transition
103 window.scrollTo(0, 0);
107 // on router mount, register new state with browser
108 window.history.pushState(null, null, null);
111 // capture browser pop in primary router
113 // store the previous onpopstate handler
114 oldPopState.current = window.onpopstate;
116 // construct new onpopstate handler
117 window.onpopstate = e => {
118 e && e.stopImmediatePropagation();
123 // reset the onpopstate to the previous version
124 window.onpopstate = oldPopState.current;
126 }, [size, pop, oldPopState]);
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list