iceshrimp-legacy/packages/sw/src/scripts/lang.ts
okayurisotto 599417de6e
Refactor sw (#10579)
* refactor(sw): remove dead code

* refactor(sw): remove dead code

* refactor(sw): remove dead code

* refactor(sw): remove dead code

* refactor(sw): remove dead code

* refactor(sw): remove dead code

* refactor(sw): 冗長な部分を変更

* refactor(sw): 使われていない煩雑な機能を削除

* refactor(sw): remove dead code

* refactor(sw): URL文字列の作成に`URL`を使うように

* refactor(sw): 型アサーションの削除とそれに伴い露呈したエラーへの対処

* refactor(sw): `append` -> `set` in `URLSearchParams`

* refactor(sw): `any`の削除とそれに伴い露呈したエラーへの対処

* refactor(sw): 型アサーションの削除とそれに伴い露呈したエラーへの対処

対処と言っても`throw`するだけ。いままでもこの状況ではエラーが投げられていたはずなので、この対処により新たな問題が起きることはないはず。

* refactor(sw): i18n loading

* refactor(sw): 型推論がうまくできる書き方に変更

`codes`が`(string | undefined)[]`から`string[]`になった

* refactor(sw): クエリ文字列の作成に`URLSearchParams`を使うように

* refactor(sw): `findClient`

* refactor(sw): `openClient`における`any`や`as`の書き換え

* refactor(sw): `openPost`における`any`の書き換え

* refactor(sw): `let` -> `const`

* refactor(sw): `any` -> `unknown`

* cleanup(sw): import

* cleanup(sw)

* cleanup(sw): `?.`

* cleanup(sw/.eslintrc.js)

* refactor(sw): `@typescript-eslint/explicit-function-return-type`

* refactor(sw): `@typescript-eslint/no-unused-vars`

* refactor(sw): どうしようもないところに`eslint-disable-next-line`を

* refactor(sw): `import/no-default-export`

* update operations.ts

* throw new Error

---------

Co-authored-by: tamaina <tamaina@hotmail.co.jp>
Co-authored-by: Kainoa kanter <kainoa@t1c.dev>
2023-07-13 16:52:04 -07:00

46 lines
1.2 KiB
TypeScript

/*
* Language manager for SW
*/
import { get, set } from "idb-keyval";
import { I18n, type Locale } from "@/scripts/i18n";
class SwLang {
public cacheName = `mk-cache-${_VERSION_}`;
public lang: Promise<string> = get("lang").then(async (prelang) => {
if (!prelang) return "en-US";
return prelang;
});
public setLang(newLang: string): Promise<I18n<Locale>> {
this.lang = Promise.resolve(newLang);
set("lang", newLang);
return this.fetchLocale();
}
public i18n: Promise<I18n> | null = null;
public fetchLocale(): Promise<I18n<Locale>> {
return (this.i18n = this._fetch());
}
private async _fetch(): Promise<I18n<Locale>> {
// 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);
const clone = localeRes.clone();
if (!clone.clone().ok) throw new Error("locale fetching error");
caches.open(this.cacheName).then((cache) => cache.put(localeUrl, clone));
}
return new I18n<Locale>(await localeRes.json());
}
}
export const swLang = new SwLang();