diff --git a/index.js b/index.js index 37847e2..b4dc15a 100644 --- a/index.js +++ b/index.js @@ -1,33 +1,29 @@ +var fs = require('fs'); +var path = require('path'); var lunr = require('lunr'); var Entities = require('html-entities').AllHtmlEntities; var Html = new Entities(); -var searchIndex; // Called with the `this` context provided by Gitbook function getSearchIndex(context) { - if (!searchIndex) { - // Create search index - var ignoreSpecialCharacters = context.config.get('pluginsConfig.lunr.ignoreSpecialCharacters') || context.config.get('lunr.ignoreSpecialCharacters'); - searchIndex = lunr(function () { - this.ref('url'); - - this.field('title', { boost: 10 }); - this.field('keywords', { boost: 15 }); - this.field('body'); - - if (!ignoreSpecialCharacters) { - // Don't trim non words characters (to allow search such as "C++") - this.pipeline.remove(lunr.trimmer); - } - }); - } - return searchIndex; + // Create search index + var ignoreSpecialCharacters = context.config.get('pluginsConfig.lunr.ignoreSpecialCharacters') || context.config.get('lunr.ignoreSpecialCharacters'); + return lunr(function () { + this.ref('url'); + + this.field('title', { boost: 10 }); + this.field('keywords', { boost: 15 }); + this.field('body'); + + if (!ignoreSpecialCharacters) { + // Don't trim non words characters (to allow search such as "C++") + this.pipeline.remove(lunr.trimmer); + } + }); } // Map of Lunr ref to document -var documentsStore = {}; - var searchIndexEnabled = true; var indexSize = 0; @@ -78,21 +74,25 @@ module.exports = { body: text }; + var documentsStore = {}; documentsStore[doc.url] = doc; - getSearchIndex(this).add(doc); - return page; - }, + var targetFile = path.resolve(this.output.root(), 'search_index.json'); + var targetJSON = JSON.parse(fs.existsSync(targetFile) ? fs.readFileSync(targetFile, { encoding: 'utf8' }) : '{"index":{},"store":{}}'); + + var searchIndex = targetJSON.index.documentStore ? + lunr.Index.load(targetJSON.index) + : getSearchIndex(this); - // Write index to disk - 'finish': function() { - if (this.output.name != 'website') return; + searchIndex.remove(doc); + searchIndex.add(doc); - this.log.debug.ln('write search index'); - return this.output.writeFile('search_index.json', JSON.stringify({ - index: getSearchIndex(this), - store: documentsStore + this.output.writeFile('search_index.json', JSON.stringify({ + index: searchIndex, + store: Object.assign(targetJSON.store, documentsStore) })); + + return page; } } }; diff --git a/package.json b/package.json index 31a91a4..b3e89de 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { - "name": "gitbook-plugin-lunr", + "name": "@aleen42/gitbook-plugin-lunr", "description": "Index book in a lunr index accessible from the search plugin", "main": "index.js", - "version": "1.2.0", + "version": "1.0.0", "engines": { "gitbook": ">=3.0.0-pre.0" },