index.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import React, { useRef, useEffect, MutableRefObject } from 'react';
  2. import { useTranslation } from '../../i18n';
  3. import Button from '../Button';
  4. import Portal from '../Portal';
  5. import {
  6. Wrapper, InputWrapper, Input, ResultInfo, ArrowButton,
  7. } from './styled';
  8. type Props = {
  9. matchesTotal: number;
  10. matchIndex: number;
  11. onEnter: (val: string) => void;
  12. onPrev: () => void;
  13. onNext: () => void;
  14. isActive?: boolean;
  15. close: () => void;
  16. };
  17. const Search: React.FC<Props> = ({
  18. matchesTotal = 0,
  19. matchIndex = 1,
  20. onPrev,
  21. onNext,
  22. onEnter,
  23. isActive = false,
  24. close,
  25. }: Props) => {
  26. const { t } = useTranslation('toolbar');
  27. const inputRef = useRef(null) as MutableRefObject<any>;
  28. const handleKeyDown = (e: React.KeyboardEvent): void => {
  29. if (e.keyCode === 13 && inputRef.current.value) {
  30. onEnter(inputRef.current.value);
  31. }
  32. };
  33. useEffect(() => {
  34. if (isActive) {
  35. inputRef.current.focus();
  36. }
  37. }, [isActive]);
  38. return (
  39. <Portal>
  40. <Wrapper open={isActive}>
  41. <InputWrapper>
  42. <Input ref={inputRef} placeholder={t('searchDocument')} onKeyDown={handleKeyDown} />
  43. <ResultInfo>
  44. {matchesTotal ? `${matchIndex + 1} / ${matchesTotal}` : ''}
  45. </ResultInfo>
  46. </InputWrapper>
  47. <ArrowButton variant="top" onClick={onPrev} />
  48. <ArrowButton variant="bottom" onClick={onNext} />
  49. <Button appearance="primary" style={{ marginLeft: '16px' }} onClick={close}>
  50. {t('close')}
  51. </Button>
  52. </Wrapper>
  53. </Portal>
  54. );
  55. };
  56. export default Search;