-
Notifications
You must be signed in to change notification settings - Fork 332
/
paper-autocomplete-highlight.js
81 lines (65 loc) · 1.72 KB
/
paper-autocomplete-highlight.js
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
/**
* @module ember-paper
*/
import Component from '@ember/component';
import { computed } from '@ember/object';
import layout from '../templates/components/paper-autocomplete-highlight';
/**
* @class PaperAutocompleteHighlight
* @extends Ember.Component
*/
export default Component.extend({
layout,
tagName: 'span',
flags: '',
tokens: computed('regex', 'label', function() {
let string = `${this.get('label')}`;
let regex = this.get('regex');
let tokens = [];
let lastIndex = 0;
// Use replace here, because it supports global and single regular expressions at same time.
string.replace(regex, (match, index) => {
let prev = string.slice(lastIndex, index);
if (prev) {
tokens.push({
text: prev,
isMatch: false
});
}
tokens.push({
text: match,
isMatch: true
});
lastIndex = index + match.length;
});
// Append the missing text as a token.
let last = string.slice(lastIndex);
if (last) {
tokens.push({
text: last,
isMatch: false
});
}
return tokens;
}),
regex: computed('searchText', 'flags', function() {
let flags = this.get('flags');
let text = this.get('searchText');
return this.getRegExp(text, flags);
}),
getRegExp(term, flags) {
let startFlag = '';
let endFlag = '';
let regexTerm = this.sanitizeRegex(term);
if (flags.indexOf('^') >= 0) {
startFlag = '^';
}
if (flags.indexOf('$') >= 0) {
endFlag = '$';
}
return new RegExp(startFlag + regexTerm + endFlag, flags.replace(/[$^]/g, ''));
},
sanitizeRegex(term) {
return term && term.toString().replace(/[\\^$*+?.()|{}[\]]/g, '\\$&');
}
});