forked from brainhubeu/gatsby-docs-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (74 loc) · 2.35 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
/**
* Extending gatsby-transformer-remark
*/
const path = require('path');
const visit = require('unist-util-visit');
const _ = require('lodash');
const isString = value => typeof value === 'string';
/**
* Get url from menu
* @param {Array} pages
* @param {String} absolutePath
* @return {String} ..
*/
function findPageUrlByMarkdownAbsoluteFilePath(pages = [], absolutePath) {
return _.chain(pages)
.map(page =>
(page.absolutePath && page.absolutePath === absolutePath && page.url)
|| findPageUrlByMarkdownAbsoluteFilePath(page.sidemenu || page.items, absolutePath),
)
.flattenDeep()
.find(x => !!x)
.value();
}
/**
* Normalize 'code' node to allow rendering and live editing React components
* @param {Object} node
*/
function normalizeCodeNode(node) {
if (!isString(node.lang) || !node.lang.startsWith('jsx') || !node.lang.includes('render')) {
return;
}
node.type = 'html';
node.value = `
<div>
<div class="gatsby-render-code" ></div>
<div class="gatsby-render-source-code" style="display:none;">
${_.escape(node.value)}
</div>
</div>`;
}
/**
* Replace local markdown links with gatsby links
* @param {Object} node
* @param {Object} markdownNode
* @param {Array} files
* @param {Function} getNode
*/
function normalizeLinkNode(node, markdownNode, files, getNode) {
if (!node.url) {
return;
}
// absolute path to directory containg markdown file
const markdownFileDirPath = path.parse(markdownNode.fileAbsolutePath).dir;
// absolute path to file, which link point to
const targetFileAbsolutePath = path.resolve(markdownFileDirPath, node.url);
// determine if tareget file exists
const targetFileExists = !!files.find(file => file && file.absolutePath === targetFileAbsolutePath);
// get menu node
const menuNode = getNode('Menu Config >> Gatsby Docs Kit'); // TODO move it magic string to constant
if (!menuNode || !targetFileExists) {
return;
}
// get url of targeted markdown file
const pageUrl = findPageUrlByMarkdownAbsoluteFilePath(menuNode.pages, targetFileAbsolutePath);
if (!pageUrl) {
return;
}
node.url = pageUrl;
}
module.exports = ({ markdownAST, markdownNode, files, getNode }) => {
visit(markdownAST, `code`, normalizeCodeNode);
visit(markdownAST, `link`, node => normalizeLinkNode(node, markdownNode, files, getNode));
};