-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.js
More file actions
63 lines (51 loc) · 1.66 KB
/
text.js
File metadata and controls
63 lines (51 loc) · 1.66 KB
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
'use strict'
function nodeToText(node, opts = {headingCallback: null}) {
if (typeof node === 'string') {
return node;
}
if (typeof node !== 'object') {
console.error(node);
throw new Error('Expected object');
}
if (node.constructor === Array) {
return node.map(item => nodeToText(item, opts)).join('');
} else if ('items' in node) {
return node.items.map(item => nodeToText(item, opts) + '\n').join('');
} else if ('content' in node) {
if (node.type === 'comment') {
return '';
}
const text = nodeToText(node.content, opts);
switch (node.type) {
case 'heading':
return (opts.headingCallback ? opts.headingCallback(text) : text) + '\n\n';
case 'table-row':
return text + '\n';
case 'table-cell':
return text + '\t';
default:
return text;
}
} else if (node.type === 'template') {
if (['zh', 'lang-zh'].includes(node.name)) {
const content = node.parameters.c || node.parameters.t || node.parameters.s || node.parameters.p;
if (content) {
return nodeToText(content, opts);
}
} else if (node.name.match(/^(lang|ipac?)-[a-z]{2}|iast|korean|ipa$/)) {
return (node.positionalParameters[0] || []).map(item => nodeToText(item, opts)).join('');
} else if (['bibleverse'].includes(node.name)) {
return node.positionalParameters.map(item => nodeToText(item, opts)).join(' ');
} else if (['audio', 'audio-nohelp', 'lang'].includes(node.name) && node.positionalParameters.length >= 2) {
return nodeToText(node.positionalParameters[1], opts);
}
}
return '';
}
function astToText(ast, ...rest) {
return nodeToText(ast, ...rest).replace(/\n\s+\n/g, '\n\n');
}
module.exports = {
nodeToText,
astToText,
};