1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00
Files
checktheroads-hyperglass/hyperglass/ui/components/results/error.tsx
2021-01-03 23:51:09 -07:00

31 lines
899 B
TypeScript

import { Text } from '@chakra-ui/react';
import type { TFormattedError } from './types';
type TFormatError = string | JSX.Element;
function formatError(text: string, values: string[], regex: RegExp): TFormatError[] | TFormatError {
if (!values.length) {
return text;
}
const parts = text.split(regex);
return parts.reduce((prev, current, i) => {
if (!i) {
return [current];
}
return prev.concat(
values.includes(current) ? <strong key={i + current}>{current}</strong> : current,
);
}, [] as TFormatError[]);
}
export const FormattedError: React.FC<TFormattedError> = (props: TFormattedError) => {
const { keywords, message } = props;
const pattern = new RegExp(keywords.map(kw => `(${kw})`).join('|'), 'gi');
const things = formatError(message, keywords, pattern);
return <Text as="span">{keywords.length !== 0 ? things : message}</Text>;
};