import { useCallback, useMemo } from "react";
import "./RequestTextArea.scss";
import Editable from "@/components/generics/editable/Editable";
import Spinner from "@/components/generics/spinner/Spinner";
import { filterMatches, getAllMatches, highlightMatches } from "@/shared/utils/highlightMatches";
import { AbbreviationsBlock } from "../abbreviationBlock/AbbreviationsBlock";
import RequestTextAreaProps from "./RequestTextAreaProps";
import { useAppSelector } from "@/store/hooks";
import { useGetAbbreviations } from "@/api/predictions/hooks";
const RequestTextArea = ({
openAbbreviations,
content,
setContent,
abbreviationArray,
handleEditRequest,
}: RequestTextAreaProps) => {
const { hasAbbreviations } = useAppSelector((state) => state.request);
const { data: abbreviationsData, isLoading } = useGetAbbreviations();
const sortedAbbreviations = useMemo(
() => Object.keys(abbreviationsData ?? {}).sort((a, b) => b.length - a.length),
[abbreviationsData]
);
const onContentChange = useCallback(
(divContent: string) => {
const initialRequest = divContent;
const newContent = initialRequest.toString().replace(/\s+/g, " ");
const allMatches: { match: string; index: number; element: string }[] = getAllMatches(
sortedAbbreviations,
newContent
);
const resultString = highlightMatches(newContent, filterMatches(allMatches));
if (newContent !== content) {
setContent(resultString === "
" ? "" : resultString);
}
handleEditRequest();
},
[content, handleEditRequest, setContent, sortedAbbreviations]
);
return (