1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
import {
createElement,
cloneElement,
createContext,
useState,
useContext,
Children,
useLayoutEffect
} from 'react';
/** @jsx createElement */
const memoryHistory = {
/**
* @typedef {{ pathname: string }} Location
* @typedef {(location: Location) => void} HistoryListener
* @type {HistoryListener[]}
*/
listeners: [],
/**
* @param {HistoryListener} listener
*/
listen(listener) {
const newLength = this.listeners.push(listener);
return () => this.listeners.splice(newLength - 1, 1);
},
/**
* @param {Location} to
*/
navigate(to) {
this.listeners.forEach(listener => listener(to));
}
};
/** @type {import('react').Context<{ history: typeof memoryHistory; location: Location }>} */
const RouterContext = createContext(null);
export function Router({ history = memoryHistory, children }) {
const [location, setLocation] = useState({ pathname: '/' });
useLayoutEffect(() => {
return history.listen(newLocation => setLocation(newLocation));
}, []);
return (
<RouterContext.Provider value={{ history, location }}>
{children}
</RouterContext.Provider>
);
}
export function Switch(props) {
const { location } = useContext(RouterContext);
let element = null;
Children.forEach(props.children, child => {
if (element == null && child.props.path == location.pathname) {
element = child;
}
});
return element;
}
/**
* @param {{ children: any; path: string; exact?: boolean; }} props
*/
export function Route({ children, path, exact }) {
return children;
}
export function Link({ to, children }) {
const { history } = useContext(RouterContext);
const onClick = event => {
event.preventDefault();
event.stopPropagation();
history.navigate({ pathname: to });
};
return (
<a href={to} onClick={onClick}>
{children}
</a>
);
}
|