Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

index.js

460 lines11.0 KB

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,
29​
30// This is the default history object if none is defined
31export const globalHistory = createHistory(
32 isDOM ? window : createMemorySource(),
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>
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>
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 } = 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(to, navigateRef.current.basepath) +
177 (search === '?' ? '' : search)
178​
179 // If this is a preview, just return the final href
180 if (preview) {
181 return href
182 }
183​
184 // Otherwise, apply the navigation to the history
185 return navigateRef.current.history._navigate(href, {
186 state: resolvedState,
187 replace,
188 })
189 },
190 [],
191 )
192​
193 const isMatch = React.useCallback(
194 (matchPath, from) =>
195 _isMatch(getResolvedBasepath(matchPath, from || basepath), pathname),
196 [basepath, pathname],
197 )
198​
199 return {
200 ...contextValue,
201 navigate,
202 isMatch,
203 }
205​
206export const Location = ({ children, render, ...rest }) => {
207 const location = useLocation(rest)
208​
209 if (children) {
210 return children(location)
211 }
212​
213 if (render) {
214 return render(location)
215 }
216​
217 return null
219​
220export const withLocation = Comp => {
221 return props => {
222 const location = useLocation()
223 return <Comp {...props} location={location} />
224 }
226​
227// MatchFirst returns the first matching child Match component or
228// any non-null non-Match component and renders only that component.
229// Comparable to React-Locations Swtich component
230export const MatchFirst = ({ children }) => {
231 const matchFirstRef = React.useRef()
232​
233 matchFirstRef.current = false
234​
235 let comp
236​
237 children = React.Children.toArray(children)
238 ;[...children.reverse()].forEach(child => {
239 comp = child.type.__isMatch
240 ? React.cloneElement(child, {
241 ...child.props,
242 miss: comp,
243 exact: child.props.path === '/',
244 })
245 : child.type.__isRedirect
246 ? React.cloneElement(child, {
247 ...child.props,
248 miss: comp,
249 })
250 : child
251 })
252​
253 return comp
255​
256// The Match component is used to match paths againts the location and
257// render content for that match
258export const Match = ({
259 path,
260 routes,
261 children,
262 render,
263 component: Comp,
264 miss = null,
265 exact,
266 ...rest
267}) => {
268 // Use the location
269 const locationValue = useLocation()
270 const { params, isMatch } = locationValue
271​
272 // See if the route is currently matched
273 let match = React.useMemo(() => isMatch(path), [isMatch, path])
274​
275 let newBasePath
276​
277 if (match) {
278 // If the route is a match, make sure we use
279 // the newBasePath from the match. It contains
280 // the interpolated path, free of route param
281 // identifiers
282 newBasePath = match.newBasePath
283 }
284​
285 const newParams = React.useMemo(
286 () => ({
287 ...params,
288 ...(match ? match.params : {}),
289 }),
290 [match, params],
291 )
292​
293 // Update the contex to use hte new basePath and params
294 const contextValue = React.useMemo(
295 () => ({
296 ...locationValue,
297 basepath: newBasePath,
298 params: newParams,
299 }),
300 [locationValue, newBasePath, newParams],
301 )
302​
303 // Not a match? Return a miss
304 if (!match || (exact && !match.isExact)) {
305 return miss
306 }
307​
308 const renderProps = {
309 ...contextValue,
310 ...contextValue.params,
311 }
312​
313 // Support the render prop
314 if (render) {
315 children = render(renderProps)
316 }
317​
318 // Support the component prop
319 if (Comp) {
320 children = <Comp {...renderProps} {...rest} />
321 }
322​
323 // Support child as a function
324 if (typeof children === 'function') {
325 children = children(renderProps)
326 }
327​
328 // Support just children
329 return <context.Provider value={contextValue}>{children}</context.Provider>
331​
332Match.__isMatch = true
333​
334// The Match component is used to match paths againts the location and
335// render content for that match
336export const Redirect = ({
337 from = '/',
338 to,
339 query,
340 state,
341 replace = true,
342 miss = null,
343}) => {
344 // Use the location
345 const locationValue = useLocation()
346 const { pathname, navigate, isMatch } = locationValue
347​
348 // See if the route is currently matched
349 let match = React.useMemo(() => isMatch(from || '/'), [from, isMatch])
350​
351 if (match && (from === '/' ? match.isExact : true)) {
352 navigate(to, { query, state, replace })
353 }
354​
355 return miss
357​
358Redirect.__isRedirect = true
359​
360export function Link({
361 to,
362 query,
363 replace,
364 state,
365 onClick,
366 target,
367 style = {},
368 className = '',
369 getActiveProps = () => ({}),
370 activeType,
371 children,
372 ...rest
373}) {
374 // Use the useLocation hook
375 const location = useLocation()
376 const { navigate, pathname, href } = location
377​
378 // If this `to` is an external URL, make a normal a href
379 try {
380 const link = new URL(to)
381 return (
382 <a
383 href={link.href}
384 target={target}
385 style={style}
386 className={className}
387 {...rest}
388 >
389 {children}
390 </a>
391 )
392 } catch (e) {
393 // if a path is not parsable by URL its a local relative path.
394 // Proceed
395 }
396​
397 // Get the preview href for this link and its variations
398 const linkHrefWithQuery = navigate(to, {
399 query,
400 state,
401 replace,
402 preview: true,
403 })
404 const linkHrefWithHash = linkHrefWithQuery.split('?')[0]
405 const linkHref = linkHrefWithHash.split('#')[0]
406​
407 // Detect if this link is active using the different activeType options
408 let isCurrent
409 if (activeType === 'partial') {
410 isCurrent = startsWith(href, linkHrefWithQuery)
411 } else if (activeType === 'path') {
412 isCurrent = pathname === linkHref
413 } else if (activeType === 'hash') {
414 isCurrent = pathname === linkHrefWithHash
415 } else {
416 isCurrent = href === linkHrefWithQuery
417 }
418​
419 // Get the active props
420 const {
421 style: activeStyle = {},
422 className: activeClassName = '',
423 ...activeRest
424 } = isCurrent ? getActiveProps(location) : {}
425​
426 // The click handler
427 const handleClick = e => {
428 if (onClick) onClick(e)
429​
430 if (
431 !e.defaultPrevented && // onClick prevented default
432 e.button === 0 && // ignore everything but left clicks
433 (!target || target === '_self') && // let browser handle "target=_blank" etc.
434 !isModifiedEvent(e) // ignore clicks with modifier keys
435 ) {
436 e.preventDefault()
437 // All is well? Navigate!
438 navigate(to, { query, state, replace })
439 }
440 }
441​
442 return (
443 <a
444 href={linkHrefWithQuery}
445 target={target}
446 onClick={handleClick}
447 style={{
448 ...style,
449 ...activeStyle,
450 }}
451 className={
452 [className, activeClassName].filter(Boolean).join(' ') || undefined
453 }
454 {...rest}
455 {...activeRest}
456 >
457 {children}
458 </a>
459 )