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