typeahead: Highlight only matching word prefixes in search suggestions.

Earlier mid word parts matching with the search query were also
highlighted (made bold), but since actual matching for showing search
suggestions is based on prefix matching, this highlighting logic is
now made to be in sync with the search suggestions matching logic.
This commit is contained in:
N-Shar-ma 2022-08-18 00:53:47 +05:30 committed by Tim Abbott
parent d899c03da6
commit c3c8bad0de
2 changed files with 17 additions and 3 deletions

View File

@ -29,16 +29,24 @@ export function build_highlight_regex(query) {
}
export function highlight_with_escaping_and_regex(regex, item) {
// if regex is empty return entire item highlighted and escaped
if (regex.source === "()") {
return "<strong>" + Handlebars.Utils.escapeExpression(item) + "</strong>";
}
// We need to assemble this manually (as opposed to doing 'join') because we need to
// (1) escape all the pieces and (2) the regex is case-insensitive, and we need
// to know the case of the content we're replacing (you can't just use a bolded
// version of 'query')
const pieces = item.split(regex);
const pieces = item.split(regex).filter(Boolean);
let result = "";
for (const piece of pieces) {
if (regex.test(piece)) {
for (let i = 0; i < pieces.length; i += 1) {
const piece = pieces[i];
if (regex.test(piece) && (i === 0 || pieces[i - 1].endsWith(" "))) {
// only highlight if the matching part is a word prefix, ie
// if it is the 1st piece or if there was a space before it
result += "<strong>" + Handlebars.Utils.escapeExpression(piece) + "</strong>";
} else {
result += Handlebars.Utils.escapeExpression(piece);

View File

@ -671,6 +671,12 @@ test("highlight_with_escaping", () => {
expected = "<strong>development h</strong>elp";
result = highlight(query, item);
assert.equal(result, expected);
item = "Prefix notprefix prefix";
query = "pre";
expected = "<strong>Pre</strong>fix notprefix <strong>pre</strong>fix";
result = highlight(query, item);
assert.equal(result, expected);
});
test("render_person when emails hidden", ({mock_template}) => {