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

Explorer.tsx

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