2023-07-07 12:54:21 +02:00
|
|
|
import { Fragment, VFC } from 'react';
|
2022-12-28 11:35:27 +01:00
|
|
|
import { safeRegExp } from '@server/util/escape-regex';
|
2023-01-05 15:23:40 +01:00
|
|
|
import { styled } from '@mui/material';
|
2022-05-05 15:34:46 +02:00
|
|
|
|
2022-04-20 14:22:50 +02:00
|
|
|
interface IHighlighterProps {
|
2022-05-05 15:34:46 +02:00
|
|
|
search?: string;
|
|
|
|
children?: string;
|
2022-04-20 14:22:50 +02:00
|
|
|
caseSensitive?: boolean;
|
|
|
|
}
|
|
|
|
|
2023-01-05 15:23:40 +01:00
|
|
|
export const StyledSpan = styled('span')(({ theme }) => ({
|
|
|
|
'&>mark': {
|
|
|
|
backgroundColor: theme.palette.highlight,
|
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
2022-05-05 15:34:46 +02:00
|
|
|
export const Highlighter: VFC<IHighlighterProps> = ({
|
2022-04-20 14:22:50 +02:00
|
|
|
search,
|
|
|
|
children,
|
|
|
|
caseSensitive,
|
2022-05-05 15:34:46 +02:00
|
|
|
}) => {
|
|
|
|
if (!children) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!search) {
|
|
|
|
return <>{children}</>;
|
|
|
|
}
|
|
|
|
|
2022-12-28 11:35:27 +01:00
|
|
|
const regex = safeRegExp(search, caseSensitive ? 'g' : 'gi');
|
2022-04-20 14:22:50 +02:00
|
|
|
|
2023-07-07 12:54:21 +02:00
|
|
|
const parts = children.split(regex);
|
|
|
|
|
|
|
|
const highlightedText = parts.map((part, index) =>
|
|
|
|
index < parts.length - 1 ? (
|
|
|
|
<Fragment key={index}>
|
|
|
|
{part}
|
|
|
|
<mark>{search}</mark>
|
|
|
|
</Fragment>
|
|
|
|
) : (
|
|
|
|
part
|
|
|
|
)
|
2022-04-20 14:22:50 +02:00
|
|
|
);
|
2023-07-07 12:54:21 +02:00
|
|
|
|
|
|
|
return <StyledSpan>{highlightedText}</StyledSpan>;
|
2022-04-20 14:22:50 +02:00
|
|
|
};
|