-
Notifications
You must be signed in to change notification settings - Fork 2
/
HighlightedText.tsx
74 lines (70 loc) · 2.31 KB
/
HighlightedText.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Common
*/
import React from "react";
import Highlighter from "react-highlight-words";
import { HighlightingEngine } from "../tree/HighlightingEngine";
/**
* Properties of [[HighlightedText]]
* @public
*/
export interface HighlightedTextProps {
/* Filter text which we want to highlight */
searchText: string;
/* Index of actively highlighted part in a text */
activeMatchIndex?: number;
/* Full text */
text: string;
/** Should search be case sensitive */
caseSensitive?: boolean;
}
/**
* Highlighted text
* Used for highlighting parts in the 'text' which match with 'searchText'
* Also actively highlights one matched part which is selected with 'activeMatchIndex'
* @public
*/
export function HighlightedText(props: HighlightedTextProps) {
const { searchText, activeMatchIndex, text, caseSensitive } = props;
return (
<Highlighter
searchWords={[searchText]}
findChunks={findChunksNoRegex as any} // .d.ts declaration wrong
activeIndex={activeMatchIndex as any} // .d.ts file seems to be wrong, doesn't work if it's a string
activeClassName={HighlightingEngine.ACTIVE_CLASS_NAME}
autoEscape={true}
textToHighlight={text}
caseSensitive={caseSensitive}
/>
);
}
interface HighlighterChunk {
highlight: boolean;
start: number;
end: number;
}
interface FindChunksArgs {
autoEscape?: boolean;
caseSensitive?: boolean;
searchWords: string[];
textToHighlight: string;
}
const findChunksNoRegex = (args: FindChunksArgs): HighlighterChunk[] => {
const text = args.caseSensitive
? args.textToHighlight
: args.textToHighlight.toUpperCase();
const term = args.caseSensitive
? args.searchWords[0]
: args.searchWords[0].toUpperCase();
const chunks: HighlighterChunk[] = [];
let index = text.indexOf(term);
while (index !== -1) {
chunks.push({ start: index, end: index + term.length, highlight: true });
index = text.indexOf(term, index + 1);
}
return chunks;
};