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

devtools.tsx

901 lines26.7 KB

1import React from 'react'
2import { RouterInstance, useRouter } from '@tanstack/react-location'
3​
4import useLocalStorage from './useLocalStorage'
5import { getStatusColor, useIsMounted, useSafeState } from './utils'
6import {
7 Panel,
8 Button,
9 Code,
10 // Input,
11 // Select,
12 ActivePanel,
13} from './styledComponents'
14import { ThemeProvider, defaultTheme as theme } from './theme'
15// import { getQueryStatusLabel, getQueryStatusColor } from './utils'
16import Explorer from './Explorer'
17import Logo from './Logo'
18​
19export type PartialKeys<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>
20​
21interface DevtoolsOptions {
22 /**
23 * Set this true if you want the dev tools to default to being open
24 */
25 initialIsOpen?: boolean
26 /**
27 * Use this to add props to the panel. For example, you can add className, style (merge and override default style), etc.
28 */
29 panelProps?: React.DetailedHTMLProps<
30 React.HTMLAttributes<HTMLDivElement>,
31 HTMLDivElement
32 >
33 /**
34 * Use this to add props to the close button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
35 */
36 closeButtonProps?: React.DetailedHTMLProps<
37 React.ButtonHTMLAttributes<HTMLButtonElement>,
38 HTMLButtonElement
39 >
40 /**
41 * Use this to add props to the toggle button. For example, you can add className, style (merge and override default style), onClick (extend default handler), etc.
42 */
43 toggleButtonProps?: React.DetailedHTMLProps<
44 React.ButtonHTMLAttributes<HTMLButtonElement>,
45 HTMLButtonElement
46 >
47 /**
48 * The position of the React Location logo to open and close the devtools panel.
49 * Defaults to 'bottom-left'.
50 */
51 position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
52 /**
53 * Use this to render the devtools inside a different type of container element for a11y purposes.
54 * Any string which corresponds to a valid intrinsic JSX element is allowed.
55 * Defaults to 'footer'.
56 */
57 containerElement?: string | any
58 /**
59 * A boolean variable indicating if the "lite" version of the library is being used
60 */
61 useRouter?: () => unknown
63​
64interface DevtoolsPanelOptions {
65 /**
66 * The standard React style object used to style a component with inline styles
67 */
68 style?: React.CSSProperties
69 /**
70 * The standard React className property used to style a component with classes
71 */
72 className?: string
73 /**
74 * A boolean variable indicating whether the panel is open or closed
75 */
76 isOpen?: boolean
77 /**
78 * A function that toggles the open and close state of the panel
79 */
80 setIsOpen: (isOpen: boolean) => void
81 /**
82 * Handles the opening and closing the devtools panel
83 */
84 handleDragStart: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
85 /**
86 * A boolean variable indicating if the "lite" version of the library is being used
87 */
88 useRouter: () => unknown
90​
91const isServer = typeof window === 'undefined'
92​
93export function ReactLocationDevtools({
94 initialIsOpen,
95 panelProps = {},
96 closeButtonProps = {},
97 toggleButtonProps = {},
98 position = 'bottom-left',
99 containerElement: Container = 'footer',
100 useRouter: useRouterImpl = useRouter,
101}: DevtoolsOptions): React.ReactElement | null {
102 const rootRef = React.useRef<HTMLDivElement>(null)
103 const panelRef = React.useRef<HTMLDivElement>(null)
104 const [isOpen, setIsOpen] = useLocalStorage(
105 'reactLocationDevtoolsOpen',
106 initialIsOpen,
107 )
108 const [devtoolsHeight, setDevtoolsHeight] = useLocalStorage<number | null>(
109 'reactLocationDevtoolsHeight',
110 null,
111 )
112 const [isResolvedOpen, setIsResolvedOpen] = useSafeState(false)
113 const [isResizing, setIsResizing] = useSafeState(false)
114 const isMounted = useIsMounted()
115​
116 const handleDragStart = (
117 panelElement: HTMLDivElement | null,
118 startEvent: React.MouseEvent<HTMLDivElement, MouseEvent>,
119 ) => {
120 if (startEvent.button !== 0) return // Only allow left click for drag
121​
122 setIsResizing(true)
123​
124 const dragInfo = {
125 originalHeight: panelElement?.getBoundingClientRect().height ?? 0,
126 pageY: startEvent.pageY,
127 }
128​
129 const run = (moveEvent: MouseEvent) => {
130 const delta = dragInfo.pageY - moveEvent.pageY
131 const newHeight = dragInfo?.originalHeight + delta
132​
133 setDevtoolsHeight(newHeight)
134​
135 if (newHeight < 70) {
136 setIsOpen(false)
137 } else {
138 setIsOpen(true)
139 }
140 }
141​
142 const unsub = () => {
143 setIsResizing(false)
144 document.removeEventListener('mousemove', run)
145 document.removeEventListener('mouseUp', unsub)
146 }
147​
148 document.addEventListener('mousemove', run)
149 document.addEventListener('mouseup', unsub)
150 }
151​
152 React.useEffect(() => {
153 setIsResolvedOpen(isOpen ?? false)
154 }, [isOpen, isResolvedOpen, setIsResolvedOpen])
155​
156 // Toggle panel visibility before/after transition (depending on direction).
157 // Prevents focusing in a closed panel.
158 React.useEffect(() => {
159 const ref = panelRef.current
160 if (ref) {
161 const handlePanelTransitionStart = () => {
162 if (ref && isResolvedOpen) {
163 ref.style.visibility = 'visible'
164 }
165 }
166​
167 const handlePanelTransitionEnd = () => {
168 if (ref && !isResolvedOpen) {
169 ref.style.visibility = 'hidden'
170 }
171 }
172​
173 ref.addEventListener('transitionstart', handlePanelTransitionStart)
174 ref.addEventListener('transitionend', handlePanelTransitionEnd)
175​
176 return () => {
177 ref.removeEventListener('transitionstart', handlePanelTransitionStart)
178 ref.removeEventListener('transitionend', handlePanelTransitionEnd)
179 }
180 }
181 }, [isResolvedOpen])
182​
183 React[isServer ? 'useEffect' : 'useLayoutEffect'](() => {
184 if (isResolvedOpen) {
185 const previousValue = rootRef.current?.parentElement?.style.paddingBottom
186​
187 const run = () => {
188 const containerHeight = panelRef.current?.getBoundingClientRect().height
189 if (rootRef.current?.parentElement) {
190 rootRef.current.parentElement.style.paddingBottom = `${containerHeight}px`
191 }
192 }
193​
194 run()
195​
196 if (typeof window !== 'undefined') {
197 window.addEventListener('resize', run)
198​
199 return () => {
200 window.removeEventListener('resize', run)
201 if (
202 rootRef.current?.parentElement &&
203 typeof previousValue === 'string'
204 ) {
205 rootRef.current.parentElement.style.paddingBottom = previousValue
206 }
207 }
208 }
209 }
210 }, [isResolvedOpen])
211​
212 const { style: panelStyle = {}, ...otherPanelProps } = panelProps
213​
214 const {
215 style: closeButtonStyle = {},
216 onClick: onCloseClick,
217 ...otherCloseButtonProps
218 } = closeButtonProps
219​
220 const {
221 style: toggleButtonStyle = {},
222 onClick: onToggleClick,
223 ...otherToggleButtonProps
224 } = toggleButtonProps
225​
226 // Do not render on the server
227 if (!isMounted()) return null
228​
229 return (
230 <Container ref={rootRef} className="ReactLocationDevtools">
231 <ThemeProvider theme={theme}>
232 <ReactLocationDevtoolsPanel
233 ref={panelRef as any}
234 {...otherPanelProps}
235 useRouter={useRouterImpl}
236 style={{
237 position: 'fixed',
238 bottom: '0',
239 right: '0',
240 zIndex: 99999,
241 width: '100%',
242 height: devtoolsHeight ?? 500,
243 maxHeight: '90%',
244 boxShadow: '0 0 20px rgba(0,0,0,.3)',
245 borderTop: `1px solid ${theme.gray}`,
246 transformOrigin: 'top',
247 // visibility will be toggled after transitions, but set initial state here
248 visibility: isOpen ? 'visible' : 'hidden',
249 ...panelStyle,
250 ...(isResizing
251 ? {
252 transition: `none`,
253 }
254 : { transition: `all .2s ease` }),
255 ...(isResolvedOpen
256 ? {
257 opacity: 1,
258 pointerEvents: 'all',
259 transform: `translateY(0) scale(1)`,
260 }
261 : {
262 opacity: 0,
263 pointerEvents: 'none',
264 transform: `translateY(15px) scale(1.02)`,
265 }),
266 }}
267 isOpen={isResolvedOpen}
268 setIsOpen={setIsOpen}
269 handleDragStart={(e) => handleDragStart(panelRef.current, e)}
270 />
271 {isResolvedOpen ? (
272 <Button
273 type="button"
274 aria-label="Close React Location Devtools"
275 {...(otherCloseButtonProps as unknown)}
276 onClick={(e) => {
277 setIsOpen(false)
278 onCloseClick && onCloseClick(e)
279 }}
280 style={{
281 position: 'fixed',
282 zIndex: 99999,
283 margin: '.5em',
284 bottom: 0,
285 ...(position === 'top-right'
286 ? {
287 right: '0',
288 }
289 : position === 'top-left'
290 ? {
291 left: '0',
292 }
293 : position === 'bottom-right'
294 ? {
295 right: '0',
296 }
297 : {
298 left: '0',
299 }),
300 ...closeButtonStyle,
301 }}
302 >
303 Close
304 </Button>
305 ) : null}
306 </ThemeProvider>
307 {!isResolvedOpen ? (
308 <button
309 type="button"
310 {...otherToggleButtonProps}
311 aria-label="Open React Location Devtools"
312 onClick={(e) => {
313 setIsOpen(true)
314 onToggleClick && onToggleClick(e)
315 }}
316 style={{
317 background: 'none',
318 border: 0,
319 padding: 0,
320 position: 'fixed',
321 zIndex: 99999,
322 display: 'inline-flex',
323 fontSize: '1.5em',
324 margin: '.5em',
325 cursor: 'pointer',
326 width: 'fit-content',
327 ...(position === 'top-right'
328 ? {
329 top: '0',
330 right: '0',
331 }
332 : position === 'top-left'
333 ? {
334 top: '0',
335 left: '0',
336 }
337 : position === 'bottom-right'
338 ? {
339 bottom: '0',
340 right: '0',
341 }
342 : {
343 bottom: '0',
344 left: '0',
345 }),
346 ...toggleButtonStyle,
347 }}
348 >
349 <Logo aria-hidden />
350 </button>
351 ) : null}
352 </Container>
353 )
355​
356export const ReactLocationDevtoolsPanel = React.forwardRef<
357 HTMLDivElement,
358 DevtoolsPanelOptions
359>(function ReactLocationDevtoolsPanel(props, ref): React.ReactElement {
360 const {
361 isOpen = true,
362 setIsOpen,
363 handleDragStart,
364 useRouter,
365 ...panelProps
366 } = props
367​
368 const router = useRouter() as RouterInstance<any>
369​
370 const [activeMatchId, setActiveRouteId] = useLocalStorage(
371 'reactLocationDevtoolsActiveRouteId',
372 '',
373 )
374​
375 const activeMatch = router.state.matches?.find((d) => d.id === activeMatchId)
376​
377 return (
378 <ThemeProvider theme={theme}>
379 <Panel ref={ref} className="ReactLocationDevtoolsPanel" {...panelProps}>
380 <style
381 dangerouslySetInnerHTML={{
382 __html: `
383 .ReactLocationDevtoolsPanel * {
384 scrollbar-color: ${theme.backgroundAlt} ${theme.gray};
385 }
386​
387 .ReactLocationDevtoolsPanel *::-webkit-scrollbar, .ReactLocationDevtoolsPanel scrollbar {
388 width: 1em;
389 height: 1em;
390 }
391​
392 .ReactLocationDevtoolsPanel *::-webkit-scrollbar-track, .ReactLocationDevtoolsPanel scrollbar-track {
393 background: ${theme.backgroundAlt};
394 }
395​
396 .ReactLocationDevtoolsPanel *::-webkit-scrollbar-thumb, .ReactLocationDevtoolsPanel scrollbar-thumb {
397 background: ${theme.gray};
398 border-radius: .5em;
399 border: 3px solid ${theme.backgroundAlt};
400 }
401 `,
402 }}
403 />
404 <div
405 style={{
406 position: 'absolute',
407 left: 0,
408 top: 0,
409 width: '100%',
410 height: '4px',
411 marginBottom: '-4px',
412 cursor: 'row-resize',
413 zIndex: 100000,
414 }}
415 onMouseDown={handleDragStart}
416 ></div>
417 <div
418 style={{
419 flex: '1 1 500px',
420 minHeight: '40%',
421 maxHeight: '100%',
422 overflow: 'auto',
423 borderRight: `1px solid ${theme.grayAlt}`,
424 display: 'flex',
425 flexDirection: 'column',
426 }}
427 >
428 <div
429 style={{
430 padding: '.5em',
431 background: theme.backgroundAlt,
432 display: 'flex',
433 justifyContent: 'space-between',
434 alignItems: 'center',
435 }}
436 >
437 <Logo
438 aria-hidden
439 style={{
440 marginRight: '.5em',
441 }}
442 />
443 <div
444 style={{
445 marginRight: 'auto',
446 fontSize: 'clamp(.8rem, 2vw, 1.3rem)',
447 fontWeight: 'bold',
448 }}
449 >
450 React Location{' '}
451 <span
452 style={{
453 fontWeight: 100,
454 }}
455 >
456 Devtools
457 </span>
458 </div>
459 <div
460 style={{
461 display: 'flex',
462 flexDirection: 'column',
463 }}
464 >
465 {/* <QueryKeys style={{ marginBottom: '.5em' }}>
466 <QueryKey
467 style={{
468 background: theme.success,
469 opacity: hasFresh ? 1 : 0.3,
470 }}
471 >
472 fresh <Code>({hasFresh})</Code>
473 </QueryKey>{' '}
474 <QueryKey
475 style={{
476 background: theme.active,
477 opacity: hasFetching ? 1 : 0.3,
478 }}
479 >
480 fetching <Code>({hasFetching})</Code>
481 </QueryKey>{' '}
482 <QueryKey
483 style={{
484 background: theme.warning,
485 color: 'black',
486 textShadow: '0',
487 opacity: hasStale ? 1 : 0.3,
488 }}
489 >
490 stale <Code>({hasStale})</Code>
491 </QueryKey>{' '}
492 <QueryKey
493 style={{
494 background: theme.gray,
495 opacity: hasInactive ? 1 : 0.3,
496 }}
497 >
498 inactive <Code>({hasInactive})</Code>
499 </QueryKey>
500 </QueryKeys> */}
501 {/* <div
502 style={{
503 display: 'flex',
504 alignItems: 'center',
505 }}
506 >
507 <Input
508 placeholder="Filter"
509 aria-label="Filter by matchhash"
510 value={filter ?? ''}
511 onChange={(e) => setFilter(e.target.value)}
512 onKeyDown={(e) => {
513 if (e.key === 'Escape') setFilter('')
514 }}
515 style={{
516 flex: '1',
517 marginRight: '.5em',
518 }}
519 />
520 {!filter ? (
521 <>
522 <Select
523 aria-label="Sort queries"
524 value={sort}
525 onChange={(e) => setSort(e.target.value)}
526 style={{
527 flex: '1',
528 minWidth: 75,
529 marginRight: '.5em',
530 }}
531 >
532 {Object.keys(sortFns).map((key) => (
533 <option key={key} value={key}>
534 Sort by {key}
535 </option>
536 ))}
537 </Select>
538 <Button
539 type="button"
540 onClick={() => setSortDesc((old) => !old)}
541 style={{
542 padding: '.3em .4em',
543 }}
544 >
545 {sortDesc ? '⬇ Desc' : '⬆ Asc'}
546 </Button>
547 </>
548 ) : null}
549 </div> */}
550 </div>
551 </div>
552 <div
553 style={{
554 overflowY: 'auto',
555 flex: '1',
556 }}
557 >
558 <div
559 style={{
560 padding: '.5em',
561 }}
562 >
563 <Explorer
564 label="Location"
565 value={router.state.location}
566 defaultExpanded={{
567 search: true,
568 }}
569 />
570 </div>
571 <div
572 style={{
573 padding: '.5em',
574 }}
575 >
576 <Explorer
577 label="Router"
578 value={{
579 basepath: router.basepath,
580 routes: router.routes,
581 routesById: router.routesById,
582 matchCache: router.matchCache,
583 defaultLinkPreloadMaxAge: router.defaultLinkPreloadMaxAge,
584 defaultLoaderMaxAge: router.defaultLoaderMaxAge,
585 defaultPendingMinMs: router.defaultPendingMinMs,
586 defaultPendingMs: router.defaultPendingMs,
587 defaultElement: router.defaultElement,
588 defaultErrorElement: router.defaultErrorElement,
589 defaultPendingElement: router.defaultPendingElement,
590 }}
591 defaultExpanded={{}}
592 />
593 </div>
594 </div>
595 </div>
596​
597 <div
598 style={{
599 flex: '1 1 500px',
600 minHeight: '40%',
601 maxHeight: '100%',
602 overflow: 'auto',
603 borderRight: `1px solid ${theme.grayAlt}`,
604 display: 'flex',
605 flexDirection: 'column',
606 }}
607 >
608 <div
609 style={{
610 padding: '.5em',
611 background: theme.backgroundAlt,
612 position: 'sticky',
613 top: 0,
614 zIndex: 1,
615 }}
616 >
617 Current Matches
618 </div>
619 {router.state.matches.map((match, i) => {
620 return (
621 <div
622 key={match.id || i}
623 role="button"
624 aria-label={`Open match details for ${match.id}`}
625 onClick={() =>
626 setActiveRouteId(activeMatchId === match.id ? '' : match.id)
627 }
628 style={{
629 display: 'flex',
630 borderBottom: `solid 1px ${theme.grayAlt}`,
631 cursor: 'pointer',
632 alignItems: 'center',
633 background:
634 match === activeMatch ? 'rgba(255,255,255,.1)' : undefined,
635 }}
636 >
637 <div
638 style={{
639 flex: '0 0 auto',
640 width: '1.3rem',
641 height: '1.3rem',
642 marginLeft: '.25rem',
643 background: getStatusColor(match, theme),
644 alignItems: 'center',
645 justifyContent: 'center',
646 fontWeight: 'bold',
647 borderRadius: '.25rem',
648 transition: 'all .2s ease-out',
649 }}
650 />
651 {/* {isDisabled ? (
652 <div
653 style={{
654 flex: '0 0 auto',
655 height: '2em',
656 background: theme.gray,
657 display: 'flex',
658 alignItems: 'center',
659 fontWeight: 'bold',
660 padding: '0 0.5em',
661 }}
662 >
663 disabled
664 </div>
665 ) : null} */}
666 <Code
667 style={{
668 padding: '.5em',
669 }}
670 >
671 {`${match.id}`}
672 </Code>
673 </div>
674 )
675 })}
676 <div
677 style={{
678 marginTop: '2rem',
679 padding: '.5em',
680 background: theme.backgroundAlt,
681 position: 'sticky',
682 top: 0,
683 zIndex: 1,
684 }}
685 >
686 Pending Matches
687 </div>
688 {router.pending?.matches.map((match, i) => {
689 return (
690 <div
691 key={match.id || i}
692 role="button"
693 aria-label={`Open match details for ${match.id}`}
694 onClick={() =>
695 setActiveRouteId(activeMatchId === match.id ? '' : match.id)
696 }
697 style={{
698 display: 'flex',
699 borderBottom: `solid 1px ${theme.grayAlt}`,
700 cursor: 'pointer',
701 background:
702 match === activeMatch ? 'rgba(255,255,255,.1)' : undefined,
703 }}
704 >
705 <div
706 style={{
707 flex: '0 0 auto',
708 width: '1.3rem',
709 height: '1.3rem',
710 marginLeft: '.25rem',
711 background: getStatusColor(match, theme),
712 alignItems: 'center',
713 justifyContent: 'center',
714 fontWeight: 'bold',
715 borderRadius: '.25rem',
716 transition: 'all .2s ease-out',
717 }}
718 />
719 {/* {isDisabled ? (
720 <div
721 style={{
722 flex: '0 0 auto',
723 height: '2em',
724 background: theme.gray,
725 display: 'flex',
726 alignItems: 'center',
727 fontWeight: 'bold',
728 padding: '0 0.5em',
729 }}
730 >
731 disabled
732 </div>
733 ) : null} */}
734 <Code
735 style={{
736 padding: '.5em',
737 }}
738 >
739 {`${match.id}`}
740 </Code>
741 </div>
742 )
743 })}
744 </div>
745​
746 {activeMatch ? (
747 <ActivePanel>
748 <div
749 style={{
750 padding: '.5em',
751 background: theme.backgroundAlt,
752 position: 'sticky',
753 top: 0,
754 zIndex: 1,
755 }}
756 >
757 Match Details
758 </div>
759 <div
760 style={{
761 padding: '.5em',
762 }}
763 >
764 <div
765 style={{
766 marginBottom: '.5em',
767 display: 'flex',
768 alignItems: 'stretch',
769 justifyContent: 'space-between',
770 }}
771 >
772 <Code
773 style={{
774 lineHeight: '1.8em',
775 }}
776 >
777 <pre
778 style={{
779 margin: 0,
780 padding: 0,
781 overflow: 'auto',
782 }}
783 >
784 {JSON.stringify(activeMatch.id, null, 2)}
785 </pre>
786 </Code>
787 {/* <span
788 style={{
789 padding: '0.3em .6em',
790 borderRadius: '0.4em',
791 fontWeight: 'bold',
792 textShadow: '0 2px 10px black',
793 background: getQueryStatusColor(activeMatch, theme),
794 flexShrink: 0,
795 }}
796 >
797 {getQueryStatusLabel(activeMatch)}
798 </span> */}
799 </div>
800 {/* <div
801 style={{
802 marginBottom: '.5em',
803 display: 'flex',
804 alignItems: 'center',
805 justifyContent: 'space-between',
806 }}
807 >
808 Observers: <Code>{activeMatch.getObserversCount()}</Code>
809 </div> */}
810 <div
811 style={{
812 display: 'flex',
813 alignItems: 'center',
814 justifyContent: 'space-between',
815 }}
816 >
817 Last Updated:{' '}
818 {activeMatch.updatedAt ? (
819 <Code>
820 {new Date(
821 activeMatch.updatedAt as number,
822 ).toLocaleTimeString()}
823 </Code>
824 ) : (
825 'N/A'
826 )}
827 </div>
828 </div>
829 {/*<div
830 style={{
831 background: theme.backgroundAlt,
832 padding: '.5em',
833 position: 'sticky',
834 top: 0,
835 zIndex: 1,
836 }}
837 >
838 Actions
839 </div>
840 <div
841 style={{
842 padding: '0.5em',
843 }}
844 >
845 <Button
846 type="button"
847 onClick={() => matchClient.invalidateQueries(activeMatch)}
848 style={{
849 background: theme.warning,
850 color: theme.inputTextColor,
851 }}
852 >
853 Invalidate
854 </Button>{' '}
855 <Button
856 type="button"
857 onClick={() => matchClient.resetQueries(activeMatch)}
858 style={{
859 background: theme.gray,
860 }}
861 >
862 Reset
863 </Button>{' '}
864 <Button
865 type="button"
866 onClick={() => matchClient.removeQueries(activeMatch)}
867 style={{
868 background: theme.danger,
869 }}
870 >
871 Remove
872 </Button>
873 </div> */}
874 <div
875 style={{
876 background: theme.backgroundAlt,
877 padding: '.5em',
878 position: 'sticky',
879 top: 0,
880 zIndex: 1,
881 }}
882 >
883 Explorer
884 </div>
885 <div
886 style={{
887 padding: '.5em',
888 }}
889 >
890 <Explorer
891 label="Match"
892 value={activeMatch}
893 defaultExpanded={{}}
894 />
895 </div>
896 </ActivePanel>
897 ) : null}
898 </Panel>
899 </ThemeProvider>
900 )
901})