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