-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
61 lines (57 loc) · 1.8 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
var fs = require('fs');
var Q = require('q');
var lexicon, lexIndex;
var config = {
"localCopy": "lexicon.json"
};
function scanner(lexicon) {
return new RegExp('(' + lexicon.map(function (t) { return t["title"] }).sort(function (a, b) { return b.length - a.length; }).join('|') + ')', "g");
};
function rewriter(lexicon) {
return function (match, p1) {
return '<span class="hint" data-hint="' + lexIndex[p1]["definition"].trim() + '">' + p1 + '</span>';
};
};
function loadLexicon(localCopy, d) {
fs.readFile(localCopy, {encoding: 'utf-8'}, function (err, content) {
if (content === undefined) {
d.resolve();
return;
}
lexicon = JSON.parse(content);
lexIndex = {};
lexicon.forEach(function (t) {
lexIndex[t["title"]] = t;
});
d.resolve();
});
};
module.exports = {
book: {
"assets": "./book",
"css": ["lexicon.css"]
},
hooks: {
"init": function (done) {
var userConfig = this.options.pluginsConfig.lexicon;
for (c in userConfig) {
config[c] = userConfig[c];
}
var d = Q.defer();
loadLexicon(config["localCopy"], d);
return d.promise;
},
"page": function(page) {
if (lexicon === undefined) {
return page;
}
page.content = page.content.replace(/<section[\s\S]*?>([\s\S]*?)<\/section>/g, function (match, section) {
return section.replace(scanner(lexicon), rewriter(lexicon));
});
if (this.options.pluginsConfig.json) {
page.sections[0].content = page.sections[0].content.replace(scanner(lexicon), rewriter(lexicon));
}
return page;
}
}
};