Browse Source

feat: partial locale type

Yidadaa 1 year ago
parent
commit
50cfbaaab5
5 changed files with 27 additions and 4 deletions
  1. 6 1
      app/locales/cn.ts
  2. 8 1
      app/locales/index.ts
  3. 1 1
      app/masks/index.ts
  4. 3 1
      app/masks/typing.ts
  5. 9 0
      app/utils/merge.ts

+ 6 - 1
app/locales/cn.ts

@@ -241,6 +241,11 @@ const cn = {
   },
 };
 
-export type LocaleType = typeof cn;
+type DeepPartial<T> = T extends object
+  ? {
+      [P in keyof T]?: DeepPartial<T[P]>;
+    }
+  : T;
+export type LocaleType = DeepPartial<typeof cn>;
 
 export default cn;

+ 8 - 1
app/locales/index.ts

@@ -11,6 +11,7 @@ import VI from "./vi";
 import RU from "./ru";
 import CS from "./cs";
 import KO from "./ko";
+import { merge } from "../utils/merge";
 
 export type { LocaleType } from "./cn";
 
@@ -80,7 +81,8 @@ export function changeLang(lang: Lang) {
   location.reload();
 }
 
-export default {
+const fallbackLang = EN;
+const targetLang = {
   en: EN,
   cn: CN,
   tw: TW,
@@ -95,3 +97,8 @@ export default {
   cs: CS,
   ko: KO,
 }[getLang()] as typeof CN;
+
+// if target lang missing some fields, it will use fallback lang string
+merge(fallbackLang, targetLang);
+
+export default fallbackLang as typeof CN;

+ 1 - 1
app/masks/index.ts

@@ -15,7 +15,7 @@ export const BUILTIN_MASK_STORE = {
     return this.masks[id] as Mask | undefined;
   },
   add(m: BuiltinMask) {
-    const mask = { ...m, id: this.buildinId++ };
+    const mask = { ...m, id: this.buildinId++, builtin: true };
     this.masks[mask.id] = mask;
     return mask;
   },

+ 3 - 1
app/masks/typing.ts

@@ -1,3 +1,5 @@
 import { type Mask } from "../store/mask";
 
-export type BuiltinMask = Omit<Mask, "id">;
+export type BuiltinMask = Omit<Mask, "id"> & {
+  builtin: true;
+};

+ 9 - 0
app/utils/merge.ts

@@ -0,0 +1,9 @@
+export function merge(target: any, source: any) {
+  Object.keys(source).forEach(function (key) {
+    if (source[key] && typeof source[key] === "object") {
+      merge((target[key] = target[key] || {}), source[key]);
+      return;
+    }
+    target[key] = source[key];
+  });
+}