Skip to content

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

FEATURE: Translate theme component translatable fields (#39282)

Natalie Tayd5173c62b534
diff --git a/app/assets/stylesheets/admin/customize.scss b/app/assets/stylesheets/admin/customize.scss
index 6efae03c06e..6d76c9780ed 100644
--- a/app/assets/stylesheets/admin/customize.scss
+++ b/app/assets/stylesheets/admin/customize.scss
@@ -254,6 +254,13 @@
width: auto;
margin-left: auto;
}
+
+ .translation-selector-controls {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ margin-left: auto;
+ }
}
&.remote-theme-metadata {
diff --git a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
index 14dab8ae192..b9ec3acc387 100644
--- a/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
+++ b/frontend/discourse/admin/templates/admin-customize-themes/show/index.gjs
@@ -409,14 +409,23 @@ export default <template>
<span class="mini-title">
{{i18n "admin.customize.theme.theme_translations"}}
</span>
- <ComboBox
- @valueProperty="value"
- @content={{@controller.availableLocales}}
- @value={{@controller.locale}}
- @onChange={{@controller.updateLocale}}
- @options={{hash filterable=true}}
- class="translation-selector"
- />
+ <div class="translation-selector-controls">
+ <PluginOutlet
+ @name="admin-customize-theme-translation-selector"
+ @outletArgs={{lazyHash
+ }}
+ />
+ <ComboBox
+ @valueProperty="value"
+ @content={{@controller.availableLocales}}
+ @value={{@controller.locale}}
+ @onChange={{@controller.updateLocale}}
+ @options={{hash filterable=true}}
+ class="translation-selector"
+ />
+ </div>
</div>
<ConditionalLoadingSpinner
@condition={{@controller.model.loadingTranslations}}
diff --git a/frontend/discourse/tests/acceptance/admin-customize-themes-show-test.gjs b/frontend/discourse/tests/acceptance/admin-customize-themes-show-test.gjs
index d8045a37a42..17ed7ea9101 100644
--- a/frontend/discourse/tests/acceptance/admin-customize-themes-show-test.gjs
+++ b/frontend/discourse/tests/acceptance/admin-customize-themes-show-test.gjs
@@ -67,7 +67,13 @@ acceptance("Admin - Customize - Themes - Show", function (needs) {
child_themes: [],
parent_themes: [],
remote_theme: null,
- translations: [],
+ translations: [
+ {
+ key: "theme_metadata.description",
+ value: "The classic Discourse theme...",
+ default: "The classic Discourse theme...",
+ },
+ ],
},
],
});
@@ -105,4 +111,25 @@ acceptance("Admin - Customize - Themes - Show", function (needs) {
"This is a custom element that replaces the included components setting."
);
});
+
+ test("admin-customize-theme-translation-selector plugin outlet exposes the theme", async function (assert) {
+ withPluginApi((api) => {
+ api.renderInOutlet(
+ "admin-customize-theme-translation-selector",
+ <template>
+ <span class="theme-translation-outlet-test">
+ theme:{{@outletArgs.theme.id}}
+ </span>
+ </template>
+ );
+ });
+
+ await visit("/admin/customize/themes/-1");
+ assert
+ .dom(".translation-selector-container .theme-translation-outlet-test")
+ .hasText(
+ "theme:-1",
+ "the theme id is exposed via outletArgs on the translation selector outlet"
+ );
+ });
});
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb
new file mode 100644
index 00000000000..68d3635cf9d
--- /dev/null
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_theme_translations_controller.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Admin
+ class AiThemeTranslationsController < ::Admin::AdminController
+ requires_plugin "discourse-ai"
+
+ def create
+ theme = Theme.find_by(id: params[:theme_id])
+ raise Discourse::NotFound if theme.blank?
+
+ Jobs.enqueue(:localize_theme_translations, theme_id: theme.id)
+
+ head :no_content
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/regular/localize_theme_translations.rb b/plugins/discourse-ai/app/jobs/regular/localize_theme_translations.rb
new file mode 100644
index 00000000000..23a2f1606d1
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/regular/localize_theme_translations.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module Jobs
+ class LocalizeThemeTranslations < ::Jobs::Base
+ sidekiq_options retry: false
+
+ def execute(args)
+ theme_id = args[:theme_id]
+ raise Discourse::InvalidParameters.new(:theme_id) if theme_id.blank?
+
+ theme = Theme.find_by(id: theme_id)
+ return if theme.blank?
+
+ en_field = theme.theme_fields.find_by(target_id: Theme.targets[:translations], name: "en")
+ return if en_field.blank?
+
+ en_data = en_field.raw_translation_data[:en] || {}
+ translations =
+ ThemeTranslationManager.list_from_hash(locale: "en", hash: en_data, theme: theme)
+ return if translations.blank?
+
+ locales = SiteSetting.content_localization_supported_locales.to_s.split("|") - ["en"]
+ return if locales.empty?
+
+ locales.each do |locale|
+ translations.each do |tm|
+ begin
+ value =
+ DiscourseAi::Translation::ShortTextTranslator.new(
+ text: tm.default,
+ target_locale: locale,
+ ).translate
+ next if value.blank?
+
+ ThemeTranslationOverride.upsert(
+ {
+ theme_id: theme.id,
+ locale: locale,
+ translation_key: tm.key,
+ value: value,
+ created_at: Time.now,
+ updated_at: Time.now,
+ },
+ unique_by: %i[theme_id locale translation_key],
+ )
+ rescue FinalDestination::SSRFDetector::LookupFailedError
+ # transient lookup failures
+ rescue => e
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Failed to translate theme #{theme.id} key #{tm.key} to #{locale}: #{e.message}",
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-customize-theme-translation-selector/ai-theme-translate.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-customize-theme-translation-selector/ai-theme-translate.gjs
new file mode 100644
index 00000000000..1ecae000954
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/admin-customize-theme-translation-selector/ai-theme-translate.gjs
@@ -0,0 +1,58 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import { extractError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+
+export default class AiThemeTranslate extends Component {
+ static shouldRender(args, { siteSettings }) {
+ return (
+ siteSettings.discourse_ai_enabled && siteSettings.ai_translation_enabled
+ );
+ }
+
+ @service toasts;
+
+ @action
+ async translate() {
+ const { theme } = this.args.outletArgs;
+ try {
+ await ajax("/admin/plugins/discourse-ai/ai-theme-translations", {
+ type: "POST",
+ data: { theme_id: theme.id },
+ });
+ this.toasts.success({
+ duration: "short",
+ data: {
+ message: i18n(
+ "discourse_ai.translations.theme_translations.translate.queued"
+ ),
+ },
+ });
+ } catch (e) {
+ this.toasts.error({
+ duration: "short",
+ data: {
+ message: extractError(
+ e,
+ i18n(
+ "discourse_ai.translations.theme_translations.translate.failed"
+ )
+ ),
+ },
+ });
+ }
+ }
+
+ <template>
+ <DButton
+ class="btn-default ai-theme-translate"
+ @icon="discourse-sparkles"
+ @label="discourse_ai.translations.theme_translations.translate.label"
+ @title="discourse_ai.translations.theme_translations.translate.title"
+ @action={{this.translate}}
+ />
+ </template>
+}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 903ab289452..9884b8b51fc 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -405,6 +405,12 @@ en:
bar_done:
one: "%{count} post"
other: "%{count} posts"
+ theme_translations:
+ translate:
+ label: "Translate"
+ title: "Translate to all supported languages"
+ queued: "Translation queued"
+ failed: "Failed to queue translation"
translations_menu:
translate:
label: "Translate post"
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index 75eb021d3db..070ae8646e5 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -149,6 +149,7 @@ Discourse::Application.routes.draw do
post "/ai-spam/fix-errors", to: "discourse_ai/admin/ai_spam#fix_errors"
get "/ai-translations", to: "discourse_ai/admin/ai_translations#show"
+ post "/ai-theme-translations", to: "discourse_ai/admin/ai_theme_translations#create"
resources :ai_llms,
only: %i[index new create edit update destroy],
diff --git a/plugins/discourse-ai/spec/jobs/regular/localize_theme_translations_spec.rb b/plugins/discourse-ai/spec/jobs/regular/localize_theme_translations_spec.rb
new file mode 100644
index 00000000000..ba5162f737e
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/regular/localize_theme_translations_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+describe Jobs::LocalizeThemeTranslations do
+ subject(:job) { described_class.new }
+
+ fab!(:theme)
+
+ before do
+ enable_current_plugin
+ SiteSetting.content_localization_supported_locales = "en|fr|es"
+
+ theme.set_field(target: :translations, name: "en", value: <<~YAML)
+ en:
+ greeting: "Hello"
+ YAML
+ theme.save!
+ end
+
+ it "raises when theme_id is missing" do
+ expect { job.execute({}) }.to raise_error(Discourse::InvalidParameters)
+ end
+
+ it "does nothing when the theme does not exist" do
+ DiscourseAi::Translation::ShortTextTranslator.expects(:new).never
+ job.execute(theme_id: -999)
+ end
+
+ it "does nothing when no target locales are configured" do
+ SiteSetting.content_localization_supported_locales = "en"
+ DiscourseAi::Translation::ShortTextTranslator.expects(:new).never
+ job.execute(theme_id: theme.id)
+ end
+
+ it "translates each key into every non-en locale and upserts overrides" do
+ translator = mock
+ translator.stubs(:translate).returns("translated")
+ DiscourseAi::Translation::ShortTextTranslator.stubs(:new).returns(translator)
+
+ job.execute(theme_id: theme.id)
+
+ overrides = ThemeTranslationOverride.where(theme_id: theme.id)
+ expect(overrides.pluck(:locale)).to contain_exactly("fr", "es")
+ expect(overrides.pluck(:value).uniq).to eq(["translated"])
+ expect(overrides.pluck(:translation_key).uniq).to eq(["greeting"])
+ end
+
+ it "only translates to locales in content_localization_supported_locales" do
+ SiteSetting.content_localization_supported_locales = "en|fr"
+ translator = mock
+ translator.stubs(:translate).returns("translated")
+ DiscourseAi::Translation::ShortTextTranslator.stubs(:new).returns(translator)
+
+ job.execute(theme_id: theme.id)
+
+ expect(ThemeTranslationOverride.where(theme_id: theme.id).pluck(:locale)).to contain_exactly(
+ "fr",
+ )
+ end
+
+ it "skips empty translations" do
+ translator = mock
+ translator.stubs(:translate).returns("")
+ DiscourseAi::Translation::ShortTextTranslator.stubs(:new).returns(translator)
+
+ job.execute(theme_id: theme.id)
+
+ expect(ThemeTranslationOverride.where(theme_id: theme.id)).to be_empty
+ end
+end
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb
new file mode 100644
index 00000000000..16bff2d0ea8
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/admin/ai_theme_translations_controller_spec.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Admin::AiThemeTranslationsController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:theme)
+
+ before { enable_current_plugin }
+
+ describe "#create" do
+ context "when logged in as admin" do
+ before { sign_in(admin) }
+
+ it "enqueues the localize job with the theme id" do
+ expect_enqueued_with(job: :localize_theme_translations, args: { theme_id: theme.id }) do
+ post "/admin/plugins/discourse-ai/ai-theme-translations.json",
+ params: {
+ theme_id: theme.id,
+ }
+ end
+
+ expect(response.status).to eq(204)
+ end
+
+ it "returns 404 when the theme does not exist" do
+ post "/admin/plugins/discourse-ai/ai-theme-translations.json", params: { theme_id: -999 }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when not admin" do
+ it "returns 404 for anonymous users" do
+ post "/admin/plugins/discourse-ai/ai-theme-translations.json",
+ params: {
+ theme_id: theme.id,
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 for regular users" do
+ sign_in(user)
+ post "/admin/plugins/discourse-ai/ai-theme-translations.json",
+ params: {
+ theme_id: theme.id,
+ }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when the plugin is disabled" do
+ before do
+ sign_in(admin)
+ SiteSetting.discourse_ai_enabled = false
+ end
+
+ it "returns 404" do
+ post "/admin/plugins/discourse-ai/ai-theme-translations.json",
+ params: {
+ theme_id: theme.id,
+ }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end