2018-10-05 06:00:45 -05:00
|
|
|
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(' '));
|
|
|
|
}
|
|
|
|
|
2018-12-01 08:26:51 -06:00
|
|
|
const cleanNeedle = (needle: string): string => {
|
|
|
|
return needle.replace(/[[{(][\w,.-?:*+]+$/, '');
|
|
|
|
};
|
|
|
|
|
2018-10-05 06:00:45 -05:00
|
|
|
/**
|
|
|
|
* 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 matches = [];
|
2018-12-01 08:26:51 -06:00
|
|
|
const cleaned = cleanNeedle(needle);
|
|
|
|
let regexp;
|
|
|
|
try {
|
|
|
|
regexp = new RegExp(`(?:${cleaned})`, 'g');
|
|
|
|
} catch (error) {
|
|
|
|
return matches;
|
2018-10-05 06:00:45 -05:00
|
|
|
}
|
2018-12-01 08:26:51 -06:00
|
|
|
haystack.replace(regexp, (substring, ...rest) => {
|
|
|
|
if (substring) {
|
|
|
|
const offset = rest[rest.length - 2];
|
|
|
|
matches.push({
|
|
|
|
text: substring,
|
|
|
|
start: offset,
|
|
|
|
length: substring.length,
|
|
|
|
end: offset + substring.length,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return '';
|
|
|
|
});
|
2018-10-05 06:00:45 -05:00
|
|
|
return matches;
|
|
|
|
}
|