import { Key } from '@solid-primitives/keyed' import { Index, Match, Show, Switch, createEffect, createMemo, createSignal, createUniqueId, on, onCleanup, onMount, } from 'solid-js' import { serialize, stringify } from 'superjson' import { useQueryDevtoolsContext, useTheme } from './contexts' import { primitiveText, searchEntries, searchExplorer } from './explorerSearch' import { Check, CopiedCopier, Copier, ErrorCopier, List, Pencil, Trash, } from './icons' import { getNativeObjectType } from './nativeObjectType' import { createThemed } from './styles' import { deleteNestedDataByPath, displayValue, isPlainObject, updateNestedDataByPath, } from './utils' import type { Query } from '@tanstack/query-core' import type { ExplorerSearch } from './explorerSearch' /** * Chunk elements in the array by size. * * When the array cannot be chunked evenly by size, the last chunk will be * filled with the remaining elements. * @param array - The elements to chunk. * @param size - The number of elements per chunk. Below `1`, no chunks are returned. * @returns The chunks. * @example * chunkArray(['a','b', 'c', 'd', 'e'], 2) // returns [['a','b'], ['c', 'd'], ['e']] */ function chunkArray( array: Array, size: number, ): Array> { if (size < 1) return [] let i = 0 const result: Array> = [] while (i < array.length) { result.push(array.slice(i, i + size)) i = i + size } return result } const Expander = (props: { expanded: boolean }) => { return ( ) } type CopyState = 'NoCopy' | 'SuccessCopy' | 'ErrorCopy' const CopyButton = (props: { value: unknown }) => { const theme = useTheme() const themed = createThemed(theme) const [copyState, setCopyState] = createSignal('NoCopy') return ( ) } const ClearArrayButton = (props: { dataPath: Array activeQuery: Query }) => { const theme = useTheme() const themed = createThemed(theme) const queryClient = useQueryDevtoolsContext().client return ( ) } const DeleteItemButton = (props: { dataPath: Array activeQuery: Query }) => { const theme = useTheme() const themed = createThemed(theme) const queryClient = useQueryDevtoolsContext().client return ( ) } const ToggleValueButton = (props: { dataPath: Array activeQuery: Query value: boolean }) => { const theme = useTheme() const themed = createThemed(theme) const queryClient = useQueryDevtoolsContext().client return ( ) } type ExplorerProps = { editable?: boolean label: string value: unknown defaultExpanded?: Array dataPath?: Array activeQuery?: Query itemsDeletable?: boolean onEdit?: () => void search?: ExplorerSearch highlight?: SearchHighlight } /** The name of the native highlight that marks search matches. */ const HIGHLIGHT_NAME = 'tsqd-data-search' /** The ranges that one search adds to the native highlight. */ type SearchHighlight = { readonly size: number add: (range: Range) => void delete: (range: Range) => void } /** * Adds nested data search without changing the explorer's manual expansion. * @param props - Data explorer options, the selected query or mutation identity, and the search * term to start with when another one is selected. * @returns The search controls and the original data tree. */ export function SearchableExplorer( props: ExplorerProps & { searchKey?: unknown; initialSearch?: string }, ) { const theme = useTheme() const themed = createThemed(theme) const [term, setTerm] = createSignal('') const [debouncedTerm, setDebouncedTerm] = createSignal('') const clear = () => { setTerm('') setDebouncedTerm('') } const searchKey = createMemo(() => props.searchKey) createEffect( on(searchKey, () => { const initial = props.initialSearch ?? '' setTerm(initial) setDebouncedTerm(initial.toLowerCase()) }), ) createEffect(() => { const next = term().toLowerCase() if (!next) { setDebouncedTerm('') return } const timeout = setTimeout(() => setDebouncedTerm(next), 150) onCleanup(() => clearTimeout(timeout)) }) const search = createMemo(() => { const activeTerm = debouncedTerm() return activeTerm ? { term: activeTerm, match: searchExplorer(props.value, activeTerm) } : undefined }) const [nativeHighlight, setNativeHighlight] = createSignal() let root!: HTMLDivElement onMount(() => { const view = root.ownerDocument.defaultView! const registry = view.CSS.highlights // Explorers share one highlight per window, so styles.css can style it by // name. Each search adds and removes only its own ranges. const getHighlight = () => { let highlight = registry.get(HIGHLIGHT_NAME) if (!highlight) { highlight = new view.Highlight() registry.set(HIGHLIGHT_NAME, highlight) } return highlight } createEffect( on(search, () => { getHighlight() const ranges = new Set() const highlight: SearchHighlight = { get size() { return ranges.size }, add(range) { ranges.add(range) getHighlight().add(range) }, delete(range) { ranges.delete(range) registry.get(HIGHLIGHT_NAME)?.delete(range) }, } setNativeHighlight(highlight) onCleanup(() => { for (const range of ranges) highlight.delete(range) if (registry.get(HIGHLIGHT_NAME)?.size === 0) { registry.delete(HIGHLIGHT_NAME) } }) }), ) }) return (
{search() && !search()!.match.hasMatch ? 'No matches' : ''}
) } const MAX_HIGHLIGHT_RANGES = 1000 /** * Marks literal, case-insensitive matches in a label or primitive value. * @param props - The text, normalized search term, and shared highlight instance. * @returns Text with matching substrings marked. */ function HighlightedText(props: { text: string term?: string highlight?: SearchHighlight }) { const matches = createMemo(() => { const term = props.term if (!term) return [] const lower = props.text.toLowerCase() let originalStart = 0 let originalEnd = 0 let lowercaseEnd = 0 const originalPosition = (index: number) => { while (lowercaseEnd <= index) { const character = String.fromCodePoint( props.text.codePointAt(originalEnd)!, ) originalStart = originalEnd originalEnd += character.length lowercaseEnd += character.toLowerCase().length } return { start: originalStart, end: originalEnd } } const ranges: Array<{ start: number; end: number }> = [] let index = lower.indexOf(term) while (index !== -1 && ranges.length < MAX_HIGHLIGHT_RANGES) { const from = originalPosition(index).start const to = originalPosition(index + term.length - 1).end ranges.push({ start: from, end: to }) index = lower.indexOf(term, index + term.length) } return ranges }) const text = document.createTextNode('') createEffect(() => { text.data = props.text const highlight = props.highlight if (!highlight) return const ranges: Array = [] for (const match of matches()) { if (highlight.size >= MAX_HIGHLIGHT_RANGES) break const range = text.ownerDocument.createRange() range.setStart(text, match.start) range.setEnd(text, match.end) highlight.add(range) ranges.push(range) } onCleanup(() => { for (const range of ranges) highlight.delete(range) }) }) return text } /** * Checks whether a value is iterable. * @param x - The value to check. * @returns `true` if `x` has a `Symbol.iterator` method. */ function isIterable(x: any): x is Iterable { return Symbol.iterator in x } /** * Renders an expandable tree view of a value, used to explore a query's data in the devtools. It * can also edit and delete entries in the query's data. * @param props - The value to show and its label, plus the options for expanding, editing, and * deleting entries. * @returns The tree view. */ export default function Explorer(props: ExplorerProps) { const theme = useTheme() const themed = createThemed(theme) const queryClient = useQueryDevtoolsContext().client const [expanded, setExpanded] = createSignal( (props.defaultExpanded || []).includes(props.label), ) const hasSearchMatchingChild = () => !!props.search && [...props.search.match.children.values()].some((child) => child.hasMatch) const isExpanded = () => expanded() || hasSearchMatchingChild() const toggleExpanded = () => { if (!hasSearchMatchingChild()) setExpanded((old) => !old) } const [expandedPages, setExpandedPages] = createSignal>([]) const nativeObjectType = createMemo(() => getNativeObjectType(props.value)) const childrenEditable = createMemo( () => props.editable && (Array.isArray(props.value) || nativeObjectType() === 'Map' || nativeObjectType() === 'Set' || isPlainObject(props.value)), ) const subEntries = createMemo(() => { if (props.search) { return props.search.match.kind === 'branch' ? (searchEntries(props.value) ?? []) : [] } if (Array.isArray(props.value)) { return props.value.map((d, i) => ({ label: i.toString(), key: i.toString(), value: d, })) } else if (nativeObjectType() === 'Map') { return Array.from( Map.prototype.entries.call(props.value), ([key, val]) => ({ label: primitiveText(key) ?? '[Object key]', key, value: val, }), ) } else if (nativeObjectType() === 'Set') { return Array.from(Set.prototype.values.call(props.value), (val, i) => ({ label: i.toString(), key: i.toString(), value: val, })) } else if ( props.value !== null && typeof props.value === 'object' && isIterable(props.value) && typeof props.value[Symbol.iterator] === 'function' ) { return Array.from(props.value, (val, i) => ({ label: i.toString(), key: i.toString(), value: val, })) } else if (typeof props.value === 'object' && props.value !== null) { return Object.entries(props.value).map(([key, val]) => ({ label: key, key, value: val, })) } return [] }) const type = createMemo(() => { if (props.search) { if (Array.isArray(props.value)) return 'array' if (nativeObjectType() === 'Map' || nativeObjectType() === 'Set') return 'Iterable' return props.value === null ? 'object' : typeof props.value } if (Array.isArray(props.value)) { return 'array' } else if ( props.value !== null && typeof props.value === 'object' && isIterable(props.value) && typeof props.value[Symbol.iterator] === 'function' ) { return 'Iterable' } else if (typeof props.value === 'object' && props.value !== null) { return 'object' } return typeof props.value }) const subEntryPages = createMemo(() => chunkArray(subEntries(), 100)) const pageHasMatch = (index: number) => !!( props.search && subEntryPages()[index]?.some( (entry) => props.search?.match.children.get(entry.key)?.hasMatch, ) ) const matchingPage = createMemo(() => subEntryPages().findIndex((_, index) => pageHasMatch(index)), ) const isPageExpanded = (index: number) => expandedPages().includes(index) || matchingPage() === index const childSearch = (key: unknown): ExplorerSearch | undefined => { const search = props.search const match = search?.match.children.get(key) return search && match ? { term: search.term, match } : undefined } const label = () => ( ) const valueText = () => { if (!props.search) return displayValue(props.value) switch (props.search.match.kind) { case 'circular': return '[Circular]' case 'accessor': return '[Getter]' case 'opaque': return '[Object]' case 'branch': return Array.isArray(props.value) ? '[]' : nativeObjectType() === 'Map' ? 'Map(0)' : nativeObjectType() === 'Set' ? 'Set(0)' : '{}' case 'value': return primitiveText(props.value) } } const renderedValue = () => ( <> {props.search && typeof props.value === 'string' ? '"' : ''} {props.search && typeof props.value === 'string' ? '"' : ''} ) const currentDataPath = props.dataPath ?? [] const inputId = createUniqueId() return (
item.key}> {(entry) => { return ( ) }}
1}>
{(entries, index) => (
entry.key}> {(entry) => ( )}
)}
{renderedValue()} } > { const oldData = props.activeQuery!.state.data const newData = updateNestedDataByPath( oldData, currentDataPath, type() === 'number' ? changeEvent.target.valueAsNumber : changeEvent.target.value, ) queryClient.setQueryData(props.activeQuery!.queryKey, newData) }} /> {renderedValue()}
) }