Skip to content

Commit

Permalink
refactor(option): support fallback option string
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Sep 25, 2024
1 parent 92b9dbb commit d2d2eb6
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"scripts": {
"prepublishOnly": "pnpm run build",
"lint": "eslint --ext .ts,.tsx . && prettier --check .",
"test": "vitest --coverage",
"test": "vitest --coverage --coverage.include=src/**",
"test:ci": "tsc --noEmit && vitest --coverage --coverage.reporter=lcov --coverage.include=src/**",
"docs": "typedoc --options typedoc.json",
"build": "cross-env NODE_ENV=production tsup --onSuccess \"node scripts/build-umd.mjs\"",
Expand Down
8 changes: 6 additions & 2 deletions src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,12 @@ export class I18n {
if (args) {
const option = args[":option"];
if (option != null) {
const newKey = `${key}.${option}`;
key = flatLocale[newKey] ? newKey : `${key}.other`;
let newKey: string;
key =
flatLocale[(newKey = `${key}.${option}`)] ||
flatLocale[(newKey = `${key}.other`)]
? newKey
: key;
}
let fn = localeFns.get(key);
fn ||
Expand Down
11 changes: 11 additions & 0 deletions test/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,17 @@ describe("template t function", () => {
expect(i18n.t("apple", { ":option": 3 })).toBe("3 apples");
});

it("should support :option without sub keys", () => {
const locales: Locales = {
en: {
message: "{{:option}} world",
},
};
const i18n = new I18n("en", locales);
expect(i18n.t("message", { ":option": "hello" })).toBe("hello world");
expect(i18n.t("message", { ":option": "bye" })).toBe("bye world");
});

it("should return key if message not exists", () => {
const i18n = new I18n("en", {});
expect(i18n.t("fruit")).toBe("fruit");
Expand Down

0 comments on commit d2d2eb6

Please sign in to comment.