2023-07-27 14:31:52 +09:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-04-30 21:52:07 +09:00
|
|
|
/*
|
|
|
|
* Language manager for SW
|
|
|
|
*/
|
|
|
|
import { get, set } from 'idb-keyval';
|
2023-04-12 01:07:24 +09:00
|
|
|
import { I18n, type Locale } from '@/scripts/i18n';
|
2022-04-30 21:52:07 +09:00
|
|
|
|
|
|
|
class SwLang {
|
|
|
|
public cacheName = `mk-cache-${_VERSION_}`;
|
|
|
|
|
|
|
|
public lang: Promise<string> = get('lang').then(async prelang => {
|
|
|
|
if (!prelang) return 'en-US';
|
|
|
|
return prelang;
|
|
|
|
});
|
|
|
|
|
2023-04-12 01:07:24 +09:00
|
|
|
public setLang(newLang: string): Promise<I18n<Locale>> {
|
2022-04-30 21:52:07 +09:00
|
|
|
this.lang = Promise.resolve(newLang);
|
|
|
|
set('lang', newLang);
|
|
|
|
return this.fetchLocale();
|
|
|
|
}
|
|
|
|
|
2023-04-12 01:07:24 +09:00
|
|
|
public i18n: Promise<I18n> | null = null;
|
2022-04-30 21:52:07 +09:00
|
|
|
|
2023-04-12 01:07:24 +09:00
|
|
|
public fetchLocale(): Promise<I18n<Locale>> {
|
|
|
|
return (this.i18n = this._fetch());
|
2022-04-30 21:52:07 +09:00
|
|
|
}
|
|
|
|
|
2023-04-12 01:07:24 +09:00
|
|
|
private async _fetch(): Promise<I18n<Locale>> {
|
2022-04-30 21:52:07 +09:00
|
|
|
// Service Workerは何度も起動しそのたびにlocaleを読み込むので、CacheStorageを使う
|
|
|
|
const localeUrl = `/assets/locales/${await this.lang}.${_VERSION_}.json`;
|
|
|
|
let localeRes = await caches.match(localeUrl);
|
|
|
|
|
|
|
|
// _DEV_がtrueの場合は常に最新化
|
|
|
|
if (!localeRes || _DEV_) {
|
|
|
|
localeRes = await fetch(localeUrl);
|
2023-04-12 01:07:24 +09:00
|
|
|
const clone = localeRes.clone();
|
|
|
|
if (!clone.clone().ok) throw new Error('locale fetching error');
|
2022-04-30 21:52:07 +09:00
|
|
|
|
|
|
|
caches.open(this.cacheName).then(cache => cache.put(localeUrl, clone));
|
|
|
|
}
|
|
|
|
|
2023-04-12 01:07:24 +09:00
|
|
|
return new I18n<Locale>(await localeRes.json());
|
2022-04-30 21:52:07 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const swLang = new SwLang();
|