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 decodeCharMap: router().pathParamsDecodeCharMap,
182 })
183β
184 // only if `interpolated` is not missing params, return the path since this
185 // means that all the params are present for a successful navigation
186 return !interpolated.isMissingParams
187 ? interpolated.interpolatedPath
188 : undefined
189 })
190β
191 return (
192 <div>
193 <div
194 role="button"
195 aria-label={`Open match details for ${route.id}`}
196 onClick={() => {
197 if (match()) {
198 setActiveId(activeId() === route.id ? '' : route.id)
199 }
200 }}
201 class={cx(
202 styles().routesRowContainer(route.id === activeId(), !!match()),
203 )}
204 >
205 <div
206 class={cx(
207 styles().matchIndicator(getRouteStatusColor(matches(), route)),
208 )}
209 />
210 <NavigateLink
211 class={cx(styles().routesRow(!!match()))}
212 left={
213 <Show when={navigationTarget()}>
214 {(navigate) => <NavigateButton to={navigate()} router={router} />}
215 </Show>
216 }
217 right={<AgeTicker match={match()} router={router} />}
218 >
219 <code class={styles().code}>
220 {isRoot ? rootRouteId : route.path || trimPath(route.id)}{' '}
221 </code>
222 <code class={styles().routeParamInfo}>{param()}</code>
223 </NavigateLink>
224 </div>
225 {route.children?.length ? (
226 <div class={styles().nestedRouteRow(!!isRoot)}>
227 {[...(route.children as Array<AnyRoute>)]
228 .sort((a, b) => {
229 return a.rank - b.rank
230 })
231 .map((r) => (
232 <RouteComp
233 routerState={routerState}
234 router={router}
235 route={r}
236 activeId={activeId}
237 setActiveId={setActiveId}
238 />
239 ))}
240 </div>
241 ) : null}
242 </div>
243 )
244}
245β
246export const BaseTanStackRouterDevtoolsPanel =
247 function BaseTanStackRouterDevtoolsPanel({
248 ...props
249 }: BaseDevtoolsPanelOptions): JSX.Element {
250 const {
251 isOpen = true,
252 setIsOpen,
253 handleDragStart,
254 router,
255 routerState,
256 shadowDOMTarget,
257 ...panelProps
258 } = props
259β
260 const { onCloseClick } = useDevtoolsOnClose()
261 const styles = useStyles()
262 const { className, style, ...otherPanelProps } = panelProps
263β
264 invariant(
265 router,
266 '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.',
267 )
268β
269 // useStore(router.__store)
270β
271 const [currentTab, setCurrentTab] = useLocalStorage<
272 'routes' | 'matches' | 'history'
273 >('tanstackRouterDevtoolsActiveTab', 'routes')
274β
275 const [activeId, setActiveId] = useLocalStorage(
276 'tanstackRouterDevtoolsActiveRouteId',
277 '',
278 )
279β
280 const [history, setHistory] = createSignal<Array<AnyRouteMatch>>([])
281 const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false)
282β
283 createEffect(() => {
284 const matches = routerState().matches
285 const currentMatch = matches[matches.length - 1]
286 if (!currentMatch) {
287 return
288 }
289 // Read history WITHOUT tracking it to avoid infinite loops
290 const historyUntracked = untrack(() => history())
291 const lastMatch = historyUntracked[0]
292 const sameLocation =
293 lastMatch &&
294 lastMatch.pathname === currentMatch.pathname &&
295 JSON.stringify(lastMatch.search ?? {}) ===
296 JSON.stringify(currentMatch.search ?? {})
297 if (!lastMatch || !sameLocation) {
298 if (historyUntracked.length >= HISTORY_LIMIT) {
299 setHasHistoryOverflowed(true)
300 }
301 setHistory((prev) => {
302 const newHistory = [currentMatch, ...prev]
303 // truncate to ensure we don't overflow too much the ui
304 newHistory.splice(HISTORY_LIMIT)
305 return newHistory
306 })
307 }
308 })
309β
310 const activeMatch = createMemo(() => {
311 const matches = [
312 ...(routerState().pendingMatches ?? []),
313 ...routerState().matches,
314 ...routerState().cachedMatches,
315 ]
316 return matches.find(
317 (d) => d.routeId === activeId() || d.id === activeId(),
318 )
319 })
320β
321 const hasSearch = createMemo(
322 () => Object.keys(routerState().location.search).length,
323 )
324β
325 const explorerState = createMemo(() => {
326 return {
327 ...router(),
328 state: routerState(),
329 }
330 })
331β
332 const routerExplorerValue = createMemo(() =>
333 Object.fromEntries(
334 multiSortBy(
335 Object.keys(explorerState()),
336 (
337 [
338 'state',
339 'routesById',
340 'routesByPath',
341 'options',
342 'manifest',
343 ] as const
344 ).map((d) => (dd) => dd !== d),
345 )
346 .map((key) => [key, (explorerState() as any)[key]])
347 .filter(
348 (d) =>
349 typeof d[1] !== 'function' &&
350 ![
351 '__store',
352 'basepath',
353 'injectedHtml',
354 'subscribers',
355 'latestLoadPromise',
356 'navigateTimeout',
357 'resetNextScroll',
358 'tempLocationKey',
359 'latestLocation',
360 'routeTree',
361 'history',
362 ].includes(d[0]),
363 ),
364 ),
365 )
366 const activeMatchLoaderData = createMemo(() => activeMatch()?.loaderData)
367 const activeMatchValue = createMemo(() => activeMatch())
368 const locationSearchValue = createMemo(() => routerState().location.search)
369β
370 return (
371 <div
372 class={cx(
373 styles().devtoolsPanel,
374 'TanStackRouterDevtoolsPanel',
375 className ? className() : '',
376 )}
377 style={style ? style() : ''}
378 {...otherPanelProps}
379 >
380 {handleDragStart ? (
381 <div class={styles().dragHandle} onMouseDown={handleDragStart}></div>
382 ) : null}
383 <button
384 class={styles().panelCloseBtn}
385 onClick={(e: any) => {
386 if (setIsOpen) {
387 setIsOpen(false)
388 }
389 onCloseClick(e)
390 }}
391 >
392 <svg
393 xmlns="http://www.w3.org/2000/svg"
394 width="10"
395 height="6"
396 fill="none"
397 viewBox="0 0 10 6"
398 class={styles().panelCloseBtnIcon}
399 >
400 <path
401 stroke="currentColor"
402 stroke-linecap="round"
403 stroke-linejoin="round"
404 stroke-width="1.667"
405 d="M1 1l4 4 4-4"
406 ></path>
407 </svg>
408 </button>
409 <div class={styles().firstContainer}>
410 <div class={styles().row}>
411 <Logo
412 aria-hidden
413 onClick={(e: any) => {
414 if (setIsOpen) {
415 setIsOpen(false)
416 }
417 onCloseClick(e)
418 }}
419 />
420 </div>
421 <div class={styles().routerExplorerContainer}>
422 <div class={styles().routerExplorer}>
423 <Explorer
424 label="Router"
425 value={routerExplorerValue}
426 defaultExpanded={{
427 state: {} as any,
428 context: {} as any,
429 options: {} as any,
430 }}
431 filterSubEntries={(subEntries) => {
432 return subEntries.filter(
433 (d: any) => typeof d.value() !== 'function',
434 )
435 }}
436 />
437 </div>
438 </div>
439 </div>
440 <div class={styles().secondContainer}>
441 <div class={styles().matchesContainer}>
442 <div class={styles().detailsHeader}>
443 <span>Pathname</span>
444 {routerState().location.maskedLocation ? (
445 <div class={styles().maskedBadgeContainer}>
446 <span class={styles().maskedBadge}>masked</span>
447 </div>
448 ) : null}
449 </div>
450 <div class={styles().detailsContent}>
451 <code>{routerState().location.pathname}</code>
452 {routerState().location.maskedLocation ? (
453 <code class={styles().maskedLocation}>
454 {routerState().location.maskedLocation?.pathname}
455 </code>
456 ) : null}
457 </div>
458 <div class={styles().detailsHeader}>
459 <div class={styles().routeMatchesToggle}>
460 <button
461 type="button"
462 onClick={() => {
463 setCurrentTab('routes')
464 }}
465 disabled={currentTab() === 'routes'}
466 class={cx(
467 styles().routeMatchesToggleBtn(
468 currentTab() === 'routes',
469 true,
470 ),
471 )}
472 >
473 Routes
474 </button>
475 <button
476 type="button"
477 onClick={() => {
478 setCurrentTab('matches')
479 }}
480 disabled={currentTab() === 'matches'}
481 class={cx(
482 styles().routeMatchesToggleBtn(
483 currentTab() === 'matches',
484 true,
485 ),
486 )}
487 >
488 Matches
489 </button>
490 <button
491 type="button"
492 onClick={() => {
493 setCurrentTab('history')
494 }}
495 disabled={currentTab() === 'history'}
496 class={cx(
497 styles().routeMatchesToggleBtn(
498 currentTab() === 'history',
499 false,
500 ),
501 )}
502 >
503 History
504 </button>
505 </div>
506 <div class={styles().detailsHeaderInfo}>
507 <div>age / staleTime / gcTime</div>
508 </div>
509 </div>
510 <div class={cx(styles().routesContainer)}>
511 <Switch>
512 <Match when={currentTab() === 'routes'}>
513 <RouteComp
514 routerState={routerState}
515 router={router}
516 route={router().routeTree}
517 isRoot
518 activeId={activeId}
519 setActiveId={setActiveId}
520 />
521 </Match>
522 <Match when={currentTab() === 'matches'}>
523 <div>
524 {(routerState().pendingMatches?.length
525 ? routerState().pendingMatches
526 : routerState().matches
527 )?.map((match: any, _i: any) => {
528 return (
529 <div
530 role="button"
531 aria-label={`Open match details for ${match.id}`}
532 onClick={() =>
533 setActiveId(activeId() === match.id ? '' : match.id)
534 }
535 class={cx(styles().matchRow(match === activeMatch()))}
536 >
537 <div
538 class={cx(
539 styles().matchIndicator(getStatusColor(match)),
540 )}
541 />
542 <NavigateLink
543 left={
544 <NavigateButton
545 to={match.pathname}
546 params={match.params}
547 search={match.search}
548 router={router}
549 />
550 }
551 right={<AgeTicker match={match} router={router} />}
552 >
553 <code class={styles().matchID}>
554 {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`}
555 </code>
556 </NavigateLink>
557 </div>
558 )
559 })}
560 </div>
561 </Match>
562 <Match when={currentTab() === 'history'}>
563 <div>
564 <ul>
565 <For each={history()}>
566 {(match, index) => (
567 <li
568 class={cx(
569 styles().matchRow(match === activeMatch()),
570 )}
571 >
572 <div
573 class={cx(
574 styles().matchIndicator(
575 index() === 0 ? 'green' : 'gray',
576 ),
577 )}
578 />
579 <NavigateLink
580 left={
581 <NavigateButton
582 to={match.pathname}
583 params={match.params}
584 search={match.search}
585 router={router}
586 />
587 }
588 right={
589 <AgeTicker match={match} router={router} />
590 }
591 >
592 <code class={styles().matchID}>
593 {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`}
594 </code>
595 </NavigateLink>
596 </li>
597 )}
598 </For>
599 {hasHistoryOverflowed() ? (
600 <li class={styles().historyOverflowContainer}>
601 This panel displays the most recent {HISTORY_LIMIT}{' '}
602 navigations.
603 </li>
604 ) : null}
605 </ul>
606 </div>
607 </Match>
608 </Switch>
609 </div>
610 </div>
611 {routerState().cachedMatches.length ? (
612 <div class={styles().cachedMatchesContainer}>
613 <div class={styles().detailsHeader}>
614 <div>Cached Matches</div>
615 <div class={styles().detailsHeaderInfo}>
616 age / staleTime / gcTime
617 </div>
618 </div>
619 <div>
620 {routerState().cachedMatches.map((match: any) => {
621 return (
622 <div
623 role="button"
624 aria-label={`Open match details for ${match.id}`}
625 onClick={() =>
626 setActiveId(activeId() === match.id ? '' : match.id)
627 }
628 class={cx(styles().matchRow(match === activeMatch()))}
629 >
630 <div
631 class={cx(
632 styles().matchIndicator(getStatusColor(match)),
633 )}
634 />
635 <NavigateLink
636 left={
637 <NavigateButton
638 to={match.pathname}
639 params={match.params}
640 search={match.search}
641 router={router}
642 />
643 }
644 right={<AgeTicker match={match} router={router} />}
645 >
646 <code class={styles().matchID}>{`${match.id}`}</code>
647 </NavigateLink>
648 </div>
649 )
650 })}
651 </div>
652 </div>
653 ) : null}
654 </div>
655 {activeMatch() && activeMatch()?.status ? (
656 <div class={styles().thirdContainer}>
657 <div class={styles().detailsHeader}>Match Details</div>
658 <div>
659 <div class={styles().matchDetails}>
660 <div
661 class={styles().matchStatus(
662 activeMatch()?.status,
663 activeMatch()?.isFetching,
664 )}
665 >
666 <div>
667 {activeMatch()?.status === 'success' &&
668 activeMatch()?.isFetching
669 ? 'fetching'
670 : activeMatch()?.status}
671 </div>
672 </div>
673 <div class={styles().matchDetailsInfoLabel}>
674 <div>ID:</div>
675 <div class={styles().matchDetailsInfo}>
676 <code>{activeMatch()?.id}</code>
677 </div>
678 </div>
679 <div class={styles().matchDetailsInfoLabel}>
680 <div>State:</div>
681 <div class={styles().matchDetailsInfo}>
682 {routerState().pendingMatches?.find(
683 (d: any) => d.id === activeMatch()?.id,
684 )
685 ? 'Pending'
686 : routerState().matches.find(
687 (d: any) => d.id === activeMatch()?.id,
688 )
689 ? 'Active'
690 : 'Cached'}
691 </div>
692 </div>
693 <div class={styles().matchDetailsInfoLabel}>
694 <div>Last Updated:</div>
695 <div class={styles().matchDetailsInfo}>
696 {activeMatch()?.updatedAt
697 ? new Date(activeMatch()?.updatedAt).toLocaleTimeString()
698 : 'N/A'}
699 </div>
700 </div>
701 </div>
702 </div>
703 {activeMatchLoaderData() ? (
704 <>
705 <div class={styles().detailsHeader}>Loader Data</div>
706 <div class={styles().detailsContent}>
707 <Explorer
708 label="loaderData"
709 value={activeMatchLoaderData}
710 defaultExpanded={{}}
711 />
712 </div>
713 </>
714 ) : null}
715 <div class={styles().detailsHeader}>Explorer</div>
716 <div class={styles().detailsContent}>
717 <Explorer
718 label="Match"
719 value={activeMatchValue}
720 defaultExpanded={{}}
721 />
722 </div>
723 </div>
724 ) : null}
725 {hasSearch() ? (
726 <div class={styles().fourthContainer}>
727 <div class={styles().detailsHeader}>
728 <span>Search Params</span>
729 {typeof navigator !== 'undefined' ? (
730 <span style="margin-left: 0.5rem;">
731 <CopyButton
732 getValue={() => {
733 const search = routerState().location.search
734 return JSON.stringify(search)
735 }}
736 />
737 </span>
738 ) : null}
739 </div>
740 <div class={styles().detailsContent}>
741 <Explorer
742 value={locationSearchValue}
743 defaultExpanded={Object.keys(
744 routerState().location.search,
745 ).reduce((obj: any, next) => {
746 obj[next] = {}
747 return obj
748 }, {})}
749 />
750 </div>
751 </div>
752 ) : null}
753 </div>
754 )
755 }
756β
757function CopyButton({ getValue }: { getValue: () => string }) {
758 const [copied, setCopied] = createSignal(false)
759β
760 let timeoutId: ReturnType<typeof setTimeout> | null = null
761β
762 const handleCopy = async () => {
763 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
764 if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) {
765 console.warn('TanStack Router Devtools: Clipboard API unavailable')
766 return
767 }
768 try {
769 const value = getValue()
770 await navigator.clipboard.writeText(value)
771 setCopied(true)
772 if (timeoutId) clearTimeout(timeoutId)
773 timeoutId = setTimeout(() => setCopied(false), 2500)
774 } catch (e) {
775 console.error('TanStack Router Devtools: Failed to copy', e)
776 }
777 }
778β
779 onCleanup(() => {
780 if (timeoutId) clearTimeout(timeoutId)
781 })
782β
783 return (
784 <button
785 type="button"
786 style="cursor: pointer;"
787 onClick={handleCopy}
788 aria-label="Copy value to clipboard"
789 title={copied() ? 'Copied!' : 'Copy'}
790 >
791 {copied() ? 'β
' : 'π'}
792 </button>
793 )
794}
795β
796export default BaseTanStackRouterDevtoolsPanel