All files / src/components/common/FilePreview/hooks useTextSearch.tsx

75% Statements 15/20
50% Branches 1/2
50% Functions 4/8
82.35% Lines 14/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42      3x         3x 2x 2x   2x 1x 1x     2x         2x   2x 1x 1x 1x       2x                    
import { useCallback, useEffect, useState } from "react";
import { CustomTextRenderer } from "react-pdf/dist/cjs/shared/types";
 
const highlightPattern = (text: string, pattern: string) => {
  const regEx = new RegExp(pattern, "ig");
  return text.replace(regEx, (value) => `<mark>${value}</mark>`);
};
 
const useTextSearch = () => {
  const [isSearchActive, setIsSearchActive] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>("");
 
  const toggleSearch = (open: boolean) => {
    Eif (!open) setSearchText("");
    setIsSearchActive(open);
  };
 
  const textRenderer: CustomTextRenderer = useCallback(
    (textItem) => highlightPattern(textItem.str, searchText),
    [searchText],
  );
 
  const onSearch = (newValue: string) => setSearchText(newValue);
 
  useEffect(() => {
    return () => {
      setIsSearchActive(false);
      setSearchText("");
    };
  }, []);
 
  return {
    isSearchActive,
    toggleSearch,
    textRenderer,
    searchText,
    onSearch,
  };
};
 
export default useTextSearch;