Open History to see the last commit
1import React from 'react'
2import * as qss from 'qss'
3β
4import {
5 createBrowserHistory,
6 createHashHistory,
7 createMemoryHistory,
8 parsePath,
9 createPath,
10} from 'history'
11β
12{
13 createBrowserHistory, createHashHistory, createMemoryHistory
14}
15β
16// The shared context for everything
17const context = React.createContext()
18β
19// Detect if we're in the DOM
20const isDOM = Boolean(
21 typeof window !== 'undefined' &&
22 window.document &&
23 window.document.createElement,
24)
25β
26// This is the default history object if none is defined
27const defaultHistory = createBrowserHistory(
28 isDOM ? window : createMemoryHistory(),
29)
30β
31const useIsMounted = () => {
32 const isMountedRef = React.useRef(false)
33β
34 React.useEffect(() => {
35 isMountedRef.current = true
36β
37 return () => {
38 isMountedRef.current = false
39 }
40 }, [])
41β
42 return isMountedRef.current
43}
44β
45const LocationRoot = ({
46 children,
47 history: userHistory,
48 basepath: userBasepath,
49}) => {
50 const isMounted = useIsMounted()
51 const getIsMounted = useGetLatest(isMounted)
52 const historyRef = React.useRef(userHistory || defaultHistory)
53 const historyListenerRef = React.useRef()
54 const [location, setLocation] = React.useState(historyRef.current.location)
55β
56 if (!historyListenerRef.current) {
57 historyListenerRef.current = history.listen((location) => {
58 if (getIsMounted()) {
59 setLocation(location)
60 }
61 })
62 }
63β
64 // Before the component unmounts, unsubscribe from the history
65 React.useEffect(() => {
66 return historyListenerRef.current
67 }, [])
68β
69 const basepath = userBasepath || '/'
70β
71 const match = React.useMemo(
72 () => ({
73 path: '/',
74 url: '/',
75 params: {},
76 isExact: location.pathname === '/',
77 }),
78 [],
79 )
80β
81 const contextValueRef = React.useMemo(
82 () => ({
83 match,
84 location,
85 basepath,
86 history: historyRef.current,
87 }),
88 [location, basepath],
89 )
90β
91 return (
92 <context.Provider value={contextValueRef.current}>
93 {children}
94 </context.Provider>
95 )
96}
97β
98const parseQuery = (search) => {
99 let query = qss.decode(search.substring(1))
100β
101 // Try to parse any query params that might be json
102 Object.keys(query).forEach((key) => {
103 try {
104 query[key] = JSON.parse(query[key])
105 } catch (err) {
106 //
107 }
108 })
109β
110 return query
111}
112β
113const useLocation = () => {
114 const {
115 location,
116 match,
117 match: { params },
118 basepath,
119 history,
120 } = React.useContext(context)
121β
122 const { pathname, search, hash: fullHash, state, key } = location
123β
124 // Get the hash without the bang
125 const [, ...hashParts] = fullHash.split('#')
126 const hash = hashParts.join('')
127β
128 const previousQueryRef = React.useRef()
129β
130 // Parse the query params into an object
131 const query = React.useMemo(() => {
132 let newQuery = parseQuery(search)
133 return replaceEqualDeep(previousQueryRef.current, newQuery)
134 }, [search])
135 previousQueryRef.current = query
136β
137 const href = pathname + (hash ? `#${hash}` : '') + search
138β
139 return {
140 location,
141 match,
142 params,
143 hash,
144 query,
145 href,
146 state,
147 key,
148 history,
149 }
150}
151β
152const useNavigate = () => {
153 // Make the navigate function
154 return React.useCallback(
155 (
156 to,
157 { query: queryUpdater, state: stateUpdater, replace, preview } = {},
158 ) => {
159 // Allow query params and state to be updated with a function
160 const resolvedQuery =
161 typeof queryUpdater === 'function'
162 ? queryUpdater(navigateRef.current.query)
163 : queryUpdater
164 const resolvedState =
165 typeof stateUpdater === 'function'
166 ? stateUpdater(navigateRef.current.state)
167 : stateUpdater
168β
169 // If the query was updated, serialize all of the subkeys
170 if (resolvedQuery) {
171 Object.keys(resolvedQuery).forEach((key) => {
172 const val = resolvedQuery[key]
173 if (typeof val === 'object' && val !== 'null') {
174 resolvedQuery[key] = JSON.stringify(val)
175 }
176 })
177 }
178β
179 // Then stringify the query params for URL encoding
180 const search = qss.encode(resolvedQuery, '?')
181β
182 // Construct the final href for the navigation
183 const href =
184 resolve(
185 typeof to === 'function' ? to(params) : to,
186 navigateRef.current.basepath,
187 ) + (search === '?' ? '' : search)
188β
189 // If this is a preview, just return the final href
190 if (preview) {
191 return href
192 }
193β
194 // Otherwise, apply the navigation to the history
195 return navigateRef.current.history._navigate(href, {
196 state: resolvedState,
197 replace,
198 })
199 },
200 [],
201 )
202}
203β
204// MatchFirst returns the first matching child Match component or
205// any non-null non-Match component and renders only that component.
206// Comparable to React-Locations Swtich component
207export const MatchFirst = ({ children }) => {
208 const matchFirstRef = React.useRef()
209β
210 matchFirstRef.current = false
211β
212 let comp
213β
214 children = React.Children.toArray(children)
215 ;[...children.reverse()].forEach((child) => {
216 comp = child.type.__isMatch
217 ? React.cloneElement(child, {
218 ...child.props,
219 miss: comp,
220 exact: child.props.path === '/',
221 })
222 : child.type.__isRedirect
223 ? React.cloneElement(child, {
224 ...child.props,
225 miss: comp,
226 })
227 : child
228 })
229β
230 return comp
231}
232β
233// The Match component is used to match paths againts the location and
234// render content for that match
235const Match = ({ path, element, miss = null }) => {
236 // Use the location
237 const {
238 location,
239 match,
240 match: { params },
241 basepath,
242 history,
243 } = React.useContext(context)
244β
245 // See if the route is currently matched
246 let match = React.useMemo(() => isMatch(path), [isMatch, path])
247β
248 let newBasePath
249β
250 if (match) {
251 // If the route is a match, make sure we use
252 // the newBasePath from the match. It contains
253 // the interpolated path, free of route param
254 // identifiers
255 newBasePath = match.newBasePath
256 }
257β
258 const newParams = React.useMemo(
259 () => ({
260 ...params,
261 ...(match ? match.params : {}),
262 }),
263 [match, params],
264 )
265β
266 // Update the contex to use hte new basePath and params
267 const contextValue = React.useMemo(
268 () => ({
269 ...locationValue,
270 basepath: newBasePath,
271 params: newParams,
272 }),
273 [locationValue, newBasePath, newParams],
274 )
275β
276 // Not a match? Return a miss
277 if (!match) {
278 return miss
279 }
280β
281 // Support just children
282 return <context.Provider value={contextValue}>{element}</context.Provider>
283}
284β
285Match.__isMatch = true
286β
287// The Match component is used to match paths againts the location and
288// render content for that match
289const Redirect = ({ from, to, query, state, replace = true, miss = null }) => {
290 // Use the location
291 const locationValue = useLocation()
292 const { pathname, navigate, isMatch } = locationValue
293β
294 // See if the route is currently matched
295 let match = React.useMemo(() => !from || isMatch(from), [from, isMatch])
296β
297 if (match && from === '/' && !match.isExact) {
298 match = false
299 }
300β
301 React.useLayoutEffect(() => {
302 if (match) {
303 navigate(to, { query, state, replace })
304 }
305 }, [match, navigate])
306β
307 if (match) {
308 return null
309 }
310β
311 return miss
312}
313β
314Redirect.__isRedirect = true
315β
316function Link({
317 to,
318 query,
319 replace,
320 state,
321 onClick,
322 target,
323 style = {},
324 className = '',
325 getActiveProps = () => ({}),
326 activeType,
327 children,
328 ...rest
329}) {
330 // Use the useLocation hook
331 const location = useLocation()
332 const { navigate, pathname, href } = location
333β
334 // If this `to` is an external URL, make a normal a href
335 if (typeof to === 'string') {
336 try {
337 const link = new URL(to)
338 return (
339 <a
340 href={link.href}
341 target={target}
342 style={style}
343 className={className}
344 {...rest}
345 >
346 {children}
347 </a>
348 )
349 } catch (e) {
350 // if a path is not parsable by URL its a local relative path.
351 // Proceed
352 }
353 }
354β
355 // Get the preview href for this link and its variations
356 const linkHrefWithQuery = navigate(to, {
357 query,
358 state,
359 replace,
360 preview: true,
361 params: location.params,
362 })
363 const linkHrefWithHash = linkHrefWithQuery.split('?')[0]
364 const linkHref = linkHrefWithHash.split('#')[0]
365β
366 // Detect if this link is active using the different activeType options
367 let isCurrent
368 if (activeType === 'partial') {
369 isCurrent = startsWith(href, linkHrefWithQuery)
370 } else if (activeType === 'path') {
371 isCurrent = pathname === linkHref
372 } else if (activeType === 'hash') {
373 isCurrent = pathname === linkHrefWithHash
374 } else {
375 isCurrent = href === linkHrefWithQuery
376 }
377β
378 // Get the active props
379 const {
380 style: activeStyle = {},
381 className: activeClassName = '',
382 ...activeRest
383 } = isCurrent ? getActiveProps(location) : {}
384β
385 // The click handler
386 const handleClick = (e) => {
387 if (onClick) onClick(e)
388β
389 if (
390 !e.defaultPrevented && // onClick prevented default
391 e.button === 0 && // ignore everything but left clicks
392 (!target || target === '_self') && // let browser handle "target=_blank" etc.
393 !isModifiedEvent(e) // ignore clicks with modifier keys
394 ) {
395 e.preventDefault()
396 // All is well? Navigate!
397 navigate(to, { query, state, replace })
398 }
399 }
400β
401 return (
402 <a
403 href={linkHrefWithQuery}
404 target={target}
405 onClick={handleClick}
406 style={{
407 ...style,
408 ...activeStyle,
409 }}
410 className={
411 [className, activeClassName].filter(Boolean).join(' ') || undefined
412 }
413 {...rest}
414 {...activeRest}
415 >
416 {children}
417 </a>
418 )
419}
420β
421function trimSlashes(str) {
422 return str.replace(/(^\/+|\/+$)/g, '')
423}
424β
425function resolve(to, base) {
426 to = String(to)
427 if (startsWith(to, '/')) {
428 return to
429 }
430β
431 const toSegments = segmentize(to)
432 const baseSegments = segmentize(base)
433β
434 if (toSegments[0] === '') {
435 return base
436 }
437β
438 if (!startsWith(toSegments[0], '.')) {
439 const pathname = baseSegments.concat(toSegments).join('/')
440 return (base === '/' ? '' : '/') + pathname
441 }
442β
443 const allSegments = baseSegments.concat(toSegments)
444β
445 const segments = []
446β
447 for (let i = 0, l = allSegments.length; i < l; i++) {
448 const segment = allSegments[i]
449 if (segment === '..') segments.pop()
450 else if (segment !== '.') segments.push(segment)
451 }
452β
453 return `/${segments.join('/')}`
454}
455β
456function isMatch(path, parentPath) {
457 const pathSegments = segmentize(path)
458 const parentPathSegments = segmentize(parentPath)
459β
460 let newBasePath = []
461 const params = {}
462β
463 const isMatched = pathSegments.every((segment, i) => {
464 if (segment === parentPathSegments[i]) {
465 newBasePath[i] = parentPathSegments[i]
466 return true
467 }
468 if (startsWith(segment, ':') && parentPathSegments[i]) {
469 const paramName = trimLeading(segment, ':')
470 params[paramName] = parentPathSegments[i]
471 newBasePath[i] = parentPathSegments[i]
472 return true
473 }
474 return false
475 })
476β
477 newBasePath = newBasePath.join('/')
478β
479 const isExact = pathSegments.length === pathnameSegments.length
480β
481 return isMatched ? { params, newBasePath, isExact } : false
482}
483β
484function startsWith(string, search) {
485 return string.substring(0, search.length) === search
486}
487β
488function trimLeading(string, search) {
489 return string.substring(string.indexOf(search) + search.length)
490}
491β
492function segmentize(uri) {
493 if (!uri) {
494 return []
495 }
496 return trimSlashes(uri).split('/')
497}
498β
499function isModifiedEvent(e) {
500 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
501}
502β
503function getResolvedBasepath(path, basepath) {
504 return path === '/'
505 ? basepath
506 : `${trimSlashes(basepath)}/${trimSlashes(path)}`
507}
508β
509/**
510 * This function returns `a` if `b` is deeply equal.
511 * If not, it will replace any deeply equal children of `b` with those of `a`.
512 * This can be used for structural sharing between JSON values for example.
513 */
514function replaceEqualDeep(a, b) {
515 if (a === b) {
516 return a
517 }
518β
519 const array = Array.isArray(a) && Array.isArray(b)
520β
521 if (array || (isPlainObject(a) && isPlainObject(b))) {
522 const aSize = array ? a.length : Object.keys(a).length
523 const bItems = array ? b : Object.keys(b)
524 const bSize = bItems.length
525 const copy = array ? [] : {}
526β
527 let equalItems = 0
528β
529 for (let i = 0; i < bSize; i++) {
530 const key = array ? i : bItems[i]
531 copy[key] = replaceEqualDeep(a[key], b[key])
532 if (copy[key] === a[key]) {
533 equalItems++
534 }
535 }
536β
537 return aSize === bSize && equalItems === aSize ? a : copy
538 }
539β
540 return b
541}
542β
543// Copied from: https://github.com/jonschlinkert/is-plain-object
544function isPlainObject(o) {
545 if (!hasObjectPrototype(o)) {
546 return false
547 }
548β
549 // If has modified constructor
550 const ctor = o.constructor
551 if (typeof ctor === 'undefined') {
552 return true
553 }
554β
555 // If has modified prototype
556 const prot = ctor.prototype
557 if (!hasObjectPrototype(prot)) {
558 return false
559 }
560β
561 // If constructor does not have an Object-specific method
562 if (!prot.hasOwnProperty('isPrototypeOf')) {
563 return false
564 }
565β
566 // Most likely a plain Object
567 return true
568}
569β
570function hasObjectPrototype(o) {
571 return Object.prototype.toString.call(o) === '[object Object]'
572}