import React, { memo, useCallback } from 'react';

export const SelectText = memo((props: any) => {
  const { onMouseUp, onClick, ...resetProps } = props;

  const handleMouseUp: React.MouseEventHandler<HTMLSpanElement> = useCallback(
    (event) => {
      if (event.button === 0) {
        if (window.getSelection()?.toString().length) {
          event.stopPropagation();
          event.preventDefault();
        } else {
          onMouseUp && onMouseUp(event);
          onClick && onClick(event as any);
        }
      }
    },
    [onMouseUp, onClick],
  );

  const handleMouseDown: React.MouseEventHandler<HTMLSpanElement> = useCallback(
    (event) => {
      if (event.button === 0) {
        window.getSelection()?.removeAllRanges();
      }
    },
    [],
  );

  return (
    <span
      {...resetProps}
      onMouseUp={handleMouseUp}
      onMouseDown={handleMouseDown}
    >
      {props.children}
    </span>
  );
});
