Tester.tsx
import React, { useEffect, useState } from "react";
import { useAppDispatch, useAppSelector } from "../hooks/hooks";
import "./styles/Tester.scss";
import { keyboardHandler, startTyping } from "../store/typer.slice";
const Tester: React.FC = () => {
const accuracy = useAppSelector((state) => state.typer.accuracy);
const text = useAppSelector(({ typer: { text } }) => Array.from(text));
const time = useAppSelector((state) => state.typer.time);
const words = useAppSelector((s) => s.typer.words);
const completeWords = useAppSelector((s) => s.typer.completeWords);
const key = useAppSelector((state) => state.typer.key);
const characters = useAppSelector((state) => state.typer.countCharacters);
const inputText = useAppSelector((s) => s.typer.inputText);
const dispatch = useAppDispatch();
const [printedText, setPrintedText] = useState(""); // Новое состояние для хранения текста с обернутыми символами
useEffect(() => {
const keyHandler = (event: KeyboardEvent) => {
dispatch(keyboardHandler(event.key));
};
dispatch(startTyping());
document.addEventListener("keydown", keyHandler);
return () => {
document.removeEventListener("keydown", keyHandler);
};
}, []);
const inputOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
let newPrintedText = "";
for (let i = 0; i < text.length; i++) {
if (i < value.length) {
// Проверка на наличие символа в введенном тексте
if (text[i] === value[i]) {
newPrintedText += `<span class="highlight">${text[i]}</span>`; // Обернуть символ в <span> с классом highlight
} else {
newPrintedText += text[i]; // Добавить символ без обертки
}
} else {
newPrintedText += text[i]; // Добавить символ без обертки
}
}
setPrintedText(newPrintedText);
};
return (
<div className="testWrapper">
<div>
<p
className="textForTest"
dangerouslySetInnerHTML={{ __html: printedText }} // Используйте dangerouslySetInnerHTML для отображения HTML-разметки
/>
<input
value={inputText}
onChange={inputOnChange}
type="text"
placeholder="text"
/>
<p>Last character: {key}</p>
<div className="typeStatistics">
<span className="statisticsItem">Accuracy: {accuracy}%</span>
<span className="statisticsItem">
Characters per minute: {characters}
</span>
<span className="statisticsItem">Time: {time} s.</span>
</div>
</div>
<div className="controls">
<button>Start</button>
<button>Restart</button>
</div>
</div>
);
};
export default Tester;
и вы можете определить стили в Tester.scss.
.highlight {
background-color: yellow;
}