我正在尝试构建一个用于数学目的的聊天机器人,现在,我正处于第一步。
我正在尝试使用动画文本显示来模拟聊天机器人的响应,就像 chatGPT 的响应一样。显示简单的字符串并不是一项艰巨的任务,但是,在大多数情况下,机器人的响应应该包含需要从乳胶表达式中显示的数学方程,为此,我正在使用“better-react-mathjax”库。
所以我的问题是,如何提取一个包含在常规字符串中找到的所有乳胶表达式的起始索引和结束索引的数组,因此当我向用户显示响应时,我可以用动画显示常规字符方式,与乳胶表达式相反,它将在没有任何动画的情况下显示。
我正在使用 React Js,这是到目前为止我的组件代码:
import React, { useState, useEffect } from "react";
import "./styles/App.css";
const ChatGtpTypingComponent = () => {
const equation4 =
"When \\(a \\ne 0\\), there exists two solutions for\\(ax^2 + bx + c = 0\\) as \\[x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}.\\]";
const [text, setText] = useState("");
const [showCursor, setCursor] = useState(true);
const messages =
"Paragraphs are the building blocks of papers.\nMany students define paragraphs in terms of length: a paragraph is a group of at least five sentences, a paragraph is half a page long, etc. In reality, though, the unity and coherence of ideas among sentences is what constitutes a paragraph. A paragraph is defined as “a group of sentences or a single sentence that forms a unit” (Lunsford and Connors 116).";
const config = {
tex2jax: {
inlineMath: [
["$", "$"],
["\\(", "\\)"],
],
displayMath: [
["$$", "$$"],
["\\[", "\\]"],
],
processEscapes: true,
},
};
useEffect(() => {
let currentCharIndex = 0;
const typeNextChar = () => {
const currentMessage = messages;
const currentChar = currentMessage.charAt(currentCharIndex);
setText((prevText) => prevText + currentChar);
if (currentCharIndex < currentMessage.length - 1) {
currentCharIndex += 1;
setTimeout(typeNextChar, 35); // Adjust the interval to control typing speed
} else {
setCursor(false);
}
};
typeNextChar(); // Start typing when the component mounts
}, [messages]);
return (
<div className="typing-effect-container">
<p>
{text}
{showCursor && (
<img
style={{
marginBottom: "1px",
height: "10px",
width: "10px",
}}
src="images/black dote.png"
></img>
)}
</p>
</div>
);
};
export default ChatGtpTypingComponent;
这是文本动画的CSS:
.typing-effect-container {
font-family: "Arial", sans-serif;
font-size: 18px;
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
max-width: auto;
height: auto;
overflow: hidden;
text-align: left;
position: relative;
}
.typing-effect-container p {
margin: 0;
padding: 0;
white-space: pre-wrap; /* Allow wrapping on the whitespace */
overflow-wrap: break-word; /* Break words when needed */
overflow: hidden;
position: relative;
animation: typing 0.8s steps(40, end);
}
@keyframes typing {
from {
width: 0;
}
to {
width: 100%;
}
}
.cursor {
display: inline-block;
width: 0.2em;
height: 1em;
background-color: #000;
margin-left: 2px; /* Adjust the cursor position */
}
.cursor-hidden {
background-color: transparent;
}
我只好使用js属性分割来解决这个问题。