Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip codeblock #11

Merged
merged 1 commit into from
Dec 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 };