-
Notifications
You must be signed in to change notification settings - Fork 58
/
nunjucks-helpers.js
72 lines (58 loc) · 1.96 KB
/
nunjucks-helpers.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
const cheerio = require('cheerio');
const nunjucksIncludeData = require('nunjucks-includeData');
const marky = require('marky-markdown');
const nunjucksMarkdown = require('nunjucks-markdown');
const stripEverythingBeforeH2Element = true;
const cleanSlug = slug => slug.replace('setup-instructions', 'setup');
module.exports = function (nunjucksEnv) {
nunjucksIncludeData.install(nunjucksEnv);
nunjucksMarkdown.register(nunjucksEnv, str => {
let dirty = marky(str, {
headingSvgClass: [],
prefixHeadingIds: false,
enableHeadingLinkIcons: false
});
// Remove everything before the first `<h2>` element.
if (stripEverythingBeforeH2Element) {
dirty = dirty.substring(dirty.indexOf('<h2'));
}
const $ = cheerio.load(dirty);
$('ol, ul').each((idx, list) => {
const $list = $(list);
$list.addClass('bullets-light');
$list.html($list.html().replace(/<li>/gi, '<li><span>').replace(/<\/li>/gi, '</span></li>'));
});
let html = '';
let sections = [];
$('h2 > a').each((idx, a) => {
const $a = $(a);
const id = cleanSlug($a.attr('id'));
const href = cleanSlug($a.attr('href'));
$a.attr('id', id);
$a.attr('href', href);
const $h2 = $a.parent();
const headingText = $h2.text();
$a.text(headingText);
$h2.html($a);
if (!html) {
const bodyHtml = $('body').html();
html = bodyHtml.substring(0, bodyHtml.indexOf('<h2'));
}
let sectionHtml = `<section data-section="${id}" id="${id}" class="section">\n`;
sectionHtml += `${$.html($h2)}\n`;
$h2.nextUntil('h2').each((idx, sibling) => {
const $sibling = $(sibling);
sectionHtml += $.html($sibling) + '\n';
$sibling.remove();
});
sectionHtml += '</section>\n';
sections.push(sectionHtml);
});
if (sections.length) {
html += sections.join('\n\n');
} else {
html = $('body').html();
}
return html;
});
};