index.tsx 1.4 KB

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