import { palette2, styled } from '@ringcentral/juno'; import type { FunctionComponent } from 'react'; import React, { Fragment, useMemo } from 'react'; const HighlightText = styled.span` background: ${palette2('highlight', 'b02')}; `; const indexesOf = (string: string, highLightText: string) => { let match; const indexes = []; const regex = new RegExp( highLightText.replace(/[-\\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'gi', ); // eslint-disable-next-line no-cond-assign while ((match = regex.exec(string)) !== null) { indexes.push(match.index); } return indexes; }; interface TextWithHighlightProps { text: string; highLightText: string; } export const TextWithHighlight: FunctionComponent = ({ text, highLightText, ...rest }) => { const highlightTextLength = highLightText?.length; const matchIndexes = useMemo( () => (highlightTextLength > 0 ? indexesOf(text, highLightText) : []), [highLightText, highlightTextLength, text], ); return ( {matchIndexes.length > 0 ? matchIndexes.map((startIndex, index) => { const endIndex = startIndex + highlightTextLength; return ( {index === 0 && text.substring(0, startIndex)} {text.substring(startIndex, endIndex)} {text.substring(endIndex, matchIndexes[index + 1])} ); }) : text} ); };