Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Load the locale catalogues from asset instead of inlining it in index.html (#82468)

Romeo Van Snicka7fb139a6537
diff --git a/bin/build/src/build/uberjar.clj b/bin/build/src/build/uberjar.clj
index 4ae1b8dff8a..0a6a4725c0e 100644
--- a/bin/build/src/build/uberjar.clj
+++ b/bin/build/src/build/uberjar.clj
@@ -143,7 +143,10 @@
#"\.rej$"
;; Driver classes are now flattened directly into the uberjar via the :drivers alias — the old nested
;; driver JARs in resources/modules/ must not be included or we'd ship everything twice.
- #"^modules/"])
+ #"^modules/"
+ ;; The frontend build compiles each locale catalogue into a hashed script under app/dist, so these
+ ;; sources are build inputs only. They are ~27 MB and nothing reads them at runtime.
+ #"^frontend_client/app/locales/"])
(defn- copy-resources! [basis]
(u/step "Copy resources"
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx
index 447bd2d29ce..80ceab1778a 100644
--- a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx
@@ -1,6 +1,7 @@
import { createRoot } from "react-dom/client";
import { sdkBundleExports } from "embedding-sdk-bundle/sdk-bundle-exports";
+import { applyDocumentLocales } from "metabase/utils/boot-locale";
import { DataAppIframeApp } from "./components/DataAppIframeApp/DataAppIframeApp";
@@ -19,9 +20,12 @@ import { DataAppIframeApp } from "./components/DataAppIframeApp/DataAppIframeApp
// implementations the package component facades look up at render time.
window.METABASE_EMBEDDING_SDK_BUNDLE = sdkBundleExports;
-const init = () => {
+const init = async () => {
document.body.style.margin = "0";
+ // This page is served from our own document, which carries the catalogues.
+ await applyDocumentLocales();
+
const rootElement = document.getElementById("root");
if (!rootElement) {
diff --git a/frontend/build/shared/rspack/plugins/LocaleCatalogManifest/locale-catalog-manifest.js b/frontend/build/shared/rspack/plugins/LocaleCatalogManifest/locale-catalog-manifest.js
new file mode 100644
index 00000000000..96f401dd647
--- /dev/null
+++ b/frontend/build/shared/rspack/plugins/LocaleCatalogManifest/locale-catalog-manifest.js
@@ -0,0 +1,52 @@
+// @ts-check
+
+const MANIFEST_FILENAME = "locale-manifest.json";
+const LOCALE_CHUNK_NAME = /^locale-(.+)-json$/;
+
+/**
+ * Publishes where the build put each locale catalogue.
+ *
+ * `metabase/utils/localization` imports the catalogues, so rspack already emits
+ * one hashed chunk per locale. The backend needs their filenames to put the one
+ * a request needs into the document as a script tag: the chunk installs itself,
+ * and the import that follows resolves from memory rather than over the network.
+ */
+class LocaleCatalogManifest {
+ apply(/** @type {import("webpack").Compiler} */ compiler) {
+ const { RawSource } = compiler.webpack.sources;
+ const publicPath = String(compiler.options.output.publicPath ?? "");
+
+ compiler.hooks.thisCompilation.tap(
+ "LocaleCatalogManifest",
+ (/** @type {import("webpack").Compilation} */ compilation) => {
+ compilation.hooks.processAssets.tap(
+ {
+ name: "LocaleCatalogManifest",
+ stage:
+ compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH,
+ },
+ () => {
+ /** @type {Record<string, string>} */
+ const urls = {};
+ for (const chunk of compilation.chunks) {
+ const locale = chunk.name?.match(LOCALE_CHUNK_NAME)?.[1];
+ const file = [...chunk.files].find((name) =>
+ name.endsWith(".js"),
+ );
+ if (locale && file) {
+ urls[locale] = publicPath + file;
+ }
+ }
+
+ compilation.emitAsset(
+ MANIFEST_FILENAME,
+ new RawSource(JSON.stringify(urls)),
+ );
+ },
+ );
+ },
+ );
+ }
+}
+
+module.exports.LocaleCatalogManifest = LocaleCatalogManifest;
diff --git a/frontend/src/metabase/app-embed-sdk.tsx b/frontend/src/metabase/app-embed-sdk.tsx
index af55f59aa82..cd7f14361c1 100644
--- a/frontend/src/metabase/app-embed-sdk.tsx
+++ b/frontend/src/metabase/app-embed-sdk.tsx
@@ -30,8 +30,12 @@ import "sdk-iframe-embedding-ee-plugins";
// Must be imported after the EE plugins are loaded
// oxfmt-ignore
import { SdkIframeEmbedRoute } from "metabase/embedding/embedding-iframe-sdk/components/SdkIframeEmbedRoute";
+import { applyDocumentLocales } from "metabase/utils/boot-locale";
+
+async function _init() {
+ // This page is served from our own document, which carries the catalogues.
+ await applyDocumentLocales();
-function _init() {
document.body.style.margin = "0";
document.body.style.backgroundColor = "transparent";
document.documentElement.style.overflow = "hidden";
diff --git a/frontend/src/metabase/app.tsx b/frontend/src/metabase/app.tsx
index 3c7817a3ef6..e404a6e872d 100644
--- a/frontend/src/metabase/app.tsx
+++ b/frontend/src/metabase/app.tsx
@@ -44,6 +44,7 @@ import { PortalContainer } from "metabase/ui";
import { EmotionCacheProvider } from "metabase/ui/components/theme/EmotionCacheProvider";
import { captureClickModifierKeys } from "metabase/urls";
import { setBasename } from "metabase/utils/basename";
+import { applyDocumentLocales } from "metabase/utils/boot-locale";
import { captureConsoleErrors } from "metabase/utils/errors";
import { initMetaplow } from "metabase/utils/metaplow";
import { initTracing, rotateTraceId } from "metabase/utils/otel";
@@ -78,11 +79,15 @@ function isLocationChangeAction(
return isAction(action) && action.type === LOCATION_CHANGE;
}
-function _init(
+async function _init(
reducers: Parameters<typeof getStore>[0],
getRoutes: (store: Store) => RouteObject[],
callback?: (store: Store) => void,
) {
+ // The catalogues are already in the page as installed chunks, so this resolves
+ // without a request. Rendering before it would paint the app in English.
+ await applyDocumentLocales();
+
// Initialize distributed tracing if enabled via MB_TRACING_ENABLED.
// Uses bootstrap data so it's available before the first API call.
const extraMiddlewares: Middleware[] = [];
diff --git a/frontend/src/metabase/utils/boot-locale.ts b/frontend/src/metabase/utils/boot-locale.ts
new file mode 100644
index 00000000000..f000d4840e9
--- /dev/null
+++ b/frontend/src/metabase/utils/boot-locale.ts
@@ -0,0 +1,29 @@
+import {
+ applyUserLocalization,
+ registerSiteLocalization,
+} from "metabase/utils/i18n";
+import { loadLocaleCatalog } from "metabase/utils/localization";
+
+/**
+ * Applies the catalogues the document asked for, before the first render.
+ *
+ * The document loads them as plain script tags, so by the time this runs the
+ * chunks are already installed and the imports below resolve without a request.
+ */
+export async function applyDocumentLocales(): Promise<void> {
+ const { user = "en", site = "en" } = window.MetabaseLocales ?? {};
+
+ try {
+ const [userCatalog, siteCatalog] = await Promise.all([
+ loadLocaleCatalog(user),
+ site === user ? null : loadLocaleCatalog(site),
+ ]);
+
+ registerSiteLocalization(siteCatalog ?? userCatalog);
+ applyUserLocalization(userCatalog);
+ } catch (error) {
+ // A missing catalogue leaves the app in English, which is the msgid source.
+ // Failing to boot over it would be worse than an untranslated page.
+ console.error("Failed to load the locale catalogues", error);
+ }
+}
diff --git a/frontend/src/metabase/utils/boot-locale.unit.spec.ts b/frontend/src/metabase/utils/boot-locale.unit.spec.ts
new file mode 100644
index 00000000000..a18ad726877
--- /dev/null
+++ b/frontend/src/metabase/utils/boot-locale.unit.spec.ts
@@ -0,0 +1,24 @@
+import { t } from "ttag";
+
+import { applyDocumentLocales } from "metabase/utils/boot-locale";
+
+describe("applyDocumentLocales", () => {
+ afterEach(() => {
+ delete window.MetabaseLocales;
+ delete window.MetabaseUserLocalization;
+ delete window.MetabaseSiteLocalization;
+ });
+
+ it("should not error on English, which has no catalogue of its own", async () => {
+ const consoleError = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => undefined);
+ window.MetabaseLocales = { user: "en", site: "en" };
+
+ await applyDocumentLocales();
+
+ expect(consoleError).not.toHaveBeenCalled();
+ expect(window.MetabaseUserLocalization?.headers.language).toBe("en");
+ expect(t`Filter`).toBe("Filter");
+ });
+});
diff --git a/frontend/src/metabase/utils/i18n.ts b/frontend/src/metabase/utils/i18n.ts
index f75775cd7b5..806c204b294 100644
--- a/frontend/src/metabase/utils/i18n.ts
+++ b/frontend/src/metabase/utils/i18n.ts
@@ -150,15 +150,25 @@ export function siteLocale(): string | undefined {
return undefined;
}
-// register site locale with ttag, if needed later
-if (window.MetabaseSiteLocalization) {
- const translationsObject = window.MetabaseSiteLocalization;
- const locale = translationsObject.headers.language;
+/**
+ * Registers the instance catalogue with ttag without making it the active one,
+ * so `withInstanceLanguage` can switch to it later.
+ */
+export function registerSiteLocalization(
+ translationsObject: LocaleDataWithLanguage,
+): void {
addMsgIds(translationsObject);
- addLocale(locale, translationsObject);
+ addLocale(translationsObject.headers.language, translationsObject);
+ window.MetabaseSiteLocalization = translationsObject;
}
-// set the initial localization to user locale
-if (window.MetabaseUserLocalization) {
- setLocalization(window.MetabaseUserLocalization);
+/**
+ * Makes a catalogue the active one. `withInstanceLanguage` restores it after
+ * running in the instance language, and custom visualizations read its name.
+ */
+export function applyUserLocalization(
+ translationsObject: LocaleDataWithLanguage,
+): void {
+ window.MetabaseUserLocalization = translationsObject;
+ setLocalization(translationsObject);
}
diff --git a/frontend/src/metabase/utils/localization.ts b/frontend/src/metabase/utils/localization.ts
index 803e0884b8f..f82b7654c90 100644
--- a/frontend/src/metabase/utils/localization.ts
+++ b/frontend/src/metabase/utils/localization.ts
@@ -3,6 +3,19 @@ import {
setLocalization,
} from "metabase/utils/i18n";
+// English is the msgid source, so the translation step builds no catalogue for
+// it. This stands in for one and falls back to the literals.
+const ENGLISH_CATALOG: LocaleDataWithLanguage = {
+ headers: {
+ language: "en",
+ "plural-forms": "nplurals=2; plural=(n != 1);",
+ },
+ translations: {
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Not a user facing string
+ "": { Metabase: { msgid: "Metabase", msgstr: ["Metabase"] } },
+ },
+};
+
/**
* Loads a locale's catalogue from our own bundle.
*
@@ -11,7 +24,13 @@ import {
* the `.br` and `.gz` siblings, and resolves the URL at runtime. A hashed chunk
* is cacheable, which a fetch of `app/locales/<locale>.json` never qualified for.
*/
-function loadLocaleCatalog(locale: string): Promise<LocaleDataWithLanguage> {
+export function loadLocaleCatalog(
+ locale: string,
+): Promise<LocaleDataWithLanguage> {
+ if (locale === "en") {
+ return Promise.resolve(ENGLISH_CATALOG);
+ }
+
return import(
/* webpackChunkName: "locale-[request]" */
`locales/${locale.replace(/-/g, "_")}.json`
@@ -22,21 +41,10 @@ function loadLocaleCatalog(locale: string): Promise<LocaleDataWithLanguage> {
export async function loadLocalization(
locale: string,
): Promise<LocaleDataWithLanguage> {
+ // English resolves without awaiting, which callers that render straight after
+ // this rely on.
const translationsObject: LocaleDataWithLanguage =
- locale !== "en"
- ? await loadLocaleCatalog(locale)
- : // English is the msgid source, so no catalogue is built for it. This
- // stands in for one and falls back to the literals.
- {
- headers: {
- language: "en",
- "plural-forms": "nplurals=2; plural=(n != 1);",
- },
- translations: {
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Not a user facing string
- "": { Metabase: { msgid: "Metabase", msgstr: ["Metabase"] } },
- },
- };
+ locale === "en" ? ENGLISH_CATALOG : await loadLocaleCatalog(locale);
setLocalization(translationsObject);
return translationsObject;
diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.ts
index 3a351fbc7d1..0e3e56ddc34 100644
--- a/frontend/src/types/global.d.ts
+++ b/frontend/src/types/global.d.ts
@@ -19,6 +19,8 @@ interface Window {
MetabaseUserColorScheme?: string;
MetabaseSiteLocalization?: MetabaseLocalization;
MetabaseUserLocalization?: MetabaseLocalization;
+ /** The locales the document loaded catalogues for, set by index_bootstrap.js. */
+ MetabaseLocales?: { user: string; site: string };
overrideIsWithinIframe?: boolean; // Mock that we're embedding, so we could test embed components
METABASE?: boolean; // Add a global so we can check if the parent iframe is Metabase
diff --git a/resources/frontend_client/data_app_template.html b/resources/frontend_client/data_app_template.html
index fa8d8976123..a2454ed3324 100644
--- a/resources/frontend_client/data_app_template.html
+++ b/resources/frontend_client/data_app_template.html
@@ -18,12 +18,8 @@
{{{bootstrapJSON}}}
</script>
- <script type="application/json" id="_metabaseUserLocalization">
- {{{userLocalizationJSON}}}
- </script>
-
- <script type="application/json" id="_metabaseSiteLocalization">
- {{{siteLocalizationJSON}}}
+ <script type="application/json" id="_metabaseLocales">
+ {"user": "{{{userLocale}}}", "site": "{{{siteLocale}}}"}
</script>
<script type="application/json" id="_metabaseUserColorScheme">
@@ -35,6 +31,12 @@
The browser blanks the attribute after parsing, so the value stays out of the DOM. -->
<script type="text/javascript" nonce="{{{nonce}}}">{{{bootstrapJS}}}</script>
<script type="text/javascript">{{{assetOnErrorJS}}}</script>
+
+ <!-- The catalogue chunks this request needs. They install themselves, so the
+ app's `import()` of them resolves without a request. Below
+ index_bootstrap.js, which repairs <base href> when the Site URL setting
+ is wrong, and these resolve against it. -->
+ {{{localeScripts}}}
</head>
<!--
diff --git a/resources/frontend_client/index_template.html b/resources/frontend_client/index_template.html
index 65bf1c84e0b..109c5a604c4 100644
--- a/resources/frontend_client/index_template.html
+++ b/resources/frontend_client/index_template.html
@@ -33,12 +33,8 @@
{{{bootstrapJSON}}}
</script>
- <script type="application/json" id="_metabaseUserLocalization">
- {{{userLocalizationJSON}}}
- </script>
-
- <script type="application/json" id="_metabaseSiteLocalization">
- {{{siteLocalizationJSON}}}
+ <script type="application/json" id="_metabaseLocales">
+ {"user": "{{{userLocale}}}", "site": "{{{siteLocale}}}"}
</script>
<script type="application/json" id="_metabaseUserColorScheme">
@@ -50,6 +46,12 @@
The browser blanks the attribute after parsing, so the value stays out of the DOM. -->
<script type="text/javascript" nonce="{{{nonce}}}">{{{bootstrapJS}}}</script>
<script type="text/javascript">{{{assetOnErrorJS}}}</script>
+
+ <!-- The catalogue chunks this request needs. They install themselves, so the
+ app's `import()` of them resolves without a request. Below
+ index_bootstrap.js, which repairs <base href> when the Site URL setting
+ is wrong, and these resolve against it. -->
+ {{{localeScripts}}}
</head>
<body dir="ltr" class="mb-wrapper">
diff --git a/resources/frontend_client/inline_js/index_bootstrap.js b/resources/frontend_client/inline_js/index_bootstrap.js
index 81f33bae477..c011786d853 100644
--- a/resources/frontend_client/inline_js/index_bootstrap.js
+++ b/resources/frontend_client/inline_js/index_bootstrap.js
@@ -1,7 +1,8 @@
(function() {
window.MetabaseBootstrap = JSON.parse(document.getElementById("_metabaseBootstrap").textContent);
- window.MetabaseUserLocalization = JSON.parse(document.getElementById("_metabaseUserLocalization").textContent);
- window.MetabaseSiteLocalization = JSON.parse(document.getElementById("_metabaseSiteLocalization").textContent);
+ // Which catalogues the script tags below carry. The app applies them before
+ // its first render.
+ window.MetabaseLocales = JSON.parse(document.getElementById("_metabaseLocales").textContent);
window.MetabaseUserColorScheme = JSON.parse(document.getElementById("_metabaseUserColorScheme").textContent);
// Read from the script element, not from a JSON block: the browser blanks a nonce content attribute
// after parsing, so the value never stays readable in the DOM.
diff --git a/rspack.main.config.js b/rspack.main.config.js
index 417197d91ba..25f4619631d 100644
--- a/rspack.main.config.js
+++ b/rspack.main.config.js
@@ -30,6 +30,9 @@ const {
const {
DropStylesEntryScriptPlugin,
} = require("./frontend/build/shared/rspack/plugins/DropStylesEntryScriptPlugin");
+const {
+ LocaleCatalogManifest,
+} = require("./frontend/build/shared/rspack/plugins/LocaleCatalogManifest/locale-catalog-manifest");
const resolveConfig = require("./frontend/build/shared/rspack/resolve-config");
const {
SIDE_EFFECT_FREE_RULE,
@@ -354,6 +357,7 @@ const config = {
new OnScriptError(),
...(isDevMode ? [] : [new DropStylesEntryScriptPlugin()]),
new PreloadAssetTags(),
+ new LocaleCatalogManifest(),
new HtmlWebpackPlugin({
filename: "../../index.html",
chunksSortMode: "manual",
diff --git a/src/metabase/server/routes/index.clj b/src/metabase/server/routes/index.clj
index 8be197c56cf..757ef96853a 100644
--- a/src/metabase/server/routes/index.clj
+++ b/src/metabase/server/routes/index.clj
@@ -21,9 +21,7 @@
[metabase.util.memoize :as memoize]
[ring.util.codec :as codec]
[ring.util.response :as response]
- [stencil.core :as stencil])
- (:import
- (java.io FileNotFoundException)))
+ [stencil.core :as stencil]))
(set! *warn-on-reflection* true)
@@ -36,38 +34,47 @@
;; https://stackoverflow.com/questions/14780858/escape-in-script-tag-contents/23983448#23983448
(str/replace s #"(?i)</script" "</scr\\\\ipt"))
-(defn- fallback-localization [locale-or-name]
- (json/encode
- {"headers"
- {"language" (str locale-or-name)
- "plural-forms" "nplurals=2; plural=(n != 1);"}
-
- "translations"
- {"" {"Metabase" {"msgid" "Metabase"
- "msgstr" ["Metabase"]}}}}))
-
-(defn- localization-json-file-name [locale-string]
- (format "frontend_client/app/locales/%s.json" (str/replace locale-string \- \_)))
-
-(defn- load-localization* [locale-string]
- (or
- (when locale-string
- (when-not (= locale-string "en")
- (try
- (slurp (or (io/resource (localization-json-file-name locale-string))
- (when-let [fallback-locale (i18n/fallback-locale locale-string)]
- (io/resource (localization-json-file-name (str fallback-locale))))
- ;; don't try to i18n the Exception message below, we have no locale to translate it to!
- (throw (FileNotFoundException. (format "Locale '%s' not found." locale-string)))))
- (catch Throwable e
- (log/warn (.getMessage e))))))
- (fallback-localization locale-string)))
-
-(let [load-fn (memoize load-localization*)]
- (defn- load-localization
- "Load a JSON-encoded map of localized strings for the current user's Locale."
- [locale-override]
- (load-fn (or locale-override (i18n/user-locale-string)))))
+(defn- catalogue-name
+ "The catalogue chunks are named with an underscore, `locales.clj` lists them with a dash."
+ [locale-string]
+ (some-> locale-string (str/replace \- \_)))
+
+(def ^:private catalogue-names
+ (delay (into #{} (map catalogue-name) (i18n/available-locale-names))))
+
+(defn- catalogue-locale*
+ [locale-string]
+ ;; English short circuits: it is the msgid source, and its own fallback is the `en_ZZ` pseudo-locale.
+ (or (when-not (= (catalogue-name locale-string) "en")
+ (->> [locale-string (some-> (i18n/fallback-locale locale-string) str)]
+ (keep catalogue-name)
+ (remove #{"en"})
+ (filter @catalogue-names)
+ first))
+ "en"))
+
+(let [resolve-fn (memoize catalogue-locale*)]
+ (defn- catalogue-locale
+ "The locale whose catalogue the document should load, or `en` when there is none to load.
+ `en` is the msgid source and has no catalogue of its own."
+ [locale-string]
+ (resolve-fn locale-string)))
+
+(defn- locale-script-urls*
+ "Locale to catalogue chunk url, written by the frontend build. Empty when the frontend has not been built."
+ []
+ (some-> (io/resource "frontend_client/app/dist/locale-manifest.json") slurp json/decode))
+
+(def ^:private ^{:arglists '([])} locale-script-urls (memoize/memo locale-script-urls*))
+
+(defn- locale-scripts
+ "Script tags for the catalogue chunks this request needs.
+ `defer` keeps them off the parser: deferred scripts run in document order, and these precede
+ the bundle tags, so a catalogue is installed before the code that imports it."
+ [urls]
+ (->> urls
+ (map #(format "<script defer src=\"%s\"></script>" (hiccup.util/escape-html %)))
+ (str/join "\n ")))
(defn- load-inline-js* [resource-name]
(slurp (io/resource (format "frontend_client/inline_js/%s.js" resource-name))))
@@ -86,12 +93,20 @@
[embeddable? {:keys [uri params nonce]}]
(let [{:keys [anon-tracking-enabled google-auth-client-id], :as public-settings} (setting/user-readable-values-map #{:public})
;; We disable `locale` parameter on static embeds/public links (metabase#50313)
- should-load-locale-params? (not embeddable?)]
+ should-load-locale-params? (not embeddable?)
+ user-locale (catalogue-locale (or (when should-load-locale-params? (:locale params))
+ (i18n/user-locale-string)))
+ site-locale (catalogue-locale (system/site-locale))
+ ;; A map, so one tag when the user and the instance share a locale. English
+ ;; has no catalogue and so no entry, which is why this can be empty.
+ locale-urls (select-keys (or (locale-script-urls) {})
+ [user-locale site-locale])]
{:bootstrapJS (load-inline-js "index_bootstrap")
:bootstrapJSON (escape-script (json/encode public-settings))
:assetOnErrorJS (load-inline-js "asset_loading_error")
- :userLocalizationJSON (escape-script (load-localization (when should-load-locale-params? (:locale params))))
- :siteLocalizationJSON (escape-script (load-localization (system/site-locale)))
+ :userLocale (escape-script user-locale)
+ :siteLocale (escape-script site-locale)
+ :localeScripts (locale-scripts (vals locale-urls))
:nonce (hiccup.util/escape-html nonce)
:language (hiccup.util/escape-html (or (i18n/user-locale-string) (system/site-locale)))
:userColorScheme (escape-script (json/encode (users-settings/color-scheme)))
diff --git a/src/metabase/util/i18n.clj b/src/metabase/util/i18n.clj
index 3451abe46e8..49547d1a759 100644
--- a/src/metabase/util/i18n.clj
+++ b/src/metabase/util/i18n.clj
@@ -21,6 +21,7 @@
[i18n.common
join-strings-with-conjunction]
[i18n.impl
+ available-locale-names
available-locale?
fallback-locale
locale
diff --git a/test/metabase/server/routes/index_test.clj b/test/metabase/server/routes/index_test.clj
index c4f10dfde4b..4b108b3ab93 100644
--- a/test/metabase/server/routes/index_test.clj
+++ b/test/metabase/server/routes/index_test.clj
@@ -3,75 +3,40 @@
[clojure.test :refer :all]
[metabase.server.routes.index :as index]
[metabase.test :as mt]
- [metabase.util.i18n :as i18n]
- [metabase.util.json :as json]))
+ [metabase.util.i18n :as i18n]))
-(deftest ^:parallel localization-json-file-name-test
- (is (= "frontend_client/app/locales/es.json"
- (#'index/localization-json-file-name "es")))
- (is (= "frontend_client/app/locales/es_MX.json"
- (#'index/localization-json-file-name "es-MX"))))
+(deftest ^:parallel catalogue-locale-test
+ (testing "a locale with a catalogue resolves to itself (#9938)"
+ (is (= "es" (#'index/catalogue-locale "es")))
+ (is (= "pt_BR" (#'index/catalogue-locale "pt-BR"))))
+ (testing "a locale without a catalogue falls back to the one its language has"
+ (is (= "es" (#'index/catalogue-locale "es-MX"))))
+ (testing "english has no catalogue, it is the msgid source"
+ (is (= "en" (#'index/catalogue-locale "en"))))
+ (testing "an unknown locale falls back to english"
+ (is (= "en" (#'index/catalogue-locale "xx"))))
+ (testing "no locale at all falls back to english"
+ (is (= "en" (#'index/catalogue-locale nil)))))
-(deftest ^:parallel load-localization-test
- (testing "make sure `load-localization` is correctly loading i18n files (#9938)"
- (is (= {"charset" "utf-8"
- "headers" {"mime-version" "1.0"
- "content-type" "text/plain; charset=UTF-8"
- "content-transfer-encoding" "8bit"
- "x-generator" "POEditor.com"
- "project-id-version" "Metabase"
- "language" "es"
- "plural-forms" "nplurals=2; plural=(n != 1);"}
- "translations" {"" {"Your database has been added!" {"msgstr" ["¡Tu base de datos ha sido añadida!"]}}}}
- (some->
- (binding [i18n/*user-locale* "es_for_test"]
- (#'index/load-localization nil))
- json/decode
- (update "translations" select-keys [""])
- (update-in ["translations" ""] select-keys ["Your database has been added!"]))))))
+(deftest ^:parallel locale-scripts-test
+ (testing "deferred, so the parser is not blocked and document order still holds"
+ (is (= "<script defer src=\"app/dist/locale-es-json.abc123.js\"></script>"
+ (#'index/locale-scripts ["app/dist/locale-es-json.abc123.js"]))))
+ (testing "english needs none, and neither does a build that has not run"
+ (is (= "" (#'index/locale-scripts [])))))
-(deftest ^:parallel fallback-localization-test
- (testing "if locale does not exist it should log a message and return the 'fallback' localalization (english)"
- (is (= {"headers" {"language" "xx", "plural-forms" "nplurals=2; plural=(n != 1);"}
- "translations" {"" {"Metabase" {"msgid" "Metabase", "msgstr" ["Metabase"]}}}}
- (some->
- (binding [i18n/*user-locale* "xx"]
- (#'index/load-localization nil))
- json/decode)))))
-
-(deftest ^:parallel english-test
- (testing "english should return the fallback localization (english)"
- (is (= {"headers" {"language" "en", "plural-forms" "nplurals=2; plural=(n != 1);"}
- "translations" {"" {"Metabase" {"msgid" "Metabase", "msgstr" ["Metabase"]}}}}
- (some->
- (binding [i18n/*user-locale* "en"]
- (#'index/load-localization nil))
- json/decode)))))
-
-(deftest ^:parallel override-localization-test
- (testing "a valid override is honored no matter what the user locale is"
- (is (= {"charset" "utf-8"
- "headers" {"mime-version" "1.0"
- "content-type" "text/plain; charset=UTF-8"
- "content-transfer-encoding" "8bit"
- "x-generator" "POEditor.com"
- "project-id-version" "Metabase"
- "language" "es"
- "plural-forms" "nplurals=2; plural=(n != 1);"}
- "translations" {"" {"Your database has been added!" {"msgstr" ["¡Tu base de datos ha sido añadida!"]}}}}
- (some->
- (binding [i18n/*user-locale* "xx"]
- (#'index/load-localization "es_for_test"))
- json/decode
- (update "translations" select-keys [""])
- (update-in ["translations" ""] select-keys ["Your database has been added!"])))))
- (testing "an invalid override causes a fallback to English"
- (is (= {"headers" {"language" "yy", "plural-forms" "nplurals=2; plural=(n != 1);"}
- "translations" {"" {"Metabase" {"msgid" "Metabase", "msgstr" ["Metabase"]}}}}
- (some->
- (binding [i18n/*user-locale* "xx"]
- (#'index/load-localization "yy"))
- json/decode)))))
+(deftest template-locales-test
+ (testing "the document names the catalogues to load rather than carrying them"
+ (binding [i18n/*user-locale* "es"]
+ (is (= "es" (:userLocale (#'index/template-parameters false {})))))
+ (mt/with-temporary-setting-values [site-locale "es"]
+ (is (= "es" (:siteLocale (#'index/template-parameters false {}))))))
+ (testing "a locale url parameter overrides the user locale, except on static embeds"
+ (binding [i18n/*user-locale* "en"]
+ (is (= "es"
+ (:userLocale (#'index/template-parameters false {:params {:locale "es"}}))))
+ (is (= "en"
+ (:userLocale (#'index/template-parameters true {:params {:locale "es"}})))))))
(deftest load-entrypoint-template-contains-user-locale
(binding [i18n/*user-locale* "es"]