-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
hbs-content-filter.js
68 lines (55 loc) · 1.56 KB
/
hbs-content-filter.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
'use strict';
const Filter = require('broccoli-filter');
const syntax = require('@glimmer/syntax');
module.exports = class HBSContentFilter extends Filter {
constructor(input) {
super(input);
this.extensions = ['hbs'];
this.targetExtension = 'template-contents';
}
processString(content) {
let parents = new Map();
let title = { level: Infinity, node: null, contents: null };
let body = [];
syntax.traverse(syntax.preprocess(content), {
Program(node) {
addContentNodes(parents, node, node.body);
},
ElementNode(node) {
addContentNodes(parents, node, node.children);
},
TextNode(node) {
let parent = parents.get(node);
if (!parent) { return; }
body.push(node.chars);
if (title.node === parent) {
title.contents.push(node.chars);
} else if (isHeading(parent) && headingLevel(parent) < title.level) {
title = {
level: headingLevel(parent),
node: parent,
contents: [node.chars]
};
}
}
});
let output = {
title: title.contents ? title.contents.join('') : null,
body: body.join('')
};
return JSON.stringify(output);
}
}
function isHeading(node) {
return node.type === 'ElementNode' && /^h\d$/.test(node.tag);
}
function headingLevel(node) {
return Number(node.tag[1]);
}
function addContentNodes(parents, parent, candidates) {
for (let candidate of candidates) {
if (candidate.type === 'TextNode') {
parents.set(candidate, parent);
}
}
}