Explore: highlight typed text in suggestions

- use react-highlight-words
- add highlighting (color and border) to the matching substring of the
  suggested items in the typeahead
- extracted match finding from logging datasource
- created new utils/text.ts class for text-related functions
- added more types
This commit is contained in:
David Kaltschmidt
2018-10-05 13:00:45 +02:00
parent c1164f5c00
commit 76a3b1a793
12 changed files with 116 additions and 98 deletions

View File

@@ -0,0 +1,32 @@
import { TextMatch } from 'app/types/explore';
/**
* Adapt findMatchesInText for react-highlight-words findChunks handler.
* See https://github.com/bvaughn/react-highlight-words#props
*/
export function findHighlightChunksInText({ searchWords, textToHighlight }) {
return findMatchesInText(textToHighlight, searchWords.join(' '));
}
/**
* Returns a list of substring regexp matches.
*/
export function findMatchesInText(haystack: string, needle: string): TextMatch[] {
// Empty search can send re.exec() into infinite loop, exit early
if (!haystack || !needle) {
return [];
}
const regexp = new RegExp(`(?:${needle})`, 'g');
const matches = [];
let match = regexp.exec(haystack);
while (match) {
matches.push({
text: match[0],
start: match.index,
length: match[0].length,
end: match.index + match[0].length,
});
match = regexp.exec(haystack);
}
return matches;
}