Skip to content

Commit 986c5aa

Browse files
committed
Add translatables
1 parent 26cc104 commit 986c5aa

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

src/lib/stores/i18n.store.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { describe, expect, it } from "vitest";
2+
import { addTranslations, createI18nStore, t } from "./i18n.store";
3+
4+
describe.skip("I18n", () => {
5+
it("can translate a translatable", () => {
6+
createI18nStore({ lng: "de" });
7+
addTranslations("de", { "hello": "hallo" });
8+
t.subscribe(($t) => {
9+
expect($t("hello")).toEqual("hallo");
10+
});
11+
});
12+
});

src/lib/stores/i18n.store.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ export type InlineTranslation = {
5959
[locale: string]: string;
6060
};
6161

62+
export interface Translatable {
63+
key: string;
64+
replacers?: Record<string, string>;
65+
}
66+
6267
export const currentLanguage = writable("de");
6368
i18nNext.on("languageChanged", (lng) => {
6469
const formattedLanguage = lng.split("-")[0];
@@ -85,15 +90,27 @@ export const it = derived(currentLanguage, () => translateInlineTranslation);
8590

8691
/** based on the input either inline translations or keys are getting translated */
8792
export const t = derived(currentLanguage, (currentLanguage: string) => {
88-
return (key: string | InlineTranslation, options?: Record<string, unknown>) => {
93+
return (key: string | InlineTranslation | Translatable, options?: Record<string, unknown>) => {
8994
if (typeof key === "string") return i18nNext.t(key, options);
90-
return translateInlineTranslation(key, { language: currentLanguage });
95+
else if (isTranslatable(key))
96+
return i18nNext.t(key.key, {
97+
...options,
98+
...key.replacers
99+
});
100+
else return translateInlineTranslation(key, { language: currentLanguage });
91101
};
92102
});
93103

94-
export function isInlineTranslation(obj: InlineTranslation): obj is InlineTranslation {
104+
export function isInlineTranslation(obj: any): obj is InlineTranslation {
95105
if (!(obj instanceof Object)) return false;
96106
for (const [key, value] of Object.entries(obj))
97107
if (typeof key !== "string" || typeof value !== "string") return false;
98108
return true;
99109
}
110+
111+
export function isTranslatable(obj: any): obj is Translatable {
112+
if (!(obj instanceof Object)) return false;
113+
if (typeof obj.key !== "string") return false;
114+
if (obj.replacers && !(obj.replacers instanceof Object)) return false;
115+
return true;
116+
}

0 commit comments

Comments
 (0)