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

Explorer.tsx

637 lines18.6 KB

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