Open History to see the last commit
1/* eslint-disable no-nested-ternary */
2/* eslint-disable react/prop-types */
3/* eslint-disable no-console */
4import React from 'react'
5import * as qss from 'qss'
6β
7import { createHistory, createMemorySource } from './history'
8import {
9 isModifiedEvent,
10 resolve,
11 isMatch as _isMatch,
12 startsWith,
13 getResolvedBasepath,
14 useForceUpdate,
15} from './utils'
16β
17// Allow creation of custom historys including memory sources
18export { createHistory, createMemorySource }
19β
20// The shared context for everything
21const context = React.createContext()
22β
23// Detect if we're in the DOM
24const isDOM = Boolean(
25 typeof window !== 'undefined' &&
26 window.document &&
27 window.document.createElement,
28)
29β
30// This is the default history object if none is defined
31export const globalHistory = createHistory(
32 isDOM ? window : createMemorySource(),
33)
34β
35const LocationRoot = ({
36 children,
37 history: userHistory,
38 basepath: userBasepath,
39}) => {
40 // If this is the first history, create it using the userHistory or browserHistory
41 const historyRef = React.useRef(userHistory || globalHistory)
42 const forceUpdate = useForceUpdate()
43β
44 const history = historyRef.current
45β
46 // Let's get at some of the nested data on the history object
47 let {
48 location: { pathname, hash: fullHash, search, state, id },
49 _onTransitionComplete,
50 } = history
51β
52 // eslint-disable-next-line react-hooks/exhaustive-deps
53 state = React.useMemo(() => state, [JSON.stringify(state)])
54β
55 // Get the hash without the bang
56 const hash = fullHash.split('#').reverse()[0]
57 // The default basepath for the entire Location
58 const basepath = userBasepath || '/'
59 // Parse the query params into an object
60 const query = React.useMemo(() => {
61 let query = qss.decode(search.substring(1))
62β
63 // Try to parse any query params that might be json
64 Object.keys(query).forEach((key) => {
65 try {
66 query[key] = JSON.parse(query[key])
67 } catch (err) {
68 //
69 }
70 })
71β
72 return query
73 }, [search])
74β
75 // Start off with fresh params at the top level
76 const params = React.useMemo(() => ({}), [])
77β
78 const href = pathname + (hash ? `#${hash}` : '') + search
79β
80 // Build our context value
81 const contextValue = {
82 basepath,
83 pathname,
84 hash,
85 params,
86 query,
87 search,
88 state,
89 href,
90 id,
91 history,
92 }
93β
94 const historyListenerRef = React.useRef()
95β
96 // Subscribe to the history, even before the component mounts
97 if (!historyListenerRef.current) {
98 // Update this component any time history updates
99 historyListenerRef.current = history.listen(forceUpdate)
100 }
101β
102 // Before the component unmounts, unsubscribe from the history
103 React.useEffect(() => {
104 return historyListenerRef.current
105 }, [])
106β
107 // After component update, mark the transition as complete
108 React.useEffect(() => {
109 _onTransitionComplete()
110 })
111β
112 return <context.Provider value={contextValue}>{children}</context.Provider>
113}
114β
115// This is the main Location component that acts like a Provider
116export const LocationProvider = ({ children, location, ...rest }) => {
117 if (location) {
118 return <context.Provider value={location}>{children}</context.Provider>
119 }
120 return <LocationRoot {...rest}>{children}</LocationRoot>
121}
122β
123// This hook powers just about everything. It is also responsible for
124// creating the navigate() function based on the depth at which the hook is used
125export const useLocation = () => {
126 const contextValue = React.useContext(context)
127 const forceUpdate = useForceUpdate()
128 const { query, state, history, basepath, pathname, params } = contextValue
129β
130 // Make sure any components using this hook update when the
131 // history changes
132 React.useEffect(() => {
133 return history.listen(forceUpdate)
134 }, [forceUpdate, history])
135β
136 const navigateRef = React.useRef()
137β
138 navigateRef.current = {
139 history,
140 basepath,
141 query,
142 state,
143 }
144β
145 // Make the navigate function
146 const navigate = React.useCallback(
147 (
148 to,
149 { query: queryUpdater, state: stateUpdater, replace, preview } = {},
150 ) => {
151 // Allow query params and state to be updated with a function
152 const resolvedQuery =
153 typeof queryUpdater === 'function'
154 ? queryUpdater(navigateRef.current.query)
155 : queryUpdater
156 const resolvedState =
157 typeof stateUpdater === 'function'
158 ? stateUpdater(navigateRef.current.state)
159 : stateUpdater
160β
161 // If the query was updated, serialize all of the subkeys
162 if (resolvedQuery) {
163 Object.keys(resolvedQuery).forEach((key) => {
164 const val = resolvedQuery[key]
165 if (typeof val === 'object' && val !== 'null') {
166 resolvedQuery[key] = JSON.stringify(val)
167 }
168 })
169 }
170β
171 // Then stringify the query params for URL encoding
172 const search = qss.encode(resolvedQuery, '?')
173β
174 // Construct the final href for the navigation
175 const href =
176 resolve(
177 typeof to === 'function' ? to(params) : to,
178 navigateRef.current.basepath,
179 ) + (search === '?' ? '' : search)
180β
181 // If this is a preview, just return the final href
182 if (preview) {
183 return href
184 }
185β
186 // Otherwise, apply the navigation to the history
187 return navigateRef.current.history._navigate(href, {
188 state: resolvedState,
189 replace,
190 })
191 },
192 [],
193 )
194β
195 const isMatch = React.useCallback(
196 (matchPath, from) =>
197 _isMatch(getResolvedBasepath(matchPath, from || basepath), pathname),
198 [basepath, pathname],
199 )
200β
201 return {
202 ...contextValue,
203 navigate,
204 isMatch,
205 }
206}
207β
208export const Location = ({ children, render, ...rest }) => {
209 const location = useLocation(rest)
210β
211 if (children) {
212 return children(location)
213 }
214β
215 if (render) {
216 return render(location)
217 }
218β
219 return null
220}
221β
222export const withLocation = (Comp) => {
223 return (props) => {
224 const location = useLocation()
225 return <Comp {...props} location={location} />
226 }
227}
228β
229// MatchFirst returns the first matching child Match component or
230// any non-null non-Match component and renders only that component.
231// Comparable to React-Locations Swtich component
232export const MatchFirst = ({ children }) => {
233 const matchFirstRef = React.useRef()
234β
235 matchFirstRef.current = false
236β
237 let comp
238β
239 children = React.Children.toArray(children)
240 ;[...children.reverse()].forEach((child) => {
241 comp = child.type.__isMatch
242 ? React.cloneElement(child, {
243 ...child.props,
244 miss: comp,
245 exact: child.props.path === '/',
246 })
247 : child.type.__isRedirect
248 ? React.cloneElement(child, {
249 ...child.props,
250 miss: comp,
251 })
252 : child
253 })
254β
255 return comp
256}
257β
258// The Match component is used to match paths againts the location and
259// render content for that match
260export const Match = ({
261 path,
262 routes,
263 children,
264 render,
265 component: Comp,
266 miss = null,
267 exact,
268 ...rest
269}) => {
270 // Use the location
271 const locationValue = useLocation()
272 const { params, isMatch } = locationValue
273β
274 // See if the route is currently matched
275 let match = React.useMemo(() => isMatch(path), [isMatch, path])
276β
277 let newBasePath
278β
279 if (match) {
280 // If the route is a match, make sure we use
281 // the newBasePath from the match. It contains
282 // the interpolated path, free of route param
283 // identifiers
284 newBasePath = match.newBasePath
285 }
286β
287 const newParams = React.useMemo(
288 () => ({
289 ...params,
290 ...(match ? match.params : {}),
291 }),
292 [match, params],
293 )
294β
295 // Update the contex to use hte new basePath and params
296 const contextValue = React.useMemo(
297 () => ({
298 ...locationValue,
299 basepath: newBasePath,
300 params: newParams,
301 }),
302 [locationValue, newBasePath, newParams],
303 )
304β
305 // Not a match? Return a miss
306 if (!match || (exact && !match.isExact)) {
307 return miss
308 }
309β
310 const renderProps = {
311 ...contextValue,
312 ...contextValue.params,
313 }
314β
315 // Support the render prop
316 if (render) {
317 children = render(renderProps)
318 }
319β
320 // Support the component prop
321 if (Comp) {
322 children = <Comp {...renderProps} {...rest} />
323 }
324β
325 // Support child as a function
326 if (typeof children === 'function') {
327 children = children(renderProps)
328 }
329β
330 // Support just children
331 return <context.Provider value={contextValue}>{children}</context.Provider>
332}
333β
334Match.__isMatch = true
335β
336// The Match component is used to match paths againts the location and
337// render content for that match
338export const Redirect = ({
339 from,
340 to,
341 query,
342 state,
343 replace = true,
344 miss = null,
345}) => {
346 // Use the location
347 const locationValue = useLocation()
348 const { pathname, navigate, isMatch } = locationValue
349β
350 // See if the route is currently matched
351 let match = React.useMemo(() => !from || isMatch(from), [from, isMatch])
352β
353 if (match && from === '/' && !match.isExact) {
354 match = false
355 }
356β
357 React.useLayoutEffect(() => {
358 if (match) {
359 navigate(to, { query, state, replace })
360 }
361 }, [match, navigate])
362β
363 if (match) {
364 return null
365 }
366β
367 return miss
368}
369β
370Redirect.__isRedirect = true
371β
372export function Link({
373 to,
374 query,
375 replace,
376 state,
377 onClick,
378 target,
379 style = {},
380 className = '',
381 getActiveProps = () => ({}),
382 activeType,
383 children,
384 ...rest
385}) {
386 // Use the useLocation hook
387 const location = useLocation()
388 const { navigate, pathname, href } = location
389β
390 // If this `to` is an external URL, make a normal a href
391 if (typeof to === 'string') {
392 try {
393 const link = new URL(to)
394 return (
395 <a
396 href={link.href}
397 target={target}
398 style={style}
399 className={className}
400 {...rest}
401 >
402 {children}
403 </a>
404 )
405 } catch (e) {
406 // if a path is not parsable by URL its a local relative path.
407 // Proceed
408 }
409 }
410β
411 // Get the preview href for this link and its variations
412 const linkHrefWithQuery = navigate(to, {
413 query,
414 state,
415 replace,
416 preview: true,
417 params: location.params,
418 })
419 const linkHrefWithHash = linkHrefWithQuery.split('?')[0]
420 const linkHref = linkHrefWithHash.split('#')[0]
421β
422 // Detect if this link is active using the different activeType options
423 let isCurrent
424 if (activeType === 'partial') {
425 isCurrent = startsWith(href, linkHrefWithQuery)
426 } else if (activeType === 'path') {
427 isCurrent = pathname === linkHref
428 } else if (activeType === 'hash') {
429 isCurrent = pathname === linkHrefWithHash
430 } else {
431 isCurrent = href === linkHrefWithQuery
432 }
433β
434 // Get the active props
435 const {
436 style: activeStyle = {},
437 className: activeClassName = '',
438 ...activeRest
439 } = isCurrent ? getActiveProps(location) : {}
440β
441 // The click handler
442 const handleClick = (e) => {
443 if (onClick) onClick(e)
444β
445 if (
446 !e.defaultPrevented && // onClick prevented default
447 e.button === 0 && // ignore everything but left clicks
448 (!target || target === '_self') && // let browser handle "target=_blank" etc.
449 !isModifiedEvent(e) // ignore clicks with modifier keys
450 ) {
451 e.preventDefault()
452 // All is well? Navigate!
453 navigate(to, { query, state, replace })
454 }
455 }
456β
457 return (
458 <a
459 href={linkHrefWithQuery}
460 target={target}
461 onClick={handleClick}
462 style={{
463 ...style,
464 ...activeStyle,
465 }}
466 className={
467 [className, activeClassName].filter(Boolean).join(' ') || undefined
468 }
469 {...rest}
470 {...activeRest}
471 >
472 {children}
473 </a>
474 )
475}