File size: 2,504 Bytes
79278ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { useCallback, useEffect, useMemo, useState } from "react";
import { setHasAbbreviations, setRequest } from "./reducer";

export const useAbbreviation = () => {
  const dispatch = useAppDispatch();
  const { abbreviations } = useAppSelector((state) => state.request);

  const [content, setContent] = useState<string>("");

  const addValues = useCallback(() => {
    let newContent = content;

    abbreviations.forEach((element) => {
      if (element.value?.length > 0) {
        const link = `<a href="#" class="abbreviation">${element?.key}</a>`;
        newContent = newContent.replace(link, `${link} @@@(${element?.value})@@@ `);
      }
    });
    return newContent;
  }, [abbreviations, content]);

  const removeValues = useCallback(() => {
    let newContent = content;

    abbreviations.forEach((element) => {
      const link = `<a href="#" class="abbreviation">${element?.key}</a>`;
      newContent = newContent
        .replace(`${link} @@@(${element.value})@@@`, link)
        .replace(`${link} (${element.value})`, link);
    });
    setContent(newContent);
    return newContent;
  }, [abbreviations, content]);

  const textContent = useMemo(() => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(addValues().replaceAll("@@@", "").replace(/\s+/g, " "), "text/html");
    return doc.body.textContent ?? "";
  }, [addValues]);

  const textContentWithoutAbbrVal = useMemo(() => {
    const parser = new DOMParser();
    const cleanedContent = content
      .replace(/@@@.*?@@@/g, "")
      .replace(/\s*\(.*?\)\s*/g, " ")
      .replace(/\s+/g, " ");

    const doc = parser.parseFromString(cleanedContent.trim(), "text/html");

    const textContent = doc.body.textContent ?? "";

    return textContent.trim();
  }, [content]);

  const abbreviationArray = useMemo(() => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, "text/html");

    const abbrElements = doc.querySelectorAll("a.abbreviation");

    const texts = Array.from(abbrElements).map((element) => element.textContent?.trim() ?? "");

    return texts;
  }, [content]);

  useEffect(() => {
    dispatch(setRequest(textContent));
    dispatch(setHasAbbreviations(abbreviationArray.length > 0));
  }, [abbreviationArray.length, content, dispatch, textContent]);

  return { content, setContent, textContent, abbreviationArray, textContentWithoutAbbrVal, addValues, removeValues };
};