Skip to content

Commit

Permalink
Merge pull request #11 from rikuson/skip-codeblock
Browse files Browse the repository at this point in the history
Skip codeblock
  • Loading branch information
K-Sato1995 authored Dec 17, 2020
2 parents c9f9ccb + 4e659ae commit b782db9
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
38 changes: 37 additions & 1 deletion src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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 '-'.", () => {
Expand Down Expand Up @@ -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
`
);
});
});
4 changes: 2 additions & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -59,7 +59,7 @@ const Toc = ({

// Mutate headings
const matchedHeadings: RegExpMatchArray | null = extractHeadingsFromMd(
markdownText,
removeCodeBlockFromMd(markdownText),
headingLevels[0],
headingLevels[1]
);
Expand Down
9 changes: 8 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

0 comments on commit b782db9

Please sign in to comment.