From cfa4f07378663ebcfaf33f331086c034bb4a1612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Guitaut?= Date: Mon, 29 Jul 2024 16:52:14 +0200 Subject: [PATCH] FIX: Don't crash when MF definitions are missing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently, if MF definitions are missing (typically because there’s a compilation error), `I18n.messageFormat` will try to access `I18n._mfMessages.hasMessage` resulting in a crash that will in turn crash Ember. This patch addresses the issue by using the optional chaining operator making the `I18n.messageFormat` method return a "Missing Key" message. MF strings won’t be rendered properly, but the site will stay usable. --- .../javascripts/discourse-i18n/src/index.js | 2 +- .../discourse/tests/unit/lib/i18n-test.js | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/assets/javascripts/discourse-i18n/src/index.js b/app/assets/javascripts/discourse-i18n/src/index.js index a9db4df2ff1..236f0e1e91f 100644 --- a/app/assets/javascripts/discourse-i18n/src/index.js +++ b/app/assets/javascripts/discourse-i18n/src/index.js @@ -379,7 +379,7 @@ export class I18n { } messageFormat(key, options) { - const message = this._mfMessages.hasMessage( + const message = this._mfMessages?.hasMessage( key, this._mfMessages.locale, this._mfMessages.defaultLocale 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 a7314664fe7..4ec3a448b34 100644 --- a/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js +++ b/app/assets/javascripts/discourse/tests/unit/lib/i18n-test.js @@ -12,6 +12,7 @@ module("Unit | Utility | i18n", function (hooks) { this._translations = I18n.translations; this._extras = I18n.extras; this._pluralizationRules = { ...I18n.pluralizationRules }; + this._mfMessages = I18n._mfMessages; I18n.locale = "fr"; @@ -109,6 +110,7 @@ module("Unit | Utility | i18n", function (hooks) { I18n.translations = this._translations; I18n.extras = this._extras; I18n.pluralizationRules = this._pluralizationRules; + I18n._mfMessages = this._mfMessages; }); test("defaults", function (assert) { @@ -356,4 +358,19 @@ module("Unit | Utility | i18n", function (hooks) { ); }); }); + + test("messageFormat", function (assert) { + assert.ok( + I18n.messageFormat("posts_likes_MF", { count: 2, ratio: "high" }).match( + /2 replies/ + ), + "It works properly" + ); + I18n._mfMessages = null; + assert.strictEqual( + I18n.messageFormat("posts_likes_MF", { count: 2, ratio: "high" }), + "Missing Key: posts_likes_MF", + "Degrades gracefully if MF definitions are not available." + ); + }); });