1import { useCallback, useMemo, useState, useRef, useEffect } from 'react';
2import { last, includes as _includes, findIndex } from 'lodash';
7 * @param primary whether or not this is the top-level router
8 * @param names map of string to view key, used for consumer references
9 * @param views map of view keys to react component views
10 * @param initialRoutes initial set of routes following the { key, data } format
12export default function useRouter({
18 const [routes, setRoutes] = useState(initialRoutes);
20 const oldPopState = useRef();
22 const size = routes.length;
23 const push = useCallback(
27 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
32 setRoutes(routes => [...routes, { key, data }]);
36 const popAndPush = useCallback(
40 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
47 ...routes.slice(0, routes.length - 1),
53 const pop = useCallback(
57 return setRoutes(routes => [...routes.slice(0, routes.length - count)]);
60 // if we are at the root, pass this event to our parent
61 if (oldPopState.current) {
62 window.history.back();
65 [size, setRoutes, oldPopState]
67 const popTo = useCallback(
69 const index = findIndex(routes, route => route.key === name);
70 return pop(routes.length - 1 - index);
74 const peek = useCallback(() => last(routes), [routes]);
75 const replaceWith = useCallback(routes => setRoutes(() => routes), [
78 const reset = useCallback(() => setRoutes(initialRoutes), [
82 const includes = useCallback(key => _includes(routes.map(r => r.key), key), [
85 const data = useMemo(() => last(routes).data || NULL_DATA, [routes]);
86 const Route = useMemo(() => views[peek().key], [views, peek]);
88 // Scroll to top of page with each route transition
90 window.scrollTo(0, 0);
94 // on router mount, register new state with browser
95 window.history.pushState(null, null, null);
98 // capture browser pop in primary router
100 // store the previous onpopstate handler
101 oldPopState.current = window.onpopstate;
103 // construct new onpopstate handler
104 window.onpopstate = e => {
105 if (size <= 1 && oldPopState.current) {
106 // if this is the root route and there's a parent handler,
107 // give the event to the handler
108 return oldPopState.current(e);
111 // on pop, tell the browser of a new state to avoid giving the user
112 // the ability to go forward
113 // TODO: allow the user to go forward by storing our data in history
114 // and using the url for other state
115 window.history.pushState(null, null, null);
117 // then update our local state for rendering
122 // reset the onpopstate to the previous version
123 window.onpopstate = oldPopState.current;
125 }, [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