mizzkey/src/client/sw/lang.ts

45 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-02-10 01:54:07 +09:00
/*
* Language manager for SW
*/
declare var self: ServiceWorkerGlobalScope;
import { get, set } from 'idb-keyval';
import { I18n } from '@/scripts/i18n';
class SwLang {
2021-02-10 02:03:05 +09:00
public cacheName = `mk-cache-${_VERSION_}`;
2021-02-10 01:54:07 +09:00
2021-02-10 02:03:05 +09:00
public lang: Promise<string> = get('lang').then(async prelang => {
if (!prelang) return 'en-US';
return prelang;
});
2021-02-10 01:54:07 +09:00
2021-02-10 22:19:09 +09:00
public i18n: Promise<I18n<any>> | null = null;
2021-02-10 01:54:07 +09:00
2021-02-10 02:03:05 +09:00
public setLang(newLang: string) {
this.lang = Promise.resolve(newLang);
2021-02-10 01:54:07 +09:00
set('lang', newLang);
return this.fetchLocale();
2021-02-10 02:03:05 +09:00
}
public async fetchLocale() {
// Service Workerは何度も起動しそのたびにlocaleを読み込むので、CacheStorageを使う
2021-02-10 22:19:09 +09:00
return this.i18n = new Promise(async (res, rej) => {
const localeUrl = `/assets/locales/${await this.lang}.${_VERSION_}.json`;
let localeRes = await caches.match(localeUrl);
2021-02-10 23:16:16 +09:00
2021-02-10 22:19:09 +09:00
if (!localeRes) {
localeRes = await fetch(localeUrl);
const clone = localeRes?.clone();
if (!clone?.clone().ok) rej('locale fetching error');
caches.open(this.cacheName).then(cache => cache.put(localeUrl, clone));
}
res(new I18n(await localeRes.json()));
});
2021-02-10 02:03:05 +09:00
}
2021-02-10 01:54:07 +09:00
}
export const swLang = new SwLang();