-
Notifications
You must be signed in to change notification settings - Fork 18
/
utils.ts
57 lines (50 loc) · 1.65 KB
/
utils.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
import type { Item } from '../../item';
import { AutosuggestHighlightable, AutosuggestItem } from './types.js';
/**
* Check whether item can be highlighted
* @param suggestion Suggestion object
* @param target item element
* @returns highlightable
*/
export const itemHighlightable: AutosuggestHighlightable = (suggestion: AutosuggestItem, target: HTMLElement): boolean => {
return (target as Item).highlightable;
};
/**
* Replace forbidden characters in regular expressions
* @param string A string to process
* @returns clean string
*/
export const escapeRegExp = (string = ''): string => {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
/**
* A basic regexp matching pattern to replace text based on string input.
* @param text Value to test against
* @param query The query
* @param [pattern=<mark>$1</mark>] Provide a pattern to replace string
* @returns innerHTML The text that can be used as innerHTML
*/
export const queryWordSelect = (text: string, query = '', pattern = '<mark>$1</mark>'): string => {
query = query && query.trim();
if (!query) {
return text;
}
const regExReplace = new RegExp(`(${escapeRegExp(query)})`, 'ig');
return text.replace(regExReplace, pattern);
};
/**
* Update element content
* @param el to update content
* @param query to search
* @param label text to test against
* @param value text to use as fallback
* @return {void}
*/
export const updateElementContent = (el: Item, query: string, label: string, value: string | number): void => {
if (itemHighlightable(value as AutosuggestItem, el)) {
el.innerHTML = queryWordSelect(label, query);
}
else {
el.label = `${value}`;
}
};