Skip to content

Commit

Permalink
correctly escape autocomplete-highlight text. closes #985
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelcobain committed Oct 5, 2018
1 parent aae6819 commit dd7979e
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 22 deletions.
76 changes: 55 additions & 21 deletions addon/components/paper-autocomplete-highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import Component from '@ember/component';

import { computed } from '@ember/object';
import { htmlSafe } from '@ember/string';
import layout from '../templates/components/paper-autocomplete-highlight';

/**
Expand All @@ -16,32 +15,67 @@ export default Component.extend({
tagName: 'span',
flags: '',

highlight: computed('searchText', 'label', 'flags', function() {
let text = `${this.get('label')}`;
let flags = this.get('flags');
let regex = this.getRegExp(this.get('searchText'), flags);
tokens: computed('regex', 'label', function() {
let string = `${this.get('label')}`;
let regex = this.get('regex');

let html = text.replace(regex, '<span class="highlight">$&</span>');
return htmlSafe(html);
}),
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
});

sanitize(term) {
if (!term) {
return term;
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 term.replace(/[\\^$*+?.()|{}[\]]/g, '\\$&');
},

getRegExp(text, flags) {
let str = '';
if (flags.indexOf('^') >= 1) {
str += '^';
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 = '^';
}
str += text;
if (flags.indexOf('$') >= 1) {
str += '$';

if (flags.indexOf('$') >= 0) {
endFlag = '$';
}
return new RegExp(this.sanitize(str), flags.replace(/[$^]/g, ''));

return new RegExp(startFlag + regexTerm + endFlag, flags.replace(/[$^]/g, ''));
},

sanitizeRegex(term) {
return term && term.toString().replace(/[\\^$*+?.()|{}[\]]/g, '\\$&');
}

});
8 changes: 7 additions & 1 deletion addon/templates/components/paper-autocomplete-highlight.hbs
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
{{highlight}}
{{#each tokens as |token|~}}
{{~#if token.isMatch~}}
<span class="highlight">{{token.text}}</span>
{{~else~}}
{{token.text}}
{{~/if~}}
{{~/each}}

0 comments on commit dd7979e

Please sign in to comment.