All files / src/features/Minibuilders/Conversations/hooks useClickableHashtags.tsx

86.2% Statements 25/29
30% Branches 3/10
80% Functions 8/10
86.2% Lines 25/29

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70              21x 21x   21x     21x   21x 21x                 21x     21x 32x 32x 32x 21x   32x   2x 2x 2x                   32x 21x     21x 21x 22x       21x 21x 22x         32x        
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
  selectReplies,
  setConversationsGeneralSearchQueryString,
} from "@redux/slices/conversations";
import { useCallback, useEffect, useMemo } from "react";
 
const replacePatterns = (input: string): string => {
  const userMentionRegex = /@\[__([^[\]]{1,100})__\]\(user:([^()]{1,50})\)/g;
 
  const userMentionReplacement = (w: unknown, custom?: boolean) =>
    `<mark class="${!custom ? "mention" : "mention-custom"}">${w}</mark>`;
 
  const hashtagRegex = /#\[__([^]+?)__\]\(hashtag:__([^]+?)__\)/g;
 
  const hashtagReplacement = '<span class="hashtag">#$1</span>';
  const updatedInput = input
    .replace(userMentionRegex, (match, p1, p2): string => {
      if (p1.startsWith('"')) {
        return userMentionReplacement(p1, true);
      } else {
        return userMentionReplacement(`@${p1}`);
      }
    })
    .replace(hashtagRegex, hashtagReplacement);
  return updatedInput;
};
 
export const useClickableHashtags = (body: string) => {
  const dispatch = useAppDispatch();
  const { isRepliesOpen } = useAppSelector(selectReplies);
  const computedBody = useMemo(() => {
    return replacePatterns(body);
  }, [body]);
  const handleClick = useCallback(
    (ev: MouseEvent) => {
      const target = ev.target as HTMLSpanElement;
      const content = target.textContent?.replace(/#|\(.*?\)/g, "") || "";
      dispatch(
        setConversationsGeneralSearchQueryString({
          queryKey: isRepliesOpen ? "Replies" : "Threads",
          queryString: content,
        }),
      );
    },
    [body],
  );
 
  useEffect(() => {
    const spans: NodeListOf<HTMLSpanElement> = document.querySelectorAll(
      ".comment-markup .hashtag",
    );
    Eif (spans) {
      spans.forEach((span) => {
        span.addEventListener("click", handleClick);
      });
    }
 
    return () => {
      spans.forEach((span) => {
        span.removeEventListener("click", handleClick);
      });
    };
  }, [computedBody]);
 
  return {
    computedBody,
  };
};