import { escapeRegExp } from "lodash"; import * as React from "react"; import replace from "string-replace-to-array"; import styled from "styled-components"; import { s } from "@shared/styles"; type Props = React.HTMLAttributes & { highlight: (string | null | undefined) | RegExp; processResult?: (tag: string) => string; text: string | undefined; caseSensitive?: boolean; }; function Highlight({ highlight, processResult, caseSensitive, text = "", ...rest }: Props) { let regex; let index = 0; if (highlight instanceof RegExp) { regex = highlight; } else { regex = new RegExp( escapeRegExp(highlight || ""), caseSensitive ? "g" : "gi" ); } return ( {highlight ? replace(text, regex, (tag: string) => ( {processResult ? processResult(tag) : tag} )) : text} ); } export const Mark = styled.mark` background: ${s("searchHighlight")}; border-radius: 2px; padding: 0 2px; `; export default Highlight;