Skip to content

Commit ff7b92e

Browse files
committed
Refined correctHeadings.
1 parent da05420 commit ff7b92e

1 file changed

Lines changed: 19 additions & 11 deletions

File tree

src/app/gbr-preset/plugins/frontmatter.ts

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,27 @@ import { Root, Heading, Paragraph } from 'mdast';
44
import { VFile as _VFile } from 'vfile';
55
import { Transformer, Attacher, Settings } from 'unified';
66

7+
type Depth = 2 | 1 | 3 | 4 | 5 | 6;
78
interface VFile extends _VFile {
89
data: {
910
matter?: any;
1011
title?: string;
1112
};
1213
}
1314

15+
const getHeadingFromStr = (text: string) => {
16+
const re = new RegExp(/(\#){1,6}/);
17+
18+
const hashes = text.match(re)[0];
19+
const _text = text.replace(hashes, '');
20+
21+
return {
22+
type: 'heading',
23+
depth: hashes.length as Depth,
24+
children: [{type: 'text', value: _text}]
25+
} as Heading;
26+
}
27+
1428
export function readMatter(): Transformer {
1529
return function transformer(node: Root, file: VFile) {
1630
if (node.children[0].type === 'yaml') {
@@ -50,21 +64,15 @@ export function correctHeadings(): Transformer {
5064
return (tree: Root, file: VFile) => {
5165
return visit(tree, 'paragraph', (node: Paragraph, index: number, parent: any) => {
5266
const text: string = node.children[0].value as string;
67+
const re = new RegExp(/(\#){1,6}([^\#]){1,}/g)
5368

54-
let re = new RegExp(/^(\#){1,3}/);
5569
if(re.test(text)){
56-
const hashes = text.match(/(\#){1,3}/)[0];
57-
const _text = text.replace(hashes, '');
58-
59-
const heading: Heading = {
60-
type: 'heading',
61-
depth: hashes.length as 2 | 1 | 3 | 4 | 5 | 6,
62-
children: [{type: 'text', value: _text}]
63-
};
70+
const headings = text.match(re).reduce((acc: Array<Heading>, _: string): Array<Heading> => {
71+
return _ ? [...acc, getHeadingFromStr(_)] : acc;
72+
}, []);
6473

65-
parent.children.splice(index, 1, heading);
74+
parent.children.splice(index, 1, ...headings);
6675
}
67-
6876
});
6977
};
7078
}

0 commit comments

Comments
 (0)