// Libs
// -----------------------------------------------------------------------------
import React, { FC, Fragment } from 'react';
import { Typography } from 'antd';

// Props
// -----------------------------------------------------------------------------
type TextHighlighterProps = {
  text: string;
  searchString: string;
};

/**
 * Компонент для подсветки части строки, например при поиске.
 */
export const TextHighlighter: FC<TextHighlighterProps> = ({
  text,
  searchString,
}) => {
  const textUpper = text.toUpperCase();
  const searchStringUpper = searchString.toUpperCase();

  const matchStart = textUpper.search(searchStringUpper);
  const matchEnd = matchStart + searchString.length;

  const hasMatch = matchStart !== -1 && searchString.length > 0;

  return hasMatch ? (
    <Fragment>
      {text.slice(0, matchStart)}
      <Typography.Text mark>{text.slice(matchStart, matchEnd)}</Typography.Text>
      {text.slice(matchEnd)}
    </Fragment>
  ) : (
    <Fragment>{text}</Fragment>
  );
};
