Files
outline/app/components/Highlight.tsx
Nan Yu 75a868e5e8 feat: Search shared documents (#3126)
* provide a type-ahead search input on shared document pages that allow search of child document tree
* improve keyboard navigation handling of all search views
* improve coloring on dark mode list selection states
* refactor PaginatedList component to eliminate edge cases
2022-04-08 10:40:51 -07:00

51 lines
1.1 KiB
TypeScript

import * as React from "react";
import replace from "string-replace-to-array";
import styled from "styled-components";
type Props = React.HTMLAttributes<HTMLSpanElement> & {
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(
(highlight || "").replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"),
caseSensitive ? "g" : "gi"
);
}
return (
<span {...rest}>
{highlight
? replace(text, regex, (tag: string) => (
<Mark key={index++}>
{processResult ? processResult(tag) : tag}
</Mark>
))
: text}
</span>
);
}
export const Mark = styled.mark`
background: ${(props) => props.theme.searchHighlight};
border-radius: 2px;
padding: 0 2px;
`;
export default Highlight;