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

Explorer.tsx

694 lines19.9 KB

1import { serialize, stringify } from 'superjson'
2import { clsx as cx } from 'clsx'
3import {
4 Index,
5 Match,
6 Show,
7 Switch,
8 createMemo,
9 createSignal,
10 createUniqueId,
11} from 'solid-js'
12import { Key } from '@solid-primitives/keyed'
13import * as goober from 'goober'
14import { tokens } from './theme'
15import {
16 deleteNestedDataByPath,
17 displayValue,
18 updateNestedDataByPath,
19} from './utils'
20import {
21 Check,
22 CopiedCopier,
23 Copier,
24 ErrorCopier,
25 List,
26 Pencil,
27 Trash,
28} from './icons'
29import { useQueryDevtoolsContext, useTheme } from './contexts'
30import type { Query } from '@tanstack/query-core'
31​
32/**
33 * Chunk elements in the array by size.
34 *
35 * When the array cannot be chunked evenly by size, the last chunk will be
36 * filled with the remaining elements.
37 *
38 * @example
39 * chunkArray(['a', 'b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
40 *
41 * @param array - The elements to chunk.
42 * @param size - The number of elements per chunk. Below `1`, no chunks are
43 * returned.
44 * @returns The chunks.
45 */
46function chunkArray<T extends { label: string; value: unknown }>(
47 array: Array<T>,
48 size: number,
49): Array<Array<T>> {
50 if (size < 1) return []
51 let i = 0
52 const result: Array<Array<T>> = []
53 while (i < array.length) {
54 result.push(array.slice(i, i + size))
55 i = i + size
56 }
57 return result
59​
60const Expander = (props: { expanded: boolean }) => {
61 const theme = useTheme()
62 const css = useQueryDevtoolsContext().shadowDOMTarget
63 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
64 : goober.css
65 const styles = createMemo(() => {
66 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
67 })
68​
69 return (
70 <span
71 class={cx(
72 styles().expander,
73 css`
74 transform: rotate(${props.expanded ? 90 : 0}deg);
75 `,
76 props.expanded &&
77 css`
78 & svg {
79 top: -1px;
80 }
81 `,
82 )}
83 >
84 <svg
85 width="16"
86 height="16"
87 viewBox="0 0 16 16"
88 fill="none"
89 xmlns="http://www.w3.org/2000/svg"
90 >
91 <path
92 d="M6 12L10 8L6 4"
93 stroke-width="2"
94 stroke-linecap="round"
95 stroke-linejoin="round"
96 />
97 </svg>
98 </span>
99 )
101​
102type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
103const CopyButton = (props: { value: unknown }) => {
104 const theme = useTheme()
105 const css = useQueryDevtoolsContext().shadowDOMTarget
106 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
107 : goober.css
108 const styles = createMemo(() => {
109 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
110 })
111 const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')
112​
113 return (
114 <button
115 class={styles().actionButton}
116 title="Copy object to clipboard"
117 aria-label={`${
118 copyState() === 'NoCopy'
119 ? 'Copy object to clipboard'
120 : copyState() === 'SuccessCopy'
121 ? 'Object copied to clipboard'
122 : 'Error copying object to clipboard'
123 }`}
124 onClick={
125 copyState() === 'NoCopy'
126 ? () => {
127 navigator.clipboard.writeText(stringify(props.value)).then(
128 () => {
129 setCopyState('SuccessCopy')
130 setTimeout(() => {
131 setCopyState('NoCopy')
132 }, 1500)
133 },
134 (err) => {
135 console.error('Failed to copy: ', err)
136 setCopyState('ErrorCopy')
137 setTimeout(() => {
138 setCopyState('NoCopy')
139 }, 1500)
140 },
141 )
142 }
143 : undefined
144 }
145 >
146 <Switch>
147 <Match when={copyState() === 'NoCopy'}>
148 <Copier />
149 </Match>
150 <Match when={copyState() === 'SuccessCopy'}>
151 <CopiedCopier theme={theme()} />
152 </Match>
153 <Match when={copyState() === 'ErrorCopy'}>
154 <ErrorCopier />
155 </Match>
156 </Switch>
157 </button>
158 )
160​
161const ClearArrayButton = (props: {
162 dataPath: Array<string>
163 activeQuery: Query
164}) => {
165 const theme = useTheme()
166 const css = useQueryDevtoolsContext().shadowDOMTarget
167 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
168 : goober.css
169 const styles = createMemo(() => {
170 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
171 })
172 const queryClient = useQueryDevtoolsContext().client
173​
174 return (
175 <button
176 class={styles().actionButton}
177 title={'Remove all items'}
178 aria-label={'Remove all items'}
179 onClick={() => {
180 const oldData = props.activeQuery.state.data
181 const newData = updateNestedDataByPath(oldData, props.dataPath, [])
182 queryClient.setQueryData(props.activeQuery.queryKey, newData)
183 }}
184 >
185 <List />
186 </button>
187 )
189​
190const DeleteItemButton = (props: {
191 dataPath: Array<string>
192 activeQuery: Query
193}) => {
194 const theme = useTheme()
195 const css = useQueryDevtoolsContext().shadowDOMTarget
196 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
197 : goober.css
198 const styles = createMemo(() => {
199 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
200 })
201 const queryClient = useQueryDevtoolsContext().client
202​
203 return (
204 <button
205 class={cx(styles().actionButton)}
206 title={'Delete item'}
207 aria-label={'Delete item'}
208 onClick={() => {
209 const oldData = props.activeQuery.state.data
210 const newData = deleteNestedDataByPath(oldData, props.dataPath)
211 queryClient.setQueryData(props.activeQuery.queryKey, newData)
212 }}
213 >
214 <Trash />
215 </button>
216 )
218​
219const ToggleValueButton = (props: {
220 dataPath: Array<string>
221 activeQuery: Query
222 value: boolean
223}) => {
224 const theme = useTheme()
225 const css = useQueryDevtoolsContext().shadowDOMTarget
226 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
227 : goober.css
228 const styles = createMemo(() => {
229 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
230 })
231 const queryClient = useQueryDevtoolsContext().client
232​
233 return (
234 <button
235 class={cx(
236 styles().actionButton,
237 css`
238 width: ${tokens.size[3.5]};
239 height: ${tokens.size[3.5]};
240 `,
241 )}
242 title={'Toggle value'}
243 aria-label={'Toggle value'}
244 aria-pressed={props.value}
245 onClick={() => {
246 const oldData = props.activeQuery.state.data
247 const newData = updateNestedDataByPath(
248 oldData,
249 props.dataPath,
250 !props.value,
251 )
252 queryClient.setQueryData(props.activeQuery.queryKey, newData)
253 }}
254 >
255 <Check theme={theme()} checked={props.value} />
256 </button>
257 )
259​
260type ExplorerProps = {
261 editable?: boolean
262 label: string
263 value: unknown
264 defaultExpanded?: Array<string>
265 dataPath?: Array<string>
266 activeQuery?: Query
267 itemsDeletable?: boolean
268 onEdit?: () => void
270​
271/**
272 * Checks whether a value is iterable.
273 *
274 * @param x - The value to check.
275 * @returns `true` if `x` has a `Symbol.iterator` method.
276 */
277function isIterable(x: any): x is Iterable<unknown> {
278 return Symbol.iterator in x
280​
281/**
282 * Renders an expandable tree view of a value, used to explore a query's data in
283 * the devtools. It can also edit and delete entries in the query's data.
284 *
285 * @param props - The value to show and its label, plus the options for
286 * expanding, editing, and deleting entries.
287 * @returns The tree view.
288 */
289export default function Explorer(props: ExplorerProps) {
290 const theme = useTheme()
291 const css = useQueryDevtoolsContext().shadowDOMTarget
292 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
293 : goober.css
294 const styles = createMemo(() => {
295 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
296 })
297 const queryClient = useQueryDevtoolsContext().client
298​
299 const [expanded, setExpanded] = createSignal(
300 (props.defaultExpanded || []).includes(props.label),
301 )
302 const toggleExpanded = () => setExpanded((old) => !old)
303 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
304​
305 const subEntries = createMemo(() => {
306 if (Array.isArray(props.value)) {
307 return props.value.map((d, i) => ({
308 label: i.toString(),
309 value: d,
310 }))
311 } else if (
312 props.value !== null &&
313 typeof props.value === 'object' &&
314 isIterable(props.value) &&
315 typeof props.value[Symbol.iterator] === 'function'
316 ) {
317 if (props.value instanceof Map) {
318 return Array.from(props.value, ([key, val]) => ({
319 label: key,
320 value: val,
321 }))
322 }
323 return Array.from(props.value, (val, i) => ({
324 label: i.toString(),
325 value: val,
326 }))
327 } else if (typeof props.value === 'object' && props.value !== null) {
328 return Object.entries(props.value).map(([key, val]) => ({
329 label: key,
330 value: val,
331 }))
332 }
333 return []
334 })
335​
336 const type = createMemo<string>(() => {
337 if (Array.isArray(props.value)) {
338 return 'array'
339 } else if (
340 props.value !== null &&
341 typeof props.value === 'object' &&
342 isIterable(props.value) &&
343 typeof props.value[Symbol.iterator] === 'function'
344 ) {
345 return 'Iterable'
346 } else if (typeof props.value === 'object' && props.value !== null) {
347 return 'object'
348 }
349 return typeof props.value
350 })
351​
352 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
353​
354 const currentDataPath = props.dataPath ?? []
355​
356 const inputId = createUniqueId()
357​
358 return (
359 <div class={styles().entry}>
360 <Show when={subEntryPages().length}>
361 <div class={styles().expanderButtonContainer}>
362 <button
363 class={styles().expanderButton}
364 onClick={() => toggleExpanded()}
365 aria-expanded={expanded() ? 'true' : 'false'}
366 >
367 <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
368 <span class={styles().info}>
369 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
370 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
371 </span>
372 </button>
373 <Show when={props.editable}>
374 <div class={styles().actions}>
375 <CopyButton value={props.value} />
376​
377 <Show
378 when={props.itemsDeletable && props.activeQuery !== undefined}
379 >
380 <DeleteItemButton
381 activeQuery={props.activeQuery!}
382 dataPath={currentDataPath}
383 />
384 </Show>
385​
386 <Show
387 when={type() === 'array' && props.activeQuery !== undefined}
388 >
389 <ClearArrayButton
390 activeQuery={props.activeQuery!}
391 dataPath={currentDataPath}
392 />
393 </Show>
394​
395 <Show when={!!props.onEdit && !serialize(props.value).meta}>
396 <button
397 class={styles().actionButton}
398 title={'Bulk Edit Data'}
399 aria-label={'Bulk Edit Data'}
400 onClick={() => {
401 props.onEdit?.()
402 }}
403 >
404 <Pencil />
405 </button>
406 </Show>
407 </div>
408 </Show>
409 </div>
410 <Show when={expanded()}>
411 <Show when={subEntryPages().length === 1}>
412 <div class={styles().subEntry}>
413 <Key each={subEntries()} by={(item) => item.label}>
414 {(entry) => {
415 return (
416 <Explorer
417 defaultExpanded={props.defaultExpanded}
418 label={entry().label}
419 value={entry().value}
420 editable={props.editable}
421 dataPath={[...currentDataPath, entry().label]}
422 activeQuery={props.activeQuery}
423 itemsDeletable={
424 type() === 'array' ||
425 type() === 'Iterable' ||
426 type() === 'object'
427 }
428 />
429 )
430 }}
431 </Key>
432 </div>
433 </Show>
434 <Show when={subEntryPages().length > 1}>
435 <div class={styles().subEntry}>
436 <Index each={subEntryPages()}>
437 {(entries, index) => (
438 <div>
439 <div class={styles().entry}>
440 <button
441 onClick={() =>
442 setExpandedPages((old) =>
443 old.includes(index)
444 ? old.filter((d) => d !== index)
445 : [...old, index],
446 )
447 }
448 class={styles().expanderButton}
449 >
450 <Expander expanded={expandedPages().includes(index)} />{' '}
451 [{index * 100}...
452 {index * 100 + 100 - 1}]
453 </button>
454 <Show when={expandedPages().includes(index)}>
455 <div class={styles().subEntry}>
456 <Key each={entries()} by={(entry) => entry.label}>
457 {(entry) => (
458 <Explorer
459 defaultExpanded={props.defaultExpanded}
460 label={entry().label}
461 value={entry().value}
462 editable={props.editable}
463 dataPath={[...currentDataPath, entry().label]}
464 activeQuery={props.activeQuery}
465 />
466 )}
467 </Key>
468 </div>
469 </Show>
470 </div>
471 </div>
472 )}
473 </Index>
474 </div>
475 </Show>
476 </Show>
477 </Show>
478 <Show when={subEntryPages().length === 0}>
479 <div class={styles().row}>
480 <label for={inputId} class={styles().label}>
481 {props.label}:
482 </label>
483 <Show
484 when={
485 props.editable &&
486 props.activeQuery !== undefined &&
487 (type() === 'string' ||
488 type() === 'number' ||
489 type() === 'boolean')
490 }
491 fallback={
492 <span class={styles().value}>{displayValue(props.value)}</span>
493 }
494 >
495 <Show
496 when={
497 props.editable &&
498 props.activeQuery !== undefined &&
499 (type() === 'string' || type() === 'number')
500 }
501 >
502 <input
503 id={inputId}
504 type={type() === 'number' ? 'number' : 'text'}
505 class={cx(styles().value, styles().editableInput)}
506 value={props.value as string | number}
507 onChange={(changeEvent) => {
508 const oldData = props.activeQuery!.state.data
509​
510 const newData = updateNestedDataByPath(
511 oldData,
512 currentDataPath,
513 type() === 'number'
514 ? changeEvent.target.valueAsNumber
515 : changeEvent.target.value,
516 )
517​
518 queryClient.setQueryData(props.activeQuery!.queryKey, newData)
519 }}
520 />
521 </Show>
522​
523 <Show when={type() === 'boolean'}>
524 <span
525 class={cx(
526 styles().value,
527 styles().actions,
528 styles().editableInput,
529 )}
530 >
531 <ToggleValueButton
532 activeQuery={props.activeQuery!}
533 dataPath={currentDataPath}
534 value={props.value as boolean}
535 />
536 {displayValue(props.value)}
537 </span>
538 </Show>
539 </Show>
540​
541 <Show
542 when={
543 props.editable &&
544 props.itemsDeletable &&
545 props.activeQuery !== undefined
546 }
547 >
548 <DeleteItemButton
549 activeQuery={props.activeQuery!}
550 dataPath={currentDataPath}
551 />
552 </Show>
553 </div>
554 </Show>
555 </div>
556 )
558​
559const stylesFactory = (
560 theme: 'light' | 'dark',
561 css: (typeof goober)['css'],
562) => {
563 const { colors, font, size, border } = tokens
564 const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
565 return {
566 entry: css`
567 & * {
568 font-size: ${font.size.xs};
569 font-family:
570 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
571 'Liberation Mono', 'Courier New', monospace;
572 }
573 position: relative;
574 outline: none;
575 word-break: break-word;
576 `,
577 subEntry: css`
578 margin: 0 0 0 0.5em;
579 padding-left: 0.75em;
580 border-left: 2px solid ${t(colors.gray[300], colors.darkGray[400])};
581 /* outline: 1px solid ${colors.teal[400]}; */
582 `,
583 expander: css`
584 & path {
585 stroke: ${colors.gray[400]};
586 }
587 & svg {
588 width: ${size[3]};
589 height: ${size[3]};
590 }
591 display: inline-flex;
592 align-items: center;
593 transition: all 0.1s ease;
594 /* outline: 1px solid ${colors.blue[400]}; */
595 `,
596 expanderButtonContainer: css`
597 display: flex;
598 align-items: center;
599 line-height: ${size[4]};
600 min-height: ${size[4]};
601 gap: ${size[2]};
602 `,
603 expanderButton: css`
604 cursor: pointer;
605 color: inherit;
606 font: inherit;
607 outline: inherit;
608 height: ${size[5]};
609 background: transparent;
610 border: none;
611 padding: 0;
612 display: inline-flex;
613 align-items: center;
614 gap: ${size[1]};
615 position: relative;
616 /* outline: 1px solid ${colors.green[400]}; */
617​
618 &:focus-visible {
619 border-radius: ${border.radius.xs};
620 outline: 2px solid ${colors.blue[800]};
621 }
622​
623 & svg {
624 position: relative;
625 left: 1px;
626 }
627 `,
628 info: css`
629 color: ${t(colors.gray[500], colors.gray[500])};
630 font-size: ${font.size.xs};
631 margin-left: ${size[1]};
632 /* outline: 1px solid ${colors.yellow[400]}; */
633 `,
634 label: css`
635 color: ${t(colors.gray[700], colors.gray[300])};
636 white-space: nowrap;
637 `,
638 value: css`
639 color: ${t(colors.purple[600], colors.purple[400])};
640 flex-grow: 1;
641 `,
642 actions: css`
643 display: inline-flex;
644 gap: ${size[2]};
645 align-items: center;
646 `,
647 row: css`
648 display: inline-flex;
649 gap: ${size[2]};
650 width: 100%;
651 margin: ${size[0.25]} 0px;
652 line-height: ${size[4.5]};
653 align-items: center;
654 `,
655 editableInput: css`
656 border: none;
657 padding: ${size[0.5]} ${size[1]} ${size[0.5]} ${size[1.5]};
658 flex-grow: 1;
659 border-radius: ${border.radius.xs};
660 background-color: ${t(colors.gray[200], colors.darkGray[500])};
661​
662 &:hover {
663 background-color: ${t(colors.gray[300], colors.darkGray[600])};
664 }
665 `,
666 actionButton: css`
667 background-color: transparent;
668 color: ${t(colors.gray[500], colors.gray[500])};
669 border: none;
670 display: inline-flex;
671 padding: 0px;
672 align-items: center;
673 justify-content: center;
674 cursor: pointer;
675 width: ${size[3]};
676 height: ${size[3]};
677 position: relative;
678 z-index: 1;
679​
680 &:hover svg {
681 color: ${t(colors.gray[600], colors.gray[400])};
682 }
683​
684 &:focus-visible {
685 border-radius: ${border.radius.xs};
686 outline: 2px solid ${colors.blue[800]};
687 outline-offset: 2px;
688 }
689 `,
690 }
692​
693const lightStyles = (css: (typeof goober)['css']) => stylesFactory('light', css)
694const darkStyles = (css: (typeof goober)['css']) => stylesFactory('dark', css)