Skip to content

Commit

Permalink
i18n: add placeholder support
Browse files Browse the repository at this point in the history
  • Loading branch information
terrablue committed Oct 28, 2023
1 parent ae8e829 commit 944ad02
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 14 deletions.
11 changes: 6 additions & 5 deletions packages/i18n/src/react/exports.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { AppContext } from "@primate/frontend/react";
import { useContext } from "react";
import locale from "./locale.js";
import reactive_locale from "./locale.js";
import resolve from "../shared/resolve.js";

export default (key, placeholders) => {
locale.init();
const { i18n } = useContext(AppContext).context;
return i18n.locales[i18n.locale][key] ?? key;
reactive_locale.init();
const { locales, locale } = useContext(AppContext).context.i18n;
return resolve(locales[locale], key, placeholders);
};

export { locale };
export { reactive_locale as locale };
9 changes: 9 additions & 0 deletions packages/i18n/src/shared/resolve.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export default (locale, key, placeholders = {}) => {
if (locale[key] === undefined) {
return key;
}

return Object.entries(placeholders).reduce((translated, [p_key, p_value]) =>
translated.replaceAll(new RegExp(`\\{${p_key}\\}`, "gu"), () => p_value),
locale[key]);
};
11 changes: 6 additions & 5 deletions packages/i18n/src/solid/exports.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { AppContext } from "@primate/frontend/solid";
import { useContext } from "solid-js";
import locale from "./locale.js";
import reactive_locale from "./locale.js";
import resolve from "../shared/resolve.js";

export default (key, placeholders) => {
locale.init();
const { i18n } = useContext(AppContext).context();
return i18n.locales[i18n.locale][key] ?? key;
reactive_locale.init();
const { locales, locale } = useContext(AppContext).context().i18n;
return resolve(locales[locale], key, placeholders);
};

export { locale };
export { reactive_locale as locale };
9 changes: 5 additions & 4 deletions packages/i18n/src/svelte/exports.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { derived } from "svelte/store";
import { getContext } from "svelte";
import locale_store from "./locale.js";
import reactive_locale from "./locale.js";
import resolve from "../shared/resolve.js";

export default derived(locale_store, locale => (key, placeholders) => {
export default derived(reactive_locale, locale => (key, placeholders) => {
const { locales } = getContext("__primate__").i18n;
return locales[locale][key] ?? key;
return resolve(locales[locale], key, placeholders);
});

export { locale_store as locale };
export { reactive_locale as locale };

0 comments on commit 944ad02

Please sign in to comment.