2019-07-07 11:18:12 +05:30
|
|
|
import fuzzaldrinPlus from 'fuzzaldrin-plus';
|
2021-01-03 14:25:43 +05:30
|
|
|
import { sanitize } from '~/lib/dompurify';
|
2019-07-07 11:18:12 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Wraps substring matches with HTML `<span>` elements.
|
|
|
|
* Inputs are sanitized before highlighting, so this
|
|
|
|
* filter is safe to use with `v-html` (as long as `matchPrefix`
|
|
|
|
* and `matchSuffix` are not being dynamically generated).
|
|
|
|
*
|
|
|
|
* Note that this function can't be used inside `v-html` as a filter
|
|
|
|
* (Vue filters cannot be used inside `v-html`).
|
|
|
|
*
|
|
|
|
* @param {String} string The string to highlight
|
|
|
|
* @param {String} match The substring match to highlight in the string
|
|
|
|
* @param {String} matchPrefix The string to insert at the beginning of a match
|
|
|
|
* @param {String} matchSuffix The string to insert at the end of a match
|
|
|
|
*/
|
|
|
|
export default function highlight(string, match = '', matchPrefix = '<b>', matchSuffix = '</b>') {
|
2020-04-08 14:13:33 +05:30
|
|
|
if (!string) {
|
2019-07-07 11:18:12 +05:30
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2020-04-08 14:13:33 +05:30
|
|
|
if (!match) {
|
2019-07-07 11:18:12 +05:30
|
|
|
return string;
|
|
|
|
}
|
|
|
|
|
2020-10-24 23:57:45 +05:30
|
|
|
const sanitizedValue = sanitize(string.toString(), { ALLOWED_TAGS: [] });
|
2019-07-07 11:18:12 +05:30
|
|
|
|
2019-09-04 21:01:54 +05:30
|
|
|
// occurrences is an array of character indices that should be
|
2019-07-07 11:18:12 +05:30
|
|
|
// highlighted in the original string, i.e. [3, 4, 5, 7]
|
2019-09-04 21:01:54 +05:30
|
|
|
const occurrences = fuzzaldrinPlus.match(sanitizedValue, match.toString());
|
2019-07-07 11:18:12 +05:30
|
|
|
|
|
|
|
return sanitizedValue
|
|
|
|
.split('')
|
|
|
|
.map((character, i) => {
|
2020-04-08 14:13:33 +05:30
|
|
|
if (occurrences.includes(i)) {
|
2019-07-07 11:18:12 +05:30
|
|
|
return `${matchPrefix}${character}${matchSuffix}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
return character;
|
|
|
|
})
|
|
|
|
.join('');
|
|
|
|
}
|