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 aria-pressed={props.value}
242 onClick={() => {
243 const oldData = props.activeQuery.state.data
244 const newData = updateNestedDataByPath(
245 oldData,
246 props.dataPath,
247 !props.value,
248 )
249 queryClient.setQueryData(props.activeQuery.queryKey, newData)
250 }}
251 >
252 <Check theme={theme()} checked={props.value} />
253 </button>
254 )
255}
256β
257type ExplorerProps = {
258 editable?: boolean
259 label: string
260 value: unknown
261 defaultExpanded?: Array<string>
262 dataPath?: Array<string>
263 activeQuery?: Query
264 itemsDeletable?: boolean
265 onEdit?: () => void
266}
267β
268/**
269 * Checks whether a value is iterable.
270 * @param x - The value to check.
271 * @returns `true` if `x` has a `Symbol.iterator` method.
272 */
273function isIterable(x: any): x is Iterable<unknown> {
274 return Symbol.iterator in x
275}
276β
277/**
278 * Renders an expandable tree view of a value, used to explore a query's data in the devtools. It
279 * can also edit and delete entries in the query's data.
280 * @param props - The value to show and its label, plus the options for expanding, editing, and
281 * deleting entries.
282 * @returns The tree view.
283 */
284export default function Explorer(props: ExplorerProps) {
285 const theme = useTheme()
286 const css = useQueryDevtoolsContext().shadowDOMTarget
287 ? goober.css.bind({ target: useQueryDevtoolsContext().shadowDOMTarget })
288 : goober.css
289 const styles = createMemo(() => {
290 return theme() === 'dark' ? darkStyles(css) : lightStyles(css)
291 })
292 const queryClient = useQueryDevtoolsContext().client
293β
294 const [expanded, setExpanded] = createSignal(
295 (props.defaultExpanded || []).includes(props.label),
296 )
297 const toggleExpanded = () => setExpanded((old) => !old)
298 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
299β
300 const subEntries = createMemo(() => {
301 if (Array.isArray(props.value)) {
302 return props.value.map((d, i) => ({
303 label: i.toString(),
304 value: d,
305 }))
306 } else if (
307 props.value !== null &&
308 typeof props.value === 'object' &&
309 isIterable(props.value) &&
310 typeof props.value[Symbol.iterator] === 'function'
311 ) {
312 if (props.value instanceof Map) {
313 return Array.from(props.value, ([key, val]) => ({
314 label: key,
315 value: val,
316 }))
317 }
318 return Array.from(props.value, (val, i) => ({
319 label: i.toString(),
320 value: val,
321 }))
322 } else if (typeof props.value === 'object' && props.value !== null) {
323 return Object.entries(props.value).map(([key, val]) => ({
324 label: key,
325 value: val,
326 }))
327 }
328 return []
329 })
330β
331 const type = createMemo<string>(() => {
332 if (Array.isArray(props.value)) {
333 return 'array'
334 } else if (
335 props.value !== null &&
336 typeof props.value === 'object' &&
337 isIterable(props.value) &&
338 typeof props.value[Symbol.iterator] === 'function'
339 ) {
340 return 'Iterable'
341 } else if (typeof props.value === 'object' && props.value !== null) {
342 return 'object'
343 }
344 return typeof props.value
345 })
346β
347 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
348β
349 const currentDataPath = props.dataPath ?? []
350β
351 const inputId = createUniqueId()
352β
353 return (
354 <div class={styles().entry}>
355 <Show when={subEntryPages().length}>
356 <div class={styles().expanderButtonContainer}>
357 <button
358 class={styles().expanderButton}
359 onClick={() => toggleExpanded()}
360 aria-expanded={expanded() ? 'true' : 'false'}
361 >
362 <Expander expanded={expanded()} /> <span>{props.label}</span>{' '}
363 <span class={styles().info}>
364 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
365 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
366 </span>
367 </button>
368 <Show when={props.editable}>
369 <div class={styles().actions}>
370 <CopyButton value={props.value} />
371β
372 <Show
373 when={props.itemsDeletable && props.activeQuery !== undefined}
374 >
375 <DeleteItemButton
376 activeQuery={props.activeQuery!}
377 dataPath={currentDataPath}
378 />
379 </Show>
380β
381 <Show
382 when={type() === 'array' && props.activeQuery !== undefined}
383 >
384 <ClearArrayButton
385 activeQuery={props.activeQuery!}
386 dataPath={currentDataPath}
387 />
388 </Show>
389β
390 <Show when={!!props.onEdit && !serialize(props.value).meta}>
391 <button
392 class={styles().actionButton}
393 title={'Bulk Edit Data'}
394 aria-label={'Bulk Edit Data'}
395 onClick={() => {
396 props.onEdit?.()
397 }}
398 >
399 <Pencil />
400 </button>
401 </Show>
402 </div>
403 </Show>
404 </div>
405 <Show when={expanded()}>
406 <Show when={subEntryPages().length === 1}>
407 <div class={styles().subEntry}>
408 <Key each={subEntries()} by={(item) => item.label}>
409 {(entry) => {
410 return (
411 <Explorer
412 defaultExpanded={props.defaultExpanded}
413 label={entry().label}
414 value={entry().value}
415 editable={props.editable}
416 dataPath={[...currentDataPath, entry().label]}
417 activeQuery={props.activeQuery}
418 itemsDeletable={
419 type() === 'array' ||
420 type() === 'Iterable' ||
421 type() === 'object'
422 }
423 />
424 )
425 }}
426 </Key>
427 </div>
428 </Show>
429 <Show when={subEntryPages().length > 1}>
430 <div class={styles().subEntry}>
431 <Index each={subEntryPages()}>
432 {(entries, index) => (
433 <div>
434 <div class={styles().entry}>
435 <button
436 onClick={() =>
437 setExpandedPages((old) =>
438 old.includes(index)
439 ? old.filter((d) => d !== index)
440 : [...old, index],
441 )
442 }
443 class={styles().expanderButton}
444 >
445 <Expander expanded={expandedPages().includes(index)} />{' '}
446 [{index * 100}...
447 {index * 100 + 100 - 1}]
448 </button>
449 <Show when={expandedPages().includes(index)}>
450 <div class={styles().subEntry}>
451 <Key each={entries()} by={(entry) => entry.label}>
452 {(entry) => (
453 <Explorer
454 defaultExpanded={props.defaultExpanded}
455 label={entry().label}
456 value={entry().value}
457 editable={props.editable}
458 dataPath={[...currentDataPath, entry().label]}
459 activeQuery={props.activeQuery}
460 />
461 )}
462 </Key>
463 </div>
464 </Show>
465 </div>
466 </div>
467 )}
468 </Index>
469 </div>
470 </Show>
471 </Show>
472 </Show>
473 <Show when={subEntryPages().length === 0}>
474 <div class={styles().row}>
475 <label for={inputId} class={styles().label}>
476 {props.label}:
477 </label>
478 <Show
479 when={
480 props.editable &&
481 props.activeQuery !== undefined &&
482 (type() === 'string' ||
483 type() === 'number' ||
484 type() === 'boolean')
485 }
486 fallback={
487 <span class={styles().value}>{displayValue(props.value)}</span>
488 }
489 >
490 <Show
491 when={
492 props.editable &&
493 props.activeQuery !== undefined &&
494 (type() === 'string' || type() === 'number')
495 }
496 >
497 <input
498 id={inputId}
499 type={type() === 'number' ? 'number' : 'text'}
500 class={cx(styles().value, styles().editableInput)}
501 value={props.value as string | number}
502 onChange={(changeEvent) => {
503 const oldData = props.activeQuery!.state.data
504β
505 const newData = updateNestedDataByPath(
506 oldData,
507 currentDataPath,
508 type() === 'number'
509 ? changeEvent.target.valueAsNumber
510 : changeEvent.target.value,
511 )
512β
513 queryClient.setQueryData(props.activeQuery!.queryKey, newData)
514 }}
515 />
516 </Show>
517β
518 <Show when={type() === 'boolean'}>
519 <span
520 class={cx(
521 styles().value,
522 styles().actions,
523 styles().editableInput,
524 )}
525 >
526 <ToggleValueButton
527 activeQuery={props.activeQuery!}
528 dataPath={currentDataPath}
529 value={props.value as boolean}
530 />
531 {displayValue(props.value)}
532 </span>
533 </Show>
534 </Show>
535β
536 <Show
537 when={
538 props.editable &&
539 props.itemsDeletable &&
540 props.activeQuery !== undefined
541 }
542 >
543 <DeleteItemButton
544 activeQuery={props.activeQuery!}
545 dataPath={currentDataPath}
546 />
547 </Show>
548 </div>
549 </Show>
550 </div>
551 )
552}
553β
554const stylesFactory = (
555 theme: 'light' | 'dark',
556 css: (typeof goober)['css'],
557) => {
558 const { colors, font, size, border } = tokens
559 const t = (light: string, dark: string) => (theme === 'light' ? light : dark)
560 return {
561 entry: css`
562 & * {
563 font-size: ${font.size.xs};
564 font-family:
565 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
566 'Liberation Mono', 'Courier New', monospace;
567 }
568 position: relative;
569 outline: none;
570 word-break: break-word;
571 `,
572 subEntry: css`
573 margin: 0 0 0 0.5em;
574 padding-left: 0.75em;
575 border-left: 2px solid ${t(colors.gray[300], colors.darkGray[400])};
576 /* outline: 1px solid ${colors.teal[400]}; */
577 `,
578 expander: css`
579 & path {
580 stroke: ${colors.gray[400]};
581 }
582 & svg {
583 width: ${size[3]};
584 height: ${size[3]};
585 }
586 display: inline-flex;
587 align-items: center;
588 transition: all 0.1s ease;
589 /* outline: 1px solid ${colors.blue[400]}; */
590 `,
591 expanderButtonContainer: css`
592 display: flex;
593 align-items: center;
594 line-height: ${size[4]};
595 min-height: ${size[4]};
596 gap: ${size[2]};
597 `,
598 expanderButton: css`
599 cursor: pointer;
600 color: inherit;
601 font: inherit;
602 outline: inherit;
603 height: ${size[5]};
604 background: transparent;
605 border: none;
606 padding: 0;
607 display: inline-flex;
608 align-items: center;
609 gap: ${size[1]};
610 position: relative;
611 /* outline: 1px solid ${colors.green[400]}; */
612β
613 &:focus-visible {
614 border-radius: ${border.radius.xs};
615 outline: 2px solid ${colors.blue[800]};
616 }
617β
618 & svg {
619 position: relative;
620 left: 1px;
621 }
622 `,
623 info: css`
624 color: ${t(colors.gray[500], colors.gray[500])};
625 font-size: ${font.size.xs};
626 margin-left: ${size[1]};
627 /* outline: 1px solid ${colors.yellow[400]}; */
628 `,
629 label: css`
630 color: ${t(colors.gray[700], colors.gray[300])};
631 white-space: nowrap;
632 `,
633 value: css`
634 color: ${t(colors.purple[600], colors.purple[400])};
635 flex-grow: 1;
636 `,
637 actions: css`
638 display: inline-flex;
639 gap: ${size[2]};
640 align-items: center;
641 `,
642 row: css`
643 display: inline-flex;
644 gap: ${size[2]};
645 width: 100%;
646 margin: ${size[0.25]} 0px;
647 line-height: ${size[4.5]};
648 align-items: center;
649 `,
650 editableInput: css`
651 border: none;
652 padding: ${size[0.5]} ${size[1]} ${size[0.5]} ${size[1.5]};
653 flex-grow: 1;
654 border-radius: ${border.radius.xs};
655 background-color: ${t(colors.gray[200], colors.darkGray[500])};
656β
657 &:hover {
658 background-color: ${t(colors.gray[300], colors.darkGray[600])};
659 }
660 `,
661 actionButton: css`
662 background-color: transparent;
663 color: ${t(colors.gray[500], colors.gray[500])};
664 border: none;
665 display: inline-flex;
666 padding: 0px;
667 align-items: center;
668 justify-content: center;
669 cursor: pointer;
670 width: ${size[3]};
671 height: ${size[3]};
672 position: relative;
673 z-index: 1;
674β
675 &:hover svg {
676 color: ${t(colors.gray[600], colors.gray[400])};
677 }
678β
679 &:focus-visible {
680 border-radius: ${border.radius.xs};
681 outline: 2px solid ${colors.blue[800]};
682 outline-offset: 2px;
683 }
684 `,
685 }
686}
687β
688const lightStyles = (css: (typeof goober)['css']) => stylesFactory('light', css)
689const darkStyles = (css: (typeof goober)['css']) => stylesFactory('dark', css)