summaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/book.js26
-rw-r--r--lib/generators/site.js11
-rw-r--r--lib/utils/page.js17
3 files changed, 52 insertions, 2 deletions
diff --git a/lib/book.js b/lib/book.js
index 90322f2..8c9d8ae 100644
--- a/lib/book.js
+++ b/lib/book.js
@@ -1,7 +1,7 @@
var Q = require("q");
var _ = require("lodash");
var path = require("path");
-
+var lunr = require('lunr');
var parsers = require("gitbook-parsers");
var fs = require("./utils/fs");
@@ -54,6 +54,14 @@ var Book = function(root, options, parent) {
// Readme file
this.readmeFile = "README.md";
+
+ // Search Index
+ this.searchIndex = lunr(function () {
+ this.ref('url');
+
+ this.field('title', { boost: 10 });
+ this.field('body');
+ });
};
// Initialize and parse the book: config, summary, glossary
@@ -333,6 +341,10 @@ Book.prototype.parsePage = function(filename) {
});
return page;
+ })
+ .then(function(page) {
+ that.indexPage(page);
+ return page;
});
};
@@ -400,4 +412,16 @@ Book.prototype.parentRoot = function() {
return this.root;
};
+// Index a page into the search index
+Book.prototype.indexPage = function(page) {
+ var nav = this.navigation[page.path];
+ if (!nav) return;
+
+ this.searchIndex.add({
+ url: page.path,
+ title: nav.title,
+ body: pageUtil.extractText(page.sections),
+ });
+};
+
module.exports= Book;
diff --git a/lib/generators/site.js b/lib/generators/site.js
index 51a6cb3..9b7dbcb 100644
--- a/lib/generators/site.js
+++ b/lib/generators/site.js
@@ -90,6 +90,7 @@ Generator.prototype.finish = function() {
return this.copyAssets()
.then(this.copyCover)
.then(this.writeGlossary)
+ .then(this.writeSearchIndex);
};
// Normalize a link to .html and convert README -> index
@@ -148,6 +149,16 @@ Generator.prototype.writeGlossary = function() {
return this._writeTemplate(this.glossaryTemplate, {}, path.join(this.options.output, "GLOSSARY.html"));
};
+// Write the search index
+Generator.prototype.writeSearchIndex = function() {
+ var that = this;
+
+ return fs.writeFile(
+ path.join(this.options.output, "search_index.json"),
+ JSON.stringify(this.book.searchIndex)
+ );
+};
+
// Convert a page into a normalized data set
Generator.prototype.normalizePage = function(page) {
var that = this;
diff --git a/lib/utils/page.js b/lib/utils/page.js
index 0168831..525722e 100644
--- a/lib/utils/page.js
+++ b/lib/utils/page.js
@@ -139,6 +139,21 @@ function normalizePage(sections, options) {
});
};
+// Extract text from sections
+function extractText(sections) {
+ return _.reduce(sections, function(prev, section) {
+ if (section.type != "normal") return prev;
+
+ var $ = cheerio.load(section.content);
+ $("*").each(function() {
+ prev = prev+" "+$(this).text();
+ });
+
+ return prev;
+ }, "");
+};
+
module.exports = {
- normalize: normalizePage
+ normalize: normalizePage,
+ extractText: extractText
};