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

explorerSearch.ts

199 lines6.3 KB

1import { getNativeObjectType } from './nativeObjectType'
2​
3/** Match metadata at one original data path. */
4export type SearchMatch = {
5 /** Whether the original entry label matches. */
6 label: boolean
7 /** Whether a primitive value matches. */
8 value: boolean
9 /** Includes descendants, so rendering never needs to search a subtree again. */
10 hasMatch: boolean
11 /** Controls safe expansion and terminal display during search. */
12 kind: 'branch' | 'value' | 'opaque' | 'circular' | 'accessor'
13 /** Entries keyed by their original label, including Map key identity. */
14 children: ReadonlyMap<unknown, SearchMatch>
16​
17/** Search information passed to an individual explorer row. */
18export type ExplorerSearch = {
19 /** The case-normalized literal search term. */
20 term: string
21 /** Match metadata for this row's original data path. */
22 match: SearchMatch
24​
25type SearchEntry = {
26 key: unknown
27 label: string
28 value: unknown
29 accessor?: boolean
31​
32/**
33 * Converts only primitive values to searchable text.
34 * @param value - The inspected value.
35 * @returns Primitive text, or undefined for objects and functions.
36 */
37export function primitiveText(value: unknown): string | undefined {
38 if (value === null) return 'null'
39 switch (typeof value) {
40 case 'string':
41 case 'number':
42 case 'boolean':
43 case 'bigint':
44 case 'symbol':
45 case 'undefined':
46 return String(value)
47 default:
48 return undefined
49 }
51​
52/**
53 * Reads finite entries through native collection methods and own descriptors.
54 * Accessors and user-defined iterators or key conversions are not evaluated.
55 * @param value - The inspected value.
56 * @returns Original entries, or undefined for opaque values.
57 */
58export function searchEntries(value: unknown): Array<SearchEntry> | undefined {
59 try {
60 if (
61 value === null ||
62 typeof value !== 'object' ||
63 ArrayBuffer.isView(value)
64 ) {
65 return undefined
66 }
67 const type = getNativeObjectType(value)
68 if (type === 'String') return undefined
69 if (type === 'Map') {
70 return Array.from(Map.prototype.entries.call(value), ([key, entry]) => ({
71 key,
72 label: primitiveText(key) ?? '[Object key]',
73 value: entry,
74 }))
75 }
76 if (type === 'Set') {
77 return Array.from(Set.prototype.values.call(value), (entry, index) => ({
78 key: String(index),
79 label: String(index),
80 value: entry,
81 }))
82 }
83 const entries = Object.entries(Object.getOwnPropertyDescriptors(value))
84 .filter(([, descriptor]) => descriptor.enumerable)
85 .map(([key, descriptor]) => ({
86 key,
87 label: key,
88 value: descriptor.value,
89 accessor: !('value' in descriptor),
90 }))
91 if (
92 !Array.isArray(value) &&
93 Object.getPrototypeOf(value) !== Object.prototype &&
94 Object.getPrototypeOf(value) !== null &&
95 !entries.some(
96 (entry) => !entry.accessor && typeof entry.value !== 'function',
97 )
98 ) {
99 return undefined
100 }
101 return entries
102 } catch {
103 return undefined
104 }
106​
107// `toLowerCase` never outputs it, so a lowercased term can't match across two joined parts
108const SEARCH_TEXT_SEPARATOR = 'A'
109​
110/**
111 * Builds the text that `searchExplorer` matches: every entry label and
112 * primitive value, lowercased. Visiting breadth-first reaches each object once
113 * at its shallowest depth, so shared data is searched once with the same depth
114 * bound.
115 * @param rootValue - The data to build the search text of.
116 * @returns Text that contains a lowercased term exactly when `searchExplorer` matches it.
117 */
118export function createSearchText(rootValue: unknown): string {
119 const rootText = primitiveText(rootValue)
120 if (rootText !== undefined) return rootText.toLowerCase()
121 const parts: Array<string> = []
122 const seen = new Set<unknown>([rootValue])
123 const queue: Array<{ value: unknown; depth: number }> = [
124 { value: rootValue, depth: 0 },
125 ]
126 // Also visits the entries pushed while iterating
127 for (const { value, depth } of queue) {
128 for (const entry of searchEntries(value) ?? []) {
129 parts.push(entry.label.toLowerCase())
130 if (entry.accessor) continue
131 const text = primitiveText(entry.value)
132 if (text !== undefined) {
133 parts.push(text.toLowerCase())
134 } else if (
135 depth < 500 &&
136 typeof entry.value === 'object' &&
137 !seen.has(entry.value)
138 ) {
139 seen.add(entry.value)
140 queue.push({ value: entry.value, depth: depth + 1 })
141 }
142 }
143 }
144 return parts.join(SEARCH_TEXT_SEPARATOR)
146​
147/**
148 * Builds one search tree, stopping ancestor cycles while visiting shared siblings.
149 * @param rootValue - The current root data.
150 * @param term - The case-normalized literal search term.
151 * @returns Match and safe rendering metadata for every original entry.
152 */
153export function searchExplorer(rootValue: unknown, term: string): SearchMatch {
154 const ancestors = new Set<unknown>()
155 /**
156 * Visits one original path with its current ancestors.
157 * @param value - The entry value.
158 * @param label - The entry label; absent for the synthetic root.
159 * @param accessor - Whether reading the entry would invoke a getter.
160 * @param depth - The current nesting depth.
161 * @returns The entry's match metadata.
162 */
163 function visit(
164 value: unknown,
165 label?: string,
166 accessor = false,
167 depth = 0,
168 ): SearchMatch {
169 const labelMatch = label?.toLowerCase().includes(term) ?? false
170 const text = accessor ? undefined : primitiveText(value)
171 const valueMatch = text?.toLowerCase().includes(term) ?? false
172 const children = new Map<unknown, SearchMatch>()
173 const match: SearchMatch = {
174 label: labelMatch,
175 value: valueMatch,
176 hasMatch: labelMatch || valueMatch,
177 kind: accessor ? 'accessor' : text !== undefined ? 'value' : 'opaque',
178 children,
179 }
180 if (accessor || text !== undefined) return match
181 if (depth > 500) return match
182 if (ancestors.has(value)) {
183 match.kind = 'circular'
184 return match
185 }
186 const entries = searchEntries(value)
187 if (!entries) return match
188 match.kind = 'branch'
189 ancestors.add(value)
190 for (const entry of entries) {
191 const child = visit(entry.value, entry.label, entry.accessor, depth + 1)
192 children.set(entry.key, child)
193 match.hasMatch ||= child.hasMatch
194 }
195 ancestors.delete(value)
196 return match
197 }
198 return visit(rootValue)