-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathsearch-input.vue
450 lines (398 loc) · 13.6 KB
/
search-input.vue
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<template>
<input
ref="inputElement"
@mouseenter="emitUserHoveredInSearchBox"
@mouseleave="emitUserHoveredOutSearchBox"
@blur="emitUserBlurredSearchBox"
@click="emitUserClickedSearchBox"
@focus="emitUserFocusedSearchBox"
@input="emitUserIsTypingAQueryEvents"
@keydown.enter="emitUserPressedEnterKey"
@keydown.up.down.prevent="emitUserPressedArrowKey"
@beforeinput="preventSpecialKey"
:maxlength="maxLength"
:value="query"
autocomplete="off"
class="x-search-input x-input"
enterkeyhint="search"
inputmode="search"
type="search"
data-test="search-input"
aria-label="type your query here"
/>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { ArrowKey } from '../../../utils';
import { debounce } from '../../../utils/debounce';
import { DebouncedFunction } from '../../../utils/types';
import { XEvent } from '../../../wiring/events.types';
import { WireMetadata } from '../../../wiring/wiring.types';
import { use$x } from '../../../composables/use-$x';
import { useState } from '../../../composables/use-state';
import { searchBoxXModule } from '../x-module';
/**
* This component renders an input field that allows the user to type a query. It also reacts to
* query changes through event listening.
*
* @public
*/
export default defineComponent({
name: 'SearchInput',
xModule: searchBoxXModule.name,
props: {
/**
* Maximum characters allowed in the input search.
*/
maxLength: {
type: Number,
default: 64
},
/**
* Allows input autofocus when the search field is rendered.
*/
autofocus: {
type: Boolean,
default: true
},
/**
* Enables the auto-accept query after debounce.
*/
instant: {
type: Boolean,
default: true
},
/**
* Debounce time for the instant.
*/
instantDebounceInMs: {
type: Number,
default: 500
}
},
setup: function (props) {
const $x = use$x();
const { query } = useState('searchBox', ['query']);
const inputElement = ref<HTMLInputElement>();
let debouncedUserAcceptedAQuery: DebouncedFunction<[string]>;
/**
* Generates the {@link WireMetadata} object omitting the moduleName.
*
* @returns The {@link WireMetadata} object omitting the moduleName.
* @internal
*/
const createEventMetadata = (): Omit<WireMetadata, 'moduleName'> => {
return {
target: inputElement.value,
feature: 'search_box'
};
};
/**
* Emits {@link XEventsTypes.UserAcceptedAQuery} event.
*
* @remarks It is necessary in a separated method to use it as the parameter of debounce in
* emitDebouncedUserAcceptedAQuery method.
* @internal
* @param query - The query that will be emitted.
*/
const emitUserAcceptedAQuery = (query: string): void => {
$x.emit('UserAcceptedAQuery', query, createEventMetadata());
};
/**
* Emits {@link XEventsTypes.UserAcceptedAQuery} event with a debounce configured in
* `instantDebounceInMs` prop.
*
* @internal
* @param query - The query that will be emitted.
*/
const emitDebouncedUserAcceptedAQuery = (query: string): void => {
if (props.instant) {
if (!debouncedUserAcceptedAQuery) {
debouncedUserAcceptedAQuery = debounce(
emitUserAcceptedAQuery,
props.instantDebounceInMs
);
}
debouncedUserAcceptedAQuery(query);
}
};
/**
* Emits event {@link SearchBoxXEvents.UserHoveredInSearchBox} when search box is hovered in.
*
* @internal
*/
const emitUserHoveredInSearchBox = (): void => {
$x.emit('UserHoveredInSearchBox', undefined, { target: inputElement.value });
};
/**
* Emits event {@link SearchBoxXEvents.UserHoveredOutSearchBox} when search box is hovered out.
*
* @internal
*/
const emitUserHoveredOutSearchBox = (): void => {
$x.emit('UserHoveredOutSearchBox', undefined, { target: inputElement.value });
};
/**
* Emits event {@link SearchBoxXEvents.UserBlurredSearchBox} when search box loses focus.
*
* @internal
*/
const emitUserBlurredSearchBox = (): void => {
$x.emit('UserBlurredSearchBox', undefined, { target: inputElement.value });
};
/**
* Emits event {@link SearchBoxXEvents.UserClickedSearchBox} when user clicks the search input.
*
* @internal
*/
const emitUserClickedSearchBox = (): void => {
$x.emit('UserClickedSearchBox', undefined, { target: inputElement.value });
};
/**
* Emits event {@link SearchBoxXEvents.UserFocusedSearchBox} when search box gains focus.
*
* @internal
*/
const emitUserFocusedSearchBox = (): void => {
$x.emit('UserFocusedSearchBox', undefined, { target: inputElement.value });
};
/**
* Emits event {@link SearchBoxXEvents.UserIsTypingAQuery} when the user typed/pasted something
* into the search-box. Also emits event {@link SearchBoxXEvents.UserClearedQuery} when the user
* removes all characters in the search-box.
*
* @internal
*/
const emitUserIsTypingAQueryEvents = (): void => {
const query = inputElement.value?.value ?? '';
$x.emit('UserIsTypingAQuery', query, { target: inputElement.value });
if (query.trim()) {
emitDebouncedUserAcceptedAQuery(query);
} else {
cancelDebouncedUserAcceptedAQuery();
}
};
/**
* Emits event {@link XEventsTypes.UserPressedArrowKey} when the user pressed an arrow key.
*
* @param event - The keyboard event with the arrow key pressed.
* @internal
*/
const emitUserPressedArrowKey = (event: KeyboardEvent): void => {
$x.emit('UserPressedArrowKey', event.key as ArrowKey, createEventMetadata());
};
/**
* Emits multiple events when the user pressed the enter key.
*
* @remarks
* Emitted events are:
* {@link SearchBoxXEvents.UserPressedEnterKey}
* {@link XEventsTypes.UserAcceptedAQuery}
*
* @internal
*/
const emitUserPressedEnterKey = (): void => {
const query = inputElement.value?.value.trim();
if (!!query && query.length > 0) {
$x.emit('UserPressedEnterKey', query, createEventMetadata());
emitUserAcceptedAQuery(query);
}
inputElement.value?.blur();
};
/**
* Prevents the user from either typing or pasting special characters in the input field.
*
* @internal
* @param event - The event that will be checked for special characters.
*/
const preventSpecialKey = (event: InputEvent): void => {
if (/[<>]/.test(event.data ?? '')) {
event.preventDefault();
}
};
/**
* When event {@link XEventsTypes.UserReachedEmpathizeTop} or
* {@link SearchBoxXEvents.UserPressedClearSearchBoxButton}
* are emitted the search input is focused.
*
* @internal
*/
function focusInput(): void {
inputElement.value?.focus();
}
['UserReachedEmpathizeTop', 'UserPressedClearSearchBoxButton'].forEach(event =>
$x.on(event as XEvent, false).subscribe(focusInput)
);
/**
* When event {@link XEventsTypes.UserAcceptedAQuery} or
* {@link SearchBoxXEvents.UserClearedQuery} are emitted the pending debounced emit
* {@link XEvent} `UserAcceptedAQuery` is canceled.
*
* @internal
*/
function cancelDebouncedUserAcceptedAQuery(): void {
debouncedUserAcceptedAQuery?.cancel();
}
['UserAcceptedAQuery', 'UserClearedQuery'].forEach(event =>
$x.on(event as XEvent, false).subscribe(cancelDebouncedUserAcceptedAQuery)
);
onMounted(() => {
if (props.autofocus) {
focusInput();
}
});
return {
query,
inputElement,
emitUserHoveredInSearchBox,
emitUserHoveredOutSearchBox,
emitUserBlurredSearchBox,
emitUserClickedSearchBox,
emitUserFocusedSearchBox,
emitUserIsTypingAQueryEvents,
emitUserPressedEnterKey,
emitUserPressedArrowKey,
preventSpecialKey
};
}
});
</script>
<style lang="css" scoped>
.x-search-input::-webkit-search-decoration,
.x-search-input::-webkit-search-cancel-button,
.x-search-input::-webkit-search-results-button,
.x-search-input::-webkit-search-results-decoration {
-webkit-appearance: none;
}
</style>
<docs lang="mdx">
## Events
This component emits the following events:
- [`UserClickedSearchBox`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserBlurredSearchBox`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserFocusedSearchBox`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserIsTypingAQuery`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserPressedEnterKey`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserPressedArrowKey`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
- [`UserAcceptedAQuery`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)
## See it in action
<!-- prettier-ignore-start -->
:::warning Backend service required
To use this component, the Search service must be implemented.
:::
<!-- prettier-ignore-end -->
Here you have a basic example of how the search input is rendered.
_Type any term in the input field to try it out!_
```vue live
<template>
<SearchInput />
</template>
<script>
import { SearchInput } from '@empathyco/x-components/search-box';
export default {
name: 'SearchInputDemo',
components: {
SearchInput
}
};
</script>
```
### Play with props
In this example, the search input has been limited to accept a maximum of 5 characters, including
spaces, it won't take the focus when it is rendered, and it will emit the `UserAcceptedAQuery` event
after 1000 milliseconds without typing.
_Type a term with more than 5 characters to try it out!_
```vue live
<template>
<SearchInput :maxLength="5" :autofocus="false" :instant="true" :instantDebounceInMs="1000" />
</template>
<script>
import { SearchInput } from '@empathyco/x-components/search-box';
export default {
name: 'SearchInputDemo',
components: {
SearchInput
}
};
</script>
```
### Play with events
In this example, a message has been added below the search input to illustrate the action performed.
For example, if you select the search input box, the message “focus” appears. When you start to
enter a search term, the message “typing” appears. If you press Enter after typing a search term,
the message “enter” appears.
<!-- prettier-ignore-start -->
:::warning X Events are only emitted from the root X Component.
At the moment, X Events are only emitted from the root X Component. This means that if you wrap
the `SearchInput` with another component of another module like the `MainScroll`, you should add
the listeners to the `MainScroll` instead of the `SearchInput`. If you need to subscribe to these
events, it is recommended to use the [`GlobalXBus`](../common/x-components.global-x-bus.md)
component instead.
:::
<!-- prettier-ignore-end -->
_Type any term in the input field to try it out!_
```vue live
<template>
<div>
<SearchInput
@UserPressedEnterKey="value = 'enter'"
@UserFocusedSearchBox="hasFocus = true"
@UserBlurredSearchBox="hasFocus = false"
@UserIsTypingAQuery="value = 'typing'"
/>
<strong>{{ value }}</strong>
<span>{{ hasFocus ? 'focused' : 'unfocused' }}</span>
</div>
</template>
<script>
import { SearchInput } from '@empathyco/x-components/search-box';
export default {
name: 'SearchInputDemo',
components: {
SearchInput
},
data() {
return {
value: '',
hasFocus: false
};
}
};
</script>
```
## Extending the component
Components can be combined and communicate with each other. Commonly, the `SearchInput` component
communicates with the [`SearchButton`](x-components.search-button.md) and the
[`ClearSearchInput`](x-components.clear-search-input.md) to offer a full query entry experience.
Furthermore, you can use it together with the [`QuerySuggestions`](query-suggestions.md) component
to autocomplete the typed search term.
_Type “trousers” or another fashion term in the input field and then click the clear icon to try it
out!_
```vue live
<template>
<div>
<div style="display: flex; flex-flow: row nowrap;">
<SearchInput />
<ClearSearchInput>
<img src="/assets/icons/cross.svg" />
</ClearSearchInput>
<SearchButton>Search</SearchButton>
</div>
<QuerySuggestions />
</div>
</template>
<script>
import { SearchInput, ClearSearchInput, SearchButton } from '@empathyco/x-components/search-box';
import { QuerySuggestions } from '@empathyco/x-components/query-suggestions';
export default {
name: 'SearchInputDemo',
components: {
SearchInput,
ClearSearchInput,
SearchButton,
QuerySuggestions
}
};
</script>
```
</docs>