Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add an InterpolatedTranslation component. (#33082)

Gary Pendergast2364d3ccd070
diff --git a/app/assets/javascripts/discourse-i18n/src/index.js b/app/assets/javascripts/discourse-i18n/src/index.js
index fe5189cc2e2..1fe78a34cef 100644
--- a/app/assets/javascripts/discourse-i18n/src/index.js
+++ b/app/assets/javascripts/discourse-i18n/src/index.js
@@ -71,26 +71,7 @@ export class I18n {
options.needsPluralization = typeof options.count === "number";
options.ignoreMissing = !this.noFallbacks;
- let translation = this.findTranslation(scope, options);
-
- if (!this.noFallbacks) {
- if (!translation && this.fallbackLocale) {
- options.locale = this.fallbackLocale;
- translation = this.findTranslation(scope, options);
- }
-
- options.ignoreMissing = false;
-
- if (!translation && this.currentLocale() !== this.defaultLocale) {
- options.locale = this.defaultLocale;
- translation = this.findTranslation(scope, options);
- }
-
- if (!translation && this.currentLocale() !== "en") {
- options.locale = "en";
- translation = this.findTranslation(scope, options);
- }
- }
+ const translation = this.findTranslationWithFallback(scope, options);
try {
return this.interpolate(translation, options, scope);
@@ -227,16 +208,19 @@ export class I18n {
interpolate(message, options, scope) {
options = this.prepareOptions(options);
- let matches = message.match(PLACEHOLDER);
- let placeholder, value, name;
+ let value;
- if (!matches) {
- return message;
+ if (message === undefined) {
+ // Throw a generic error to be caught in _translate()
+ throw new Error();
}
- for (let i = 0; (placeholder = matches[i]); i++) {
- name = placeholder.replace(PLACEHOLDER, "$1");
+ const placeholders = this.findPlaceholders(message);
+ if (placeholders.size === 0) {
+ return message;
+ }
+ for (const [name, placeholderValues] of placeholders) {
if (typeof options[name] === "string") {
// The dollar sign (`$`) is a special replace pattern, and `$&` inserts
// the matched string. Thus dollars signs need to be escaped with the
@@ -247,24 +231,54 @@ export class I18n {
value = options[name];
}
- if (!this.isValidNode(options, name)) {
- value = "[missing " + placeholder + " value]";
+ for (const placeholder of placeholderValues) {
+ if (!this.isValidNode(options, name)) {
+ value = "[missing " + placeholder + " value]";
- if (this.testing) {
- throw new I18nMissingInterpolationArgument(`${scope}: ${value}`);
+ if (this.testing) {
+ throw new I18nMissingInterpolationArgument(`${scope}: ${value}`);
+ }
}
- }
- let regex = new RegExp(
- placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}")
- );
+ let regex = new RegExp(
+ placeholder.replace(/\{/gm, "\\{").replace(/\}/gm, "\\}")
+ );
- message = message.replace(regex, value);
+ message = message.replace(regex, value);
+ }
}
return message;
}
+ /**
+ * Extract the placeholders from the translated string before interpolation.
+ *
+ * @param {String} message The translated string.
+ *
+ * @returns {Map<String, Array<String>>} A Map keyed by the placeholder name, with the value set to
+ * how the placeholder appears in the string. If it appears multiple times, each instance will be
+ * recorded (eg, "foo" => ["%{foo}", "{{foo}}"]).
+ */
+ findPlaceholders(message) {
+ if (!message) {
+ return new Map();
+ }
+
+ const placeholders = message.match(PLACEHOLDER) || [];
+
+ const placeholderMap = new Map();
+
+ placeholders.forEach((placeholder) => {
+ const name = placeholder.replace(PLACEHOLDER, "$1");
+ const values = placeholderMap.get(name) ?? [];
+ values.push(placeholder);
+ placeholderMap.set(name, values);
+ });
+
+ return placeholderMap;
+ }
+
findTranslation(scope, options) {
let translation = this.lookup(scope, options);
@@ -275,6 +289,40 @@ export class I18n {
return translation;
}
+ /**
+ * Given the current options (and if fallback is enabled), find the translation
+ * for the given scope.
+ *
+ * @param {String} scope The reference for the translatable string.
+ * @param {Object} options Custom options for this string.
+ *
+ * @returns {Array<String>|String} The translated string, or array of strings for pluralizable translations.
+ */
+ findTranslationWithFallback(scope, options) {
+ let translation = this.findTranslation(scope, options);
+
+ if (!this.noFallbacks) {
+ if (!translation && this.fallbackLocale) {
+ options.locale = this.fallbackLocale;
+ translation = this.findTranslation(scope, options);
+ }
+
+ options.ignoreMissing = false;
+
+ if (!translation && this.currentLocale() !== this.defaultLocale) {
+ options.locale = this.defaultLocale;
+ translation = this.findTranslation(scope, options);
+ }
+
+ if (!translation && this.currentLocale() !== "en") {
+ options.locale = "en";
+ translation = this.findTranslation(scope, options);
+ }
+ }
+
+ return translation;
+ }
+
findAndTranslateValidNode(keys, translation) {
for (let key of keys) {
if (this.isValidNode(translation, key)) {
diff --git a/app/assets/javascripts/discourse/app/components/interpolated-translation.gjs b/app/assets/javascripts/discourse/app/components/interpolated-translation.gjs
new file mode 100644
index 00000000000..8ddf51d8fff
--- /dev/null
+++ b/app/assets/javascripts/discourse/app/components/interpolated-translation.gjs
@@ -0,0 +1,238 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import curryComponent from "ember-curry-component";
+import uniqueId from "discourse/helpers/unique-id";
+import { isProduction } from "discourse/lib/environment";
+import I18n, { i18n, I18nMissingInterpolationArgument } from "discourse-i18n";
+
+/**
+ * Provides the ability to interpolate both strings and components into translatable strings.
+ * This component allows for complex i18n scenarios where you need to embed interactive
+ * components within translated text.
+ *
+ * If you don't require this specific functionality, use the standard i18n() function.
+ *
+ * @component InterpolatedTranslation
+ *
+ * @template Usage example:
+ * ```gjs
+ * // Translation key: "some.translation.key" = "Welcome, %{username}! The date is %{shortdate}!"
+ * <InterpolatedTranslation
+ * @key="some.translation.key"
+ * @options={{hash shortdate=shortDate}}
+ * as |Placeholder|
+ * >
+ * <Placeholder @name="username">
+ * <UserLink @user={{user}}>{{user.username}}</UserLink>
+ * </Placeholder>
+ * </InterpolatedTranslation>
+ * ```
+ *
+ * @param {String} key - The i18n translation key to use
+ * @param {Object} [options] - Hash of options to pass to the i18n function for string interpolation
+ */
+export default class InterpolatedTranslation extends Component {
+ /**
+ * Throws errors in dev, or logs them to the browser console in production.
+ *
+ * @param {String} The error message.
+ * @param {Class} The type of Error class to throw.
+ **/
+ static log(message, errorClass = Error) {
+ if (isProduction()) {
+ // eslint-disable-next-line no-console
+ console.error(message);
+ } else {
+ throw new errorClass(message);
+ }
+ }
+
+ /**
+ * Processes the translation string and returns all of the rendering data.
+ *
+ * @returns {Object}
+ */
+ get textAndPlaceholders() {
+ const optionsArg = this.args.options || {};
+
+ // Find all of the placeholders in the string we're looking at.
+ const message = I18n.findTranslationWithFallback(this.args.key, {
+ ...optionsArg,
+ });
+ const placeholderAppearance = I18n.findPlaceholders(message);
+
+ // We only need to keep the placeholders that aren't being handled by those passed in @options.
+ Object.keys(optionsArg).forEach((stringPlaceholder) =>
+ placeholderAppearance.delete(stringPlaceholder)
+ );
+
+ const placeholderKeys = new Map();
+ const placeholderElements = new Map();
+
+ placeholderAppearance.forEach((placeholderAppearances, placeholderName) => {
+ placeholderKeys.set(
+ placeholderName,
+ `__PLACEHOLDER__${placeholderName}__${uniqueId()}__`
+ );
+ placeholderElements.set(
+ placeholderName,
+ placeholderAppearances.map(() => document.createElement("span"))
+ );
+ });
+
+ const text = i18n(this.args.key, {
+ ...Object.fromEntries(placeholderKeys),
+ ...optionsArg,
+ });
+
+ const parts = [];
+ let currentIndex = 0;
+ const placeholderRegex = /__PLACEHOLDER__([^_]+)__[^_]+__/g;
+ const foundCount = [];
+ let match;
+
+ while ((match = placeholderRegex.exec(text)) !== null) {
+ // Add text before placeholder if exists
+ if (match.index > currentIndex) {
+ parts.push(text.slice(currentIndex, match.index));
+ }
+
+ // Add the placeholder element, but only if the placeholder string we found matches
+ // the uniqueId we generated earlier for that placeholder.
+ if (placeholderKeys.get(match[1]) === match[0]) {
+ const elIdx = foundCount[match[1]] ?? 0;
+ parts.push(placeholderElements.get(match[1])[elIdx]);
+ foundCount[match[1]] = elIdx + 1;
+ }
+
+ currentIndex = match.index + match[0].length;
+ }
+
+ // Add remaining text if any
+ if (currentIndex < text.length) {
+ parts.push(text.slice(currentIndex));
+ }
+
+ return {
+ appearance: placeholderAppearance,
+ elements: placeholderElements,
+ keys: placeholderKeys,
+ rendered: [],
+ parts,
+ };
+ }
+
+ /**
+ * Creates a curried TranslationPlaceholder component for all of the placeholders.
+ *
+ * @param {Map<String, Array<HTMLElement>>} elements A map of the elements assigned to each placeholder.
+ * @param {Array<string>} rendered An array of the placeholders that have been
+ *
+ * @returns {Component} A curried TranslationPlaceholder component
+ */
+ @action
+ curriedPlaceholderComponent(elements, rendered) {
+ return curryComponent(
+ Placeholder,
+ {
+ markAsRendered: (name) => rendered.push(name),
+ elements,
+ },
+ getOwner(this)
+ );
+ }
+
+ /**
+ * Checks for any mismatches between the placeholders expected, and those provided.
+ *
+ * @param {Object} info The rendering object returned by textAndPlaceholders().
+ */
+ @action
+ checkPlaceholders(info) {
+ let missing = [];
+ for (const [name, elements] of info.elements) {
+ if (!info.rendered.includes(name)) {
+ const value = `[missing ${info.appearance.get(name)} placeholder]`;
+ elements.forEach((el) => (el.innerText = value));
+ missing.push(value);
+ }
+ }
+
+ if (missing.length > 0) {
+ InterpolatedTranslation.log(
+ `Translation error for key '${this.args.key}': ${missing.join(", ")}`,
+ I18nMissingInterpolationArgument
+ );
+ }
+ }
+
+ <template>
+ {{#let this.textAndPlaceholders as |info|}}
+ {{#each info.parts as |part|}}
+ {{part}}
+ {{/each}}
+
+ {{yield (this.curriedPlaceholderComponent info.elements info.rendered)}}
+ {{this.checkPlaceholders info}}
+ {{/let}}
+
+ {{#unless (has-block)}}
+ {{InterpolatedTranslation.log
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ }}
+ {{/unless}}
+ </template>
+}
+
+/**
+ * Internally used by the Translation component to render placeholder
+ * content. This component conditionally renders its content only when the
+ * placeholder name matches the expected placeholder key.
+ *
+ * This component is only used through the Translation component's yielded
+ * Placeholder component, rather than directly.
+ *
+ * @component Placeholder
+ *
+ * @template Usage example:
+ * ```gjs
+ * <Placeholder @name="username">
+ * <UserLink @user={{user}}>{{user.username}}</UserLink>
+ * </Placeholder>
+ * ```
+ *
+ * @param {String} name - The name of the placeholder this content should fill
+ */
+class Placeholder extends Component {
+ constructor() {
+ super(...arguments);
+ this.args.markAsRendered(this.args.name);
+ }
+
+ /**
+ * Since {{get}} doesn't work with Maps, we need a helper to handle it.
+ *
+ * @param {Map<any,any>} map The map we're retrieving from.
+ * @param {any} key The key of the value we're retrieving.
+ *
+ * @returns {any|undefined} The value found, or undefined if there was no matching entry.
+ **/
+ getFromMap(map, key) {
+ return map.get(key);
+ }
+
+ <template>
+ {{#each (this.getFromMap @elements @name) as |element|}}
+ {{#in-element element}}
+ {{yield}}
+ {{/in-element}}
+ {{/each}}
+
+ {{#unless (has-block)}}
+ {{InterpolatedTranslation.log
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ }}
+ {{/unless}}
+ </template>
+}
diff --git a/app/assets/javascripts/discourse/tests/integration/components/interpolated-translation-test.gjs b/app/assets/javascripts/discourse/tests/integration/components/interpolated-translation-test.gjs
new file mode 100644
index 00000000000..4a085d1a611
--- /dev/null
+++ b/app/assets/javascripts/discourse/tests/integration/components/interpolated-translation-test.gjs
@@ -0,0 +1,265 @@
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import {
+ render,
+ resetOnerror,
+ settled,
+ setupOnerror,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import InterpolatedTranslation from "discourse/components/interpolated-translation";
+import UserLink from "discourse/components/user-link";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import I18n, { I18nMissingInterpolationArgument } from "discourse-i18n";
+
+module("Integration | Component | InterpolatedTranslation", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this._locale = I18n.locale;
+ this._translations = I18n.translations;
+
+ I18n.locale = "fr";
+
+ I18n.translations = {
+ fr: {
+ js: {
+ hello: "Bonjour, %{username}",
+ simple_text: "Simple text without placeholders",
+ with_options: "Hello %{name}, welcome to %{site}!",
+ multiple_placeholders:
+ "User %{user} commented on %{topic} at %{time}",
+ mixed_placeholders:
+ "Welcome %{username}! You have %{count} messages.",
+ repeated_placeholders: "Welcome %{username}! Hello %{username}!",
+ user: {
+ profile_possessive: "Profil de %{username}",
+ },
+ },
+ },
+ };
+ });
+
+ hooks.afterEach(function () {
+ I18n.locale = this._locale;
+ I18n.translations = this._translations;
+ });
+
+ test("renders translation with component placeholder", async function (assert) {
+ await render(
+ <template>
+ <InterpolatedTranslation @key="hello" as |Placeholder|>
+ <Placeholder @name="username">
+ <UserLink @username="pento">pento</UserLink>
+ </Placeholder>
+ </InterpolatedTranslation>
+ </template>
+ );
+
+ assert.dom().hasText("Bonjour, pento");
+ assert.dom("a[data-user-card='pento']").exists();
+ assert
+ .dom("a[data-user-card='pento']")
+ .hasAttribute("aria-label", "Profil de pento");
+ });
+
+ test("renders translation with repeated component placeholder", async function (assert) {
+ await render(
+ <template>
+ <InterpolatedTranslation @key="repeated_placeholders" as |Placeholder|>
+ <Placeholder @name="username">
+ <UserLink @username="pento">pento</UserLink>
+ </Placeholder>
+ </InterpolatedTranslation>
+ </template>
+ );
+
+ assert.dom().hasText("Welcome pento ! Hello pento !");
+ assert.dom("a[data-user-card='pento']").exists({ count: 2 });
+ });
+
+ test("throws an error on simple translation without placeholders", async function (assert) {
+ let errors = 0;
+
+ setupOnerror((error) => {
+ assert.strictEqual(
+ error.message,
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ );
+
+ errors++;
+ });
+
+ await render(
+ <template><InterpolatedTranslation @key="simple_text" /></template>
+ );
+
+ assert.strictEqual(errors, 1);
+ resetOnerror();
+ });
+
+ test("renders translation with string options only", async function (assert) {
+ let errors = 0;
+
+ setupOnerror((error) => {
+ assert.strictEqual(
+ error.message,
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ );
+
+ errors++;
+ });
+
+ await render(
+ <template>
+ <InterpolatedTranslation
+ @key="with_options"
+ @options={{hash name="John" site="Discourse"}}
+ />
+ </template>
+ );
+
+ assert.strictEqual(errors, 1);
+ resetOnerror();
+ });
+
+ test("renders translation with both string options and component placeholders", async function (assert) {
+ await render(
+ <template>
+ <InterpolatedTranslation
+ @key="mixed_placeholders"
+ @options={{hash count=5}}
+ as |Placeholder|
+ >
+ <Placeholder @name="username">
+ <UserLink @username="alice">alice</UserLink>
+ </Placeholder>
+ </InterpolatedTranslation>
+ </template>
+ );
+
+ assert.dom().hasText("Welcome alice ! You have 5 messages.");
+ assert.dom("a[data-user-card='alice']").exists();
+ });
+
+ test("renders translation with multiple component placeholders", async function (assert) {
+ await render(
+ <template>
+ <InterpolatedTranslation
+ @key="multiple_placeholders"
+ @options={{hash time="2:30 PM"}}
+ as |Placeholder|
+ >
+ <Placeholder @name="user">
+ <UserLink @username="bob">bob</UserLink>
+ </Placeholder>
+ <Placeholder @name="topic">
+ <strong>Important Topic</strong>
+ </Placeholder>
+ </InterpolatedTranslation>
+ </template>
+ );
+
+ assert.dom().hasText("User bob commented on Important Topic at 2:30 PM");
+ assert.dom("a[data-user-card='bob']").exists();
+ assert.dom("strong").hasText("Important Topic");
+ });
+
+ test("handles missing translation key gracefully", async function (assert) {
+ let errors = 0;
+
+ setupOnerror((error) => {
+ assert.strictEqual(
+ error.message,
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ );
+
+ errors++;
+ });
+
+ await render(
+ <template><InterpolatedTranslation @key="nonexistent_key" /></template>
+ );
+
+ // When a translation key is missing, i18n returns the key itself
+ assert.dom().hasText("[fr.nonexistent_key]");
+
+ assert.strictEqual(errors, 1);
+ resetOnerror();
+ });
+
+ test("handles placeholder not provided in template", async function (assert) {
+ let errors = 0;
+ setupOnerror((error) => {
+ assert.true(error instanceof I18nMissingInterpolationArgument);
+ assert.strictEqual(
+ error.message,
+ "Translation error for key 'hello': [missing %{username} placeholder]"
+ );
+
+ errors++;
+ });
+
+ // Translation has %{username} placeholder but no placeholder component is provided
+ await render(<template><InterpolatedTranslation @key="hello" /></template>);
+
+ assert.strictEqual(errors, 1);
+ resetOnerror();
+
+ // Should render the placeholder string since no component was provided
+ assert.dom().includesText("Bonjour, [missing %{username} placeholder]");
+ });
+
+ test("handles empty placeholder provided in template", async function (assert) {
+ let errors = 0;
+ setupOnerror((error) => {
+ assert.true(error instanceof Error);
+ assert.strictEqual(
+ error.message,
+ "The <InterpolatedTranslation> component shouldn't be used for translations that don't insert components. Use `i18n()` instead."
+ );
+
+ errors++;
+ });
+
+ await render(
+ <template>
+ <InterpolatedTranslation @key="hello" as |Placeholder|>
+ <Placeholder @name="username" /></InterpolatedTranslation>
+ </template>
+ );
+
+ assert.strictEqual(errors, 1);
+ resetOnerror();
+ });
+
+ test("correctly re-renders when args change", async function (assert) {
+ const state = new (class {
+ @tracked key = "hello";
+ @tracked options = {};
+ })();
+
+ await render(
+ <template>
+ <InterpolatedTranslation
+ @key={{state.key}}
+ @options={{state.options}}
+ as |Placeholder|
+ >
+ <Placeholder @name="username">
+ <UserLink @username="pento">pento</UserLink>
+ </Placeholder>
+ </InterpolatedTranslation>
+ </template>
+ );
+
+ assert.dom().hasText("Bonjour, pento");
+
+ state.options = { username: "admin" };
+ await settled();
+
+ assert.dom().hasText("Bonjour, admin");
+ assert.dom("a[data-user-card='pento']").doesNotExist();
+ assert.dom("a[data-user-card='admin']").doesNotExist();
+ });
+});
diff --git a/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js b/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js
index c46e43046dc..219bf28d6ff 100644
--- a/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js
+++ b/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js
@@ -71,6 +71,8 @@ module("Unit | Utility | i18n", function (hooks) {
},
dollar_sign: "Hi {{description}}",
with_multiple_interpolate_arguments: "Hi %{username}, %{username2}",
+ with_repeated_interpolate_arguments:
+ "Hi, %{username}, your username is %{username}",
},
},
ja: {
@@ -333,6 +335,13 @@ module("Unit | Utility | i18n", function (hooks) {
}
});
+ test("having an interpolation argument multiple times in a translation works correctly", function (assert) {
+ assert.strictEqual(
+ i18n("with_repeated_interpolate_arguments", { username: "pento" }),
+ "Hi, pento, your username is pento"
+ );
+ });
+
test("pluralizationNormalizedLocale", function (assert) {
I18n.locale = "pt";