|
| 1 | +import { RichTextarea } from "rich-textarea"; |
| 2 | +import { actions, useGrammar } from "../store/grammar"; |
| 3 | +import { Options } from "./Options"; |
| 4 | + |
| 5 | +const HighlightText = () => { |
| 6 | + const { selection, answer, question: text } = useGrammar(); |
| 7 | + const highlights = answer?.matches || []; |
| 8 | + let lastIndex = 0; |
| 9 | + const renderedHighlights = []; |
| 10 | + let counter = 0; |
| 11 | + |
| 12 | + for (let i = 0; i < highlights.length; i++) { |
| 13 | + const { offset, length, replacements } = highlights[i]; |
| 14 | + const nCount = text.substring(0, offset).match(/\\[ntrvf]/g)?.length ?? 0; |
| 15 | + const nOffset = nCount; |
| 16 | + if (offset > lastIndex) { |
| 17 | + // Add the text before the current highlight |
| 18 | + renderedHighlights.push( |
| 19 | + <span key={counter}>{text.substring(lastIndex, offset + nOffset)}</span> |
| 20 | + ); |
| 21 | + counter = counter + 1; |
| 22 | + } |
| 23 | + |
| 24 | + renderedHighlights.push( |
| 25 | + <Options |
| 26 | + key={counter} |
| 27 | + replacements={replacements} |
| 28 | + isSelected={selection === i} |
| 29 | + text={text.substring(nOffset + offset, nOffset + offset + length)} |
| 30 | + context={highlights[i]} |
| 31 | + index={i} |
| 32 | + /> |
| 33 | + ); |
| 34 | + counter = counter + 1; |
| 35 | + |
| 36 | + // Update lastIndex to the end of the current highlight |
| 37 | + lastIndex = offset + length + nOffset; |
| 38 | + } |
| 39 | + |
| 40 | + // Add any remaining text after the last highlight |
| 41 | + if (lastIndex < text.length) { |
| 42 | + renderedHighlights.push( |
| 43 | + <span key={counter}>{text.substring(lastIndex)}</span> |
| 44 | + ); |
| 45 | + counter = counter + 1; |
| 46 | + } |
| 47 | + return <div>{renderedHighlights}</div>; |
| 48 | +}; |
| 49 | + |
| 50 | +export const Content = () => { |
| 51 | + const { question } = useGrammar(); |
| 52 | + |
| 53 | + return ( |
| 54 | + <RichTextarea |
| 55 | + value={question} |
| 56 | + style={{ width: "600px", height: "400px" }} |
| 57 | + onChange={(e) => actions.setQuestion(e.target.value)} |
| 58 | + > |
| 59 | + {() => <HighlightText />} |
| 60 | + </RichTextarea> |
| 61 | + ); |
| 62 | +}; |
0 commit comments