2019-01-22 16:09:38 +03:00
|
|
|
import markdownit from 'markdown-it';
|
|
|
|
import markdownitFootnote from 'markdown-it-footnote';
|
|
|
|
import markdownitLazyHeaders from 'markdown-it-lazy-headers';
|
|
|
|
import markdownitMark from 'markdown-it-mark';
|
2018-08-09 16:59:03 +03:00
|
|
|
import {sanitizeHtml} from 'koenig-editor/helpers/sanitize-html';
|
2017-09-11 06:39:22 +03:00
|
|
|
|
|
|
|
let slugify = function slugify(inputString, usedHeaders) {
|
|
|
|
let slug = inputString.replace(/[^\w]/g, '').toLowerCase();
|
|
|
|
if (usedHeaders[slug]) {
|
2018-01-05 18:38:23 +03:00
|
|
|
usedHeaders[slug] += 1;
|
2017-09-11 06:39:22 +03:00
|
|
|
slug += usedHeaders[slug];
|
|
|
|
}
|
|
|
|
return slug;
|
|
|
|
};
|
|
|
|
|
|
|
|
// originally from https://github.com/leff/markdown-it-named-headers
|
|
|
|
// moved here to avoid pulling in http://stringjs.com dependency
|
|
|
|
let markdownitNamedHeaders = function markdownitNamedHeaders(md) {
|
|
|
|
let originalHeadingOpen = md.renderer.rules.heading_open;
|
|
|
|
|
|
|
|
// eslint-disable-next-line camelcase
|
|
|
|
md.renderer.rules.heading_open = function (tokens, idx, options, env, self) {
|
|
|
|
let usedHeaders = {};
|
|
|
|
|
|
|
|
tokens[idx].attrs = tokens[idx].attrs || [];
|
|
|
|
|
|
|
|
let title = tokens[idx + 1].children.reduce(function (acc, t) {
|
|
|
|
return acc + t.content;
|
|
|
|
}, '');
|
|
|
|
|
|
|
|
let slug = slugify(title, usedHeaders);
|
|
|
|
tokens[idx].attrs.push(['id', slug]);
|
|
|
|
|
|
|
|
if (originalHeadingOpen) {
|
|
|
|
return originalHeadingOpen.apply(this, arguments);
|
|
|
|
} else {
|
|
|
|
return self.renderToken(...arguments);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|
2017-05-15 19:51:19 +03:00
|
|
|
|
|
|
|
let md = markdownit({
|
|
|
|
html: true,
|
|
|
|
breaks: true,
|
|
|
|
linkify: true
|
|
|
|
})
|
2017-09-11 10:56:11 +03:00
|
|
|
.use(markdownitFootnote)
|
|
|
|
.use(markdownitLazyHeaders)
|
|
|
|
.use(markdownitMark)
|
|
|
|
.use(markdownitNamedHeaders);
|
2017-05-15 19:51:19 +03:00
|
|
|
|
2017-10-03 13:14:40 +03:00
|
|
|
// configure linkify-it
|
|
|
|
md.linkify.set({
|
|
|
|
fuzzyLink: false
|
|
|
|
});
|
|
|
|
|
2017-05-30 16:07:12 +03:00
|
|
|
export default function formatMarkdown(_markdown, replaceJS = true) {
|
2017-05-15 19:51:19 +03:00
|
|
|
let markdown = _markdown || '';
|
|
|
|
let escapedhtml = '';
|
|
|
|
|
|
|
|
// convert markdown to HTML
|
|
|
|
escapedhtml = md.render(markdown);
|
|
|
|
|
2018-08-09 16:59:03 +03:00
|
|
|
return sanitizeHtml(escapedhtml, {replaceJS});
|
2017-05-15 19:51:19 +03:00
|
|
|
}
|