index.tsx 1.7 KB

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