javascript - React Text Selection with overlaping sentences - Stack Overflow

`The user selects and highlights a sentence, and I capture the highlighted text along with its start in

`The user selects and highlights a sentence, and I capture the highlighted text along with its start index. A popup then appears, allowing the user to choose custom colors to highlight the selected sentence. While I have implemented basic logic to render the highlighted text, I am facing challenges in handling overlapping highlights effectively.

const preprocessData = (data: HightLightText\[\]): HightLightText\[\] =\> {
return data.reduce\<HightLightText\[\]\>((acc, current, index) =\> {
// If underline is "none", inherit from the previous item if available
const parentUnderline =
index \> 0 && acc\[index - 1\].startIndex + acc\[index - 1\].selectedText.length \> current.startIndex
? acc\[index - 1\].underline
: "none";

    const effectiveUnderline =
      current.underline !== "none" ? current.underline : parentUnderline;
    
    acc.push({ ...current, underline: effectiveUnderline as any});
    return acc;

}, \[\]);
};

const renderNestedData = (
data: HightLightText\[\],
handleHighlightedTextClick: (
highlightText: string,
startIndex: number,
e: React.MouseEvent
) =\> void
) =\> {
const sortedData = preprocessData(data).sort((a, b) =\> a.startIndex - b.startIndex);

const merge = (index: number): (string | JSX.Element) =\> {

    if (index >= sortedData.length) {
      return <></>;
    }
    
    const currentItem = sortedData[index];
    const nextItem = sortedData[index + 1];
    
    if (nextItem && nextItem.startIndex < currentItem.startIndex + currentItem.selectedText.length) {
      
      const overlapStart = currentItem.startIndex + currentItem.selectedText.length - nextItem.startIndex;
      const beforeOverlap = currentItem.selectedText.slice(0, currentItem.selectedText.length - overlapStart);
      const afterOverlap = currentItem.selectedText.slice(beforeOverlap.length + nextItem.selectedText.length);
      const mergedContent = (
        <>
          <span
            key={`start-${currentItem.startIndex}`}
            className={`${customColors[currentItem.bgColor]} focus:outline-none focus:${focusedColors[currentItem.bgColor]} cursor-auto inline`}
            style={{
              textDecorationLine: currentItem.underline !== "none" ? "underline" : "none",
              textDecorationStyle: currentItem.underline !== "none" ? (currentItem.underline as any) : undefined,
            }}
            onClick={(evt) => handleHighlightedTextClick(currentItem.selectedText, currentItem.startIndex, evt)}
          >
            {beforeOverlap}
          </span>
          {merge(index + 1)}
          <span
            key={`end-${currentItem.startIndex}`}
            className={`${customColors[currentItem.bgColor]} focus:outline-none focus:${focusedColors[currentItem.bgColor]} cursor-auto inline`}
            style={{
              textDecorationLine: currentItem.underline !== "none" ? "underline" : "none",
              textDecorationStyle: currentItem.underline !== "none" ? (currentItem.underline as any) : undefined,
            }}
            onClick={(evt) => handleHighlightedTextClick(currentItem.selectedText, currentItem.startIndex, evt)}
          >
            {afterOverlap}
          </span>
        </>
      );
    
      return mergedContent;
    }
    
    return (
      <span
        key={`highlight-${currentItem.startIndex}`}
        className={`${customColors[currentItem.bgColor]} focus:outline-none focus:${focusedColors[currentItem.bgColor]} cursor-auto inline`}
        style={{
          textDecorationLine: currentItem.underline !== "none" ? "underline" : "none",
          textDecorationStyle: currentItem.underline !== "none" ? (currentItem.underline as any) : undefined,
        }}
        onClick={(evt) => handleHighlightedTextClick(currentItem.selectedText, currentItem.startIndex, evt)}
      >
        {currentItem.selectedText}
      </span>
    );

};

return merge(0);
};

