1
0
mirror of https://github.com/kkapsner/CanvasBlocker synced 2024-11-01 02:48:44 +01:00
CanvasBlocker/lib/search.js

75 lines
1.8 KiB
JavaScript
Raw Normal View History

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function(){
"use strict";
2019-11-28 01:26:35 +01:00
let scope;
if ((typeof exports) !== "undefined"){
scope = exports;
}
else {
2019-03-12 22:24:23 +01:00
scope = require.register("./search", {});
}
2019-04-09 08:29:52 +02:00
const extension = require("./extension");
const texts = [];
scope.register = function(text, content){
texts.push({text: text.toLowerCase(), content});
};
scope.search = function(search){
const resultSets = search.toLowerCase().split(/\s+/).filter(function(term){
return term.trim();
}).map(function(term){
return new RegExp(term);
}).map(function(term){
const matching = new Set();
texts.forEach(function(text){
if (term.test(text.text)){
matching.add(text.content);
}
});
return matching;
});
if (resultSets.length){
return Array.from(
resultSets.reduce(function(previousSet, set){
2019-11-28 01:26:35 +01:00
const andSet = new Set();
set.forEach(function(entry){
if (previousSet.has(entry)){
andSet.add(entry);
}
});
return andSet;
})
);
}
else {
return [];
}
};
const searchListeners = [];
scope.init = function(){
const node = document.createElement("input");
node.id = "search";
2019-04-09 08:29:52 +02:00
node.placeholder = extension.getTranslation("search");
window.setTimeout(() => node.focus(), 1);
let lastResults = [];
node.addEventListener("input", function(){
this.search();
});
node.search = function(){
const search = this.value;
const results = search? scope.search(search): [];
searchListeners.forEach(function(callback){
callback({search, results, lastResults});
});
lastResults = results;
};
return node;
};
scope.on = function(callback){
searchListeners.push(callback);
};
}());