-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
51 lines (40 loc) · 1.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const urljoin = require('url-join');
const visit = require('unist-util-visit');
const Draw = require('./lib/draw');
const DEPLOY_DIR = 'public';
module.exports = ({ markdownAST, pathPrefix }, pluginOptions = {}) => {
visit(markdownAST, 'code', (node, index, parent) => {
let draw = new Draw();
let lang = node.lang || '';
if (!draw.isValidLanguage(lang)) {
return;
}
try {
if (pluginOptions.strategy === 'img') {
let svg = draw.render(lang, node.value, pluginOptions);
const hash = crypto.createHmac('sha1', 'gatsby-remark-draw').update(svg.value).digest('hex');
const fileName = `${hash}.svg`;
const fullPath = path.join(DEPLOY_DIR, fileName);
fs.writeFileSync(fullPath, svg.value);
const image = {
type: 'image',
title: 'remark-draw image',
url: urljoin('/', pathPrefix, fileName)
};
parent.children.splice(index, 1, image);
}
else {
let svg = draw.renderWrapped(lang, node.value, pluginOptions);
node.type = 'html';
node.value = svg;
}
} catch (e) {
// eslint-disable-next-line no-console
console.error(`Unhandled exception in rendering: ${e}`);
}
});
};