const renderHighlightedText = (
textContent: string\[\],
highlightedContent: HightLightTextData\[\],
questionId: string,
contentType: string,
handleHighlightedTextClick: (
highlightText: string,
startIndex: number,
e: React.MouseEvent
) =\> void
): (string | JSX.Element)\[\] =\> {
const elements: (string | JSX.Element)\[\] = \[\];
const highlightData = getHighlightData(highlightedContent, questionId, contentType);

if (!highlightData) {
return textContent.map((text) =\> \<span key={highlight-text-${text.length}}\>{text}\</span\>);
}

textContent.forEach((text) =\> {
let currentIndex = 0;
const sortedHighlights = \[...highlightData\].sort((a, b) =\> a.startIndex - b.startIndex);
let skipNextHighlight :boolean\[\] = \[\];

    sortedHighlights.forEach((highlight, index) => {
      if (skipNextHighlight.some((value) => value)) {
        return; // Skip this iteration
      }
    
      const { startIndex, selectedText, bgColor } = highlight;
    
      if (startIndex > currentIndex) {
        elements.push(<span key={`text-before-${startIndex}`}>{text.slice(currentIndex, startIndex)}</span>);
      }
    
      let endIndex = startIndex + (selectedText.length);
    
      const nestedHighlights = sortedHighlights.filter(
        (innerHighlight, innerIndex) =>
          innerIndex > index &&
          innerHighlight.startIndex < endIndex && // Allow overlap
          innerHighlight.startIndex + innerHighlight.selectedText.length > startIndex // Ensure it intersects
      );
    
      if (nestedHighlights.length > 0) {
        
        let lastElementIndex = nestedHighlights[nestedHighlights.length-1].startIndex + nestedHighlights[nestedHighlights.length-1].selectedText.length;
        endIndex = Math.max(endIndex, lastElementIndex);
       
        skipNextHighlight = [];
        //if(endIndex > lastElementIndex){
          nestedHighlights.forEach(() => skipNextHighlight.push(true));
        //}
        
        
        let nestedHighlightedData = renderNestedData([highlight,...nestedHighlights],handleHighlightedTextClick)
        //console.log([highlight,...nestedHighlights],ReactDOMServer.renderToString(nestedHighlightedData),"nested")
        elements.push(
          <span key={`nested-${startIndex}`}>
            {nestedHighlightedData}
          </span>
        );
        
      } else {
        elements.push(
          <span
            role="button"
            key={`highlight-${startIndex}`}
            className={`${customColors[bgColor]} focus:outline-none focus:${focusedColors[bgColor]} cursor-auto inline`}
            style={{
              textDecorationLine: highlight.underline !== "none" ? "underline" : "none",
              textDecorationStyle: highlight.underline !== "none" ? (highlight.underline as any) : undefined,
            }}
            tabIndex={0}
            onClick={(evt) => handleHighlightedTextClick(selectedText, startIndex, evt)}
          >
            {selectedText}
          </span>
        );
      }
    
      currentIndex = endIndex;
    });
    
    //console.log(currentIndex,text.length,ReactDOMServer.renderToString(elements),"nested")
    if (currentIndex < text.length) {
      elements.push(<span key={`text-after-${currentIndex}`}>{text.slice(currentIndex)}</span>);
    }
     return elements; };
`});

And the input for is:

(["A poet often writes about themes of isolation and self-discovery in her work. In one of her most well-known poems, the speaker describes wandering through a dense forest, feeling lost and disconnected from the world. As the poem progresses, the speaker gradually embraces solitude, finding peace and clarity in being alone. The poet suggests that isolation can lead to self-awareness and personal growth, as it allows individuals to reflect on their inner selves without external distractions."], [ { "selectedText": "ns.", "startIndex": 490, "bgColor": "lightPink", "underline": "none", "contentType": "description", "isNotes": false, "notes": "" }, { "selectedText": "isolation can lead to", "startIndex": 347, "bgColor": "lightBlue", "underline": "none", "contentType": "description", "isNotes": false, "notes": "" }, { "selectedText": "The poet suggests that isolation can lead to self-awareness ", "startIndex": 324, "bgColor": "lightYellow", "underline": "none", "contentType": "description", "isNotes": false, "notes": "" }, { "selectedText": "The poet suggests that isolation can lead to self-awareness and personal growth", "startIndex": 324, "bgColor": "lightPink", "underline": "none", "contentType": "description", "isNotes": false, "notes": "" } ],"quesId","desc",dummyFunc)

I have tried implementing the basic recursive logic to handle overlap sentences but there is some issue with that`

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745628240a4636943.html

相关推荐

  • javascript - React Text Selection with overlaping sentences - Stack Overflow

    `The user selects and highlights a sentence, and I capture the highlighted text along with its start in

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信