Skip to content

Commit 8c4f17b

Browse files
fix(toolbar): apply heading levels across multiline selections (#1901)
Co-authored-by: sunsonliu <sunsonliu@tencent.com>
1 parent b7b33dd commit 8c4f17b

3 files changed

Lines changed: 16 additions & 4 deletions

File tree

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+
fix: apply heading levels consistently across multiline selections

‎packages/cherry-markdown/src/toolbars/hooks/Header.js‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export default class Header extends MenuBase {
7171
}
7272

7373
$testIsHead(selection) {
74-
return /^\s*(#+)\s*.+/.test(selection);
74+
return /^[ \t]*#+[ \t]*.+/m.test(selection);
7575
}
7676

7777
/**
@@ -99,9 +99,9 @@ export default class Header extends MenuBase {
9999
// 如果选中的内容里有标题语法,并且标记级别与目标一致,则去掉标题语法
100100
// 反之,修改标题级别与目标一致
101101
let needClean = true;
102-
const tmp = $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, (w, m1, m2, m3, m4) => {
103-
needClean = needClean ? m2.length === header.length : false;
104-
return `${m1}${header}${m3}${m4}`;
102+
const tmp = $selection.replace(/^([ \t]*)(#+)?([ \t]*)(.+)$/gm, (w, m1, m2, m3, m4) => {
103+
needClean = needClean && !!m2 && m2.length === header.length;
104+
return `${m1}${header}${m2 ? m3 : ' '}${m4}`;
105105
});
106106
if (needClean) {
107107
return $selection.replace(/(^\s*)(#+)(\s*)(.+$)/gm, '$1$4');

‎packages/cherry-markdown/test/toolbars/hooks/formatting.spec.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,13 @@ describe('toolbars/hooks formatting', () => {
108108
expect(createHook(Hook, input).hook.onClick(input)).toBe(expected);
109109
});
110110

111+
it('replaces an existing heading after ordinary text in a multiline selection', () => {
112+
const input = 'ordinary text\n## existing heading';
113+
const header = createHook(Header, input).hook;
114+
115+
expect(header.onClick(input, '1')).toBe('# ordinary text\n# existing heading');
116+
});
117+
111118
it.each([
112119
[H1, '# h1'],
113120
[H2, '## h2'],

0 commit comments

Comments
 (0)