Welcome to mirror list, hosted at ThFree Co, Russian Federation.

search-lunr.js « controllers « js « assets - github.com/bep/docuapi.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 175770b731ba5fe166a234065a2e740726e22518 (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
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import * as lunr from 'js/lib/lunr.js';
import { Highlight } from 'js/helpers';

function nextUntil(elem, selector) {
	var siblings = [];

	elem = elem.nextElementSibling;

	while (elem) {
		if (elem.matches(selector)) break;
		siblings.push(elem);
		elem = elem.nextElementSibling;
	}

	return siblings;
}

export function newSearchController() {
	var index;

	var buildIndex = function (config) {
		var builder = new lunr.Builder();

		builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);

		builder.searchPipeline.add(lunr.stemmer);

		config.call(builder, builder);
		return builder.build();
	};

	function populateIndex() {
		index = buildIndex(function () {
			this.ref('id');
			this.field('title', { boost: 10 });
			this.field('body');
			this.pipeline.add(lunr.trimmer, lunr.stopWordFilter);

			document.querySelectorAll('h1, h2').forEach((headerEl) => {
				let body = '';
				nextUntil(headerEl, 'h1, h2').forEach((el) => {
					body = body.concat(' ', el.textContent);
				});
				this.add({
					id: headerEl.id,
					title: headerEl.textContent,
					body: body,
				});
			});
		});
	}

	let highlight = new Highlight();

	return {
		query: '',
		results: [],
		init: function () {
			return this.$nextTick(() => {
				populateIndex();
				this.$watch('query', () => {
					this.search();
				});
			});
		},
		search: function () {
			highlight.remove();
			let results = index.search(this.query).filter((item) => item.score > 0.0001);

			this.results = results.map((item) => {
				var elem = document.getElementById(item.ref);

				return {
					title: elem.innerText,
				};
			});

			if (this.results.length > 0) {
				highlight.apply(new RegExp(this.query, 'i'));
			}
		},
	};
}