summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-plugin-lunr/src/index.js
blob: 1135f51b185ce9157d20de01eb10412e46c97513 (plain)
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
const GitBook = require('gitbook-core');
const reduce = require('./reducer');
const actions = require('./actions');

/**
 * Search in the local index
 * @param  {String} query
 * @return {Promise<List>}
 */
function searchHandler(query, dispatch, getState) {
    // Fetch the index if non loaded
    return dispatch(actions.fetch())

    // Execute the search
    .then(() => {
        const { idx, store } = getState().lunr;
        const results = idx.search(query);

        return results.map(({ref}) => store.get(ref).toJS());
    });
}

module.exports = GitBook.createPlugin({
    activate: (dispatch, getState, { Search }) => {
        dispatch(Search.registerHandler('lunr', searchHandler));
    },
    reduce
});