debian-mirror-gitlab/app/assets/javascripts/lib/gfm/index.js

62 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-06-21 17:19:12 +05:30
import { unified } from 'unified';
import remarkParse from 'remark-parse';
2022-07-23 23:45:48 +05:30
import remarkGfm from 'remark-gfm';
import remarkRehype, { all } from 'remark-rehype';
2022-06-21 17:19:12 +05:30
import rehypeRaw from 'rehype-raw';
const createParser = () => {
2022-07-23 23:45:48 +05:30
return unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype, {
allowDangerousHtml: true,
handlers: {
footnoteReference: (h, node) =>
h(
node.position,
'footnoteReference',
{ identifier: node.identifier, label: node.label },
[],
),
footnoteDefinition: (h, node) =>
h(
node.position,
'footnoteDefinition',
{ identifier: node.identifier, label: node.label },
all(h, node),
),
},
})
.use(rehypeRaw);
2022-06-21 17:19:12 +05:30
};
const compilerFactory = (renderer) =>
function compiler() {
Object.assign(this, {
Compiler(tree) {
return renderer(tree);
},
});
};
/**
* Parses a Markdown string and provides the result Abstract
* Syntax Tree (AST) to a renderer function to convert the
* tree in any desired representation
*
* @param {String} params.markdown Markdown to parse
* @param {(tree: MDast -> any)} params.renderer A function that accepts mdast
* AST tree and returns an object of any type that represents the result of
* rendering the tree. See the references below to for more information
* about MDast.
*
* MDastTree documentation https://github.com/syntax-tree/mdast
* @returns {Promise<any>} Returns a promise with the result of rendering
* the MDast tree
*/
export const render = async ({ markdown, renderer }) => {
2022-07-16 23:28:13 +05:30
const { result } = await createParser().use(compilerFactory(renderer)).process(markdown);
2022-06-21 17:19:12 +05:30
2022-07-16 23:28:13 +05:30
return result;
2022-06-21 17:19:12 +05:30
};