-
Notifications
You must be signed in to change notification settings - Fork 470
/
Copy pathquery-helpers.ts
270 lines (247 loc) · 7.53 KB
/
query-helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import {
type GetErrorFunction,
type Matcher,
type MatcherOptions,
type QueryMethod,
type Variant,
type waitForOptions as WaitForOptions,
type WithSuggest,
} from '../types'
import {getSuggestedQuery} from './suggestions'
import {fuzzyMatches, matches, makeNormalizer} from './matches'
import {waitFor} from './wait-for'
import {getConfig} from './config'
function getElementError(message: string | null, container: HTMLElement) {
return getConfig().getElementError(message, container)
}
function getMultipleElementsFoundError(
message: string,
container: HTMLElement,
) {
return getElementError(
`${message}\n\n(If this is intentional, then use the \`*AllBy*\` variant of the query (like \`queryAllByText\`, \`getAllByText\`, or \`findAllByText\`)).`,
container,
)
}
function queryAllByAttribute(
attribute: string,
container: HTMLElement,
text: Matcher,
{exact = true, collapseWhitespace, trim, normalizer}: MatcherOptions = {},
): HTMLElement[] {
const matcher = exact ? matches : fuzzyMatches
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
return Array.from(
container.querySelectorAll<HTMLElement>(`[${attribute}]`),
).filter(node =>
matcher(node.getAttribute(attribute), node, text, matchNormalizer),
)
}
function queryByAttribute(
attribute: string,
container: HTMLElement,
text: Matcher,
options?: MatcherOptions,
) {
const els = queryAllByAttribute(attribute, container, text, options)
if (els.length > 1) {
throw getMultipleElementsFoundError(
`Found multiple elements by [${attribute}=${text}]`,
container,
)
}
return els[0] || null
}
// this accepts a query function and returns a function which throws an error
// if more than one elements is returned, otherwise it returns the first
// element or null
function makeSingleQuery<Arguments extends unknown[]>(
allQuery: QueryMethod<Arguments, HTMLElement[]>,
getMultipleError: GetErrorFunction<Arguments>,
) {
return (container: HTMLElement, ...args: Arguments) => {
const els = allQuery(container, ...args)
if (els.length > 1) {
const elementStrings = els
.map(element => getElementError(null, element).message)
.join('\n\n')
throw getMultipleElementsFoundError(
`${getMultipleError(container, ...args)}
Here are the matching elements:
${elementStrings}`,
container,
)
}
return els[0] || null
}
}
function getSuggestionError(
suggestion: {toString(): string},
container: HTMLElement,
) {
return getConfig().getElementError(
`A better query is available, try this:
${suggestion.toString()}
`,
container,
)
}
// this accepts a query function and returns a function which throws an error
// if an empty list of elements is returned
function makeGetAllQuery<Arguments extends unknown[]>(
allQuery: (container: HTMLElement, ...args: Arguments) => HTMLElement[],
getMissingError: GetErrorFunction<Arguments>,
) {
return (container: HTMLElement, ...args: Arguments) => {
const els = allQuery(container, ...args)
if (!els.length) {
throw getConfig().getElementError(
getMissingError(container, ...args),
container,
)
}
return els
}
}
// this accepts a getter query function and returns a function which calls
// waitFor and passing a function which invokes the getter.
function makeFindQuery<QueryFor>(
getter: (
container: HTMLElement,
text: Matcher,
options: MatcherOptions,
) => QueryFor,
) {
return (
container: HTMLElement,
text: Matcher,
options: MatcherOptions,
waitForOptions: WaitForOptions,
) => {
return waitFor(
() => {
return getter(container, text, options)
},
{container, ...waitForOptions},
)
}
}
const wrapSingleQueryWithSuggestion =
<Arguments extends [...unknown[], WithSuggest]>(
query: (container: HTMLElement, ...args: Arguments) => HTMLElement | null,
queryAllByName: string,
variant: Variant,
) =>
(container: HTMLElement, ...args: Arguments) => {
const element = query(container, ...args)
const [{suggest = getConfig().throwSuggestions} = {}] = args.slice(-1) as [
WithSuggest,
]
if (element && suggest) {
const suggestion = getSuggestedQuery(element, variant)
if (
suggestion &&
!queryAllByName.endsWith(suggestion.queryName as string)
) {
throw getSuggestionError(suggestion.toString(), container)
}
}
return element
}
const wrapAllByQueryWithSuggestion =
<
// We actually want `Arguments extends [args: ...unknown[], options?: Options]`
// But that's not supported by TS so we have to `@ts-expect-error` every callsite
Arguments extends [...unknown[], WithSuggest],
>(
query: (container: HTMLElement, ...args: Arguments) => HTMLElement[],
queryAllByName: string,
variant: Variant,
) =>
(container: HTMLElement, ...args: Arguments) => {
const els = query(container, ...args)
const [{suggest = getConfig().throwSuggestions} = {}] = args.slice(-1) as [
WithSuggest,
]
if (els.length && suggest) {
// get a unique list of all suggestion messages. We are only going to make a suggestion if
// all the suggestions are the same
const uniqueSuggestionMessages = [
...new Set(
els.map(
element =>
getSuggestedQuery(element, variant)?.toString() as string,
),
),
]
if (
// only want to suggest if all the els have the same suggestion.
uniqueSuggestionMessages.length === 1 &&
!queryAllByName.endsWith(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TODO: Can this be null at runtime?
getSuggestedQuery(els[0], variant)!.queryName as string,
)
) {
throw getSuggestionError(uniqueSuggestionMessages[0], container)
}
}
return els
}
// TODO: This deviates from the published declarations
// However, the implementation always required a dyadic (after `container`) not variadic `queryAllBy` considering the implementation of `makeFindQuery`
// This is at least statically true and can be verified by accepting `QueryMethod<Arguments, HTMLElement[]>`
function buildQueries(
queryAllBy: QueryMethod<
[matcher: Matcher, options: MatcherOptions],
HTMLElement[]
>,
getMultipleError: GetErrorFunction<
[matcher: Matcher, options: MatcherOptions]
>,
getMissingError: GetErrorFunction<
[matcher: Matcher, options: MatcherOptions]
>,
) {
const queryBy = wrapSingleQueryWithSuggestion(
makeSingleQuery(queryAllBy, getMultipleError),
queryAllBy.name,
'query',
)
const getAllBy = makeGetAllQuery(queryAllBy, getMissingError)
const getBy = makeSingleQuery(getAllBy, getMultipleError)
const getByWithSuggestions = wrapSingleQueryWithSuggestion(
getBy,
queryAllBy.name,
'get',
)
const getAllWithSuggestions = wrapAllByQueryWithSuggestion(
getAllBy,
queryAllBy.name.replace('query', 'get'),
'getAll',
)
const findAllBy = makeFindQuery(
wrapAllByQueryWithSuggestion(getAllBy, queryAllBy.name, 'findAll'),
)
const findBy = makeFindQuery(
wrapSingleQueryWithSuggestion(getBy, queryAllBy.name, 'find'),
)
return [
queryBy,
getAllWithSuggestions,
getByWithSuggestions,
findAllBy,
findBy,
]
}
export {
getElementError,
wrapAllByQueryWithSuggestion,
wrapSingleQueryWithSuggestion,
getMultipleElementsFoundError,
queryAllByAttribute,
queryByAttribute,
makeSingleQuery,
makeGetAllQuery,
makeFindQuery,
buildQueries,
}