index.tsx 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. }
  41. }, [isActive]);
  42. return (
  43. <Portal>
  44. <Wrapper open={isActive}>
  45. <InputWrapper>
  46. <Input
  47. ref={inputRef}
  48. placeholder={t('searchDocument')}
  49. onKeyDown={handleKeyDown}
  50. />
  51. <ResultInfo>
  52. {matchesTotal ? `${current} / ${matchesTotal}` : ''}
  53. </ResultInfo>
  54. </InputWrapper>
  55. <ArrowButton variant="top" onClick={onPrev} />
  56. <ArrowButton variant="bottom" onClick={onNext} />
  57. <Button
  58. appearance="primary"
  59. style={{ marginLeft: '16px' }}
  60. onClick={close}
  61. >
  62. {t('close')}
  63. </Button>
  64. </Wrapper>
  65. </Portal>
  66. );
  67. };
  68. export default Search;