1import { useCallback, useMemo, useState, useEffect } from 'react';
2import { last, includes as _includes } from 'lodash';
5 * @param primary whether or not this is the top-level router
6 * @param names map of string to view key, used for consumer references
7 * @param views map of view keys to react component views
8 * @param initialRoutes initial set of routes following the { key, data } format
10export default function useRouter({
16 const [routes, setRoutes] = useState(initialRoutes);
18 const push = useCallback(
22 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
27 setRoutes(routes => [...routes, { key, data }]);
31 const popAndPush = useCallback(
35 `Invalid Route: ${key}. Possible Routes: ${Object.keys(views).join(
42 ...routes.slice(0, routes.length - 1),
48 const pop = useCallback(
51 routes.length > 1 ? [...routes.slice(0, routes.length - count)] : routes
53 // ^ can't pop root route
56 const peek = useCallback(() => last(routes), [routes]);
57 const replaceWith = useCallback(routes => setRoutes(() => routes), [
60 const reset = useCallback(() => setRoutes(initialRoutes), [
64 const includes = useCallback(key => _includes(routes.map(r => r.key), key), [
67 const size = routes.length;
68 const data = useMemo(() => last(routes).data, [routes]);
69 const Route = useMemo(() => views[peek().key], [views, peek]);
71 // Scroll to top of page with each route transition
73 window.scrollTo(0, 0);
76 // capture browser pop in primary router
78 const oldPopState = window.onpopstate;
80 window.history.pushState(null, null, null);
82 window.onpopstate = e => {
84 // if this is the root route, give the event to parent router
85 return oldPopState(e);
88 window.history.pushState(null, null, null);
93 window.onpopstate = 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