rust-search-extension/extension/main.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-11-03 07:45:04 +00:00
setup();
function setup() {
chrome.omnibox.setDefaultSuggestion({
2018-11-19 16:05:50 +00:00
description: "Search Rust crates for <match>%s</match>"
2018-11-03 07:45:04 +00:00
});
chrome.omnibox.onInputChanged.addListener(function(query, suggestFn) {
2018-11-19 16:05:50 +00:00
if (!query) return;
var searchResults = window.search(query);
var suggestResults = [];
for (var i = 0; i < searchResults.length; i++) {
var result = searchResults[i];
suggestResults.push(buildSuggestResultItem(result));
2018-11-19 16:05:50 +00:00
}
if (suggestResults.length === 0) {
suggestResults = [
{
content: "https://doc.rust-lang.org/stable/std/?search=" + query,
description: "Sorry, no Rust official documentation result about <match>" + query
+ "</match> found, click here to search on <dim>doc.rust-lang.org</dim>"
},
2018-11-19 16:05:50 +00:00
]
}
suggestFn(suggestResults);
2018-11-03 07:45:04 +00:00
});
chrome.omnibox.onInputEntered.addListener(function(text) {
2018-11-19 16:05:50 +00:00
if (text && text.startsWith(window.rootPath)) {
2018-11-03 07:45:04 +00:00
navigateToUrl(text);
} else {
navigateToUrl('https://crates.io/search?q=' + encodeURIComponent(text));
}
});
}
function navigateToUrl(url) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.update(tab.id, {url: url});
});
2018-11-19 16:05:50 +00:00
}
// Escape the five predefined entities to display them as text.
function escape(text) {
text = text || "";
return text
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function buildSuggestResultItem(item) {
var description = item.displayPath + "<match>" + item.name + "</match>";
if (item.desc) {
description += " <dim>" + escape(item.desc) + "</dim>";
}
return {
content: item.href,
description: description,
2018-11-19 16:05:50 +00:00
}
}