admin管理员组

文章数量:1026203

`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`

`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`

本文标签: javascriptReact Text Selection with overlaping sentencesStack Overflow