Load latest crates index if available on popup page

This commit is contained in:
Folyd 2019-12-11 12:17:36 +08:00
parent 2214017845
commit 92151225d8
3 changed files with 46 additions and 6 deletions

View file

@ -64,19 +64,23 @@ function cleanMinifiedDescription(rawDescription) {
.replace("$c", "crate")
}
function CrateSearch(crateIndex) {
this.crateIndexVersion = CrateSearch.latestIndexVersion() || 1;
function CrateSearch(crateIndex, crateIndexVersion = 1) {
this.crateIndexVersion = crateIndexVersion;
this.crateIndex = crateIndex;
this.crateIds = Object.keys(crateIndex).sort();
}
CrateSearch.latestIndexVersion = function() {
return parseInt(localStorage.getItem("crate-index-version"));
CrateSearch.getLatestIndexVersion = function() {
return parseInt(localStorage.getItem("crate-index-version") || 1);
};
CrateSearch.getLatestCrateIndex = function() {
return JSON.parse(localStorage.getItem("crate-index") || null);
};
CrateSearch.prototype.ensureLatestCrateIndex = async function() {
if (CrateSearch.latestIndexVersion() > this.crateIndexVersion) {
this.crateIndex = JSON.parse(localStorage.getItem("crate-index")) || this.crateIndex;
if (CrateSearch.getLatestCrateIndex() > this.crateIndexVersion) {
this.crateIndex = CrateSearch.getLatestCrateIndex() || this.crateIndex;
this.crateIds = Object.keys(crateIndex).sort();
}
};

View file

@ -1,2 +1,8 @@
let latestCrateIndexVersion = CrateSearch.getLatestIndexVersion();
// Load the latest crates index if we got one.
const crateSearcher = latestCrateIndexVersion > 1 ?
new CrateSearch(CrateSearch.getLatestCrateIndex(), latestCrateIndexVersion) : new CrateSearch(crateIndex);
const omnibox = new Omnibox();
omnibox.bootstrap();

View file

@ -1,4 +1,30 @@
const omnibox = new Omnibox();
const CRATES_INDEX_ENDPOINT = "chrome-extension://hlpbdelgppbbhoilofpcfjebkbdgkgma";
async function checkLatestCratesIndex() {
let response = await fetch(`${CRATES_INDEX_ENDPOINT}/crate-index-version.json`, {
mode: "no-cors",
});
console.log(response);
let {version} = await response.json();
if (parseInt(localStorage.getItem("crate-index-version") || 1) < version) {
await loadLatestCratesIndex(version);
localStorage.setItem('crate-index', JSON.stringify(window.crateIndex));
localStorage.setItem('crate-index-version', version);
}
}
async function loadLatestCratesIndex(version) {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
script.src = `${CRATES_INDEX_ENDPOINT}/crates-index.js?${version}`;
script.onload = resolve;
script.onerror = reject;
document.body.appendChild(script);
});
}
document.addEventListener('DOMContentLoaded', function() {
// Open type
@ -53,3 +79,7 @@ function toggleOfflinePathEnableState(enable) {
offlineDocPath.classList.add('disable');
}
}
(async () => {
await checkLatestCratesIndex();
})();