Skip to content

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

UX: Allow enabling the language switcher without `set_locale_from_cookie` (#42421)

Keegan George227978306fde
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index b92fcfb72a9..b06725895d9 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -3074,7 +3074,7 @@ en:
invalid_uncategorized_category_setting: 'The "Uncategorized" category cannot be selected if ''allow uncategorized topics'' is not enabled.'
invalid_search_ranking_weights: "Value is invalid for search_ranking_weights site setting. Example: '{0.1,0.2,0.3,1.0}'. Note that maximum value for each weight is 1.0."
content_localization_locale_limit: "The number of supported locales cannot exceed %{max}."
- content_localization_language_switcher_requirements: "The language switcher requires {{setting:set_locale_from_cookie}} and {{setting:allow_user_locale}} to be enabled, and {{setting:content_localization_supported_locales}} to have at least one language. {{settings:content_localization_language_switcher,set_locale_from_cookie,allow_user_locale,content_localization_supported_locales|All required settings}}"
+ content_localization_language_switcher_requirements: "The language switcher requires {{setting:allow_user_locale}} to be enabled, and {{setting:content_localization_supported_locales}} to have at least one language. {{settings:content_localization_language_switcher,allow_user_locale,content_localization_supported_locales|All required settings}}"
content_localization_crawler_param_requirements: "You must first enable 'set locale from param' before enabling this setting."
mediaconvert_role_arn_required: "AWS IAM role ARN is required when using AWS MediaConvert for video conversion."
mediaconvert_output_subdirectory_required: "MediaConvert output subdirectory is required."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index 67c15f27e17..f8c8dd8bc88 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -1934,6 +1934,8 @@ content_localization:
client: true
area: "localization"
validator: "LanguageSwitcherSettingValidator"
+ depends_on:
+ - "content_localization_enabled"
content_localization_allowed_groups:
type: group_list
list_type: compact
diff --git a/frontend/discourse/app/components/header/icons.gjs b/frontend/discourse/app/components/header/icons.gjs
index 9350f730028..2ebe4630077 100644
--- a/frontend/discourse/app/components/header/icons.gjs
+++ b/frontend/discourse/app/components/header/icons.gjs
@@ -5,6 +5,7 @@ import { service } from "@ember/service";
import InterfaceColorSelector from "discourse/components/interface-color-selector";
import LanguageSwitcher from "discourse/components/language-switcher";
import { ALL_PAGES_EXCLUDED_ROUTES } from "discourse/components/welcome-banner";
+import { languageSwitcherEnabled } from "discourse/lib/content-localization";
import DAG from "discourse/lib/dag";
import getURL from "discourse/lib/get-url";
import { eq } from "discourse/truth-helpers";
@@ -81,19 +82,15 @@ export default class Icons extends Component {
}
get showLanguageSwitcher() {
- if (!this.siteSettings.content_localization_enabled) {
+ if (!languageSwitcherEnabled(this.siteSettings)) {
return false;
}
- const has_locales =
- !!this.siteSettings.content_localization_supported_locales;
switch (this.siteSettings.content_localization_language_switcher) {
- case "none":
- return false;
case "anonymous":
- return !this.currentUser && has_locales;
+ return !this.currentUser;
case "all":
- return has_locales;
+ return true;
default:
return false;
}
diff --git a/frontend/discourse/app/components/language-switcher.gjs b/frontend/discourse/app/components/language-switcher.gjs
index 5186996e909..5f35dbf2dfc 100644
--- a/frontend/discourse/app/components/language-switcher.gjs
+++ b/frontend/discourse/app/components/language-switcher.gjs
@@ -4,7 +4,12 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import DMenu from "discourse/float-kit/components/d-menu";
import { ajax } from "discourse/lib/ajax";
+import {
+ LOCALE_COOKIE,
+ LOCALE_COOKIE_EXPIRY,
+} from "discourse/lib/content-localization";
import cookie from "discourse/lib/cookie";
+import getURL from "discourse/lib/get-url";
import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dIcon from "discourse/ui-kit/helpers/d-icon";
@@ -24,7 +29,10 @@ export default class LanguageSwitcher extends Component {
data: { locale },
});
} else {
- cookie("locale", locale, { path: "/" });
+ cookie(LOCALE_COOKIE, locale, {
+ path: getURL("/"),
+ expires: LOCALE_COOKIE_EXPIRY,
+ });
}
this.dMenu.close();
diff --git a/frontend/discourse/app/components/modal/content-language-preferences.gjs b/frontend/discourse/app/components/modal/content-language-preferences.gjs
index 5f03bf2d5b9..c8fa1d274a3 100644
--- a/frontend/discourse/app/components/modal/content-language-preferences.gjs
+++ b/frontend/discourse/app/components/modal/content-language-preferences.gjs
@@ -10,6 +10,9 @@ import {
AUTOMATICALLY_TRANSLATE_COOKIE,
AUTOMATICALLY_TRANSLATE_COOKIE_EXPIRY,
automaticallyTranslate,
+ languageSwitcherEnabled,
+ LOCALE_COOKIE,
+ LOCALE_COOKIE_EXPIRY,
normalizeUnderstoodLanguages,
} from "discourse/lib/content-localization";
import cookie from "discourse/lib/cookie";
@@ -41,18 +44,36 @@ export default class ContentLanguagePreferencesModal extends Component {
};
}
+ get allLanguageOptions() {
+ return this.#toOptions(this.siteSettings.available_locales);
+ }
+
get interfaceLanguageOptions() {
- return this.siteSettings.available_locales.map(({ value }) => ({
- name: this.languageNameLookup.getLanguageName(value),
- value,
- id: value,
- }));
+ // Anonymous visitors change locale through the `locale` cookie. When the language switcher is
+ // what makes that cookie honoured, the server only accepts the site's configured locales, so
+ // offering the rest would silently discard the choice.
+ if (
+ !this.currentUser &&
+ !this.siteSettings.set_locale_from_cookie &&
+ languageSwitcherEnabled(this.siteSettings)
+ ) {
+ return this.#toOptions(
+ this.siteSettings.available_content_localization_locales
+ );
+ }
+
+ return this.allLanguageOptions;
}
get canChangeInterfaceLanguage() {
+ if (!this.siteSettings.allow_user_locale) {
+ return false;
+ }
+
return (
- this.siteSettings.allow_user_locale &&
- (this.currentUser || this.siteSettings.set_locale_from_cookie)
+ !!this.currentUser ||
+ this.siteSettings.set_locale_from_cookie ||
+ languageSwitcherEnabled(this.siteSettings)
);
}
@@ -64,6 +85,14 @@ export default class ContentLanguagePreferencesModal extends Component {
return getURL("/login");
}
+ #toOptions(locales) {
+ return (locales ?? []).map(({ value }) => ({
+ name: this.languageNameLookup.getLanguageName(value),
+ value,
+ id: value,
+ }));
+ }
+
@action
registerFormApi(formApi) {
this.formApi = formApi;
@@ -121,7 +150,10 @@ export default class ContentLanguagePreferencesModal extends Component {
);
} else {
if (this.canChangeInterfaceLanguage) {
- cookie("locale", data.interfaceLanguage, { path: "/" });
+ cookie(LOCALE_COOKIE, data.interfaceLanguage, {
+ path: getURL("/"),
+ expires: LOCALE_COOKIE_EXPIRY,
+ });
}
cookie(AUTOMATICALLY_TRANSLATE_COOKIE, data.automaticallyTranslate, {
path: "/",
@@ -141,6 +173,7 @@ export default class ContentLanguagePreferencesModal extends Component {
<DModal
@title={{i18n "content_localization.preferences.title"}}
@closeModal={{@closeModal}}
+ @inline={{@inline}}
class="content-language-preferences-modal"
>
<:body>
@@ -186,7 +219,7 @@ export default class ContentLanguagePreferencesModal extends Component {
<MultiSelect
@valueProperty="value"
@langProperty="value"
- @content={{this.interfaceLanguageOptions}}
+ @content={{this.allLanguageOptions}}
@value={{field.value}}
@onChange={{field.set}}
@options={{hash filterable=true}}
diff --git a/frontend/discourse/app/lib/content-localization.js b/frontend/discourse/app/lib/content-localization.js
index 048193054ef..c1a5b34d582 100644
--- a/frontend/discourse/app/lib/content-localization.js
+++ b/frontend/discourse/app/lib/content-localization.js
@@ -2,6 +2,27 @@ import cookie from "discourse/lib/cookie";
export const AUTOMATICALLY_TRANSLATE_COOKIE = "automatically_translate";
export const AUTOMATICALLY_TRANSLATE_COOKIE_EXPIRY = 30;
+export const LOCALE_COOKIE = "locale";
+export const LOCALE_COOKIE_EXPIRY = 365;
+
+/**
+ * Whether the site offers anonymous visitors a way to pick their own locale.
+ *
+ * Mirrors `ContentLocalization.language_switcher_enabled?` server-side, which is what decides
+ * whether the `locale` cookie is honoured. Keep the two in sync: a cookie that is honoured
+ * without the corresponding UI leaves visitors stuck in a locale they cannot change back.
+ *
+ * @param {Object} siteSettings - the siteSettings service
+ * @returns {boolean}
+ */
+export function languageSwitcherEnabled(siteSettings) {
+ return (
+ siteSettings.content_localization_enabled &&
+ siteSettings.allow_user_locale &&
+ siteSettings.content_localization_language_switcher !== "none" &&
+ !!siteSettings.content_localization_supported_locales
+ );
+}
export function normalizeUnderstoodLanguages(languages) {
return [...new Set((languages ?? []).filter(Boolean))];
diff --git a/frontend/discourse/tests/integration/components/header-icons-test.gjs b/frontend/discourse/tests/integration/components/header-icons-test.gjs
index 01404dbb2f0..2f313cf2898 100644
--- a/frontend/discourse/tests/integration/components/header-icons-test.gjs
+++ b/frontend/discourse/tests/integration/components/header-icons-test.gjs
@@ -103,6 +103,32 @@ module("Integration | Component | Header | Icons", function (hooks) {
);
});
+ test("the language switcher needs user locales to be allowed", async function (assert) {
+ const noop = () => {};
+ this.siteSettings.content_localization_enabled = true;
+ this.siteSettings.content_localization_supported_locales = "en|fr";
+ this.siteSettings.content_localization_language_switcher = "all";
+ this.siteSettings.allow_user_locale = false;
+
+ await render(
+ <template>
+ <Icons
+ @sidebarEnabled={{true}}
+ @toggleSearchMenu={{noop}}
+ @toggleNavigationMenu={{noop}}
+ @toggleUserMenu={{noop}}
+ @searchButtonId={{SEARCH_BUTTON_ID}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".language-switcher-trigger")
+ .doesNotExist(
+ "switching language would have no effect, so the switcher is hidden"
+ );
+ });
+
test("every header icon is a list item", async function (assert) {
const noop = () => {};
this.siteSettings.content_localization_enabled = true;
diff --git a/frontend/discourse/tests/integration/components/modal/content-language-preferences-test.gjs b/frontend/discourse/tests/integration/components/modal/content-language-preferences-test.gjs
new file mode 100644
index 00000000000..71c865e0faa
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/modal/content-language-preferences-test.gjs
@@ -0,0 +1,99 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import ContentLanguagePreferences from "discourse/components/modal/content-language-preferences";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+const ALL_LOCALES = [
+ { name: "English", value: "en" },
+ { name: "Español", value: "es" },
+ { name: "Français", value: "fr" },
+ { name: "日本語", value: "ja" },
+];
+
+const CONFIGURED_LOCALES = [
+ { name: "English", value: "en" },
+ { name: "Español", value: "es" },
+];
+
+module(
+ "Integration | Component | Modal | content-language-preferences",
+ function (hooks) {
+ // The interface language field is only editable by anonymous visitors when something
+ // honours the `locale` cookie, so these cases have to run without a current user.
+ setupRenderingTest(hooks, { anonymous: true });
+
+ hooks.beforeEach(function () {
+ this.siteSettings.available_locales = ALL_LOCALES;
+ this.siteSettings.available_content_localization_locales =
+ CONFIGURED_LOCALES;
+ this.siteSettings.allow_user_locale = true;
+ });
+
+ const noop = () => {};
+
+ test("anonymous visitors only get the locales the switcher honours", async function (assert) {
+ this.siteSettings.set_locale_from_cookie = false;
+ this.siteSettings.content_localization_enabled = true;
+ this.siteSettings.content_localization_supported_locales = "es";
+ this.siteSettings.content_localization_language_switcher = "all";
+
+ await render(
+ <template>
+ <ContentLanguagePreferences @closeModal={{noop}} @inline={{true}} />
+ </template>
+ );
+
+ assert
+ .dom(".content-language-preferences-modal select")
+ .exists({ count: 1 });
+ assert
+ .dom(".content-language-preferences-modal select option")
+ .exists(
+ { count: 2 },
+ "only the configured locales are offered, since the server discards the rest"
+ );
+ assert.dom(".content-language-preferences-modal select").isNotDisabled();
+ });
+
+ test("set_locale_from_cookie keeps the full locale list", async function (assert) {
+ this.siteSettings.set_locale_from_cookie = true;
+ this.siteSettings.content_localization_enabled = true;
+ this.siteSettings.content_localization_supported_locales = "es";
+ this.siteSettings.content_localization_language_switcher = "none";
+
+ await render(
+ <template>
+ <ContentLanguagePreferences @closeModal={{noop}} @inline={{true}} />
+ </template>
+ );
+
+ assert
+ .dom(".content-language-preferences-modal select option")
+ .exists(
+ { count: 4 },
+ "the server honours any available locale, so offer them all"
+ );
+ });
+
+ test("the interface language is read-only when nothing honours the cookie", async function (assert) {
+ this.siteSettings.set_locale_from_cookie = false;
+ this.siteSettings.content_localization_enabled = true;
+ this.siteSettings.content_localization_supported_locales = "es";
+ this.siteSettings.content_localization_language_switcher = "none";
+
+ await render(
+ <template>
+ <ContentLanguagePreferences @closeModal={{noop}} @inline={{true}} />
+ </template>
+ );
+
+ assert.dom(".content-language-preferences-modal select").isDisabled();
+ assert
+ .dom(".content-language-preferences-modal select option")
+ .exists(
+ { count: 4 },
+ "the read-only field still shows the full list so the current locale resolves"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/unit/lib/content-localization-test.js b/frontend/discourse/tests/unit/lib/content-localization-test.js
index 04e62920d9b..85c8723e6f0 100644
--- a/frontend/discourse/tests/unit/lib/content-localization-test.js
+++ b/frontend/discourse/tests/unit/lib/content-localization-test.js
@@ -3,6 +3,7 @@ import { module, test } from "qunit";
import {
AUTOMATICALLY_TRANSLATE_COOKIE,
automaticallyTranslate,
+ languageSwitcherEnabled,
normalizeUnderstoodLanguages,
} from "discourse/lib/content-localization";
import cookie, { removeCookie } from "discourse/lib/cookie";
@@ -62,4 +63,50 @@ module("Unit | Lib | content-localization", function (hooks) {
"the interface language does not change explicit selections"
);
});
+
+ test("resolves whether the language switcher is available", function (assert) {
+ const settings = {
+ content_localization_enabled: true,
+ allow_user_locale: true,
+ content_localization_language_switcher: "all",
+ content_localization_supported_locales: "es|fr",
+ };
+
+ assert.true(
+ languageSwitcherEnabled(settings),
+ "a fully configured site offers the switcher"
+ );
+ assert.true(
+ languageSwitcherEnabled({
+ ...settings,
+ content_localization_language_switcher: "anonymous",
+ }),
+ "the anonymous audience still counts as enabled"
+ );
+ assert.false(
+ languageSwitcherEnabled({
+ ...settings,
+ content_localization_language_switcher: "none",
+ }),
+ "the switcher can be turned off"
+ );
+ assert.false(
+ languageSwitcherEnabled({
+ ...settings,
+ content_localization_enabled: false,
+ }),
+ "it requires content localization"
+ );
+ assert.false(
+ languageSwitcherEnabled({ ...settings, allow_user_locale: false }),
+ "it requires user locales to be allowed"
+ );
+ assert.false(
+ languageSwitcherEnabled({
+ ...settings,
+ content_localization_supported_locales: "",
+ }),
+ "it requires at least one configured locale"
+ );
+ });
});
diff --git a/lib/content_localization.rb b/lib/content_localization.rb
index 8e087547ff1..83ea383c9fe 100644
--- a/lib/content_localization.rb
+++ b/lib/content_localization.rb
@@ -83,4 +83,13 @@ class ContentLocalization
SiteSetting.content_localization_enabled && SiteSetting.content_localization_crawler_param &&
SiteSetting.set_locale_from_param
end
+
+ # These are the same conditions the header renders the switcher on. Keeping the two set-equal
+ # means a locale cookie is only ever honoured while there is UI to change it back.
+ # @return [Boolean]
+ def self.language_switcher_enabled?
+ SiteSetting.content_localization_enabled && SiteSetting.allow_user_locale &&
+ SiteSetting.content_localization_language_switcher != "none" &&
+ SiteSetting.content_localization_supported_locales.present?
+ end
end
diff --git a/lib/discourse.rb b/lib/discourse.rb
index 81252e1d1cd..c6e6056dc9a 100644
--- a/lib/discourse.rb
+++ b/lib/discourse.rb
@@ -1350,12 +1350,26 @@ module Discourse
def self.anonymous_locale(request)
locale = request.params[LOCALE_PARAM] if SiteSetting.set_locale_from_param
- locale ||= request.cookies["locale"] if SiteSetting.set_locale_from_cookie
+ locale ||= locale_from_cookie(request)
locale ||=
request.env["HTTP_ACCEPT_LANGUAGE"] if SiteSetting.set_locale_from_accept_language_header
HttpLanguageParser.parse(locale)
end
+ def self.locale_from_cookie(request)
+ cookie = request.cookies["locale"]
+ return if cookie.blank?
+ return cookie if SiteSetting.set_locale_from_cookie
+
+ # The language switcher writes this cookie, so reading it back needs no separate opt-in.
+ # Restricted to the configured locales so anonymous cache variance stays bounded by the
+ # site's own locale list rather than every available locale.
+ if ContentLocalization.language_switcher_enabled? &&
+ SiteSetting.content_localization_locales.include?(cookie)
+ cookie
+ end
+ end
+
# For test environment only
def self.enable_sidekiq_logging
@@sidekiq_logging_enabled = true
diff --git a/lib/validators/language_switcher_setting_validator.rb b/lib/validators/language_switcher_setting_validator.rb
index 9ac4410f2cf..d60d78a1cf3 100644
--- a/lib/validators/language_switcher_setting_validator.rb
+++ b/lib/validators/language_switcher_setting_validator.rb
@@ -7,8 +7,7 @@ class LanguageSwitcherSettingValidator
def valid_value?(val)
return true if val == "none"
- SiteSetting.set_locale_from_cookie && SiteSetting.allow_user_locale &&
- SiteSetting.content_localization_supported_locales.present?
+ SiteSetting.allow_user_locale && SiteSetting.content_localization_supported_locales.present?
end
def error_message
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-translations.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-translations.gjs
index ae87199a736..1a81f33f6f7 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-translations.gjs
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-translations.gjs
@@ -14,7 +14,7 @@ import Category from "discourse/models/category";
import CategorySelector from "discourse/select-kit/components/category-selector";
import ComboBox from "discourse/select-kit/components/combo-box";
import MultiSelect from "discourse/select-kit/components/multi-select";
-import { eq } from "discourse/truth-helpers";
+import { eq, not } from "discourse/truth-helpers";
import DAsyncContent from "discourse/ui-kit/d-async-content";
import DButton from "discourse/ui-kit/d-button";
import DPageSubheader from "discourse/ui-kit/d-page-subheader";
@@ -41,6 +41,12 @@ export default class AiTranslations extends Component {
this.args.model?.translation_enabled &&
!this.args.model?.no_locales_configured;
@tracked enabled = this.args.model?.enabled;
+ // Pre-checked during first-time setup so enabling translations also surfaces the switcher;
+ // reflects the real setting once translations are already on.
+ @tracked
+ languageSwitcherRequested =
+ this.siteSettings.content_localization_language_switcher !== "none" ||
+ !this.translationEnabled;
@tracked
selectedLocales = this.siteSettings.content_localization_supported_locales
? this.siteSettings.content_localization_supported_locales.split("|")
@@ -171,6 +177,10 @@ export default class AiTranslations extends Component {
);
}
+ get languageSwitcherValue() {
+ return this.languageSwitcherRequested ? "all" : "none";
+ }
+
get availableLocales() {
const locales = this.siteSettings.available_locales;
if (!locales) {
@@ -296,6 +306,32 @@ export default class AiTranslations extends Component {
this.categories = [];
}
+ @action
+ async toggleLanguageSwitcher(event) {
+ const previous = this.languageSwitcherRequested;
+ this.languageSwitcherRequested = event.target.checked;
+
+ // Not yet enabled: the value is applied together with the enable toggle.
+ if (!this.translationEnabled) {
+ return;
+ }
+
+ try {
+ await ajax(
+ "/admin/site_settings/content_localization_language_switcher",
+ {
+ type: "PUT",
+ data: {
+ content_localization_language_switcher: this.languageSwitcherValue,
+ },
+ }
+ );
+ } catch (e) {
+ this.languageSwitcherRequested = previous;
+ popupAjaxError(e);
+ }
+ }
+
@action
async toggleTranslationEnabled() {
if (this.isTogglingTranslation) {
@@ -309,16 +345,24 @@ export default class AiTranslations extends Component {
this.isTogglingTranslation = true;
try {
if (!this.translationEnabled && this.hasSavedLocales) {
- await ajax("/admin/site_settings/content_localization_enabled", {
+ await ajax("/admin/site_settings/bulk_update", {
type: "PUT",
- data: { content_localization_enabled: true },
+ data: {
+ settings: {
+ content_localization_enabled: { value: true },
+ content_localization_language_switcher: {
+ value: this.languageSwitcherValue,
+ },
+ ai_translation_enabled: { value: true },
+ },
+ },
+ });
+ } else {
+ await ajax("/admin/site_settings/ai_translation_enabled", {
+ type: "PUT",
+ data: { ai_translation_enabled: false },
});
}
-
- await ajax("/admin/site_settings/ai_translation_enabled", {
- type: "PUT",
- data: { ai_translation_enabled: !this.translationEnabled },
- });
this.translationEnabled = !this.translationEnabled;
if (this.translationEnabled && this.hasSavedLocales) {
@@ -651,6 +695,22 @@ export default class AiTranslations extends Component {
</div>
</div>
</div>
+ <div class="setting ai-translations__language-switcher">
+ <label class="checkbox-label">
+ <input
+ type="checkbox"
+ checked={{this.languageSwitcherRequested}}
+ disabled={{not this.hasSavedLocales}}
+ {{on "input" this.toggleLanguageSwitcher}}
+ />
+ <span>{{i18n
+ "discourse_ai.translations.admin_actions.show_language_switcher"
+ }}</span>
+ </label>
+ <div class="desc">{{i18n
+ "discourse_ai.translations.admin_actions.show_language_switcher_description"
+ }}</div>
+ </div>
<div class="setting ai-translations__toggle-container">
{{#if this.toggleDisabledReason}}
<DTooltip
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/translation/admin/translations.scss b/plugins/discourse-ai/assets/stylesheets/modules/translation/admin/translations.scss
index 8d4b8188a1d..0baa5b7cfbf 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/translation/admin/translations.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/translation/admin/translations.scss
@@ -6,6 +6,10 @@
border-radius: var(--d-border-radius);
}
+ &__language-switcher {
+ margin-block: var(--space-3);
+ }
+
&__toggle-container {
margin-block-end: var(--space-3);
}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index bcf84d6a5a0..c924ec7a6a6 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -521,6 +521,8 @@ en:
localization_settings: "App language settings"
enable_translations: "Enable automatic translations"
enable_translations_disabled: "You must add a supported language to enable translations"
+ show_language_switcher: "Show a language switcher in the header"
+ show_language_switcher_description: "Lets everyone pick a language and see your site in it."
stats:
title: "Translation statistics"
backfill_disabled: "Backfilling is disabled, only new posts will be translated."
diff --git a/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb
index d42ac8928f3..318eb4c5c54 100644
--- a/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb
+++ b/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb
@@ -284,6 +284,32 @@ describe "Admin AI translations" do
expect(translations_page).to have_no_overview_cards
end
+ it "enables the language switcher along with translations" do
+ SiteSetting.ai_translation_enabled = false
+ SiteSetting.content_localization_language_switcher = "none"
+
+ translations_page.visit
+
+ expect(translations_page.language_switcher_checkbox).to be_checked
+ translations_page.toggle_translations
+
+ wait_for { SiteSetting.ai_translation_enabled }
+ expect(SiteSetting.content_localization_enabled).to eq(true)
+ expect(SiteSetting.content_localization_language_switcher).to eq("all")
+ end
+
+ it "leaves the language switcher off when the admin opts out" do
+ SiteSetting.ai_translation_enabled = false
+ SiteSetting.content_localization_language_switcher = "none"
+
+ translations_page.visit
+ translations_page.language_switcher_checkbox.click
+ translations_page.toggle_translations
+
+ wait_for { SiteSetting.ai_translation_enabled }
+ expect(SiteSetting.content_localization_language_switcher).to eq("none")
+ end
+
it "keeps toggle disabled when no locales are configured" do
SiteSetting.ai_translation_enabled = false
SiteSetting.content_localization_supported_locales = ""
diff --git a/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_translations.rb b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_translations.rb
index 6df560ef45d..2366aaed779 100644
--- a/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_translations.rb
+++ b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_translations.rb
@@ -59,6 +59,17 @@ module PageObjects
)
end
+ def toggle_translations
+ PageObjects::Components::DToggleSwitch.new(
+ ".ai-translations__toggle-container .d-toggle-switch__checkbox",
+ ).toggle
+ self
+ end
+
+ def language_switcher_checkbox
+ page.find(".ai-translations__language-switcher input[type='checkbox']")
+ end
+
def has_locale_selector?
page.has_css?(".ai-translations__settings-panel .multi-select")
end
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-translations-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-translations-test.gjs
index a9caccfb09c..555379ad524 100644
--- a/plugins/discourse-ai/test/javascripts/integration/components/ai-translations-test.gjs
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-translations-test.gjs
@@ -132,9 +132,7 @@ module("Integration | Component | AiTranslations", function (hooks) {
pretender.put("/admin/site_settings/ai_translation_enabled", () =>
response({})
);
- pretender.put("/admin/site_settings/content_localization_enabled", () =>
- response({})
- );
+ pretender.put("/admin/site_settings/bulk_update", () => response({}));
await render(<template><AiTranslations @model={{this.model}} /></template>);
@@ -199,6 +197,69 @@ module("Integration | Component | AiTranslations", function (hooks) {
.isDisabled("the toggle stays disabled after saving no locales");
});
+ test("enables the language switcher along with translations", async function (assert) {
+ let bulkUpdate;
+ this.model = {
+ ...this.model,
+ enabled: false,
+ translation_enabled: false,
+ };
+ this.siteSettings.content_localization_language_switcher = "none";
+ pretender.put("/admin/site_settings/bulk_update", (request) => {
+ bulkUpdate = decodeURIComponent(request.requestBody);
+ return response({});
+ });
+
+ await render(<template><AiTranslations @model={{this.model}} /></template>);
+
+ assert
+ .dom(".ai-translations__language-switcher input[type='checkbox']")
+ .isChecked("first-time setup opts into the switcher by default");
+
+ await click(
+ ".ai-translations__toggle-container .d-toggle-switch__checkbox"
+ );
+
+ assert.true(
+ bulkUpdate.includes(
+ "settings[content_localization_language_switcher][value]=all"
+ ),
+ "enabling translations turns the switcher on in the same request"
+ );
+ assert.true(
+ bulkUpdate.includes("settings[ai_translation_enabled][value]=true"),
+ "translations are enabled in the same request"
+ );
+ });
+
+ test("respects opting out of the language switcher before enabling", async function (assert) {
+ let bulkUpdate;
+ this.model = {
+ ...this.model,
+ enabled: false,
+ translation_enabled: false,
+ };
+ this.siteSettings.content_localization_language_switcher = "none";
+ pretender.put("/admin/site_settings/bulk_update", (request) => {
+ bulkUpdate = decodeURIComponent(request.requestBody);
+ return response({});
+ });
+
+ await render(<template><AiTranslations @model={{this.model}} /></template>);
+
+ await click(".ai-translations__language-switcher input[type='checkbox']");
+ await click(
+ ".ai-translations__toggle-container .d-toggle-switch__checkbox"
+ );
+
+ assert.true(
+ bulkUpdate.includes(
+ "settings[content_localization_language_switcher][value]=none"
+ ),
+ "the switcher stays off when the admin unchecks it"
+ );
+ });
+
test("shows the fixed backfill start date", async function (assert) {
this.owner.lookup("service:router").urlFor = () =>
"/admin/plugins/discourse-ai/ai-features/6/edit";
diff --git a/spec/lib/discourse_spec.rb b/spec/lib/discourse_spec.rb
index eb08e8fecda..e6736321d65 100644
--- a/spec/lib/discourse_spec.rb
+++ b/spec/lib/discourse_spec.rb
@@ -783,4 +783,75 @@ RSpec.describe Discourse do
expect(css).to include("url(#{new_upload_url})")
end
end
+
+ describe ".anonymous_locale" do
+ def locale_for(cookie: nil, path: "/")
+ env = cookie ? { "HTTP_COOKIE" => "locale=#{cookie}" } : {}
+ Discourse.anonymous_locale(ActionDispatch::Request.new(Rack::MockRequest.env_for(path, env)))
+ end
+
+ before do
+ SiteSetting.default_locale = "en"
+ SiteSetting.allow_user_locale = true
+ end
+
+ it "ignores the locale cookie by default" do
+ expect(locale_for(cookie: "es")).to eq("en")
+ end
+
+ context "when set_locale_from_cookie is enabled" do
+ before { SiteSetting.set_locale_from_cookie = true }
+
+ it "honours any available locale, even one that is not a supported content locale" do
+ SiteSetting.content_localization_supported_locales = "fr"
+
+ expect(locale_for(cookie: "es")).to eq("es")
+ end
+ end
+
+ context "when the language switcher is enabled" do
+ before do
+ SiteSetting.set_locale_from_cookie = false
+ SiteSetting.content_localization_supported_locales = "es|fr"
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_language_switcher = "all"
+ end
+
+ it "honours the locale cookie without set_locale_from_cookie" do
+ expect(locale_for(cookie: "es")).to eq("es")
+ end
+
+ it "honours the default locale, which the switcher also offers" do
+ expect(locale_for(cookie: "en")).to eq("en")
+ end
+
+ it "ignores an available locale that is not configured for this site" do
+ expect(locale_for(cookie: "ja")).to eq("en")
+ end
+
+ it "ignores the cookie once the switcher is turned off" do
+ SiteSetting.content_localization_language_switcher = "none"
+
+ expect(locale_for(cookie: "es")).to eq("en")
+ end
+
+ it "ignores the cookie when content localization is disabled" do
+ SiteSetting.content_localization_enabled = false
+
+ expect(locale_for(cookie: "es")).to eq("en")
+ end
+
+ it "ignores the cookie when user locales are not allowed" do
+ SiteSetting.allow_user_locale = false
+
+ expect(locale_for(cookie: "es")).to eq("en")
+ end
+
+ it "still prefers the locale param over the cookie" do
+ SiteSetting.set_locale_from_param = true
+
+ expect(locale_for(cookie: "es", path: "/?tl=fr")).to eq("fr")
+ end
+ end
+ end
end
diff --git a/spec/lib/middleware/anonymous_cache_spec.rb b/spec/lib/middleware/anonymous_cache_spec.rb
index 83da8517d77..12617a4d0bf 100644
--- a/spec/lib/middleware/anonymous_cache_spec.rb
+++ b/spec/lib/middleware/anonymous_cache_spec.rb
@@ -117,6 +117,33 @@ RSpec.describe Middleware::AnonymousCache do
SiteSetting.set_locale_from_cookie = true
expect(new_helper("HTTP_COOKIE" => "locale=es;").cache_key).to include("l=es")
end
+
+ it "keys on the locale cookie when the language switcher is enabled" do
+ SiteSetting.default_locale = "en"
+ SiteSetting.allow_user_locale = true
+ SiteSetting.set_locale_from_cookie = false
+ SiteSetting.content_localization_supported_locales = "es|fr"
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_language_switcher = "all"
+
+ expect(new_helper("HTTP_COOKIE" => "locale=es;").cache_key).to include("l=es")
+
+ # An unsupported locale is not honoured, so it must not fan the cache out either.
+ expect(new_helper("HTTP_COOKIE" => "locale=ja;").cache_key).to eq(new_helper.cache_key)
+ end
+
+ it "keys on the same locale the request renders in" do
+ SiteSetting.default_locale = "en"
+ SiteSetting.allow_user_locale = true
+ SiteSetting.content_localization_supported_locales = "es"
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_language_switcher = "all"
+
+ env = { "HTTP_COOKIE" => "locale=es;" }
+ request = ActionDispatch::Request.new(Rack::MockRequest.env_for("/", env))
+
+ expect(new_helper(env).cache_key).to include("l=#{Discourse.anonymous_locale(request)}")
+ end
end
it "handles old browsers" do
diff --git a/spec/lib/validators/language_switcher_setting_validator_spec.rb b/spec/lib/validators/language_switcher_setting_validator_spec.rb
new file mode 100644
index 00000000000..b08ed7e0654
--- /dev/null
+++ b/spec/lib/validators/language_switcher_setting_validator_spec.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+RSpec.describe LanguageSwitcherSettingValidator do
+ subject(:validator) { described_class.new }
+
+ it "always allows disabling the switcher" do
+ SiteSetting.allow_user_locale = false
+ SiteSetting.content_localization_supported_locales = ""
+
+ expect(validator.valid_value?("none")).to eq(true)
+ end
+
+ context "when enabling the switcher" do
+ before { SiteSetting.content_localization_supported_locales = "es|fr" }
+
+ it "does not require the locale cookie setting" do
+ SiteSetting.set_locale_from_cookie = false
+
+ expect(validator.valid_value?("all")).to eq(true)
+ expect(validator.valid_value?("anonymous")).to eq(true)
+ end
+
+ it "requires allow_user_locale" do
+ SiteSetting.allow_user_locale = false
+
+ expect(validator.valid_value?("all")).to eq(false)
+ end
+
+ it "requires at least one supported locale" do
+ SiteSetting.content_localization_supported_locales = ""
+
+ expect(validator.valid_value?("all")).to eq(false)
+ end
+ end
+
+ it "links the remaining requirements from its error message" do
+ expect(validator.error_message).to include(
+ "{{setting:allow_user_locale}}",
+ "{{setting:content_localization_supported_locales}}",
+ )
+ expect(validator.error_message).not_to include("set_locale_from_cookie")
+ end
+end
diff --git a/spec/requests/admin/site_settings_controller_spec.rb b/spec/requests/admin/site_settings_controller_spec.rb
index ab83632dde4..bd9922f3fc2 100644
--- a/spec/requests/admin/site_settings_controller_spec.rb
+++ b/spec/requests/admin/site_settings_controller_spec.rb
@@ -721,7 +721,7 @@ RSpec.describe Admin::SiteSettingsController do
end
it "returns html_message: true with linkified errors when a validator message references settings" do
- SiteSetting.set_locale_from_cookie = false
+ SiteSetting.allow_user_locale = false
put "/admin/site_settings/content_localization_language_switcher.json",
params: {
@@ -738,12 +738,12 @@ RSpec.describe Admin::SiteSettingsController do
end
it "keeps the exception message plain text for non-admin-UI consumers" do
- SiteSetting.set_locale_from_cookie = false
+ SiteSetting.allow_user_locale = false
expect { SiteSetting.set("content_localization_language_switcher", "all") }.to raise_error(
Discourse::InvalidHTMLParameters,
) do |error|
- expect(error.message).to include("'Set locale from cookie'")
+ expect(error.message).to include("'Allow user locale'")
expect(error.message).not_to include("<a", "{{setting")
expect(error.html_message).to include('class="site-setting-link"')
end
diff --git a/spec/requests/application_controller_spec.rb b/spec/requests/application_controller_spec.rb
index 3054c1443ec..bb7fc380eb2 100644
--- a/spec/requests/application_controller_spec.rb
+++ b/spec/requests/application_controller_spec.rb
@@ -1576,6 +1576,53 @@ RSpec.describe ApplicationController do
end
end
+ context "with the language switcher enabled and set_locale_from_cookie disabled" do
+ before do
+ SiteSetting.allow_user_locale = true
+ SiteSetting.default_locale = "en"
+ SiteSetting.set_locale_from_cookie = false
+ SiteSetting.content_localization_supported_locales = "es|fr"
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_language_switcher = "all"
+ end
+
+ context "with an anonymous user" do
+ it "uses the locale from the cookie" do
+ get "/latest", headers: { Cookie: "locale=es" }
+ expect(response.status).to eq(200)
+ expect(main_locale_scripts(response.body)).to contain_exactly("es")
+ end
+
+ it "ignores a locale the site has not configured" do
+ get "/latest", headers: { Cookie: "locale=ja" }
+ expect(response.status).to eq(200)
+ expect(main_locale_scripts(response.body)).to contain_exactly("en")
+ end
+
+ it "ignores the cookie once the switcher is turned off" do
+ SiteSetting.content_localization_language_switcher = "none"
+
+ get "/latest", headers: { Cookie: "locale=es" }
+ expect(response.status).to eq(200)
+ expect(main_locale_scripts(response.body)).to contain_exactly("en")
+ end
+ end
+
+ context "with a logged-in user" do
+ fab!(:user) { Fabricate(:user, locale: "fr") }
+
+ it "ignores the cookie and uses the user's preference" do
+ sign_in(user)
+ # Set through the jar rather than a Cookie header, which would drop the auth cookie.
+ cookies[:locale] = "es"
+
+ get "/latest"
+ expect(response.status).to eq(200)
+ expect(main_locale_scripts(response.body)).to contain_exactly("fr")
+ end
+ end
+ end
+
context "with set_locale_from_param" do
context "when param locale differs from default locale" do
before do
diff --git a/spec/system/content_localization_language_switcher_spec.rb b/spec/system/content_localization_language_switcher_spec.rb
index f165f5da037..5da147df9df 100644
--- a/spec/system/content_localization_language_switcher_spec.rb
+++ b/spec/system/content_localization_language_switcher_spec.rb
@@ -32,7 +32,6 @@ describe "Content localization language switcher" do
SiteSetting.content_localization_supported_locales = "es|ja"
SiteSetting.content_localization_enabled = true
SiteSetting.allow_user_locale = true
- SiteSetting.set_locale_from_cookie = true
Fabricate(:topic_localization, topic:, locale: "ja", fancy_title: "孫子兵法からの人生戦略")
Fabricate(
@@ -100,6 +99,16 @@ describe "Content localization language switcher" do
expect(page).to have_css(switcher_selector)
end
+ it "lets anonymous visitors switch language when set_locale_from_cookie is also enabled" do
+ SiteSetting.set_locale_from_cookie = true
+ SiteSetting.content_localization_language_switcher = "anonymous"
+
+ visit("/")
+ language_switcher.select_language("es")
+
+ expect(topic_list).to have_content("Estrategias de vida de El arte de la guerra")
+ end
+
it "displays the current language code on the trigger button" do
SiteSetting.content_localization_language_switcher = "all"