redoc/src/services/SearchWorker.worker.ts

97 lines
2.0 KiB
TypeScript
Raw Normal View History

2018-02-08 19:41:02 +03:00
import * as lunr from 'lunr';
try {
2018-06-25 13:59:11 +03:00
// tslint:disable-next-line
2019-08-01 10:34:53 +03:00
require('core-js/es/promise'); // bundle into worker
} catch (_) {
// nope
}
2018-02-08 19:41:02 +03:00
/* just for better typings */
export default class Worker {
2018-05-18 15:13:46 +03:00
add: typeof add = add;
2018-02-08 19:41:02 +03:00
done = done;
2018-05-18 15:13:46 +03:00
search: typeof search = search;
2018-03-06 14:10:08 +03:00
toJS = toJS;
load = load;
2018-02-08 19:41:02 +03:00
}
export interface SearchDocument {
title: string;
description: string;
id: string;
}
2018-05-18 15:13:46 +03:00
export interface SearchResult<T = string> {
meta: T;
2018-02-22 19:48:50 +03:00
score: number;
}
2018-05-18 15:13:46 +03:00
let store: any[] = [];
2018-02-08 19:41:02 +03:00
let resolveIndex: (v: lunr.Index) => void = () => {
throw new Error('Should not be called');
};
2018-02-08 19:41:02 +03:00
const index: Promise<lunr.Index> = new Promise(resolve => {
resolveIndex = resolve;
});
2018-05-18 15:13:46 +03:00
lunr.tokenizer.separator = /\s+/;
2018-02-08 19:41:02 +03:00
const builder = new lunr.Builder();
builder.field('title');
builder.field('description');
2018-05-18 15:13:46 +03:00
builder.ref('ref');
2018-02-08 19:41:02 +03:00
builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);
const expandTerm = term => '*' + lunr.stemmer(new lunr.Token(term, {})) + '*';
2018-05-18 15:13:46 +03:00
export function add<T>(title: string, description: string, meta?: T) {
const ref = store.push(meta) - 1;
const item = { title: title.toLowerCase(), description: description.toLowerCase(), ref };
2018-02-08 19:41:02 +03:00
builder.add(item);
}
export async function done() {
resolveIndex(builder.build());
}
2018-03-06 14:10:08 +03:00
export async function toJS() {
return {
2018-03-06 14:12:49 +03:00
store,
2018-03-06 14:10:08 +03:00
index: (await index).toJSON(),
};
}
export async function load(state: any) {
store = state.store;
resolveIndex(lunr.Index.load(state.index));
}
2018-05-18 15:13:46 +03:00
export async function search<Meta = string>(
q: string,
limit = 0,
): Promise<Array<SearchResult<Meta>>> {
2018-02-08 19:41:02 +03:00
if (q.trim().length === 0) {
return [];
}
2018-05-18 15:13:46 +03:00
let searchResults = (await index).query(t => {
q.trim()
2018-05-18 15:13:46 +03:00
.toLowerCase()
.split(/\s+/)
.forEach(term => {
const exp = expandTerm(term);
t.term(exp, {});
});
});
if (limit > 0) {
searchResults = searchResults.slice(0, limit);
}
return searchResults.map(res => ({ meta: store[res.ref], score: res.score }));
2018-02-08 19:41:02 +03:00
}