Skip to content

Commit 0b6f597

Browse files
committed
feat: #1549 流式渲染场景,优化代码块自动闭合的时机并优化行内公式在表格里也可以自动闭合
1 parent 253d68f commit 0b6f597

File tree

3 files changed

+32
-6
lines changed

3 files changed

+32
-6
lines changed

.changeset/cool-rooms-drum.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'cherry-markdown': patch
3+
---
4+
5+
feat: #1549 流式渲染场景,优化代码块自动闭合的时机并优化行内公式在表格里也可以自动闭合

packages/cherry-markdown/src/core/hooks/CodeBlock.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,13 @@ export default class CodeBlock extends ParagraphBase {
390390
if ($codes.length % 2 === 1) {
391391
const lastCode = $codes[$codes.length - 1].replace(/(`)[^`]+$/, '$1').replace(/\n+/, '');
392392
const $str = str.replace(/\n+$/, '').replace(/\n`{1,2}$/, '');
393-
return `${$str}\n${lastCode}\n`;
393+
return (
394+
`${$str}\n${lastCode}\n`
395+
// 如果自动闭合后代码块为空,则删除代码块
396+
.replace(/\n`{3,}[^`\n]*\n\s*`{3,}\n$/g, '\n')
397+
// 如果自动闭合的是mermaid图,则再判断第二行以后的内容是否为空,如果为空,则删除代码块
398+
.replace(/\n`{3,}\s*mermaid\s*\n[^\n]+\n\s*`{3,}\n$/g, '\n')
399+
);
394400
}
395401
return str;
396402
}

packages/cherry-markdown/src/core/hooks/InlineMath.js

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ export default class InlineMath extends ParagraphBase {
3636
// 非浏览器环境下配置为 node
3737
this.engine = isBrowser() ? (config.engine ?? 'MathJax') : 'node';
3838
this.$cherry = cherry;
39+
/**
40+
* 这里本意是用来存储「上一轮」成功渲染里的最后一个公式
41+
* 但因为偷懒,存的是「上一次」成功渲染里的公式,所以这里有个大大的「TODO」
42+
* 同时,mermaid渲染那里也有同样的问题,也有个大大的「TODO」
43+
*/
3944
this.lastCode = '';
4045
}
4146

@@ -105,17 +110,27 @@ export default class InlineMath extends ParagraphBase {
105110
let $str = str;
106111
// 格里处理行内公式,让一个td里的行内公式语法生效,让跨td的行内公式语法失效
107112
$str = $str.replace(getTableRule(true), (whole, ...args) => {
108-
return whole
109-
.split('|')
110-
.map((oneTd) => {
113+
const arr = whole.split('|');
114+
return arr
115+
.map((oneTd, index) => {
111116
// 单元格里的段落公式直接替换成行内公式
112-
return this.makeInlineMath(this.transformBlockMathToInlineMath(oneTd));
117+
const tdContent = this.transformBlockMathToInlineMath(oneTd);
118+
// 判断是否为最后一个td
119+
if (index === arr.length - 1) {
120+
return this.makeInlineMathWithSelfClosing(tdContent);
121+
}
122+
return this.makeInlineMath(tdContent);
113123
})
114124
.join('|')
115125
.replace(/\\~D/g, '~D') // 出现反斜杠的情况(如/$e=m^2$)会导致多一个反斜杠,这里替换掉
116126
.replace(/~D/g, '\\~D');
117127
});
118-
$str = this.makeInlineMath($str);
128+
$str = this.makeInlineMathWithSelfClosing($str);
129+
return $str;
130+
}
131+
132+
makeInlineMathWithSelfClosing(str) {
133+
let $str = this.makeInlineMath(str);
119134
if (this.isSelfClosing()) {
120135
const $oldStr = $str;
121136
$str = this.$dealUnclosingMath($str);

0 commit comments

Comments
 (0)