forked from MarkBind/markbind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeProcessor.js
365 lines (323 loc) · 11.9 KB
/
NodeProcessor.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
const path = require('path');
const cheerio = require('cheerio');
const htmlparser = require('htmlparser2'); require('../patches/htmlparser2');
const fm = require('fastmatter');
const Promise = require('bluebird');
const _ = {};
_.isArray = require('lodash/isArray');
_.cloneDeep = require('lodash/cloneDeep');
_.has = require('lodash/has');
_.find = require('lodash/find');
const { PageNavProcessor, renderSiteNav, addSitePageNavPortal } = require('./siteAndPageNavProcessor');
const { processInclude, processPanelSrc, processPopoverSrc } = require('./includePanelProcessor');
const { Context } = require('./Context');
const linkProcessor = require('./linkProcessor');
const { highlightCodeBlock, setCodeLineNumbers } = require('./codeblockProcessor');
const { setHeadingId, assignPanelId } = require('./headerProcessor');
const { MarkdownProcessor } = require('./MarkdownProcessor');
const { FootnoteProcessor } = require('./FootnoteProcessor');
const { MdAttributeRenderer } = require('./MdAttributeRenderer');
const { shiftSlotNodeDeeper, transformOldSlotSyntax, renameSlot } = require('./vueSlotSyntaxProcessor');
const { warnConflictingAtributesMap, warnDeprecatedAtributesMap } = require('./warnings');
const { processScriptAndStyleTag } = require('./scriptAndStyleTagProcessor');
const { createErrorNode } = require('./elements');
const fsUtil = require('../utils/fsUtil');
const logger = require('../utils/logger');
const { FRONT_MATTER_FENCE } = require('../Page/constants');
const {
ATTRIB_CWF,
} = require('../constants');
cheerio.prototype.options.decodeEntities = false; // Don't escape HTML entities
class NodeProcessor {
constructor(config, pageSources, variableProcessor, pluginManager,
siteLinkManager, userScriptsAndStyles, docId = '') {
this.config = config;
this.frontMatter = {};
this.headTop = [];
this.headBottom = [];
this.scriptBottom = [];
this.userScriptsAndStyles = userScriptsAndStyles;
this.pageSources = pageSources;
this.variableProcessor = variableProcessor;
this.pluginManager = pluginManager;
this.siteLinkManager = siteLinkManager;
this.markdownProcessor = new MarkdownProcessor(docId);
this.footnoteProcessor = new FootnoteProcessor();
this.mdAttributeRenderer = new MdAttributeRenderer(this.markdownProcessor);
this.pageNavProcessor = new PageNavProcessor();
}
/*
* Private utility functions
*/
static _trimNodes(node) {
if (node.name === 'pre' || node.name === 'code') {
return;
}
if (node.children) {
for (let n = 0; n < node.children.length; n += 1) {
const child = node.children[n];
if (child.type === 'comment'
|| (child.type === 'text' && n === node.children.length - 1 && !/\S/.test(child.data))) {
node.children.splice(n, 1);
n -= 1;
} else if (child.type === 'tag') {
NodeProcessor._trimNodes(child);
}
}
}
}
static _isText(node) {
return node.type === 'text' || node.type === 'comment';
}
/*
* FrontMatter collection
*/
_processFrontMatter(node, context) {
let currentFrontMatter = {};
const frontMatter = cheerio(node);
if (!context.processingOptions.omitFrontmatter && frontMatter.text().trim()) {
// Retrieves the front matter from either the first frontmatter element
// or from a frontmatter element that includes from another file
// The latter case will result in the data being wrapped in a div
const frontMatterData = frontMatter.find('div').length
? frontMatter.find('div')[0].children[0].data
: frontMatter[0].children[0].data;
const frontMatterWrapped = `${FRONT_MATTER_FENCE}\n${frontMatterData}\n${FRONT_MATTER_FENCE}`;
currentFrontMatter = fm(frontMatterWrapped).attributes;
}
this.frontMatter = {
...this.frontMatter,
...currentFrontMatter,
};
cheerio(node).remove();
}
/*
* Layout element collection
*/
_collectLayoutEl(node, property) {
const $ = cheerio(node);
this[property].push($.html());
$.remove();
}
/*
* API
*/
processNode(node, context) {
try {
transformOldSlotSyntax(node);
shiftSlotNodeDeeper(node);
// log warnings for deprecated and conflicting attributes
if (_.has(warnDeprecatedAtributesMap, node.name)) { warnDeprecatedAtributesMap[node.name](node); }
if (_.has(warnConflictingAtributesMap, node.name)) { warnConflictingAtributesMap[node.name](node); }
switch (node.name) {
case 'frontmatter':
this._processFrontMatter(node, context);
break;
case 'body':
console.warn(`<body> tag found in ${node.attribs[ATTRIB_CWF]}. This may cause formatting errors.`);
break;
case 'include':
this.markdownProcessor.docId += 1; // used in markdown-it-footnotes
return processInclude(node, context, this.pageSources, this.variableProcessor,
text => this.markdownProcessor.renderMd(text),
text => this.markdownProcessor.renderMdInline(text),
this.config);
case 'panel':
this.mdAttributeRenderer.processPanelAttributes(node);
return processPanelSrc(node, context, this.pageSources, this.config);
case 'question':
this.mdAttributeRenderer.processQuestion(node);
break;
case 'q-option':
this.mdAttributeRenderer.processQOption(node);
break;
case 'quiz':
this.mdAttributeRenderer.processQuiz(node);
break;
case 'popover':
this.mdAttributeRenderer.processPopoverAttributes(node);
return processPopoverSrc(node, context, this.pageSources, this.variableProcessor,
text => this.markdownProcessor.renderMd(text), this.config);
case 'tooltip':
this.mdAttributeRenderer.processTooltip(node);
break;
case 'modal':
// Transform deprecated slot names; remove when deprecating
renameSlot(node, 'modal-header', 'header');
renameSlot(node, 'modal-footer', 'footer');
this.mdAttributeRenderer.processModalAttributes(node);
break;
case 'tab':
case 'tab-group':
this.mdAttributeRenderer.processTabAttributes(node);
break;
case 'box':
this.mdAttributeRenderer.processBoxAttributes(node);
break;
case 'dropdown':
this.mdAttributeRenderer.processDropdownAttributes(node);
break;
case 'thumbnail':
this.mdAttributeRenderer.processThumbnailAttributes(node);
break;
case 'page-nav':
this.pageNavProcessor.renderPageNav(node);
break;
case 'site-nav':
renderSiteNav(node);
break;
case 'mb-temp-footnotes':
this.footnoteProcessor.processMbTempFootnotes(node);
break;
case 'script':
case 'style':
processScriptAndStyleTag(node, this.userScriptsAndStyles);
break;
case 'code':
setCodeLineNumbers(node, this.config.codeLineNumbers);
// fall through
case 'annotation': // Annotations are added automatically by KaTeX when rendering math formulae.
case 'eq': // markdown-it-texmath html tag
case 'eqn': // markdown-it-texmath html tag
case 'thumb': // image
/*
* These are not components from MarkBind Vue components.
* We have to add 'v-pre' to let Vue know to ignore this tag and not compile it.
*
* Although there won't be warnings if we use production Vue, it is still good to add this.
*/
if (!_.has(node.attribs, 'v-pre')) { node.attribs['v-pre'] = ''; }
break;
default:
break;
}
} catch (error) {
logger.error(error);
}
return context;
}
postProcessNode(node) {
try {
switch (node.name) {
case 'pre':
highlightCodeBlock(node);
break;
case 'panel':
assignPanelId(node);
break;
case 'head-top':
this._collectLayoutEl(node, 'headTop');
break;
case 'head-bottom':
this._collectLayoutEl(node, 'headBottom');
break;
case 'script-bottom':
this._collectLayoutEl(node, 'scriptBottom');
break;
default:
break;
}
} catch (error) {
logger.error(error);
}
if (node.attribs) {
delete node.attribs[ATTRIB_CWF];
}
}
_process(node, context) {
if (_.isArray(node)) {
return node.map(el => this._process(el, context));
}
if (NodeProcessor._isText(node)) {
return node;
}
if (node.name) {
node.name = node.name.toLowerCase();
}
if (linkProcessor.hasTagLink(node)) {
linkProcessor.convertRelativeLinks(node, context.cwf, this.config.rootPath, this.config.baseUrl);
linkProcessor.convertMdExtToHtmlExt(node);
if (this.config.intrasiteLinkValidation.enabled) {
this.siteLinkManager.collectIntraLinkToValidate(node, context.cwf);
}
linkProcessor.collectSource(node, this.config.rootPath, this.config.baseUrl, this.pageSources);
}
switch (node.name) {
case 'md':
node.name = 'span';
node.children = cheerio.parseHTML(
this.markdownProcessor.renderMdInline(cheerio.html(node.children)), true);
break;
case 'markdown':
node.name = 'div';
node.children = cheerio.parseHTML(
this.markdownProcessor.renderMd(cheerio.html(node.children)), true);
break;
default:
break;
}
// eslint-disable-next-line no-param-reassign
context = this.processNode(node, context);
this.pluginManager.processNode(node, this.config);
if (node.children) {
node.children.forEach((child) => {
this._process(child, context);
});
}
this.postProcessNode(node);
addSitePageNavPortal(node);
const isHeadingTag = (/^h[1-6]$/).test(node.name);
if (isHeadingTag && !node.attribs.id) {
setHeadingId(node, this.config);
}
// If a sticky header is applied to the page, generate dummy spans as anchor points
if (isHeadingTag && node.attribs.id) {
cheerio(node).prepend(`<span id="${node.attribs.id}" class="anchor"></span>`);
}
this.pluginManager.postProcessNode(node, this.config);
return node;
}
process(file, content, cwf = file, extraVariables = {}) {
const context = new Context(cwf, [], extraVariables, {});
return new Promise((resolve, reject) => {
const handler = new htmlparser.DomHandler((error, dom) => {
if (error) {
reject(error);
return;
}
const mainHtmlNodes = dom.map((d) => {
let processed;
try {
processed = this._process(d, context);
} catch (err) {
err.message += `\nError while rendering '${file}'`;
logger.error(err);
processed = createErrorNode(d, err);
}
return processed;
});
mainHtmlNodes.forEach(d => NodeProcessor._trimNodes(d));
const footnotesHtml = this.footnoteProcessor.combineFootnotes(node => this.processNode(node));
const mainHtml = cheerio(mainHtmlNodes).html();
const mainHtmlWithUniqPageNavUuid = this.pageNavProcessor.finalizePageNavUuid(
mainHtml, mainHtmlNodes, footnotesHtml);
resolve(mainHtmlWithUniqPageNavUuid + footnotesHtml);
});
const parser = new htmlparser.Parser(handler);
const fileExt = path.extname(file);
if (fsUtil.isMarkdownFileExt(fileExt)) {
const renderedContent = this.markdownProcessor.renderMd(content);
// Wrap with <root> as $.remove() does not work on top level nodes
parser.parseComplete(`<root>${renderedContent}</root>`);
} else if (fileExt === '.html') {
parser.parseComplete(`<root>${content}</root>`);
} else {
const error = new Error(`Unsupported File Extension: '${fileExt}'`);
reject(error);
}
});
}
}
module.exports = {
NodeProcessor,
};