File tree Expand file tree Collapse file tree 1 file changed +30
-1
lines changed Expand file tree Collapse file tree 1 file changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -328,7 +328,9 @@ async function fetchAiResponse(message) {
328328
329329对于后端返回的所有回复内容,我们需要用打字机形式打印出来。
330330
331- 最初的方案是
331+ 最初的方案是每次接收到后端的返回后就立即显示到页面里,后来发现这样速度太快了,眨眼就显示完了,没有打印机效果。
332+ 所以后来的方案就改成了用定时器实现定时打印,那么就需要把收到的先放进数组里缓存起来,然后定时每 50 毫秒执行一次,打印一个内容出来。
333+ 具体实现代码如下:
332334
333335``` js
334336function typingWords (){
@@ -382,6 +384,33 @@ function typingWords(){
382384}
383385```
384386
387+ ### 代码渲染
388+
389+ 如果严格按照输出什么打印什么的话,那么当正在打印一段代码,需要等到代码全部打完,才能被格式化为代码块,才能高亮显示代码。
390+ 那这个体验也太差了。
391+ 有什么办法能够解决这个问题呢?
392+ 答案就在问题里,既然是因为代码块有开始标记没有结束标记,那就我们给他补全结束标记就好了,直到真的结束标记来了,才不需要补全。
393+
394+ 具体的实现就是下面几行代码:
395+
396+ ``` js
397+ if (content .indexOf (' `' ) != - 1 ){
398+ if (content .indexOf (' ```' ) != - 1 ){
399+ codeStart = ! codeStart;
400+ }else if (content .indexOf (' ``' ) != - 1 && (lastWord + content).indexOf (' ```' ) != - 1 ){
401+ codeStart = ! codeStart;
402+ }else if (content .indexOf (' `' ) != - 1 && (lastLastWord + lastWord + content).indexOf (' ```' ) != - 1 ){
403+ codeStart = ! codeStart;
404+ }
405+ }
406+
407+ lastLastWord = lastWord;
408+ lastWord = content;
409+
410+ answerContent += content;
411+ answers[qaIdx].innerHTML = marked .parse (answerContent+ (codeStart? ' \n\n ```' : ' ' ));
412+ ```
413+
385414### 其它
386415
387416更多其它细节请看代码,如果对代码有疑问的,请加我微信(同 GitHub id)
You can’t perform that action at this time.
0 commit comments