Open History to see the last commit
1import { Key } from '@solid-primitives/keyed'
2import {
3 Index,
4 Match,
5 Show,
6 Switch,
7 createEffect,
8 createMemo,
9 createSignal,
10 createUniqueId,
11 on,
12 onCleanup,
13 onMount,
14} from 'solid-js'
15import { serialize, stringify } from 'superjson'
16import { useQueryDevtoolsContext, useTheme } from './contexts'
17import { primitiveText, searchEntries, searchExplorer } from './explorerSearch'
18import {
19 Check,
20 CopiedCopier,
21 Copier,
22 ErrorCopier,
23 List,
24 Pencil,
25 Trash,
26} from './icons'
27import { getNativeObjectType } from './nativeObjectType'
28import { createThemed } from './styles'
29import {
30 deleteNestedDataByPath,
31 displayValue,
32 isPlainObject,
33 updateNestedDataByPath,
34} from './utils'
35import type { Query } from '@tanstack/query-core'
36import type { ExplorerSearch } from './explorerSearch'
37
38/**
39 * Chunk elements in the array by size.
40 *
41 * When the array cannot be chunked evenly by size, the last chunk will be
42 * filled with the remaining elements.
43 * @param array - The elements to chunk.
44 * @param size - The number of elements per chunk. Below `1`, no chunks are returned.
45 * @returns The chunks.
46 * @example
47 * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']]
48 */
49function chunkArray<T extends { label: string; value: unknown }>(
50 array: Array<T>,
51 size: number,
52): Array<Array<T>> {
53 if (size < 1) return []
54 let i = 0
55 const result: Array<Array<T>> = []
56 while (i < array.length) {
57 result.push(array.slice(i, i + size))
58 i = i + size
59 }
60 return result
61}
62
63const Expander = (props: { expanded: boolean }) => {
64 return (
65 <span
66 class={`tsqd-style-explorer-expander ${props.expanded ? 'tsqd-style-explorer-expander-expanded' : ''}`}
67 >
68 <svg
69 width="16"
70 height="16"
71 viewBox="0 0 16 16"
72 fill="none"
73 xmlns="http://www.w3.org/2000/svg"
74 >
75 <path
76 d="M6 12L10 8L6 4"
77 stroke-width="2"
78 stroke-linecap="round"
79 stroke-linejoin="round"
80 />
81 </svg>
82 </span>
83 )
84}
85
86type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy'
87const CopyButton = (props: { value: unknown }) => {
88 const theme = useTheme()
89 const themed = createThemed(theme)
90 const [copyState, setCopyState] = createSignal<CopyState>('NoCopy')
91
92 return (
93 <button
94 class={themed('tsqd-style-explorer-action-button')}
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 )
138}
139
140const ClearArrayButton = (props: {
141 dataPath: Array<string>
142 activeQuery: Query
143}) => {
144 const theme = useTheme()
145 const themed = createThemed(theme)
146 const queryClient = useQueryDevtoolsContext().client
147
148 return (
149 <button
150 class={themed('tsqd-style-explorer-action-button')}
151 title={'Remove all items'}
152 aria-label={'Remove all items'}
153 onClick={() => {
154 const oldData = props.activeQuery.state.data
155 const newData = updateNestedDataByPath(oldData, props.dataPath, [])
156 queryClient.setQueryData(props.activeQuery.queryKey, newData)
157 }}
158 >
159 <List />
160 </button>
161 )
162}
163
164const DeleteItemButton = (props: {
165 dataPath: Array<string>
166 activeQuery: Query
167}) => {
168 const theme = useTheme()
169 const themed = createThemed(theme)
170 const queryClient = useQueryDevtoolsContext().client
171
172 return (
173 <button
174 class={themed('tsqd-style-explorer-action-button')}
175 title={'Delete item'}
176 aria-label={'Delete item'}
177 onClick={() => {
178 const oldData = props.activeQuery.state.data
179 const newData = deleteNestedDataByPath(oldData, props.dataPath)
180 queryClient.setQueryData(props.activeQuery.queryKey, newData)
181 }}
182 >
183 <Trash />
184 </button>
185 )
186}
187
188const ToggleValueButton = (props: {
189 dataPath: Array<string>
190 activeQuery: Query
191 value: boolean
192}) => {
193 const theme = useTheme()
194 const themed = createThemed(theme)
195 const queryClient = useQueryDevtoolsContext().client
196
197 return (
198 <button
199 class={`${themed('tsqd-style-explorer-action-button')} tsqd-style-explorer-toggle-button`}
200 title={'Toggle value'}
201 aria-label={'Toggle value'}
202 aria-pressed={props.value}
203 onClick={() => {
204 const oldData = props.activeQuery.state.data
205 const newData = updateNestedDataByPath(
206 oldData,
207 props.dataPath,
208 !props.value,
209 )
210 queryClient.setQueryData(props.activeQuery.queryKey, newData)
211 }}
212 >
213 <Check theme={theme()} checked={props.value} />
214 </button>
215 )
216}
217
218type ExplorerProps = {
219 editable?: boolean
220 label: string
221 value: unknown
222 defaultExpanded?: Array<string>
223 dataPath?: Array<string>
224 activeQuery?: Query
225 itemsDeletable?: boolean
226 onEdit?: () => void
227 search?: ExplorerSearch
228 highlight?: SearchHighlight
229}
230
231/** The name of the native highlight that marks search matches. */
232const HIGHLIGHT_NAME = 'tsqd-data-search'
233
234/** The ranges that one search adds to the native highlight. */
235type SearchHighlight = {
236 readonly size: number
237 add: (range: Range) => void
238 delete: (range: Range) => void
239}
240
241/**
242 * Adds nested data search without changing the explorer's manual expansion.
243 * @param props - Data explorer options, the selected query or mutation identity, and the search
244 * term to start with when another one is selected.
245 * @returns The search controls and the original data tree.
246 */
247export function SearchableExplorer(
248 props: ExplorerProps & { searchKey?: unknown; initialSearch?: string },
249) {
250 const theme = useTheme()
251 const themed = createThemed(theme)
252 const [term, setTerm] = createSignal('')
253 const [debouncedTerm, setDebouncedTerm] = createSignal('')
254 const clear = () => {
255 setTerm('')
256 setDebouncedTerm('')
257 }
258 const searchKey = createMemo(() => props.searchKey)
259 createEffect(
260 on(searchKey, () => {
261 const initial = props.initialSearch ?? ''
262 setTerm(initial)
263 setDebouncedTerm(initial.toLowerCase())
264 }),
265 )
266 createEffect(() => {
267 const next = term().toLowerCase()
268 if (!next) {
269 setDebouncedTerm('')
270 return
271 }
272 const timeout = setTimeout(() => setDebouncedTerm(next), 150)
273 onCleanup(() => clearTimeout(timeout))
274 })
275 const search = createMemo<ExplorerSearch | undefined>(() => {
276 const activeTerm = debouncedTerm()
277 return activeTerm
278 ? { term: activeTerm, match: searchExplorer(props.value, activeTerm) }
279 : undefined
280 })
281 const [nativeHighlight, setNativeHighlight] = createSignal<SearchHighlight>()
282 let root!: HTMLDivElement
283 onMount(() => {
284 const view = root.ownerDocument.defaultView!
285 const registry = view.CSS.highlights
286 // Explorers share one highlight per window, so styles.css can style it by
287 // name. Each search adds and removes only its own ranges.
288 const getHighlight = () => {
289 let highlight = registry.get(HIGHLIGHT_NAME)
290 if (!highlight) {
291 highlight = new view.Highlight()
292 registry.set(HIGHLIGHT_NAME, highlight)
293 }
294 return highlight
295 }
296 createEffect(
297 on(search, () => {
298 getHighlight()
299 const ranges = new Set<Range>()
300 const highlight: SearchHighlight = {
301 get size() {
302 return ranges.size
303 },
304 add(range) {
305 ranges.add(range)
306 getHighlight().add(range)
307 },
308 delete(range) {
309 ranges.delete(range)
310 registry.get(HIGHLIGHT_NAME)?.delete(range)
311 },
312 }
313 setNativeHighlight(highlight)
314 onCleanup(() => {
315 for (const range of ranges) highlight.delete(range)
316 if (registry.get(HIGHLIGHT_NAME)?.size === 0) {
317 registry.delete(HIGHLIGHT_NAME)
318 }
319 })
320 }),
321 )
322 })
323 return (
324 <div ref={root} class={themed('tsqd-style-explorer-search-root')}>
325 <div class="tsqd-style-explorer-search">
326 <input
327 type="search"
328 aria-label={`Search ${props.label.toLowerCase()}`}
329 placeholder={`Search ${props.label.toLowerCase()}`}
330 class={themed('tsqd-style-explorer-search-input')}
331 value={term()}
332 onInput={(event) => setTerm(event.currentTarget.value)}
333 onKeyDown={(event) => {
334 if (event.key === 'Escape') {
335 event.stopPropagation()
336 clear()
337 }
338 }}
339 />
340 <Show when={term()}>
341 <button
342 type="button"
343 class="tsqd-style-explorer-clear-search"
344 onClick={clear}
345 aria-label="Clear search"
346 >
347 Clear
348 </button>
349 </Show>
350 </div>
351 <div role="status" aria-live="polite">
352 {search() && !search()!.match.hasMatch ? 'No matches' : ''}
353 </div>
354 <Explorer {...props} search={search()} highlight={nativeHighlight()} />
355 </div>
356 )
357}
358
359const MAX_HIGHLIGHT_RANGES = 1000
360
361/**
362 * Marks literal, case-insensitive matches in a label or primitive value.
363 * @param props - The text, normalized search term, and shared highlight instance.
364 * @returns Text with matching substrings marked.
365 */
366function HighlightedText(props: {
367 text: string
368 term?: string
369 highlight?: SearchHighlight
370}) {
371 const matches = createMemo(() => {
372 const term = props.term
373 if (!term) return []
374 const lower = props.text.toLowerCase()
375 let originalStart = 0
376 let originalEnd = 0
377 let lowercaseEnd = 0
378 const originalPosition = (index: number) => {
379 while (lowercaseEnd <= index) {
380 const character = String.fromCodePoint(
381 props.text.codePointAt(originalEnd)!,
382 )
383 originalStart = originalEnd
384 originalEnd += character.length
385 lowercaseEnd += character.toLowerCase().length
386 }
387 return { start: originalStart, end: originalEnd }
388 }
389 const ranges: Array<{ start: number; end: number }> = []
390 let index = lower.indexOf(term)
391 while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) {
392 const from = originalPosition(index).start
393 const to = originalPosition(index + term.length - 1).end
394 ranges.push({ start: from, end: to })
395 index = lower.indexOf(term, index + term.length)
396 }
397 return ranges
398 })
399 const text = document.createTextNode('')
400 createEffect(() => {
401 text.data = props.text
402 const highlight = props.highlight
403 if (!highlight) return
404 const ranges: Array<Range> = []
405 for (const match of matches()) {
406 if (highlight.size >= MAX_HIGHLIGHT_RANGES) break
407 const range = text.ownerDocument.createRange()
408 range.setStart(text, match.start)
409 range.setEnd(text, match.end)
410 highlight.add(range)
411 ranges.push(range)
412 }
413 onCleanup(() => {
414 for (const range of ranges) highlight.delete(range)
415 })
416 })
417 return text
418}
419
420/**
421 * Checks whether a value is iterable.
422 * @param x - The value to check.
423 * @returns `true` if `x` has a `Symbol.iterator` method.
424 */
425function isIterable(x: any): x is Iterable<unknown> {
426 return Symbol.iterator in x
427}
428
429/**
430 * Renders an expandable tree view of a value, used to explore a query's data in the devtools. It
431 * can also edit and delete entries in the query's data.
432 * @param props - The value to show and its label, plus the options for expanding, editing, and
433 * deleting entries.
434 * @returns The tree view.
435 */
436export default function Explorer(props: ExplorerProps) {
437 const theme = useTheme()
438 const themed = createThemed(theme)
439 const queryClient = useQueryDevtoolsContext().client
440
441 const [expanded, setExpanded] = createSignal(
442 (props.defaultExpanded || []).includes(props.label),
443 )
444 const hasSearchMatchingChild = () =>
445 !!props.search &&
446 [...props.search.match.children.values()].some((child) => child.hasMatch)
447 const isExpanded = () => expanded() || hasSearchMatchingChild()
448 const toggleExpanded = () => {
449 if (!hasSearchMatchingChild()) setExpanded((old) => !old)
450 }
451 const [expandedPages, setExpandedPages] = createSignal<Array<number>>([])
452 const nativeObjectType = createMemo(() => getNativeObjectType(props.value))
453 const childrenEditable = createMemo(
454 () =>
455 props.editable &&
456 (Array.isArray(props.value) ||
457 nativeObjectType() === 'Map' ||
458 nativeObjectType() === 'Set' ||
459 isPlainObject(props.value)),
460 )
461
462 const subEntries = createMemo(() => {
463 if (props.search) {
464 return props.search.match.kind === 'branch'
465 ? (searchEntries(props.value) ?? [])
466 : []
467 }
468 if (Array.isArray(props.value)) {
469 return props.value.map((d, i) => ({
470 label: i.toString(),
471 key: i.toString(),
472 value: d,
473 }))
474 } else if (nativeObjectType() === 'Map') {
475 return Array.from(
476 Map.prototype.entries.call(props.value),
477 ([key, val]) => ({
478 label: primitiveText(key) ?? '[Object key]',
479 key,
480 value: val,
481 }),
482 )
483 } else if (nativeObjectType() === 'Set') {
484 return Array.from(Set.prototype.values.call(props.value), (val, i) => ({
485 label: i.toString(),
486 key: i.toString(),
487 value: val,
488 }))
489 } else if (
490 props.value !== null &&
491 typeof props.value === 'object' &&
492 isIterable(props.value) &&
493 typeof props.value[Symbol.iterator] === 'function'
494 ) {
495 return Array.from(props.value, (val, i) => ({
496 label: i.toString(),
497 key: i.toString(),
498 value: val,
499 }))
500 } else if (typeof props.value === 'object' && props.value !== null) {
501 return Object.entries(props.value).map(([key, val]) => ({
502 label: key,
503 key,
504 value: val,
505 }))
506 }
507 return []
508 })
509
510 const type = createMemo<string>(() => {
511 if (props.search) {
512 if (Array.isArray(props.value)) return 'array'
513 if (nativeObjectType() === 'Map' || nativeObjectType() === 'Set')
514 return 'Iterable'
515 return props.value === null ? 'object' : typeof props.value
516 }
517 if (Array.isArray(props.value)) {
518 return 'array'
519 } else if (
520 props.value !== null &&
521 typeof props.value === 'object' &&
522 isIterable(props.value) &&
523 typeof props.value[Symbol.iterator] === 'function'
524 ) {
525 return 'Iterable'
526 } else if (typeof props.value === 'object' && props.value !== null) {
527 return 'object'
528 }
529 return typeof props.value
530 })
531
532 const subEntryPages = createMemo(() => chunkArray(subEntries(), 100))
533
534 const pageHasMatch = (index: number) =>
535 !!(
536 props.search &&
537 subEntryPages()[index]?.some(
538 (entry) => props.search?.match.children.get(entry.key)?.hasMatch,
539 )
540 )
541 const matchingPage = createMemo(() =>
542 subEntryPages().findIndex((_, index) => pageHasMatch(index)),
543 )
544 const isPageExpanded = (index: number) =>
545 expandedPages().includes(index) || matchingPage() === index
546 const childSearch = (key: unknown): ExplorerSearch | undefined => {
547 const search = props.search
548 const match = search?.match.children.get(key)
549 return search && match ? { term: search.term, match } : undefined
550 }
551 const label = () => (
552 <HighlightedText
553 text={props.label}
554 term={props.search?.match.label ? props.search.term : undefined}
555 highlight={props.highlight}
556 />
557 )
558 const valueText = () => {
559 if (!props.search) return displayValue(props.value)
560 switch (props.search.match.kind) {
561 case 'circular':
562 return '[Circular]'
563 case 'accessor':
564 return '[Getter]'
565 case 'opaque':
566 return '[Object]'
567 case 'branch':
568 return Array.isArray(props.value)
569 ? '[]'
570 : nativeObjectType() === 'Map'
571 ? 'Map(0)'
572 : nativeObjectType() === 'Set'
573 ? 'Set(0)'
574 : '{}'
575 case 'value':
576 return primitiveText(props.value)
577 }
578 }
579 const renderedValue = () => (
580 <>
581 {props.search && typeof props.value === 'string' ? '"' : ''}
582 <HighlightedText
583 text={valueText() ?? ''}
584 term={props.search?.match.value ? props.search.term : undefined}
585 highlight={props.highlight}
586 />
587 {props.search && typeof props.value === 'string' ? '"' : ''}
588 </>
589 )
590
591 const currentDataPath = props.dataPath ?? []
592
593 const inputId = createUniqueId()
594
595 return (
596 <div class="tsqd-style-explorer-entry">
597 <Show when={subEntryPages().length}>
598 <div class="tsqd-style-explorer-expander-button-container">
599 <button
600 class="tsqd-style-explorer-expander-button"
601 onClick={() => toggleExpanded()}
602 aria-expanded={isExpanded() ? 'true' : 'false'}
603 >
604 <Expander expanded={isExpanded()} /> <span>{label()}</span>{' '}
605 <span class="tsqd-style-explorer-info">
606 {String(type()).toLowerCase() === 'iterable' ? '(Iterable) ' : ''}
607 {subEntries().length} {subEntries().length > 1 ? `items` : `item`}
608 </span>
609 </button>
610 <Show when={props.editable}>
611 <div class="tsqd-style-explorer-actions">
612 <CopyButton value={props.value} />
613
614 <Show
615 when={props.itemsDeletable && props.activeQuery !== undefined}
616 >
617 <DeleteItemButton
618 activeQuery={props.activeQuery!}
619 dataPath={currentDataPath}
620 />
621 </Show>
622
623 <Show
624 when={type() === 'array' && props.activeQuery !== undefined}
625 >
626 <ClearArrayButton
627 activeQuery={props.activeQuery!}
628 dataPath={currentDataPath}
629 />
630 </Show>
631
632 <Show
633 when={
634 !!props.onEdit &&
635 !props.search &&
636 !serialize(props.value).meta
637 }
638 >
639 <button
640 class={themed('tsqd-style-explorer-action-button')}
641 title={'Bulk Edit Data'}
642 aria-label={'Bulk Edit Data'}
643 onClick={() => {
644 props.onEdit?.()
645 }}
646 >
647 <Pencil />
648 </button>
649 </Show>
650 </div>
651 </Show>
652 </div>
653 <Show when={isExpanded()}>
654 <Show when={subEntryPages().length === 1}>
655 <div class={themed('tsqd-style-explorer-sub-entry')}>
656 <Key each={subEntries()} by={(item) => item.key}>
657 {(entry) => {
658 return (
659 <Explorer
660 defaultExpanded={props.defaultExpanded}
661 label={entry().label}
662 search={childSearch(entry().key)}
663 highlight={props.highlight}
664 value={entry().value}
665 editable={childrenEditable()}
666 dataPath={[...currentDataPath, entry().key]}
667 activeQuery={props.activeQuery}
668 itemsDeletable={
669 type() === 'array' ||
670 type() === 'Iterable' ||
671 type() === 'object'
672 }
673 />
674 )
675 }}
676 </Key>
677 </div>
678 </Show>
679 <Show when={subEntryPages().length > 1}>
680 <div class={themed('tsqd-style-explorer-sub-entry')}>
681 <Index each={subEntryPages()}>
682 {(entries, index) => (
683 <div>
684 <div class="tsqd-style-explorer-entry">
685 <button
686 onClick={() => {
687 if (matchingPage() === index) return
688 setExpandedPages((old) =>
689 old.includes(index)
690 ? old.filter((d) => d !== index)
691 : [...old, index],
692 )
693 }}
694 class={`tsqd-style-explorer-expander-button ${pageHasMatch(index) ? themed('tsqd-style-explorer-highlight') : ''}`}
695 aria-expanded={isPageExpanded(index)}
696 aria-description={
697 pageHasMatch(index)
698 ? 'Contains search matches'
699 : undefined
700 }
701 >
702 <Expander expanded={isPageExpanded(index)} /> [
703 {index * 100}...
704 {index * 100 + 100 - 1}]
705 </button>
706 <Show when={isPageExpanded(index)}>
707 <div class={themed('tsqd-style-explorer-sub-entry')}>
708 <Key each={entries()} by={(entry) => entry.key}>
709 {(entry) => (
710 <Explorer
711 defaultExpanded={props.defaultExpanded}
712 label={entry().label}
713 search={childSearch(entry().key)}
714 highlight={props.highlight}
715 value={entry().value}
716 editable={childrenEditable()}
717 dataPath={[...currentDataPath, entry().key]}
718 activeQuery={props.activeQuery}
719 />
720 )}
721 </Key>
722 </div>
723 </Show>
724 </div>
725 </div>
726 )}
727 </Index>
728 </div>
729 </Show>
730 </Show>
731 </Show>
732 <Show when={subEntryPages().length === 0}>
733 <div class="tsqd-style-explorer-row">
734 <label for={inputId} class={themed('tsqd-style-explorer-label')}>
735 {label()}:
736 </label>
737 <Show
738 when={
739 props.editable &&
740 props.activeQuery !== undefined &&
741 (type() === 'string' ||
742 type() === 'number' ||
743 type() === 'boolean')
744 }
745 fallback={
746 <span class={themed('tsqd-style-explorer-value')}>
747 {renderedValue()}
748 </span>
749 }
750 >
751 <Show
752 when={
753 props.editable &&
754 props.activeQuery !== undefined &&
755 (type() === 'string' || type() === 'number')
756 }
757 >
758 <input
759 id={inputId}
760 type={type() === 'number' ? 'number' : 'text'}
761 class={`${themed('tsqd-style-explorer-value')} ${themed('tsqd-style-explorer-editable-input')} ${props.search?.match.value ? themed('tsqd-style-explorer-highlight') : ''}`}
762 data-search-match={props.search?.match.value || undefined}
763 value={props.value as string | number}
764 onChange={(changeEvent) => {
765 const oldData = props.activeQuery!.state.data
766
767 const newData = updateNestedDataByPath(
768 oldData,
769 currentDataPath,
770 type() === 'number'
771 ? changeEvent.target.valueAsNumber
772 : changeEvent.target.value,
773 )
774
775 queryClient.setQueryData(props.activeQuery!.queryKey, newData)
776 }}
777 />
778 </Show>
779
780 <Show when={type() === 'boolean'}>
781 <span
782 class={`${themed('tsqd-style-explorer-value')} tsqd-style-explorer-actions ${themed('tsqd-style-explorer-editable-input')}`}
783 >
784 <ToggleValueButton
785 activeQuery={props.activeQuery!}
786 dataPath={currentDataPath}
787 value={props.value as boolean}
788 />
789 {renderedValue()}
790 </span>
791 </Show>
792 </Show>
793
794 <Show
795 when={
796 props.editable &&
797 props.itemsDeletable &&
798 props.activeQuery !== undefined
799 }
800 >
801 <DeleteItemButton
802 activeQuery={props.activeQuery!}
803 dataPath={currentDataPath}
804 />
805 </Show>
806 </div>
807 </Show>
808 </div>
809 )
810}