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

BaseTanStackRouterDevtoolsPanel.tsx

687 lines21.0 KB

1import { clsx as cx } from 'clsx'
2import { default as invariant } from 'tiny-invariant'
3import { interpolatePath, rootRouteId, trimPath } from '@tanstack/router-core'
4import { Show, createMemo, createSignal, onCleanup } from 'solid-js'
5import { useDevtoolsOnClose } from './context'
6import { useStyles } from './useStyles'
7import useLocalStorage from './useLocalStorage'
8import { Explorer } from './Explorer'
9import { getRouteStatusColor, getStatusColor, multiSortBy } from './utils'
10import { AgeTicker } from './AgeTicker'
11// import type { DevtoolsPanelOptions } from './TanStackRouterDevtoolsPanel'
12​
13import { NavigateButton } from './NavigateButton'
14import type {
15 AnyContext,
16 AnyRoute,
17 AnyRouter,
18 FileRouteTypes,
19 MakeRouteMatchUnion,
20 Route,
21 RouterState,
22} from '@tanstack/router-core'
23import type { Accessor, JSX } from 'solid-js'
24​
25export interface BaseDevtoolsPanelOptions {
26 /**
27 * The standard React style object used to style a component with inline styles
28 */
29 style?: Accessor<JSX.CSSProperties>
30 /**
31 * The standard React class property used to style a component with classes
32 */
33 className?: Accessor<string>
34 /**
35 * A boolean variable indicating whether the panel is open or closed
36 */
37 isOpen?: boolean
38 /**
39 * A function that toggles the open and close state of the panel
40 */
41 setIsOpen?: (isOpen: boolean) => void
42 /**
43 * Handles the opening and closing the devtools panel
44 */
45 handleDragStart?: (e: any) => void
46 /**
47 * A boolean variable indicating if the "lite" version of the library is being used
48 */
49 router: Accessor<AnyRouter>
50 routerState: Accessor<any>
51 /**
52 * Use this to attach the devtool's styles to specific element in the DOM.
53 */
54 shadowDOMTarget?: ShadowRoot
56​
57function Logo(props: any) {
58 const { className, ...rest } = props
59 const styles = useStyles()
60 return (
61 <button {...rest} class={cx(styles().logo, className ? className() : '')}>
62 <div class={styles().tanstackLogo}>TANSTACK</div>
63 <div class={styles().routerLogo}>TanStack Router v1</div>
64 </button>
65 )
67​
68function NavigateLink(props: {
69 class?: string
70 left?: JSX.Element
71 children?: JSX.Element
72 right?: JSX.Element
73}) {
74 return (
75 <div
76 class={props.class}
77 style={{
78 display: 'flex',
79 'align-items': 'center',
80 width: '100%',
81 }}
82 >
83 {props.left}
84 <div style={{ 'flex-grow': 1, 'min-width': 0 }}>{props.children}</div>
85 {props.right}
86 </div>
87 )
89​
90function RouteComp({
91 routerState,
92 router,
93 route,
94 isRoot,
95 activeId,
96 setActiveId,
97}: {
98 routerState: Accessor<
99 RouterState<
100 Route<
101 any,
102 any,
103 any,
104 '/',
105 '/',
106 string,
107 '__root__',
108 undefined,
109 {},
110 {},
111 AnyContext,
112 AnyContext,
113 {},
114 undefined,
115 any,
116 FileRouteTypes,
117 unknown,
118 undefined
119 >,
120 MakeRouteMatchUnion
121 >
122 >
123 router: Accessor<AnyRouter>
124 route: AnyRoute
125 isRoot?: boolean
126 activeId: Accessor<string | undefined>
127 setActiveId: (id: string) => void
128}) {
129 const styles = useStyles()
130 const matches = createMemo(
131 () => routerState().pendingMatches || routerState().matches,
132 )
133 const match = createMemo(() =>
134 routerState().matches.find((d) => d.routeId === route.id),
135 )
136​
137 const param = createMemo(() => {
138 try {
139 if (match()?.params) {
140 const p = match()?.params
141 const r: string = route.path || trimPath(route.id)
142 if (r.startsWith('$')) {
143 const trimmed = r.slice(1)
144​
145 if (p[trimmed]) {
146 return `(${p[trimmed]})`
147 }
148 }
149 }
150 return ''
151 } catch (error) {
152 return ''
153 }
154 })
155​
156 const navigationTarget = createMemo<string | undefined>(() => {
157 if (isRoot) return undefined // rootRouteId has no path
158 if (!route.path) return undefined // no path to navigate to
159​
160 // flatten all params in the router state, into a single object
161 const allParams = Object.assign({}, ...matches().map((m) => m.params))
162​
163 // interpolatePath is used by router-core to generate the `to`
164 // path for the navigate function in the router
165 const interpolated = interpolatePath({
166 path: route.fullPath,
167 params: allParams,
168 leaveWildcards: false,
169 leaveParams: false,
170 decodeCharMap: router().pathParamsDecodeCharMap,
171 })
172​
173 // only if `interpolated` is not missing params, return the path since this
174 // means that all the params are present for a successful navigation
175 return !interpolated.isMissingParams
176 ? interpolated.interpolatedPath
177 : undefined
178 })
179​
180 return (
181 <div>
182 <div
183 role="button"
184 aria-label={`Open match details for ${route.id}`}
185 onClick={() => {
186 if (match()) {
187 setActiveId(activeId() === route.id ? '' : route.id)
188 }
189 }}
190 class={cx(
191 styles().routesRowContainer(route.id === activeId(), !!match()),
192 )}
193 >
194 <div
195 class={cx(
196 styles().matchIndicator(getRouteStatusColor(matches(), route)),
197 )}
198 />
199 <NavigateLink
200 class={cx(styles().routesRow(!!match()))}
201 left={
202 <Show when={navigationTarget()}>
203 {(navigate) => <NavigateButton to={navigate()} router={router} />}
204 </Show>
205 }
206 right={<AgeTicker match={match()} router={router} />}
207 >
208 <code class={styles().code}>
209 {isRoot ? rootRouteId : route.path || trimPath(route.id)}{' '}
210 </code>
211 <code class={styles().routeParamInfo}>{param()}</code>
212 </NavigateLink>
213 </div>
214 {route.children?.length ? (
215 <div class={styles().nestedRouteRow(!!isRoot)}>
216 {[...(route.children as Array<AnyRoute>)]
217 .sort((a, b) => {
218 return a.rank - b.rank
219 })
220 .map((r) => (
221 <RouteComp
222 routerState={routerState}
223 router={router}
224 route={r}
225 activeId={activeId}
226 setActiveId={setActiveId}
227 />
228 ))}
229 </div>
230 ) : null}
231 </div>
232 )
234​
235export const BaseTanStackRouterDevtoolsPanel =
236 function BaseTanStackRouterDevtoolsPanel({
237 ...props
238 }: BaseDevtoolsPanelOptions): JSX.Element {
239 const {
240 isOpen = true,
241 setIsOpen,
242 handleDragStart,
243 router,
244 routerState,
245 shadowDOMTarget,
246 ...panelProps
247 } = props
248​
249 const { onCloseClick } = useDevtoolsOnClose()
250 const styles = useStyles()
251 const { className, style, ...otherPanelProps } = panelProps
252​
253 invariant(
254 router,
255 'No router was found for the TanStack Router Devtools. Please place the devtools in the <RouterProvider> component tree or pass the router instance to the devtools manually.',
256 )
257​
258 // useStore(router.__store)
259​
260 const [showMatches, setShowMatches] = useLocalStorage(
261 'tanstackRouterDevtoolsShowMatches',
262 true,
263 )
264​
265 const [activeId, setActiveId] = useLocalStorage(
266 'tanstackRouterDevtoolsActiveRouteId',
267 '',
268 )
269​
270 const activeMatch = createMemo(() => {
271 const matches = [
272 ...(routerState().pendingMatches ?? []),
273 ...routerState().matches,
274 ...routerState().cachedMatches,
275 ]
276 return matches.find(
277 (d) => d.routeId === activeId() || d.id === activeId(),
278 )
279 })
280​
281 const hasSearch = createMemo(
282 () => Object.keys(routerState().location.search).length,
283 )
284​
285 const explorerState = createMemo(() => {
286 return {
287 ...router(),
288 state: routerState(),
289 }
290 })
291​
292 const routerExplorerValue = createMemo(() =>
293 Object.fromEntries(
294 multiSortBy(
295 Object.keys(explorerState()),
296 (
297 [
298 'state',
299 'routesById',
300 'routesByPath',
301 'flatRoutes',
302 'options',
303 'manifest',
304 ] as const
305 ).map((d) => (dd) => dd !== d),
306 )
307 .map((key) => [key, (explorerState() as any)[key]])
308 .filter(
309 (d) =>
310 typeof d[1] !== 'function' &&
311 ![
312 '__store',
313 'basepath',
314 'injectedHtml',
315 'subscribers',
316 'latestLoadPromise',
317 'navigateTimeout',
318 'resetNextScroll',
319 'tempLocationKey',
320 'latestLocation',
321 'routeTree',
322 'history',
323 ].includes(d[0]),
324 ),
325 ),
326 )
327 const activeMatchLoaderData = createMemo(() => activeMatch()?.loaderData)
328 const activeMatchValue = createMemo(() => activeMatch())
329 const locationSearchValue = createMemo(() => routerState().location.search)
330​
331 return (
332 <div
333 class={cx(
334 styles().devtoolsPanel,
335 'TanStackRouterDevtoolsPanel',
336 className ? className() : '',
337 )}
338 style={style ? style() : ''}
339 {...otherPanelProps}
340 >
341 {handleDragStart ? (
342 <div class={styles().dragHandle} onMouseDown={handleDragStart}></div>
343 ) : null}
344 <button
345 class={styles().panelCloseBtn}
346 onClick={(e: any) => {
347 if (setIsOpen) {
348 setIsOpen(false)
349 }
350 onCloseClick(e)
351 }}
352 >
353 <svg
354 xmlns="http://www.w3.org/2000/svg"
355 width="10"
356 height="6"
357 fill="none"
358 viewBox="0 0 10 6"
359 class={styles().panelCloseBtnIcon}
360 >
361 <path
362 stroke="currentColor"
363 stroke-linecap="round"
364 stroke-linejoin="round"
365 stroke-width="1.667"
366 d="M1 1l4 4 4-4"
367 ></path>
368 </svg>
369 </button>
370 <div class={styles().firstContainer}>
371 <div class={styles().row}>
372 <Logo
373 aria-hidden
374 onClick={(e: any) => {
375 if (setIsOpen) {
376 setIsOpen(false)
377 }
378 onCloseClick(e)
379 }}
380 />
381 </div>
382 <div class={styles().routerExplorerContainer}>
383 <div class={styles().routerExplorer}>
384 <Explorer
385 label="Router"
386 value={routerExplorerValue}
387 defaultExpanded={{
388 state: {} as any,
389 context: {} as any,
390 options: {} as any,
391 }}
392 filterSubEntries={(subEntries) => {
393 return subEntries.filter(
394 (d: any) => typeof d.value() !== 'function',
395 )
396 }}
397 />
398 </div>
399 </div>
400 </div>
401 <div class={styles().secondContainer}>
402 <div class={styles().matchesContainer}>
403 <div class={styles().detailsHeader}>
404 <span>Pathname</span>
405 {routerState().location.maskedLocation ? (
406 <div class={styles().maskedBadgeContainer}>
407 <span class={styles().maskedBadge}>masked</span>
408 </div>
409 ) : null}
410 </div>
411 <div class={styles().detailsContent}>
412 <code>{routerState().location.pathname}</code>
413 {routerState().location.maskedLocation ? (
414 <code class={styles().maskedLocation}>
415 {routerState().location.maskedLocation?.pathname}
416 </code>
417 ) : null}
418 </div>
419 <div class={styles().detailsHeader}>
420 <div class={styles().routeMatchesToggle}>
421 <button
422 type="button"
423 onClick={() => {
424 setShowMatches(false)
425 }}
426 disabled={!showMatches()}
427 class={cx(
428 styles().routeMatchesToggleBtn(!showMatches(), true),
429 )}
430 >
431 Routes
432 </button>
433 <button
434 type="button"
435 onClick={() => {
436 setShowMatches(true)
437 }}
438 disabled={showMatches()}
439 class={cx(
440 styles().routeMatchesToggleBtn(!!showMatches(), false),
441 )}
442 >
443 Matches
444 </button>
445 </div>
446 <div class={styles().detailsHeaderInfo}>
447 <div>age / staleTime / gcTime</div>
448 </div>
449 </div>
450 <div class={cx(styles().routesContainer)}>
451 {!showMatches() ? (
452 <RouteComp
453 routerState={routerState}
454 router={router}
455 route={router().routeTree}
456 isRoot
457 activeId={activeId}
458 setActiveId={setActiveId}
459 />
460 ) : (
461 <div>
462 {(routerState().pendingMatches?.length
463 ? routerState().pendingMatches
464 : routerState().matches
465 )?.map((match: any, _i: any) => {
466 return (
467 <div
468 role="button"
469 aria-label={`Open match details for ${match.id}`}
470 onClick={() =>
471 setActiveId(activeId() === match.id ? '' : match.id)
472 }
473 class={cx(styles().matchRow(match === activeMatch()))}
474 >
475 <div
476 class={cx(
477 styles().matchIndicator(getStatusColor(match)),
478 )}
479 />
480 <NavigateLink
481 left={
482 <NavigateButton
483 to={match.pathname}
484 params={match.params}
485 search={match.search}
486 router={router}
487 />
488 }
489 right={<AgeTicker match={match} router={router} />}
490 >
491 <code class={styles().matchID}>
492 {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`}
493 </code>
494 </NavigateLink>
495 </div>
496 )
497 })}
498 </div>
499 )}
500 </div>
501 </div>
502 {routerState().cachedMatches.length ? (
503 <div class={styles().cachedMatchesContainer}>
504 <div class={styles().detailsHeader}>
505 <div>Cached Matches</div>
506 <div class={styles().detailsHeaderInfo}>
507 age / staleTime / gcTime
508 </div>
509 </div>
510 <div>
511 {routerState().cachedMatches.map((match: any) => {
512 return (
513 <div
514 role="button"
515 aria-label={`Open match details for ${match.id}`}
516 onClick={() =>
517 setActiveId(activeId() === match.id ? '' : match.id)
518 }
519 class={cx(styles().matchRow(match === activeMatch()))}
520 >
521 <div
522 class={cx(
523 styles().matchIndicator(getStatusColor(match)),
524 )}
525 />
526 <NavigateLink
527 left={
528 <NavigateButton
529 to={match.pathname}
530 params={match.params}
531 search={match.search}
532 router={router}
533 />
534 }
535 right={<AgeTicker match={match} router={router} />}
536 >
537 <code class={styles().matchID}>{`${match.id}`}</code>
538 </NavigateLink>
539 </div>
540 )
541 })}
542 </div>
543 </div>
544 ) : null}
545 </div>
546 {activeMatch() && activeMatch()?.status ? (
547 <div class={styles().thirdContainer}>
548 <div class={styles().detailsHeader}>Match Details</div>
549 <div>
550 <div class={styles().matchDetails}>
551 <div
552 class={styles().matchStatus(
553 activeMatch()?.status,
554 activeMatch()?.isFetching,
555 )}
556 >
557 <div>
558 {activeMatch()?.status === 'success' &&
559 activeMatch()?.isFetching
560 ? 'fetching'
561 : activeMatch()?.status}
562 </div>
563 </div>
564 <div class={styles().matchDetailsInfoLabel}>
565 <div>ID:</div>
566 <div class={styles().matchDetailsInfo}>
567 <code>{activeMatch()?.id}</code>
568 </div>
569 </div>
570 <div class={styles().matchDetailsInfoLabel}>
571 <div>State:</div>
572 <div class={styles().matchDetailsInfo}>
573 {routerState().pendingMatches?.find(
574 (d: any) => d.id === activeMatch()?.id,
575 )
576 ? 'Pending'
577 : routerState().matches.find(
578 (d: any) => d.id === activeMatch()?.id,
579 )
580 ? 'Active'
581 : 'Cached'}
582 </div>
583 </div>
584 <div class={styles().matchDetailsInfoLabel}>
585 <div>Last Updated:</div>
586 <div class={styles().matchDetailsInfo}>
587 {activeMatch()?.updatedAt
588 ? new Date(activeMatch()?.updatedAt).toLocaleTimeString()
589 : 'N/A'}
590 </div>
591 </div>
592 </div>
593 </div>
594 {activeMatchLoaderData() ? (
595 <>
596 <div class={styles().detailsHeader}>Loader Data</div>
597 <div class={styles().detailsContent}>
598 <Explorer
599 label="loaderData"
600 value={activeMatchLoaderData}
601 defaultExpanded={{}}
602 />
603 </div>
604 </>
605 ) : null}
606 <div class={styles().detailsHeader}>Explorer</div>
607 <div class={styles().detailsContent}>
608 <Explorer
609 label="Match"
610 value={activeMatchValue}
611 defaultExpanded={{}}
612 />
613 </div>
614 </div>
615 ) : null}
616 {hasSearch() ? (
617 <div class={styles().fourthContainer}>
618 <div class={styles().detailsHeader}>
619 <span>Search Params</span>
620 {typeof navigator !== 'undefined' ? (
621 <span style="margin-left: 0.5rem;">
622 <CopyButton
623 getValue={() => {
624 const search = routerState().location.search
625 return JSON.stringify(search)
626 }}
627 />
628 </span>
629 ) : null}
630 </div>
631 <div class={styles().detailsContent}>
632 <Explorer
633 value={locationSearchValue}
634 defaultExpanded={Object.keys(
635 routerState().location.search,
636 ).reduce((obj: any, next) => {
637 obj[next] = {}
638 return obj
639 }, {})}
640 />
641 </div>
642 </div>
643 ) : null}
644 </div>
645 )
646 }
647​
648function CopyButton({ getValue }: { getValue: () => string }) {
649 const [copied, setCopied] = createSignal(false)
650​
651 let timeoutId: ReturnType<typeof setTimeout> | null = null
652​
653 const handleCopy = async () => {
654 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
655 if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) {
656 console.warn('TanStack Router Devtools: Clipboard API unavailable')
657 return
658 }
659 try {
660 const value = getValue()
661 await navigator.clipboard.writeText(value)
662 setCopied(true)
663 if (timeoutId) clearTimeout(timeoutId)
664 timeoutId = setTimeout(() => setCopied(false), 2500)
665 } catch (e) {
666 console.error('TanStack Router Devtools: Failed to copy', e)
667 }
668 }
669​
670 onCleanup(() => {
671 if (timeoutId) clearTimeout(timeoutId)
672 })
673​
674 return (
675 <button
676 type="button"
677 style="cursor: pointer;"
678 onClick={handleCopy}
679 aria-label="Copy value to clipboard"
680 title={copied() ? 'Copied!' : 'Copy'}
681 >
682 {copied() ? 'βœ…' : 'πŸ“‹'}
683 </button>
684 )
686​
687export default BaseTanStackRouterDevtoolsPanel