Spaces:
Running
Running
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 }; | |
}; | |