Skip to content

Commit

Permalink
feat: add slugify option, improve example in README, add correspond…
Browse files Browse the repository at this point in the history
…ing test
  • Loading branch information
medfreeman committed Dec 23, 2018
1 parent 72501d0 commit a085aaf
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,9 +194,9 @@ documents on the same page.
Allows you to customize the slug function that create ids from string.

Ex:
```jsx
```js
// ...
slugify : string => `/some/prefix/${uslug(string).replace(/\//g, '_')}`
slugify : string => `/some/prefix/${string.replace(/(\/| |')/g, "_")}`
// ...
```

Expand Down
14 changes: 14 additions & 0 deletions src/__tests__/anchor.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,18 @@ test("markdown-it-toc-and-anchor anchor", t => {
"should handle not including default class" +
" in anchors when setting anchorClassName to null"
);

t.is(
mdIt(
`@[toc]
# test me i'm famous`,
{
slugify: string => `/some/prefix/${string.replace(/(\/| |')/g, "_")}`
}
),
`<p></p>
<h1 id="/some/prefix/test_me_i_m_famous">test me i'm famous</h1>
`,
"should support custom slugify function from readme"
);
});
12 changes: 8 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ let tocHtml = "";

const repeat = (string, num) => new Array(num + 1).join(string);

const makeSafe = (string, headingIds) => {
const key = uslug(string); // slugify
const makeSafe = (string, headingIds, slugifyFn) => {
const key = slugifyFn(string); // slugify
if (!headingIds[key]) {
headingIds[key] = 0;
}
Expand Down Expand Up @@ -167,6 +167,9 @@ export default function(md, options) {
let tocMarkdown = "";
let tocTokens = [];

const slugifyFn =
(typeof options.slugify === "function" && options.slugify) || uslug;

for (let i = 0; i < tokens.length; i++) {
if (tokens[i].type !== "heading_close") {
continue;
Expand All @@ -185,12 +188,13 @@ export default function(md, options) {
// headings that contain links have to be processed
// differently since nested links aren't allowed in markdown
content = heading.children[1].content;
heading._tocAnchor = makeSafe(content, headingIds);
heading._tocAnchor = makeSafe(content, headingIds, slugifyFn);
} else {
content = heading.content;
heading._tocAnchor = makeSafe(
heading.children.reduce((acc, t) => acc + t.content, ""),
headingIds
headingIds,
slugifyFn
);
}

Expand Down

0 comments on commit a085aaf

Please sign in to comment.