From 4e659aee08b37502e93e6314e58bdac9dd8d3295 Mon Sep 17 00:00:00 2001 From: Rikson Date: Wed, 16 Dec 2020 14:32:37 +0900 Subject: [PATCH] Skip codeblock To avoid etracting headings from codeblock. --- src/__tests__/utils.test.ts | 38 ++++++++++++++++++++++++++++++++++++- src/index.tsx | 4 ++-- src/utils.ts | 9 ++++++++- 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/__tests__/utils.test.ts b/src/__tests__/utils.test.ts index ed90b2b..9b235a3 100644 --- a/src/__tests__/utils.test.ts +++ b/src/__tests__/utils.test.ts @@ -1,4 +1,4 @@ -import { createLink, createTitle, extractHeadingsFromMd } from "../utils"; +import { createLink, createTitle, extractHeadingsFromMd, removeCodeBlockFromMd } from "../utils"; describe("createLink", () => { it("removes # and connects each word with '-'.", () => { @@ -61,3 +61,39 @@ describe("extractHeadingsFromMd", () => { ]); }); }); + +describe("removeCodeBlockFromMd", () => { + const markdownText = ` +# Heading1 + This is the first paragraph. +## Heading2 + This is the second paragraph. +\`\`\` +### This is typical codeblock +\`\`\` +Text between codeblock +\`\`\`\` +\`\`\` +### Escaped codeblock +\`\`\` +\`\`\`\` +Text between codeblock +~~~ +\`\`\` +### Escaped codeblock +\`\`\` +~~~ + `; + + it("It removes codeblock from the given markdownText.", () => { + expect(removeCodeBlockFromMd(markdownText)).toEqual(` +# Heading1 + This is the first paragraph. +## Heading2 + This is the second paragraph. +Text between codeblock +Text between codeblock + ` + ); + }); +}); diff --git a/src/index.tsx b/src/index.tsx index d9a8cf8..2aa9c07 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import styles from "./styles.module.css"; -import { extractHeadingsFromMd } from "./utils"; +import { extractHeadingsFromMd, removeCodeBlockFromMd } from "./utils"; import Heading, { newHeading } from "./Heading"; interface Props { @@ -59,7 +59,7 @@ const Toc = ({ // Mutate headings const matchedHeadings: RegExpMatchArray | null = extractHeadingsFromMd( - markdownText, + removeCodeBlockFromMd(markdownText), headingLevels[0], headingLevels[1] ); diff --git a/src/utils.ts b/src/utils.ts index 92a3546..15172df 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -35,4 +35,11 @@ const extractHeadingsFromMd = ( return markdownText.match(headingRegex); }; -export { createLink, createTitle, extractHeadingsFromMd }; +const removeCodeBlockFromMd = ( + markdownText: string +): string => { + const codeBlockRegex = new RegExp('((````.+?````)|(```.+?```)|(~~~.+?~~~))\n', 'gms'); + return markdownText.replace(codeBlockRegex, ''); +}; + +export { createLink, createTitle, extractHeadingsFromMd, removeCodeBlockFromMd };