Skip to content

Commit ba44259

Browse files
committed
fix: ignore ## in code blocks for table of content
1 parent 0fd7651 commit ba44259

File tree

2 files changed

+30
-12
lines changed

2 files changed

+30
-12
lines changed

packages/site-kit/src/lib/markdown/utils.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ export const SHIKI_LANGUAGE_MAP = {
1414
'': ''
1515
};
1616

17+
export function is_in_code_block(body: string, index: number) {
18+
const code_blocks = [...body.matchAll(/```.*\n(.|\n)+```/gm)].map((match) => {
19+
return [match.index ?? 0, match[0].length + (match.index ?? 0)] as const;
20+
});
21+
22+
return code_blocks.some(([start, end]) => {
23+
if (index >= start && index <= end) return true;
24+
return false;
25+
});
26+
}
27+
1728
/**
1829
* Strip styling/links etc from markdown
1930
*/

packages/site-kit/src/lib/server/content/index.ts

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { extract_frontmatter, slugify, smart_quotes } from '../../markdown/utils';
1+
import { extract_frontmatter, is_in_code_block, slugify, smart_quotes } from '../../markdown/utils';
22
import type { Document } from '../../types';
33

44
export async function create_index(
@@ -31,17 +31,24 @@ export async function create_index(
3131
'<code>$1</code>'
3232
);
3333

34-
const sections = Array.from(body.matchAll(/^##\s+(.*)$/gm)).map((match) => {
35-
const title = smart_quotes(match[1])
36-
// replace < and > inside code spans
37-
.replace(/`(.+?)`/g, (_, contents) => contents.replace(/</g, '&lt;').replace(/>/g, '&gt;'))
38-
// turn e.g. `class:_name_` into `class:<em>name</em>`
39-
.replace(/_(.+)_/g, (_, contents) => `<em>${contents}</em>`);
40-
41-
const slug = slugify(title);
42-
43-
return { slug, title };
44-
});
34+
const sections = Array.from(body.matchAll(/^##\s+(.*)$/gm)).reduce(
35+
(arr, match) => {
36+
if (is_in_code_block(body, match.index || 0)) return arr;
37+
const title = smart_quotes(match[1])
38+
// replace < and > inside code spans
39+
.replace(/`(.+?)`/g, (_, contents) =>
40+
contents.replace(/</g, '&lt;').replace(/>/g, '&gt;')
41+
)
42+
// turn e.g. `class:_name_` into `class:<em>name</em>`
43+
.replace(/_(.+)_/g, (_, contents) => `<em>${contents}</em>`);
44+
45+
const slug = slugify(title);
46+
47+
arr.push({ slug, title });
48+
return arr;
49+
},
50+
[] as Array<{ slug: string; title: string }>
51+
);
4552

4653
content[slug] = {
4754
slug,

0 commit comments

Comments
 (0)