Skip to content

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

FEATURE: Allow admins to localize custom sidebar section and links (#41795)

Natalie Tayee7985f8767b
diff --git a/app/assets/stylesheets/common/base/sidebar.scss b/app/assets/stylesheets/common/base/sidebar.scss
index ee4ecd047d7..573fd2a2243 100644
--- a/app/assets/stylesheets/common/base/sidebar.scss
+++ b/app/assets/stylesheets/common/base/sidebar.scss
@@ -225,6 +225,62 @@
}
}
+ .sidebar-section-form__links-label {
+ display: flex;
+ align-items: flex-start;
+ margin-bottom: 5px;
+ color: var(--token-color-text-subtle);
+ font-weight: var(--token-font-weight-bold);
+ }
+
+ .sidebar-section-form__localizations,
+ .sidebar-section-form-link__localizations {
+ margin-block: 0 1em;
+ }
+
+ .sidebar-section-form__localization-row {
+ display: grid;
+ grid-template-columns: 6.2em 0.8em 1fr 0.5em 2em;
+ align-items: center;
+ margin-bottom: 0.5em;
+
+ .sidebar-section-form__localization-locale {
+ grid-column: 1;
+ width: auto;
+ }
+
+ .sidebar-section-form__localization-value {
+ grid-column: 3;
+ }
+
+ .remove-localization {
+ grid-column: 5;
+ width: 2em;
+ min-width: 2em;
+ padding-inline: 0;
+ justify-self: center;
+ }
+
+ @include viewport.until(sm) {
+ grid-template-columns: 1fr auto;
+
+ .sidebar-section-form__localization-locale,
+ .sidebar-section-form__localization-value {
+ grid-column: 1 / span 2;
+ }
+
+ .remove-localization {
+ grid-column: 2;
+ grid-row: auto;
+ }
+ }
+
+ input,
+ select {
+ width: 100%;
+ }
+ }
+
.row-wrapper {
display: grid;
grid-template-columns: 2em 4.5em repeat(2, 1fr) 2em;
diff --git a/app/controllers/sidebar_sections_controller.rb b/app/controllers/sidebar_sections_controller.rb
index c4d395003fb..2b84778adc7 100644
--- a/app/controllers/sidebar_sections_controller.rb
+++ b/app/controllers/sidebar_sections_controller.rb
@@ -8,7 +8,7 @@ class SidebarSectionsController < ApplicationController
sections =
SidebarSection
.strict_loading
- .includes(:sidebar_urls)
+ .includes(:localizations, sidebar_urls: :localizations)
.where("public OR user_id = ?", current_user.id)
.order("section_type IS NOT NULL DESC, public DESC, title ASC")
@@ -23,6 +23,16 @@ class SidebarSectionsController < ApplicationController
render json: sections
end
+ def show
+ sidebar_section =
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(params[:id])
+ @guardian.ensure_can_edit!(sidebar_section)
+
+ render_serialized(sidebar_section, SidebarSectionEditSerializer, root: "sidebar_section")
+ rescue Discourse::InvalidAccess
+ render json: failed_json, status: :forbidden
+ end
+
def create
sidebar_section =
SidebarSection.create!(section_params.merge(sidebar_urls_attributes: links_params))
@@ -43,6 +53,7 @@ class SidebarSectionsController < ApplicationController
def update
sidebar_section = SidebarSection.find(section_params["id"])
@guardian.ensure_can_edit!(sidebar_section)
+ @guardian.ensure_can_localize_sidebar_section!(sidebar_section) if localization_params_present?
ActiveRecord::Base.transaction do
sidebar_section.update!(section_params.merge(sidebar_urls_attributes: links_params))
@@ -106,13 +117,46 @@ class SidebarSectionsController < ApplicationController
end
def section_params
- section_params = params.permit(:id, :title, :public)
- section_params.merge!(user: current_user) if !params[:public]
+ section_params = params.permit(:id, :title).to_h.with_indifferent_access
+
+ if current_user.admin?
+ section_params.merge!(params.permit(:public).to_h.with_indifferent_access)
+
+ if SiteSetting.content_localization_enabled
+ section_params.merge!(
+ params
+ .permit(:locale, localizations: %i[id locale title _destroy])
+ .to_h
+ .with_indifferent_access,
+ )
+ end
+ end
+
+ section_is_public = ActiveModel::Type::Boolean.new.cast(section_params[:public])
+ section_params.merge!(user: current_user) if !section_is_public
+ if section_params[:localizations]
+ section_params[:localizations_attributes] = prepare_localization_attributes(
+ section_params.delete(:localizations),
+ )
+ end
section_params
end
def links_params
- params.permit(links: %i[icon name value id _destroy segment])["links"]
+ permitted_link_params = %i[icon name value id _destroy segment]
+ if current_user.admin? && SiteSetting.content_localization_enabled
+ permitted_link_params << { localizations: %i[id locale name _destroy] }
+ end
+
+ links = params.permit(links: permitted_link_params)["links"]
+
+ links&.each do |link|
+ next if link[:localizations].blank?
+
+ link[:localizations_attributes] = prepare_localization_attributes(link.delete(:localizations))
+ end
+
+ links
end
def reorder_params
@@ -137,7 +181,24 @@ class SidebarSectionsController < ApplicationController
end
def check_access_if_public
- return true if !params[:public]
+ public_section = ActiveModel::Type::Boolean.new.cast(params[:public])
+ return true if !public_section
+
raise Discourse::InvalidAccess.new if !guardian.can_create_public_sidebar_section?
end
+
+ def localization_params_present?
+ params[:localizations].present? || params[:links]&.any? { |link| link[:localizations].present? }
+ end
+
+ def prepare_localization_attributes(localizations)
+ localizations.filter_map do |localization|
+ destroy = ActiveModel::Type::Boolean.new.cast(localization[:_destroy])
+ if !destroy && LocaleNormalizer.is_same?(localization[:locale], SiteSetting.default_locale)
+ next
+ end
+
+ localization
+ end
+ end
end
diff --git a/app/models/sidebar_section.rb b/app/models/sidebar_section.rb
index 11dffea1dd0..7f607123cd5 100644
--- a/app/models/sidebar_section.rb
+++ b/app/models/sidebar_section.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
class SidebarSection < ActiveRecord::Base
+ include Localizable
+
MAX_TITLE_LENGTH = 30
MAX_USER_CATEGORY_LINKS = 100
@@ -15,7 +17,9 @@ class SidebarSection < ActiveRecord::Base
accepts_nested_attributes_for :sidebar_urls,
allow_destroy: true,
limit: -> { SiteSetting.max_sidebar_section_links }
+ accepts_nested_attributes_for :localizations, allow_destroy: true
+ before_validation :set_default_locale
before_save :set_system_user_for_public_section
validates :title,
@@ -28,8 +32,13 @@ class SidebarSection < ActiveRecord::Base
}
scope :public_sections, -> { where("public") }
+ scope :custom_sections, -> { where(section_type: nil) }
enum :section_type, { community: 0 }, scopes: false, suffix: true
+ def custom_section?
+ section_type.blank?
+ end
+
def reset_community!
ActiveRecord::Base.transaction do
update!(title: "Community")
@@ -62,6 +71,10 @@ class SidebarSection < ActiveRecord::Base
def set_system_user_for_public_section
self.user_id = Discourse.system_user.id if public
end
+
+ def set_default_locale
+ self.locale ||= SiteSetting.default_locale.to_s
+ end
end
# == Schema Information
@@ -69,6 +82,7 @@ end
# Table name: sidebar_sections
#
# id :bigint not null, primary key
+# locale :string(20)
# public :boolean default(FALSE), not null
# section_type :integer
# title :string(30) not null
diff --git a/app/models/sidebar_section_localization.rb b/app/models/sidebar_section_localization.rb
new file mode 100644
index 00000000000..2288a57388d
--- /dev/null
+++ b/app/models/sidebar_section_localization.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+class SidebarSectionLocalization < ActiveRecord::Base
+ include LocaleMatchable
+
+ belongs_to :sidebar_section
+
+ validates :locale, presence: true, length: { maximum: 20 }
+ validates :title, presence: true, length: { maximum: SidebarSection::MAX_TITLE_LENGTH }
+ validates :sidebar_section_id, uniqueness: { scope: :locale }
+end
+
+# == Schema Information
+#
+# Table name: sidebar_section_localizations
+#
+# id :bigint not null, primary key
+# locale :string(20) not null
+# title :string(30) not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# sidebar_section_id :bigint not null
+#
+# Indexes
+#
+# idx_on_sidebar_section_id_locale_271bd8ee1c (sidebar_section_id,locale) UNIQUE
+# index_sidebar_section_localizations_on_sidebar_section_id (sidebar_section_id)
+#
diff --git a/app/models/sidebar_url.rb b/app/models/sidebar_url.rb
index 76fe9530d4e..586a981ba15 100644
--- a/app/models/sidebar_url.rb
+++ b/app/models/sidebar_url.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
class SidebarUrl < ActiveRecord::Base
+ include Localizable
+
enum :segment, { primary: 0, secondary: 1 }, scopes: false, suffix: true
MAX_ICON_LENGTH = 40
@@ -62,7 +64,10 @@ class SidebarUrl < ActiveRecord::Base
validate :path_validator
+ accepts_nested_attributes_for :localizations, allow_destroy: true
+
before_validation :remove_internal_hostname, :set_external
+ before_validation :set_default_locale
def path_validator
return true if !external?
@@ -81,6 +86,10 @@ class SidebarUrl < ActiveRecord::Base
def set_external
self.external = value.start_with?("http://", "https://")
end
+
+ def set_default_locale
+ self.locale ||= SiteSetting.default_locale.to_s
+ end
end
# == Schema Information
@@ -90,6 +99,7 @@ end
# id :bigint not null, primary key
# external :boolean default(FALSE), not null
# icon :string(40) not null
+# locale :string(20)
# name :string(80) not null
# segment :integer default("primary"), not null
# value :string(1000) not null
diff --git a/app/models/sidebar_url_localization.rb b/app/models/sidebar_url_localization.rb
new file mode 100644
index 00000000000..b43d743bfd9
--- /dev/null
+++ b/app/models/sidebar_url_localization.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+class SidebarUrlLocalization < ActiveRecord::Base
+ include LocaleMatchable
+
+ belongs_to :sidebar_url
+
+ validates :locale, presence: true, length: { maximum: 20 }
+ validates :name, presence: true, length: { maximum: SidebarUrl::MAX_NAME_LENGTH }
+ validates :sidebar_url_id, uniqueness: { scope: :locale }
+end
+
+# == Schema Information
+#
+# Table name: sidebar_url_localizations
+#
+# id :bigint not null, primary key
+# locale :string(20) not null
+# name :string(80) not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# sidebar_url_id :bigint not null
+#
+# Indexes
+#
+# index_sidebar_url_localizations_on_sidebar_url_id (sidebar_url_id)
+# index_sidebar_url_localizations_on_sidebar_url_id_and_locale (sidebar_url_id,locale) UNIQUE
+#
diff --git a/app/models/site.rb b/app/models/site.rb
index 3457b664a6a..7eaea993bc4 100644
--- a/app/models/site.rb
+++ b/app/models/site.rb
@@ -231,7 +231,7 @@ class Site
def anonymous_sidebar_sections
SidebarSection
.public_sections
- .includes(:sidebar_urls)
+ .includes(:localizations, sidebar_urls: :localizations)
.order("(section_type IS NOT NULL) DESC, (public IS TRUE) DESC")
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 443e20d77c7..bbada2b7eec 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -395,7 +395,7 @@ class User < ActiveRecord::Base
def all_sidebar_sections
sidebar_sections
.or(SidebarSection.public_sections)
- .includes(:sidebar_urls)
+ .includes(:localizations, sidebar_urls: :localizations)
.order("(section_type IS NOT NULL) DESC, (public IS TRUE) DESC")
end
diff --git a/app/serializers/sidebar_section_edit_serializer.rb b/app/serializers/sidebar_section_edit_serializer.rb
new file mode 100644
index 00000000000..4b196e424a4
--- /dev/null
+++ b/app/serializers/sidebar_section_edit_serializer.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+class SidebarSectionEditSerializer < SidebarSectionSerializer
+ def title
+ object.title
+ end
+
+ def links
+ object.sidebar_urls.map do |sidebar_url|
+ SidebarUrlSerializer.new(
+ sidebar_url,
+ root: false,
+ scope: scope,
+ include_localizations: scope.can_localize_sidebar_section?(object),
+ ).as_json
+ end
+ end
+
+ def include_localizations?
+ object.localizations.loaded? && scope.can_localize_sidebar_section?(object)
+ end
+end
diff --git a/app/serializers/sidebar_section_localization_serializer.rb b/app/serializers/sidebar_section_localization_serializer.rb
new file mode 100644
index 00000000000..61b97cd4530
--- /dev/null
+++ b/app/serializers/sidebar_section_localization_serializer.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class SidebarSectionLocalizationSerializer < ApplicationSerializer
+ attributes :id, :sidebar_section_id, :locale, :title
+end
diff --git a/app/serializers/sidebar_section_serializer.rb b/app/serializers/sidebar_section_serializer.rb
index a1b184589c1..9c77c59ab76 100644
--- a/app/serializers/sidebar_section_serializer.rb
+++ b/app/serializers/sidebar_section_serializer.rb
@@ -1,13 +1,34 @@
# frozen_string_literal: true
class SidebarSectionSerializer < ApplicationSerializer
- attributes :id, :title, :links, :slug, :public, :section_type
+ attributes :id, :title, :links, :slug, :public, :section_type, :locale
+
+ has_many :localizations, embed: :objects, serializer: SidebarSectionLocalizationSerializer
def links
- object.sidebar_urls.map { |sidebar_url| SidebarUrlSerializer.new(sidebar_url, root: false) }
+ object.sidebar_urls.map do |sidebar_url|
+ SidebarUrlSerializer.new(
+ sidebar_url,
+ root: false,
+ scope: scope,
+ show_translated_name: object.public? && object.custom_section?,
+ ).as_json
+ end
+ end
+
+ def title
+ if ContentLocalization.show_translated_sidebar_section?(object, scope)
+ object.get_localization&.title || object.title
+ else
+ object.title
+ end
end
def slug
object.title.parameterize
end
+
+ def include_localizations?
+ false
+ end
end
diff --git a/app/serializers/sidebar_url_localization_serializer.rb b/app/serializers/sidebar_url_localization_serializer.rb
new file mode 100644
index 00000000000..219fd160100
--- /dev/null
+++ b/app/serializers/sidebar_url_localization_serializer.rb
@@ -0,0 +1,5 @@
+# frozen_string_literal: true
+
+class SidebarUrlLocalizationSerializer < ApplicationSerializer
+ attributes :id, :sidebar_url_id, :locale, :name
+end
diff --git a/app/serializers/sidebar_url_serializer.rb b/app/serializers/sidebar_url_serializer.rb
index fb7ab90cd9b..8e45ac8a4e8 100644
--- a/app/serializers/sidebar_url_serializer.rb
+++ b/app/serializers/sidebar_url_serializer.rb
@@ -1,9 +1,24 @@
# frozen_string_literal: true
class SidebarUrlSerializer < ApplicationSerializer
- attributes :id, :name, :value, :icon, :external, :segment
+ attributes :id, :name, :value, :icon, :external, :segment, :locale
+
+ has_many :localizations, embed: :objects, serializer: SidebarUrlLocalizationSerializer
+
+ def name
+ if @options[:show_translated_name] &&
+ ContentLocalization.show_translated_sidebar_url?(object, scope)
+ object.get_localization&.name || object.name
+ else
+ object.name
+ end
+ end
def external
object.external?
end
+
+ def include_localizations?
+ @options[:include_localizations]
+ end
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index ea6993c850f..3f6b9c43281 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -6211,7 +6211,16 @@ en:
public: "Visible to everyone"
always_public: "Content in this section is always public"
more_menu: "More menu"
+ localizations:
+ title: "Translations"
+ locale: "Language"
+ title_label: "Section title"
+ link_label: "Link name"
+ add_section: "Add section title translation"
+ add_link: "Add link name translation"
+ remove: "Remove translation"
links:
+ title: "Section links"
add: "Add another link"
delete: "Delete link"
reset: "Reset to default"
diff --git a/config/routes.rb b/config/routes.rb
index 56a64513d2d..c8617125bab 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1964,7 +1964,7 @@ Discourse::Application.routes.draw do
put "user-status" => "user_status#set"
delete "user-status" => "user_status#clear"
- resources :sidebar_sections, only: %i[index create update destroy]
+ resources :sidebar_sections, only: %i[index show create update destroy]
put "/sidebar_sections/reset/:id" => "sidebar_sections#reset"
get "/form-templates/:id" => "form_templates#show"
diff --git a/db/migrate/20260715113008_create_sidebar_localizations.rb b/db/migrate/20260715113008_create_sidebar_localizations.rb
new file mode 100644
index 00000000000..4d2d82f7fdf
--- /dev/null
+++ b/db/migrate/20260715113008_create_sidebar_localizations.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+class CreateSidebarLocalizations < ActiveRecord::Migration[8.0]
+ def change
+ add_column :sidebar_sections, :locale, :string, limit: 20
+ add_column :sidebar_urls, :locale, :string, limit: 20
+
+ create_table :sidebar_section_localizations do |t|
+ t.references :sidebar_section, null: false
+ t.string :locale, limit: 20, null: false
+ t.string :title, limit: 30, null: false
+
+ t.timestamps null: false
+ end
+
+ add_index :sidebar_section_localizations, %i[sidebar_section_id locale], unique: true
+
+ create_table :sidebar_url_localizations do |t|
+ t.references :sidebar_url, null: false
+ t.string :locale, limit: 20, null: false
+ t.string :name, limit: 80, null: false
+
+ t.timestamps null: false
+ end
+
+ add_index :sidebar_url_localizations, %i[sidebar_url_id locale], unique: true
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index 53926dbfac7..079ea9657f1 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -8823,6 +8823,39 @@ CREATE SEQUENCE public.sidebar_section_links_id_seq
ALTER SEQUENCE public.sidebar_section_links_id_seq OWNED BY public.sidebar_section_links.id;
+--
+-- Name: sidebar_section_localizations; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.sidebar_section_localizations (
+ id bigint NOT NULL,
+ sidebar_section_id bigint NOT NULL,
+ locale character varying(20) NOT NULL,
+ title character varying(30) NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: sidebar_section_localizations_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.sidebar_section_localizations_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: sidebar_section_localizations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.sidebar_section_localizations_id_seq OWNED BY public.sidebar_section_localizations.id;
+
+
--
-- Name: sidebar_sections; Type: TABLE; Schema: public; Owner: -
--
@@ -8834,7 +8867,8 @@ CREATE TABLE public.sidebar_sections (
created_at timestamp(6) without time zone NOT NULL,
updated_at timestamp(6) without time zone NOT NULL,
public boolean DEFAULT false NOT NULL,
- section_type integer
+ section_type integer,
+ locale character varying(20)
);
@@ -8857,6 +8891,39 @@ CREATE SEQUENCE public.sidebar_sections_id_seq
ALTER SEQUENCE public.sidebar_sections_id_seq OWNED BY public.sidebar_sections.id;
+--
+-- Name: sidebar_url_localizations; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.sidebar_url_localizations (
+ id bigint NOT NULL,
+ sidebar_url_id bigint NOT NULL,
+ locale character varying(20) NOT NULL,
+ name character varying(80) NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: sidebar_url_localizations_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.sidebar_url_localizations_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: sidebar_url_localizations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.sidebar_url_localizations_id_seq OWNED BY public.sidebar_url_localizations.id;
+
+
--
-- Name: sidebar_urls; Type: TABLE; Schema: public; Owner: -
--
@@ -8869,7 +8936,8 @@ CREATE TABLE public.sidebar_urls (
updated_at timestamp(6) without time zone NOT NULL,
icon character varying(40) NOT NULL,
external boolean DEFAULT false NOT NULL,
- segment integer DEFAULT 0 NOT NULL
+ segment integer DEFAULT 0 NOT NULL,
+ locale character varying(20)
);
@@ -13862,6 +13930,13 @@ ALTER TABLE ONLY public.shelved_notifications ALTER COLUMN id SET DEFAULT nextva
ALTER TABLE ONLY public.sidebar_section_links ALTER COLUMN id SET DEFAULT nextval('public.sidebar_section_links_id_seq'::regclass);
+--
+-- Name: sidebar_section_localizations id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.sidebar_section_localizations ALTER COLUMN id SET DEFAULT nextval('public.sidebar_section_localizations_id_seq'::regclass);
+
+
--
-- Name: sidebar_sections id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -13869,6 +13944,13 @@ ALTER TABLE ONLY public.sidebar_section_links ALTER COLUMN id SET DEFAULT nextva
ALTER TABLE ONLY public.sidebar_sections ALTER COLUMN id SET DEFAULT nextval('public.sidebar_sections_id_seq'::regclass);
+--
+-- Name: sidebar_url_localizations id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.sidebar_url_localizations ALTER COLUMN id SET DEFAULT nextval('public.sidebar_url_localizations_id_seq'::regclass);
+
+
--
-- Name: sidebar_urls id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -16340,6 +16422,14 @@ ALTER TABLE ONLY public.sidebar_section_links
ADD CONSTRAINT sidebar_section_links_pkey PRIMARY KEY (id);
+--
+-- Name: sidebar_section_localizations sidebar_section_localizations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.sidebar_section_localizations
+ ADD CONSTRAINT sidebar_section_localizations_pkey PRIMARY KEY (id);
+
+
--
-- Name: sidebar_sections sidebar_sections_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -16348,6 +16438,14 @@ ALTER TABLE ONLY public.sidebar_sections
ADD CONSTRAINT sidebar_sections_pkey PRIMARY KEY (id);
+--
+-- Name: sidebar_url_localizations sidebar_url_localizations_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.sidebar_url_localizations
+ ADD CONSTRAINT sidebar_url_localizations_pkey PRIMARY KEY (id);
+
+
--
-- Name: sidebar_urls sidebar_urls_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -17687,6 +17785,13 @@ CREATE INDEX idx_notifications_speedup_unread_count ON public.notifications USIN
CREATE UNIQUE INDEX idx_on_llm_model_id_feature_name_2b0b794b27 ON public.llm_feature_credit_costs USING btree (llm_model_id, feature_name);
+--
+-- Name: idx_on_sidebar_section_id_locale_271bd8ee1c; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_on_sidebar_section_id_locale_271bd8ee1c ON public.sidebar_section_localizations USING btree (sidebar_section_id, locale);
+
+
--
-- Name: idx_on_target_id_target_type_summary_type_3355609fbb; Type: INDEX; Schema: public; Owner: -
--
@@ -20893,6 +20998,13 @@ CREATE INDEX index_shelved_notifications_on_notification_id ON public.shelved_no
CREATE INDEX index_sidebar_section_links_on_linkable_type_and_linkable_id ON public.sidebar_section_links USING btree (linkable_type, linkable_id);
+--
+-- Name: index_sidebar_section_localizations_on_sidebar_section_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_sidebar_section_localizations_on_sidebar_section_id ON public.sidebar_section_localizations USING btree (sidebar_section_id);
+
+
--
-- Name: index_sidebar_sections_on_section_type; Type: INDEX; Schema: public; Owner: -
--
@@ -20907,6 +21019,20 @@ CREATE UNIQUE INDEX index_sidebar_sections_on_section_type ON public.sidebar_sec
CREATE UNIQUE INDEX index_sidebar_sections_on_user_id_and_title ON public.sidebar_sections USING btree (user_id, title);
+--
+-- Name: index_sidebar_url_localizations_on_sidebar_url_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_sidebar_url_localizations_on_sidebar_url_id ON public.sidebar_url_localizations USING btree (sidebar_url_id);
+
+
+--
+-- Name: index_sidebar_url_localizations_on_sidebar_url_id_and_locale; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_sidebar_url_localizations_on_sidebar_url_id_and_locale ON public.sidebar_url_localizations USING btree (sidebar_url_id, locale);
+
+
--
-- Name: index_silenced_assignments_on_assignment_id; Type: INDEX; Schema: public; Owner: -
--
@@ -22704,6 +22830,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260715202231'),
('20260715183411'),
('20260715134306'),
+('20260715113008'),
('20260715090434'),
('20260715090355'),
('20260715064155'),
diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjs
index 350fecb1436..5a5cf6de242 100644
--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs
+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs
@@ -20,13 +20,16 @@ import { autoTrackedArray } from "discourse/lib/tracked-tools";
import { and, not } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DModal from "discourse/ui-kit/d-modal";
+import DSelect from "discourse/ui-kit/d-select";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
class Section {
@tracked title;
+ @tracked public;
@autoTrackedArray links;
@autoTrackedArray secondaryLinks;
+ @autoTrackedArray localizations;
constructor({
title,
@@ -36,6 +39,7 @@ class Section {
publicSection,
sectionType,
hideTitleInput,
+ localizations,
}) {
this.title = title;
this.public = publicSection;
@@ -44,6 +48,7 @@ class Section {
this.secondaryLinks = secondaryLinks;
this.id = id;
this.hideTitleInput = hideTitleInput;
+ this.localizations = localizations || [];
}
get valid() {
@@ -51,8 +56,18 @@ class Section {
.filter((link) => !link._destroy)
.concat(this.secondaryLinks?.filter((link) => !link._destroy) || []);
const validLinks =
- allLinks.length > 0 && allLinks.every((link) => link.valid);
- return this.validTitle && validLinks;
+ allLinks.length > 0 &&
+ allLinks.every((link) => (this.public ? link.valid : link.validSource));
+ const validLocalizations =
+ !this.public ||
+ this.localizations
+ .filter((localization) => !localization._destroy)
+ .every((localization) => localization.valid);
+ return this.validTitle && validLinks && validLocalizations;
+ }
+
+ get customSection() {
+ return !this.sectionType;
}
get validTitle() {
@@ -86,13 +101,91 @@ class Section {
}
}
+class SectionLocalization {
+ @tracked locale;
+ @tracked title;
+ @tracked _destroy;
+
+ constructor({ id, locale, title }) {
+ this.id = id;
+ this.locale = locale;
+ this.title = title;
+ }
+
+ get valid() {
+ return !isEmpty(this.locale) && !isEmpty(this.title) && !this.#tooLongTitle;
+ }
+
+ get invalidTitleMessage() {
+ if (this.title === undefined) {
+ return;
+ }
+ if (isEmpty(this.title)) {
+ return i18n("sidebar.sections.custom.title.validation.blank");
+ }
+ if (this.#tooLongTitle) {
+ return i18n("sidebar.sections.custom.title.validation.maximum", {
+ count: SIDEBAR_SECTION.max_title_length,
+ });
+ }
+ }
+
+ get #tooLongTitle() {
+ return this.title?.length > SIDEBAR_SECTION.max_title_length;
+ }
+}
+
+class LinkLocalization {
+ @tracked locale;
+ @tracked name;
+ @tracked _destroy;
+
+ constructor({ id, locale, name }) {
+ this.id = id;
+ this.locale = locale;
+ this.name = name;
+ }
+
+ get valid() {
+ return !isEmpty(this.locale) && !isEmpty(this.name) && !this.#tooLongName;
+ }
+
+ get invalidNameMessage() {
+ if (this.name === undefined) {
+ return;
+ }
+ if (isEmpty(this.name)) {
+ return i18n("sidebar.sections.custom.links.name.validation.blank");
+ }
+ if (this.#tooLongName) {
+ return i18n("sidebar.sections.custom.links.name.validation.maximum", {
+ count: SIDEBAR_URL.max_name_length,
+ });
+ }
+ }
+
+ get #tooLongName() {
+ return this.name?.length > SIDEBAR_URL.max_name_length;
+ }
+}
+
class SectionLink {
@tracked icon;
@tracked name;
@tracked value;
+ @autoTrackedArray localizations;
@tracked _destroy;
- constructor({ router, icon: iconName, name, value, id, objectId, segment }) {
+ constructor({
+ router,
+ icon: iconName,
+ name,
+ value,
+ id,
+ objectId,
+ segment,
+ localizations,
+ }) {
this.router = router;
this.icon = iconName || "link";
this.name = name;
@@ -102,6 +195,7 @@ class SectionLink {
this.httpsHost = "https://" + window.location.host;
this.objectId = objectId;
this.segment = segment;
+ this.localizations = localizations || [];
}
get path() {
@@ -109,6 +203,13 @@ class SectionLink {
}
get valid() {
+ const validLocalizations = this.localizations
+ .filter((localization) => !localization._destroy)
+ .every((localization) => localization.valid);
+ return this.validSource && validLocalizations;
+ }
+
+ get validSource() {
return this.validIcon && this.validName && this.validValue;
}
@@ -222,7 +323,9 @@ class SectionLink {
@tagName("")
export default class SidebarSectionForm extends Component {
@service dialog;
+ @service languageNameLookup;
@service router;
+ @service siteSettings;
@tracked flash;
@tracked flashType;
@@ -254,6 +357,10 @@ export default class SidebarSectionForm extends Component {
}, []),
id: section.id,
hideTitleInput: this.model.hideSectionHeader,
+ localizations: this.initLocalizations(
+ section.localizations,
+ SectionLocalization
+ ),
});
} else {
return new Section({
@@ -277,9 +384,17 @@ export default class SidebarSectionForm extends Component {
id: link.id,
objectId: this.nextObjectId,
segment: link.segment,
+ localizations: this.initLocalizations(
+ link.localizations,
+ LinkLocalization
+ ),
});
}
+ initLocalizations(localizations, klass) {
+ return (localizations || []).map((localization) => new klass(localization));
+ }
+
create() {
return ajax(`/sidebar_sections`, {
type: "POST",
@@ -288,11 +403,13 @@ export default class SidebarSectionForm extends Component {
data: JSON.stringify({
title: this.transformedModel.title,
public: this.transformedModel.public,
+ localizations: this.serializeSectionLocalizations(),
links: this.transformedModel.links.map((link) => {
return {
icon: link.icon,
name: link.name,
value: link.path,
+ localizations: this.serializeLinkLocalizations(link),
};
}),
}),
@@ -335,6 +452,7 @@ export default class SidebarSectionForm extends Component {
data: JSON.stringify({
title: this.transformedModel.title,
public: this.transformedModel.public,
+ localizations: this.serializeSectionLocalizations(),
links: this.transformedModel.links
.concat(this.transformedModel?.secondaryLinks || [])
.map((link) => {
@@ -345,6 +463,7 @@ export default class SidebarSectionForm extends Component {
value: link.path,
segment: link.segment,
_destroy: link._destroy,
+ localizations: this.serializeLinkLocalizations(link),
};
}),
}),
@@ -377,6 +496,55 @@ export default class SidebarSectionForm extends Component {
);
}
+ get activeLocalizations() {
+ return this.transformedModel.localizations.filter(
+ (localization) => !localization._destroy
+ );
+ }
+
+ get localeOptions() {
+ const configuredLocales =
+ this.siteSettings.available_content_localization_locales?.map(
+ (locale) => locale.value
+ ) ||
+ this.siteSettings.content_localization_supported_locales
+ ?.split("|")
+ .filter(Boolean) ||
+ [];
+ const locales = new Set(configuredLocales);
+
+ this.transformedModel.localizations.forEach((localization) =>
+ locales.add(localization.locale)
+ );
+ this.transformedModel.links
+ .concat(this.transformedModel.secondaryLinks || [])
+ .forEach((link) =>
+ link.localizations.forEach((localization) =>
+ locales.add(localization.locale)
+ )
+ );
+
+ return [...locales]
+ .filter((locale) => locale && locale !== this.siteSettings.default_locale)
+ .map((locale) => ({
+ name: this.languageNameLookup.getLanguageName(locale),
+ value: locale,
+ }));
+ }
+
+ get showLocalizations() {
+ return (
+ this.currentUser?.admin &&
+ this.siteSettings.content_localization_enabled &&
+ this.transformedModel.public &&
+ this.transformedModel.customSection
+ );
+ }
+
+ get canAddSectionLocalization() {
+ return this.nextLocale(this.transformedModel.localizations) !== "";
+ }
+
get header() {
return this.transformedModel.id
? "sidebar.sections.custom.edit"
@@ -438,6 +606,141 @@ export default class SidebarSectionForm extends Component {
}
}
+ @bind
+ deleteLocalization(localization) {
+ if (localization.id) {
+ localization._destroy = "1";
+ } else {
+ removeValueFromArray(this.transformedModel.localizations, localization);
+ }
+ }
+
+ @bind
+ deleteLinkLocalization(link, localization) {
+ if (localization.id) {
+ localization._destroy = "1";
+ } else {
+ removeValueFromArray(link.localizations, localization);
+ }
+ }
+
+ @bind
+ addLinkLocalization(link) {
+ const locale = this.nextLocale(link.localizations);
+ if (!locale) {
+ return;
+ }
+
+ link.localizations.push(
+ new LinkLocalization({
+ locale,
+ })
+ );
+ }
+
+ @action
+ addLocalization() {
+ const locale = this.nextLocale(this.transformedModel.localizations);
+ if (!locale) {
+ return;
+ }
+
+ this.transformedModel.localizations.push(
+ new SectionLocalization({
+ locale,
+ })
+ );
+ }
+
+ nextLocale(localizations) {
+ const selectedLocales = localizations
+ .filter((localization) => !localization._destroy)
+ .map((localization) => localization.locale);
+
+ return (
+ this.localeOptions.find(
+ (locale) => !selectedLocales.includes(locale.value)
+ )?.value || ""
+ );
+ }
+
+ @bind
+ setSectionLocalizationLocale(localization, locale) {
+ this.setLocalizationLocale(
+ this.transformedModel.localizations,
+ localization,
+ locale
+ );
+ }
+
+ @bind
+ setLinkLocalizationLocale(link, localization, locale) {
+ this.setLocalizationLocale(link.localizations, localization, locale);
+ }
+
+ @bind
+ isSectionLocalizationLocaleDisabled(localization, locale) {
+ return this.isLocalizationLocaleSelected(
+ this.transformedModel.localizations,
+ localization,
+ locale
+ );
+ }
+
+ @bind
+ isLinkLocalizationLocaleDisabled(link, localization, locale) {
+ return this.isLocalizationLocaleSelected(
+ link.localizations,
+ localization,
+ locale
+ );
+ }
+
+ setLocalizationLocale(localizations, localization, locale) {
+ if (
+ !this.isLocalizationLocaleSelected(localizations, localization, locale)
+ ) {
+ localization.locale = locale;
+ }
+ }
+
+ isLocalizationLocaleSelected(localizations, localization, locale) {
+ return localizations
+ .filter((existingLocalization) => {
+ return (
+ existingLocalization !== localization &&
+ !existingLocalization._destroy
+ );
+ })
+ .some((existingLocalization) => existingLocalization.locale === locale);
+ }
+
+ serializeSectionLocalizations() {
+ if (!this.showLocalizations) {
+ return [];
+ }
+
+ return this.transformedModel.localizations.map((localization) => ({
+ id: localization.id,
+ locale: localization.locale,
+ title: localization.title,
+ _destroy: localization._destroy,
+ }));
+ }
+
+ serializeLinkLocalizations(link) {
+ if (!this.showLocalizations) {
+ return [];
+ }
+
+ return link.localizations.map((localization) => ({
+ id: localization.id,
+ locale: localization.locale,
+ name: localization.name,
+ _destroy: localization._destroy,
+ }));
+ }
+
@action
addLink() {
this.nextObjectId = this.nextObjectId + 1;
@@ -495,6 +798,11 @@ export default class SidebarSectionForm extends Component {
this.transformedModel.id ? this.update() : this.create();
}
+ @action
+ setPublic(event) {
+ this.transformedModel.public = event.target.checked;
+ }
+
@action
delete() {
return this.dialog.deleteConfirm({
@@ -529,7 +837,7 @@ export default class SidebarSectionForm extends Component {
@flash={{this.flash}}
@flashType={{this.flashType}}
@title={{i18n this.header}}
- class="sidebar-section-form-modal"
+ class="sidebar-section-form-modal --large"
>
<:body>
<form class="form-horizontal sidebar-section-form">
@@ -558,8 +866,88 @@ export default class SidebarSectionForm extends Component {
{{/if}}
</div>
{{/unless}}
+ {{#if this.showLocalizations}}
+ <div class="sidebar-section-form__localizations">
+ {{#each this.activeLocalizations as |localization|}}
+ <div class="sidebar-section-form__localization-row">
+ <DSelect
+ @value={{localization.locale}}
+ @onChange={{fn
+ this.setSectionLocalizationLocale
+ localization
+ }}
+ @includeNone={{false}}
+ class="sidebar-section-form__localization-locale"
+ aria-label={{i18n
+ "sidebar.sections.custom.localizations.locale"
+ }}
+ as |select|
+ >
+ {{#each this.localeOptions as |locale|}}
+ <select.Option
+ @value={{locale.value}}
+ disabled={{this.isSectionLocalizationLocaleDisabled
+ localization
+ locale.value
+ }}
+ >{{locale.name}}</select.Option>
+ {{/each}}
+ </DSelect>
+
+ <Input
+ @type="text"
+ @value={{localization.title}}
+ class="sidebar-section-form__localization-value"
+ placeholder={{i18n
+ "sidebar.sections.custom.localizations.title_label"
+ }}
+ aria-label={{i18n
+ "sidebar.sections.custom.localizations.title_label"
+ }}
+ {{on
+ "input"
+ (withEventValue (fn (mut localization.title)))
+ }}
+ />
+
+ <DButton
+ @icon="trash-can"
+ @action={{fn this.deleteLocalization localization}}
+ @title="sidebar.sections.custom.localizations.remove"
+ class="btn-flat delete-link remove-localization"
+ />
+ </div>
+
+ {{#if localization.invalidTitleMessage}}
+ <div role="alert" aria-live="assertive" class="title warning">
+ {{localization.invalidTitleMessage}}
+ </div>
+ {{/if}}
+ {{/each}}
+
+ {{#if this.canAddSectionLocalization}}
+ <DButton
+ @action={{this.addLocalization}}
+ @title="sidebar.sections.custom.localizations.add_section"
+ @icon="plus"
+ @label="sidebar.sections.custom.localizations.add_section"
+ class="btn-flat btn-text add-localization"
+ />
+ {{/if}}
+ </div>
+ <hr />
+ {{/if}}
+
+ <div
+ id="section-links-label"
+ class="sidebar-section-form__links-label"
+ >
+ {{i18n "sidebar.sections.custom.links.title"}}
+ </div>
+
<div
role="table"
+ aria-labelledby="section-links-label"
aria-rowcount={{this.activeLinks.length}}
class="sidebar-section-form__links-wrapper"
>
@@ -605,6 +993,12 @@ export default class SidebarSectionForm extends Component {
@deleteLink={{this.deleteLink}}
@reorderCallback={{this.reorder}}
@setDraggedLinkCallback={{this.setDraggedLink}}
+ @showLocalizations={{this.showLocalizations}}
+ @localeOptions={{this.localeOptions}}
+ @deleteLocalization={{this.deleteLinkLocalization}}
+ @addLocalization={{this.addLinkLocalization}}
+ @setLocalizationLocale={{this.setLinkLocalizationLocale}}
+ @isLocalizationLocaleDisabled={{this.isLinkLocalizationLocaleDisabled}}
/>
{{/each}}
@@ -627,6 +1021,12 @@ export default class SidebarSectionForm extends Component {
@deleteLink={{this.deleteLink}}
@reorderCallback={{this.reorder}}
@setDraggedLinkCallback={{this.setDraggedLink}}
+ @showLocalizations={{this.showLocalizations}}
+ @localeOptions={{this.localeOptions}}
+ @deleteLocalization={{this.deleteLinkLocalization}}
+ @addLocalization={{this.addLinkLocalization}}
+ @setLocalizationLocale={{this.setLinkLocalizationLocale}}
+ @isLocalizationLocaleDisabled={{this.isLinkLocalizationLocaleDisabled}}
/>
{{/each}}
<DButton
@@ -671,6 +1071,7 @@ export default class SidebarSectionForm extends Component {
@checked={{this.transformedModel.public}}
class="mark-public"
disabled={{this.transformedModel.sectionType}}
+ {{on "change" this.setPublic}}
/>
<span>{{i18n "sidebar.sections.custom.public"}}</span>
{{/if}}
diff --git a/frontend/discourse/app/components/sidebar/section-form-link.gjs b/frontend/discourse/app/components/sidebar/section-form-link.gjs
index c7fc11e77c1..5c87b963279 100644
--- a/frontend/discourse/app/components/sidebar/section-form-link.gjs
+++ b/frontend/discourse/app/components/sidebar/section-form-link.gjs
@@ -9,6 +9,7 @@ import withEventValue from "discourse/helpers/with-event-value";
import discourseLater from "discourse/lib/later";
import DButton from "discourse/ui-kit/d-button";
import DIconGridPicker from "discourse/ui-kit/d-icon-grid-picker";
+import DSelect from "discourse/ui-kit/d-select";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
@@ -77,92 +78,176 @@ export default class SectionFormLink extends Component {
this.dragCssClass = null;
}
- <template>
- <div
- {{on "dragover" this.dragOver}}
- {{on "dragenter" this.dragEnter}}
- {{on "dragleave" this.dragLeave}}
- {{on "dragend" this.dragEnd}}
- {{on "drop" this.dropItem}}
- role="row"
- data-row-id={{@link.objectId}}
- class={{dConcatClass
- "sidebar-section-form-link"
- "row-wrapper"
- this.dragCssClass
- }}
- >
- {{#if this.site.desktopView}}
- <div
- {{on "dragstart" this.dragHasStarted}}
- class="draggable"
- data-link-name={{@link.name}}
- draggable="true"
- >
- {{dIcon "grip-lines"}}
- </div>
- {{/if}}
+ get activeLocalizations() {
+ return this.args.link.localizations.filter(
+ (localization) => !localization._destroy
+ );
+ }
- <div class="input-group" role="cell">
- <DIconGridPicker
- @value={{@link.icon}}
- @onChange={{fn (mut @link.icon)}}
- @showCaret={{true}}
- @btnClass={{dConcatClass "btn-default" @link.iconCssClass}}
- aria-label={{i18n "sidebar.sections.custom.links.icon.label"}}
- />
+ get canAddLocalization() {
+ const selectedLocales = this.activeLocalizations.map(
+ (localization) => localization.locale
+ );
- {{#if @link.invalidIconMessage}}
- <div class="icon warning" role="alert" aria-live="assertive">
- {{@link.invalidIconMessage}}
+ return this.args.localeOptions.some(
+ (locale) => !selectedLocales.includes(locale.value)
+ );
+ }
+
+ <template>
+ <div class="sidebar-section-form-link-wrapper" role="rowgroup">
+ <div
+ {{on "dragover" this.dragOver}}
+ {{on "dragenter" this.dragEnter}}
+ {{on "dragleave" this.dragLeave}}
+ {{on "dragend" this.dragEnd}}
+ {{on "drop" this.dropItem}}
+ role="row"
+ data-row-id={{@link.objectId}}
+ class={{dConcatClass
+ "sidebar-section-form-link"
+ "row-wrapper"
+ this.dragCssClass
+ }}
+ >
+ {{#if this.site.desktopView}}
+ <div
+ {{on "dragstart" this.dragHasStarted}}
+ class="draggable"
+ data-link-name={{@link.name}}
+ draggable="true"
+ >
+ {{dIcon "grip-lines"}}
</div>
{{/if}}
- </div>
- <div class="input-group" role="cell">
- {{! eslint-disable-next-line ember/template-no-nested-interactive }}
- <Input
- {{on "input" (withEventValue (fn (mut @link.name)))}}
- @type="text"
- @value={{@link.name}}
- name="link-name"
- aria-label={{i18n "sidebar.sections.custom.links.name.label"}}
- class={{@link.nameCssClass}}
- data-1p-ignore
- />
+ <div class="input-group" role="cell">
+ <DIconGridPicker
+ @value={{@link.icon}}
+ @onChange={{fn (mut @link.icon)}}
+ @showCaret={{true}}
+ @btnClass={{dConcatClass "btn-default" @link.iconCssClass}}
+ aria-label={{i18n "sidebar.sections.custom.links.icon.label"}}
+ />
+
+ {{#if @link.invalidIconMessage}}
+ <div class="icon warning" role="alert" aria-live="assertive">
+ {{@link.invalidIconMessage}}
+ </div>
+ {{/if}}
+ </div>
- {{#if @link.invalidNameMessage}}
- <div role="alert" aria-live="assertive" class="name warning">
- {{@link.invalidNameMessage}}
- </div>
- {{/if}}
- </div>
+ <div class="input-group" role="cell">
+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}
+ <Input
+ {{on "input" (withEventValue (fn (mut @link.name)))}}
+ @type="text"
+ @value={{@link.name}}
+ name="link-name"
+ aria-label={{i18n "sidebar.sections.custom.links.name.label"}}
+ class={{@link.nameCssClass}}
+ data-1p-ignore
+ />
+
+ {{#if @link.invalidNameMessage}}
+ <div role="alert" aria-live="assertive" class="name warning">
+ {{@link.invalidNameMessage}}
+ </div>
+ {{/if}}
+ </div>
- <div class="input-group" role="cell">
- {{! eslint-disable-next-line ember/template-no-nested-interactive }}
- <Input
- {{on "input" (withEventValue (fn (mut @link.value)))}}
- @type="text"
- @value={{@link.value}}
- name="link-url"
- aria-label={{i18n "sidebar.sections.custom.links.value.label"}}
- class={{@link.valueCssClass}}
- />
+ <div class="input-group" role="cell">
+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}
+ <Input
+ {{on "input" (withEventValue (fn (mut @link.value)))}}
+ @type="text"
+ @value={{@link.value}}
+ name="link-url"
+ aria-label={{i18n "sidebar.sections.custom.links.value.label"}}
+ class={{@link.valueCssClass}}
+ />
+
+ {{#if @link.invalidValueMessage}}
+ <div role="alert" aria-live="assertive" class="value warning">
+ {{@link.invalidValueMessage}}
+ </div>
+ {{/if}}
+ </div>
- {{#if @link.invalidValueMessage}}
- <div role="alert" aria-live="assertive" class="value warning">
- {{@link.invalidValueMessage}}
- </div>
- {{/if}}
+ <DButton
+ @icon="trash-can"
+ @action={{fn @deleteLink @link}}
+ @title="sidebar.sections.custom.links.delete"
+ role="cell"
+ class="btn-flat delete-link"
+ />
</div>
- <DButton
- @icon="trash-can"
- @action={{fn @deleteLink @link}}
- @title="sidebar.sections.custom.links.delete"
- role="cell"
- class="btn-flat delete-link"
- />
+ {{#if @showLocalizations}}
+ <div class="sidebar-section-form-link__localizations">
+ {{#each this.activeLocalizations as |localization|}}
+ <div class="sidebar-section-form__localization-row">
+ <DSelect
+ @value={{localization.locale}}
+ @onChange={{fn @setLocalizationLocale @link localization}}
+ @includeNone={{false}}
+ class="sidebar-section-form__localization-locale"
+ aria-label={{i18n
+ "sidebar.sections.custom.localizations.locale"
+ }}
+ as |select|
+ >
+ {{#each @localeOptions as |locale|}}
+ <select.Option
+ @value={{locale.value}}
+ disabled={{@isLocalizationLocaleDisabled
+ @link
+ localization
+ locale.value
+ }}
+ >{{locale.name}}</select.Option>
+ {{/each}}
+ </DSelect>
+
+ <Input
+ @type="text"
+ @value={{localization.name}}
+ class="sidebar-section-form__localization-value"
+ placeholder={{i18n
+ "sidebar.sections.custom.localizations.link_label"
+ }}
+ aria-label={{i18n
+ "sidebar.sections.custom.localizations.link_label"
+ }}
+ {{on "input" (withEventValue (fn (mut localization.name)))}}
+ />
+
+ <DButton
+ @icon="trash-can"
+ @action={{fn @deleteLocalization @link localization}}
+ @title="sidebar.sections.custom.localizations.remove"
+ class="btn-flat delete-link remove-localization"
+ />
+ </div>
+
+ {{#if localization.invalidNameMessage}}
+ <div role="alert" aria-live="assertive" class="name warning">
+ {{localization.invalidNameMessage}}
+ </div>
+ {{/if}}
+ {{/each}}
+
+ {{#if this.canAddLocalization}}
+ <DButton
+ @action={{fn @addLocalization @link}}
+ @title="sidebar.sections.custom.localizations.add_link"
+ @icon="plus"
+ @label="sidebar.sections.custom.localizations.add_link"
+ class="btn-flat btn-text add-link-localization"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
</div>
</template>
}
diff --git a/frontend/discourse/app/lib/sidebar/section.js b/frontend/discourse/app/lib/sidebar/section.js
index b674dd5286a..06ae423f957 100644
--- a/frontend/discourse/app/lib/sidebar/section.js
+++ b/frontend/discourse/app/lib/sidebar/section.js
@@ -43,9 +43,16 @@ export default class Section {
if (!this.section.public || this.currentUser?.admin) {
return [
{
- action: () => {
+ action: async () => {
+ const json = await ajax(
+ `/sidebar_sections/${this.section.id}.json`
+ );
+
return this.modal.show(SidebarSectionForm, {
- model: this,
+ model: {
+ hideSectionHeader: this.hideSectionHeader,
+ section: json.sidebar_section,
+ },
});
},
title: i18n("sidebar.sections.custom.edit"),
diff --git a/lib/content_localization.rb b/lib/content_localization.rb
index 816d8118d69..dfa7f8071d8 100644
--- a/lib/content_localization.rb
+++ b/lib/content_localization.rb
@@ -46,6 +46,16 @@ class ContentLocalization
SiteSetting.content_localization_enabled && tag.locale.present? && !tag.in_user_locale?
end
+ def self.show_translated_sidebar_section?(section, scope)
+ SiteSetting.content_localization_enabled && section.public? && section.custom_section? &&
+ section.locale.present? && !section.in_user_locale?
+ end
+
+ def self.show_translated_sidebar_url?(sidebar_url, scope)
+ SiteSetting.content_localization_enabled && sidebar_url.locale.present? &&
+ !sidebar_url.in_user_locale?
+ end
+
def self.crawler_locale_param_enabled?
SiteSetting.content_localization_enabled && SiteSetting.content_localization_crawler_param &&
SiteSetting.set_locale_from_param
diff --git a/lib/guardian/localization_guardian.rb b/lib/guardian/localization_guardian.rb
index 3ff1115cdb9..f031dfe8fce 100644
--- a/lib/guardian/localization_guardian.rb
+++ b/lib/guardian/localization_guardian.rb
@@ -48,4 +48,20 @@ module LocalizationGuardian
tag = tag_or_tag_id.is_a?(Tag) ? tag_or_tag_id : Tag.find_by(id: tag_or_tag_id)
!hidden_tag_names.include?(tag.name)
end
+
+ def can_localize_sidebar_section?(section_or_section_id)
+ return false if !SiteSetting.content_localization_enabled
+ return false if anonymous?
+ return false if [email protected]?
+
+ section =
+ (
+ if section_or_section_id.is_a?(SidebarSection)
+ section_or_section_id
+ else
+ SidebarSection.find_by(id: section_or_section_id)
+ end
+ )
+ section.present? && section.public? && section.custom_section?
+ end
end
diff --git a/plugins/discourse-ai/app/jobs/regular/localize_sidebar_sections.rb b/plugins/discourse-ai/app/jobs/regular/localize_sidebar_sections.rb
new file mode 100644
index 00000000000..d5a10035fee
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/regular/localize_sidebar_sections.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+module Jobs
+ class LocalizeSidebarSections < ::Jobs::Base
+ cluster_concurrency 1
+ sidekiq_options retry: false
+
+ def execute(args)
+ return if !SiteSetting.content_localization_enabled
+ return if !DiscourseAi::Translation.enabled?
+
+ unless DiscourseAi::Translation.credits_available_for_sidebar_localization?
+ Rails.logger.info(
+ "Translation skipped for sidebar sections: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ limit = args[:limit]
+ raise Discourse::InvalidParameters.new(:limit) if limit.nil?
+ return if limit <= 0
+
+ short_text_llm_model =
+ find_llm_model_for_agent(SiteSetting.ai_translation_short_text_translator_agent)
+ return if short_text_llm_model.blank?
+
+ sidebar_sections =
+ DiscourseAi::Translation::SidebarSectionCandidates
+ .get
+ .includes(:sidebar_urls)
+ .where.not(locale: nil)
+ .order(:id)
+ .limit(limit)
+ return if sidebar_sections.empty?
+
+ changed =
+ SidebarSectionLocalization
+ .joins(
+ "INNER JOIN sidebar_sections ON sidebar_sections.id = sidebar_section_localizations.sidebar_section_id",
+ )
+ .where(sidebar_section_id: sidebar_sections)
+ .where("sidebar_section_localizations.locale = sidebar_sections.locale")
+ .delete_all
+ .positive?
+
+ changed ||=
+ SidebarUrlLocalization
+ .joins(
+ "INNER JOIN sidebar_urls ON sidebar_urls.id = sidebar_url_localizations.sidebar_url_id",
+ )
+ .where(sidebar_url_id: sidebar_sections.flat_map(&:sidebar_url_ids))
+ .where("sidebar_url_localizations.locale = sidebar_urls.locale")
+ .delete_all
+ .positive?
+
+ remaining_limit = limit
+ locales = SiteSetting.content_localization_supported_locales.split("|")
+ sidebar_sections.each do |sidebar_section|
+ break if remaining_limit <= 0
+
+ existing_locales =
+ SidebarSectionLocalization.where(sidebar_section_id: sidebar_section.id).pluck(:locale)
+ missing_locales = locales - existing_locales - [sidebar_section.locale]
+ missing_locales.each do |locale|
+ break if remaining_limit <= 0
+ next if LocaleNormalizer.is_same?(locale, sidebar_section.locale)
+
+ begin
+ DiscourseAi::Translation::SidebarSectionLocalizer.localize(
+ sidebar_section,
+ locale,
+ short_text_llm_model:,
+ )
+ changed = true
+ rescue FinalDestination::SSRFDetector::LookupFailedError
+ rescue => e
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Failed to translate sidebar section #{sidebar_section.id} to #{locale}: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",
+ )
+ ensure
+ remaining_limit -= 1
+ end
+ end
+ end
+
+ Site.clear_anon_cache! if changed
+ end
+
+ private
+
+ def find_llm_model_for_agent(agent_id)
+ return nil if agent_id.blank?
+
+ agent_klass = AiAgent.find_by_id_from_cache(agent_id)
+ return nil if agent_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(agent_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/sidebar_localization_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/sidebar_localization_backfill.rb
new file mode 100644
index 00000000000..02f235396cd
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/sidebar_localization_backfill.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module Jobs
+ class SidebarLocalizationBackfill < ::Jobs::Scheduled
+ every 1.hour
+ cluster_concurrency 1
+
+ def execute(args)
+ return if !DiscourseAi::Translation.backfill_enabled?
+
+ short_text_llm =
+ find_llm_model_for_agent(SiteSetting.ai_translation_short_text_translator_agent)
+
+ if short_text_llm && !LlmCreditAllocation.credits_available?(short_text_llm)
+ Rails.logger.info(
+ "Sidebar localization backfill skipped: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ limit = SiteSetting.ai_translation_backfill_hourly_rate
+
+ Jobs.enqueue(:localize_sidebar_sections, limit:)
+ end
+
+ private
+
+ def find_llm_model_for_agent(agent_id)
+ return nil if agent_id.blank?
+
+ agent_klass = AiAgent.find_by_id_from_cache(agent_id)
+ return nil if agent_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(agent_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/sidebar_sections_locale_detection_backfill.rb b/plugins/discourse-ai/app/jobs/scheduled/sidebar_sections_locale_detection_backfill.rb
new file mode 100644
index 00000000000..c3f5371fcec
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/sidebar_sections_locale_detection_backfill.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+module Jobs
+ class SidebarSectionsLocaleDetectionBackfill < ::Jobs::Scheduled
+ every 1.hour
+ sidekiq_options retry: false
+ cluster_concurrency 1
+
+ def execute(args)
+ return if !SiteSetting.content_localization_enabled
+ return if !DiscourseAi::Translation.backfill_enabled?
+
+ llm_model = find_llm_model
+ return if llm_model.blank?
+
+ unless LlmCreditAllocation.credits_available?(llm_model)
+ Rails.logger.info(
+ "Sidebar section locale detection backfill skipped: insufficient credits. Will resume when credits reset.",
+ )
+ return
+ end
+
+ sidebar_sections =
+ DiscourseAi::Translation::SidebarSectionCandidates
+ .get
+ .includes(:sidebar_urls)
+ .where(locale: nil)
+ .limit(SiteSetting.ai_translation_backfill_hourly_rate)
+ return if sidebar_sections.empty?
+
+ sidebar_sections.each do |sidebar_section|
+ DiscourseAi::Translation::SidebarSectionLocaleDetector.detect_locale(sidebar_section)
+ rescue FinalDestination::SSRFDetector::LookupFailedError
+ rescue => e
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Failed to detect sidebar section #{sidebar_section.id}'s locale: #{e.message}\n\n#{e.backtrace[0..3].join("\n")}",
+ )
+ end
+
+ DiscourseAi::Translation::VerboseLogger.log(
+ "Detected #{sidebar_sections.size} sidebar section locales",
+ )
+ end
+
+ private
+
+ def find_llm_model
+ agent_klass = AiAgent.find_by_id_from_cache(SiteSetting.ai_translation_locale_detector_agent)
+ return nil if agent_klass.blank?
+
+ DiscourseAi::Translation::BaseTranslator.preferred_llm_model(agent_klass)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation.rb b/plugins/discourse-ai/lib/translation.rb
index 2cc6f2a3f3f..645c6901b88 100644
--- a/plugins/discourse-ai/lib/translation.rb
+++ b/plugins/discourse-ai/lib/translation.rb
@@ -188,5 +188,9 @@ module DiscourseAi
def self.credits_available_for_tag_localization?
credits_available_for_agent_ids?([SiteSetting.ai_translation_short_text_translator_agent])
end
+
+ def self.credits_available_for_sidebar_localization?
+ credits_available_for_agent_ids?([SiteSetting.ai_translation_short_text_translator_agent])
+ end
end
end
diff --git a/plugins/discourse-ai/lib/translation/sidebar_section_candidates.rb b/plugins/discourse-ai/lib/translation/sidebar_section_candidates.rb
new file mode 100644
index 00000000000..74eac008e6c
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/sidebar_section_candidates.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class SidebarSectionCandidates < BaseCandidates
+ private
+
+ def self.get
+ SidebarSection.public_sections.custom_sections
+ end
+
+ def self.calculate_completion_per_locale(locale)
+ base_locale = "#{locale.split("_").first}%"
+ sql = <<~SQL
+ WITH eligible_sidebar_sections AS (
+ #{get.where.not(sidebar_sections: { locale: nil }).to_sql}
+ ),
+ total_count AS (
+ SELECT COUNT(*) AS count FROM eligible_sidebar_sections
+ ),
+ done_count AS (
+ SELECT COUNT(DISTINCT ss.id)
+ FROM eligible_sidebar_sections ss
+ LEFT JOIN sidebar_section_localizations ssl
+ ON ss.id = ssl.sidebar_section_id AND ssl.locale LIKE :base_locale
+ WHERE ss.locale LIKE :base_locale OR ssl.sidebar_section_id IS NOT NULL
+ )
+ SELECT d.count AS done, t.count AS total
+ FROM total_count t, done_count d
+ SQL
+
+ done, total = DB.query_single(sql, base_locale:)
+ { done:, total: }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation/sidebar_section_locale_detector.rb b/plugins/discourse-ai/lib/translation/sidebar_section_locale_detector.rb
new file mode 100644
index 00000000000..f3cc4165a48
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/sidebar_section_locale_detector.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class SidebarSectionLocaleDetector
+ def self.detect_locale(sidebar_section)
+ return if sidebar_section.blank?
+
+ text =
+ ([sidebar_section.title] + sidebar_section.sidebar_urls.map(&:name)).compact.join("\n\n")
+ return if text.blank?
+
+ detected_locale = LanguageDetector.new(text).detect
+ return if detected_locale.blank?
+
+ locale = LocaleNormalizer.normalize_to_i18n(detected_locale)
+ sidebar_section.update_column(:locale, locale)
+ sidebar_section.sidebar_urls.where(locale: nil).update_all(locale:)
+ locale
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/translation/sidebar_section_localizer.rb b/plugins/discourse-ai/lib/translation/sidebar_section_localizer.rb
new file mode 100644
index 00000000000..121b59f21a4
--- /dev/null
+++ b/plugins/discourse-ai/lib/translation/sidebar_section_localizer.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Translation
+ class SidebarSectionLocalizer
+ def self.localize(sidebar_section, target_locale = I18n.locale, short_text_llm_model: nil)
+ return if sidebar_section.blank? || !sidebar_section.custom_section? || target_locale.blank?
+
+ target_locale = target_locale.to_s.sub("-", "_")
+
+ translated_title =
+ ShortTextTranslator.new(
+ text: sidebar_section.title,
+ target_locale:,
+ llm_model: short_text_llm_model,
+ ).translate
+
+ localization =
+ SidebarSectionLocalization.find_or_initialize_by(
+ sidebar_section_id: sidebar_section.id,
+ locale: target_locale,
+ )
+ localization.title = translated_title
+ localization.save!
+
+ sidebar_section.sidebar_urls.each do |sidebar_url|
+ translated_name =
+ ShortTextTranslator.new(
+ text: sidebar_url.name,
+ target_locale:,
+ llm_model: short_text_llm_model,
+ ).translate
+
+ url_localization =
+ SidebarUrlLocalization.find_or_initialize_by(
+ sidebar_url_id: sidebar_url.id,
+ locale: target_locale,
+ )
+ url_localization.name = translated_name
+ url_localization.save!
+ end
+
+ localization
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/regular/localize_sidebar_sections_spec.rb b/plugins/discourse-ai/spec/jobs/regular/localize_sidebar_sections_spec.rb
new file mode 100644
index 00000000000..090f7bb9506
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/regular/localize_sidebar_sections_spec.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+describe Jobs::LocalizeSidebarSections do
+ subject(:job) { described_class.new }
+
+ before do
+ assign_fake_provider_to(:ai_default_llm_model)
+ enable_current_plugin
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "pt_BR|zh_CN"
+
+ Jobs.run_immediately!
+ end
+
+ it "translates public sidebar sections to configured locales" do
+ sidebar_section = Fabricate(:sidebar_section, public: true, locale: "en")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, "pt_BR", has_entries(short_text_llm_model: anything))
+ .once
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, "zh_CN", has_entries(short_text_llm_model: anything))
+ .once
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does not translate when content localization is disabled" do
+ SiteSetting.content_localization_enabled = false
+ sidebar_section = Fabricate(:sidebar_section, public: true, locale: "en")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, any_parameters)
+ .never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does not translate private sidebar sections" do
+ sidebar_section = Fabricate(:sidebar_section, public: false, locale: "en")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, any_parameters)
+ .never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "does not translate built-in sidebar sections" do
+ community_section =
+ SidebarSection.find_by(section_type: SidebarSection.section_types[:community])
+ community_section.update!(locale: "en")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(community_section, any_parameters)
+ .never
+
+ job.execute({ limit: 10 })
+ end
+
+ it "skips target locales that match the source locale" do
+ sidebar_section = Fabricate(:sidebar_section, public: true, locale: "pt")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, "pt_BR", has_entries(short_text_llm_model: anything))
+ .never
+ DiscourseAi::Translation::SidebarSectionLocalizer
+ .expects(:localize)
+ .with(sidebar_section, "zh_CN", has_entries(short_text_llm_model: anything))
+ .once
+
+ job.execute({ limit: 10 })
+ end
+
+ it "clears the anonymous sidebar cache once after translating sidebar sections" do
+ Fabricate(:sidebar_section, title: "Public section one", public: true, locale: "en")
+ Fabricate(:sidebar_section, title: "Public section two", public: true, locale: "en")
+
+ DiscourseAi::Translation::SidebarSectionLocalizer.stubs(:localize)
+
+ messages = MessageBus.track_publish(Site::SITE_JSON_CHANNEL) { job.execute({ limit: 10 }) }
+
+ expect(messages.size).to eq(1)
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/sidebar_localization_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/sidebar_localization_backfill_spec.rb
new file mode 100644
index 00000000000..410791ad6ea
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/sidebar_localization_backfill_spec.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+describe Jobs::SidebarLocalizationBackfill do
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.ai_translation_backfill_hourly_rate = 100
+ SiteSetting.ai_translation_backfill_max_age_days = 30
+ SiteSetting.content_localization_supported_locales = "pt_BR|zh_CN"
+ end
+
+ it "does not enqueue when AI is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+
+ described_class.new.execute({})
+
+ expect_not_enqueued_with(job: :localize_sidebar_sections)
+ end
+
+ it "enqueues localize_sidebar_sections job with the hourly rate limit" do
+ described_class.new.execute({})
+
+ expect_job_enqueued(job: :localize_sidebar_sections, args: { limit: 100 })
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/sidebar_sections_locale_detection_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/sidebar_sections_locale_detection_backfill_spec.rb
new file mode 100644
index 00000000000..27c0bd421f7
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/sidebar_sections_locale_detection_backfill_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+describe Jobs::SidebarSectionsLocaleDetectionBackfill do
+ subject(:job) { described_class.new }
+
+ fab!(:sidebar_section) { Fabricate(:sidebar_section, public: true, locale: nil) }
+
+ before do
+ assign_fake_provider_to(:ai_default_llm_model)
+ enable_current_plugin
+ SiteSetting.ai_translation_enabled = true
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.ai_translation_backfill_hourly_rate = 100
+ SiteSetting.content_localization_supported_locales = "en"
+ SidebarSection.update_all(locale: "en")
+ sidebar_section.update_column(:locale, nil)
+ end
+
+ it "detects locale for public sections with nil locale" do
+ private_section = Fabricate(:sidebar_section, public: false, locale: nil)
+
+ DiscourseAi::Translation::SidebarSectionLocaleDetector
+ .expects(:detect_locale)
+ .with(sidebar_section)
+ .once
+ DiscourseAi::Translation::SidebarSectionLocaleDetector
+ .expects(:detect_locale)
+ .with(private_section)
+ .never
+
+ job.execute({})
+ end
+
+ it "does not detect locales when content localization is disabled" do
+ SiteSetting.content_localization_enabled = false
+
+ DiscourseAi::Translation::SidebarSectionLocaleDetector
+ .expects(:detect_locale)
+ .with(sidebar_section)
+ .never
+
+ job.execute({})
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/translation/sidebar_section_locale_detector_spec.rb b/plugins/discourse-ai/spec/lib/translation/sidebar_section_locale_detector_spec.rb
new file mode 100644
index 00000000000..ad05a64b033
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/translation/sidebar_section_locale_detector_spec.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Translation::SidebarSectionLocaleDetector do
+ before { enable_current_plugin }
+
+ fab!(:sidebar_section) { Fabricate(:sidebar_section, title: "Participate", locale: nil) }
+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Welcome", value: "/welcome", locale: nil) }
+
+ before do
+ sidebar_section.update_column(:locale, nil)
+ sidebar_url.update_column(:locale, nil)
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+ end
+
+ def language_detector_stub(text:, locale:)
+ detector = instance_double(DiscourseAi::Translation::LanguageDetector)
+ allow(DiscourseAi::Translation::LanguageDetector).to receive(:new).with(text).and_return(
+ detector,
+ )
+ allow(detector).to receive(:detect).and_return(locale)
+ end
+
+ it "updates the section and link locale with the detected locale" do
+ language_detector_stub(text: "Participate\n\nWelcome", locale: "ja")
+
+ expect { described_class.detect_locale(sidebar_section) }.to change {
+ sidebar_section.reload.locale
+ }.from(nil).to("ja")
+
+ expect(sidebar_url.reload.locale).to eq("ja")
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/translation/sidebar_section_localizer_spec.rb b/plugins/discourse-ai/spec/lib/translation/sidebar_section_localizer_spec.rb
new file mode 100644
index 00000000000..34a36e5350a
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/translation/sidebar_section_localizer_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+describe DiscourseAi::Translation::SidebarSectionLocalizer do
+ subject(:localizer) { described_class }
+
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ end
+
+ fab!(:sidebar_section) { Fabricate(:sidebar_section, title: "Participate") }
+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Welcome", value: "/welcome") }
+
+ before { Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url) }
+
+ def short_text_translator_stub(text:, target_locale:, translated:)
+ translator = instance_double(DiscourseAi::Translation::ShortTextTranslator)
+ allow(DiscourseAi::Translation::ShortTextTranslator).to receive(:new).with(
+ text:,
+ target_locale:,
+ llm_model: be_nil,
+ ).and_return(translator)
+ allow(translator).to receive(:translate).and_return(translated)
+ end
+
+ it "translates the sidebar section title and link names" do
+ short_text_translator_stub(text: "Participate", target_locale: "ja", translated: "参加")
+ short_text_translator_stub(text: "Welcome", target_locale: "ja", translated: "ようこそ")
+
+ localization = localizer.localize(sidebar_section, "ja")
+
+ expect(localization).to have_attributes(locale: "ja", title: "参加")
+ expect(sidebar_url.localizations.last).to have_attributes(locale: "ja", name: "ようこそ")
+ end
+
+ it "updates existing localizations" do
+ existing = Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "古い")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "古い")
+ short_text_translator_stub(text: "Participate", target_locale: "ja", translated: "参加")
+ short_text_translator_stub(text: "Welcome", target_locale: "ja", translated: "ようこそ")
+
+ expect { localizer.localize(sidebar_section, "ja") }.not_to change {
+ SidebarSectionLocalization.count
+ }
+
+ expect(existing.reload.title).to eq("参加")
+ expect(sidebar_url.localizations.last.reload.name).to eq("ようこそ")
+ end
+
+ it "does not translate built-in sidebar sections" do
+ community_section =
+ SidebarSection.find_by(section_type: SidebarSection.section_types[:community])
+
+ expect { localizer.localize(community_section, "ja") }.not_to change {
+ SidebarSectionLocalization.count
+ }
+ end
+end
diff --git a/spec/fabricators/sidebar_section_localization_fabricator.rb b/spec/fabricators/sidebar_section_localization_fabricator.rb
new file mode 100644
index 00000000000..cef7d292027
--- /dev/null
+++ b/spec/fabricators/sidebar_section_localization_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+Fabricator(:sidebar_section_localization) do
+ sidebar_section
+ locale "ja"
+ title "サイドバー"
+end
diff --git a/spec/fabricators/sidebar_url_localization_fabricator.rb b/spec/fabricators/sidebar_url_localization_fabricator.rb
new file mode 100644
index 00000000000..af882efc3d0
--- /dev/null
+++ b/spec/fabricators/sidebar_url_localization_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+Fabricator(:sidebar_url_localization) do
+ sidebar_url
+ locale "ja"
+ name "タグ"
+end
diff --git a/spec/models/sidebar_section_localization_spec.rb b/spec/models/sidebar_section_localization_spec.rb
new file mode 100644
index 00000000000..714b8dd5664
--- /dev/null
+++ b/spec/models/sidebar_section_localization_spec.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+describe SidebarSectionLocalization do
+ it "enforces one localization per sidebar section and locale" do
+ sidebar_section = Fabricate(:sidebar_section)
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja")
+
+ localization = Fabricate.build(:sidebar_section_localization, sidebar_section:, locale: "ja")
+
+ expect(localization).not_to be_valid
+ expect(localization.errors.details[:sidebar_section_id]).to contain_exactly(
+ include(error: :taken),
+ )
+ end
+end
diff --git a/spec/models/sidebar_url_localization_spec.rb b/spec/models/sidebar_url_localization_spec.rb
new file mode 100644
index 00000000000..97af8d02a28
--- /dev/null
+++ b/spec/models/sidebar_url_localization_spec.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+describe SidebarUrlLocalization do
+ it "enforces one localization per sidebar URL and locale" do
+ sidebar_url = Fabricate(:sidebar_url)
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja")
+
+ localization = Fabricate.build(:sidebar_url_localization, sidebar_url:, locale: "ja")
+
+ expect(localization).not_to be_valid
+ expect(localization.errors.details[:sidebar_url_id]).to contain_exactly(include(error: :taken))
+ end
+end
diff --git a/spec/requests/sidebar_sections_controller_spec.rb b/spec/requests/sidebar_sections_controller_spec.rb
index 12b91837a4b..e3cb1719371 100644
--- a/spec/requests/sidebar_sections_controller_spec.rb
+++ b/spec/requests/sidebar_sections_controller_spec.rb
@@ -39,6 +39,63 @@ RSpec.describe SidebarSectionsController do
end
end
+ describe "#show" do
+ fab!(:sidebar_section) { Fabricate(:sidebar_section, title: "Public section", public: true) }
+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags") }
+
+ before do
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "公開セクション")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "タグ")
+ end
+
+ it "returns source labels for admins editing a localized section" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(admin)
+
+ I18n.with_locale("ja") { get "/sidebar_sections/#{sidebar_section.id}.json" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("sidebar_section", "title")).to eq("Public section")
+ expect(response.parsed_body.dig("sidebar_section", "links", 0, "name")).to eq("Sidebar Tags")
+ expect(response.parsed_body.dig("sidebar_section", "localizations", 0, "title")).to eq(
+ "公開セクション",
+ )
+ expect(
+ response.parsed_body.dig("sidebar_section", "links", 0, "localizations", 0, "name"),
+ ).to eq("タグ")
+ end
+
+ it "does not return localization rows for admins editing a built-in section" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(admin)
+ community_section =
+ SidebarSection.find_by(section_type: SidebarSection.section_types[:community])
+ topics_link = community_section.sidebar_urls.find_by(name: "Topics")
+ Fabricate(:sidebar_section_localization, sidebar_section: community_section, locale: "ja")
+ Fabricate(:sidebar_url_localization, sidebar_url: topics_link, locale: "ja")
+
+ get "/sidebar_sections/#{community_section.id}.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("sidebar_section", "localizations")).to eq(nil)
+ expect(
+ response
+ .parsed_body
+ .dig("sidebar_section", "links")
+ .filter_map { |link| link["localizations"] },
+ ).to be_empty
+ end
+
+ it "does not allow regular users to load a public section for editing" do
+ sign_in(user)
+
+ get "/sidebar_sections/#{sidebar_section.id}.json"
+
+ expect(response.status).to eq(403)
+ end
+ end
+
describe "#create" do
it "is not available for anonymous" do
post "/sidebar_sections.json",
@@ -133,6 +190,33 @@ RSpec.describe SidebarSectionsController do
expect(response.status).to eq(403)
end
+ it "does not allow regular user to create section localizations" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(user)
+
+ post "/sidebar_sections.json",
+ params: {
+ title: "custom section",
+ locale: "ja",
+ localizations: [{ locale: "ja", title: "カスタム" }],
+ links: [
+ {
+ icon: "link",
+ name: "categories",
+ value: "/categories",
+ localizations: [{ locale: "ja", name: "カテゴリー" }],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+
+ sidebar_section = SidebarSection.last
+ expect(sidebar_section.locale).to eq(SiteSetting.default_locale)
+ expect(sidebar_section.localizations).to be_blank
+ expect(sidebar_section.sidebar_urls.first.localizations).to be_blank
+ end
+
it "does not allow moderator to create public section" do
sign_in(moderator)
@@ -174,6 +258,68 @@ RSpec.describe SidebarSectionsController do
expect(user_history.subject).to eq("custom section")
expect(user_history.details).to eq("links: categories - /categories, tags - /tags")
end
+
+ it "allows admin to create public section localizations" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(admin)
+
+ post "/sidebar_sections.json",
+ params: {
+ title: "custom section",
+ public: true,
+ localizations: [
+ { locale: SiteSetting.default_locale, title: "Default locale" },
+ { locale: "ja", title: "カスタム" },
+ ],
+ links: [
+ {
+ icon: "link",
+ name: "categories",
+ value: "/categories",
+ localizations: [
+ { locale: SiteSetting.default_locale, name: "Default locale" },
+ { locale: "ja", name: "カテゴリー" },
+ ],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+
+ sidebar_section = SidebarSection.last
+ expect(sidebar_section.localizations.map { |localization| localization.title }).to eq(
+ ["カスタム"],
+ )
+ expect(sidebar_section.sidebar_urls.first.localizations.map(&:name)).to eq(["カテゴリー"])
+ end
+
+ it "does not create localizations when content localization is disabled" do
+ SiteSetting.content_localization_enabled = false
+ sign_in(admin)
+
+ post "/sidebar_sections.json",
+ params: {
+ title: "custom section",
+ public: true,
+ locale: "ja",
+ localizations: [{ locale: "ja", title: "カスタム" }],
+ links: [
+ {
+ icon: "link",
+ name: "categories",
+ value: "/categories",
+ localizations: [{ locale: "ja", name: "カテゴリー" }],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+
+ sidebar_section = SidebarSection.last
+ expect(sidebar_section.locale).to eq(SiteSetting.default_locale)
+ expect(sidebar_section.localizations).to be_blank
+ expect(sidebar_section.sidebar_urls.first.localizations).to be_blank
+ end
end
describe "#update" do
@@ -215,6 +361,45 @@ RSpec.describe SidebarSectionsController do
expect { sidebar_url_2.reload }.to raise_error(ActiveRecord::RecordNotFound)
end
+ it "does not allow a user to update their own section locale" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(user)
+
+ put "/sidebar_sections/#{sidebar_section.id}.json",
+ params: {
+ title: "custom section edited",
+ locale: "ja",
+ links: [{ icon: "link", id: sidebar_url_1.id, name: "latest", value: "/latest" }],
+ }
+
+ expect(response.status).to eq(200)
+ expect(sidebar_section.reload.locale).to eq(SiteSetting.default_locale)
+ end
+
+ it "does not allow a user to update their own section localizations" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(user)
+
+ put "/sidebar_sections/#{sidebar_section.id}.json",
+ params: {
+ title: "custom section edited",
+ localizations: [{ locale: "ja", title: "カスタム" }],
+ links: [
+ {
+ icon: "link",
+ id: sidebar_url_1.id,
+ name: "latest",
+ value: "/latest",
+ localizations: [{ locale: "ja", name: "最新" }],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(403)
+ expect(sidebar_section.reload.localizations).to be_blank
+ expect(sidebar_url_1.reload.localizations).to be_blank
+ end
+
it "allows admin to update public section and links" do
sign_in(admin)
sidebar_section.update!(public: true)
@@ -266,6 +451,109 @@ RSpec.describe SidebarSectionsController do
)
end
+ it "allows admin to update public section localizations" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.default_locale = "en"
+ sign_in(admin)
+ sidebar_section.update_columns(public: true, locale: nil)
+ sidebar_url_1.update_column(:locale, nil)
+ section_localization =
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "古い")
+ url_localization =
+ Fabricate(:sidebar_url_localization, sidebar_url: sidebar_url_1, locale: "ja", name: "古い")
+
+ put "/sidebar_sections/#{sidebar_section.id}.json",
+ params: {
+ title: "custom section edited",
+ localizations: [
+ { id: section_localization.id, locale: "ja", title: "新しい" },
+ { locale: "fr", title: "Nouveau" },
+ { locale: SiteSetting.default_locale, title: "Default locale" },
+ ],
+ links: [
+ {
+ icon: "link",
+ id: sidebar_url_1.id,
+ name: "latest",
+ value: "/latest",
+ localizations: [
+ { id: url_localization.id, locale: "ja", name: "最新" },
+ { locale: "fr", name: "Récent" },
+ { locale: SiteSetting.default_locale, name: "Default locale" },
+ ],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+ expect(sidebar_section.reload.locale).to eq("en")
+ expect(sidebar_url_1.reload.locale).to eq("en")
+ expect(sidebar_section.reload.localizations.order(:locale).pluck(:locale, :title)).to eq(
+ [%w[fr Nouveau], %w[ja 新しい]],
+ )
+ expect(sidebar_url_1.reload.localizations.order(:locale).pluck(:locale, :name)).to eq(
+ [%w[fr Récent], %w[ja 最新]],
+ )
+ end
+
+ it "does not allow admin to update built-in section localizations" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(admin)
+ topics_link = community_section.sidebar_urls.find_by(name: "Topics")
+
+ put "/sidebar_sections/#{community_section.id}.json",
+ params: {
+ title: "community section edited",
+ localizations: [{ locale: "ja", title: "コミュニティ" }],
+ links: [
+ {
+ icon: "link",
+ id: topics_link.id,
+ name: "topics edited",
+ value: "/latest",
+ localizations: [{ locale: "ja", name: "トピック" }],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(403)
+ expect(community_section.reload.localizations).to be_blank
+ expect(topics_link.reload.localizations).to be_blank
+ end
+
+ it "allows admin to remove public section localizations" do
+ SiteSetting.content_localization_enabled = true
+ sign_in(admin)
+ sidebar_section.update!(public: true)
+ section_localization =
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "古い")
+ url_localization =
+ Fabricate(:sidebar_url_localization, sidebar_url: sidebar_url_1, locale: "ja", name: "古い")
+
+ put "/sidebar_sections/#{sidebar_section.id}.json",
+ params: {
+ title: "custom section edited",
+ localizations: [
+ { id: section_localization.id, locale: "ja", title: "古い", _destroy: "1" },
+ ],
+ links: [
+ {
+ icon: "link",
+ id: sidebar_url_1.id,
+ name: "latest",
+ value: "/latest",
+ localizations: [
+ { id: url_localization.id, locale: "ja", name: "古い", _destroy: "1" },
+ ],
+ },
+ ],
+ }
+
+ expect(response.status).to eq(200)
+ expect(SidebarSectionLocalization.exists?(section_localization.id)).to eq(false)
+ expect(SidebarUrlLocalization.exists?(url_localization.id)).to eq(false)
+ end
+
it "validates limit of links" do
SiteSetting.max_sidebar_section_links = 5
diff --git a/spec/serializers/current_user_serializer_spec.rb b/spec/serializers/current_user_serializer_spec.rb
index 67ee4a19fbf..7aacf994b47 100644
--- a/spec/serializers/current_user_serializer_spec.rb
+++ b/spec/serializers/current_user_serializer_spec.rb
@@ -343,7 +343,7 @@ RSpec.describe CurrentUserSerializer do
expect(serialized[:sidebar_sections].count).to eq(2)
- expect(serialized[:sidebar_sections].last[:links].map { |link| link.id }).to eq(
+ expect(serialized[:sidebar_sections].last[:links].map { |link| link[:id] }).to eq(
[custom_sidebar_section_link_1.linkable.id],
)
end.count
@@ -357,7 +357,7 @@ RSpec.describe CurrentUserSerializer do
expect(serialized[:sidebar_sections].count).to eq(2)
- expect(serialized[:sidebar_sections].last[:links].map { |link| link.id }).to eq(
+ expect(serialized[:sidebar_sections].last[:links].map { |link| link[:id] }).to eq(
[custom_sidebar_section_link_1.linkable.id, custom_sidebar_section_link_2.linkable.id],
)
end.count
diff --git a/spec/serializers/sidebar_section_serializer_spec.rb b/spec/serializers/sidebar_section_serializer_spec.rb
new file mode 100644
index 00000000000..4e04066f29a
--- /dev/null
+++ b/spec/serializers/sidebar_section_serializer_spec.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+describe SidebarSectionSerializer do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:sidebar_section) do
+ Fabricate(:sidebar_section, title: "Participate", public: true, locale: "en")
+ end
+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Welcome", value: "/welcome", locale: "en") }
+
+ before do
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "参加")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "ようこそ")
+ end
+
+ def serialized_for(guardian)
+ reloaded =
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(sidebar_section.id)
+ described_class.new(reloaded, scope: guardian, root: false).as_json
+ end
+
+ it "returns localized section titles and link names when content localization is enabled" do
+ SiteSetting.content_localization_enabled = true
+
+ I18n.with_locale("ja") do
+ json = serialized_for(Guardian.new(user))
+
+ expect(json[:title]).to eq("参加")
+ expect(json[:links].first[:name]).to eq("ようこそ")
+ end
+ end
+
+ it "returns original labels when content localization is disabled" do
+ SiteSetting.content_localization_enabled = false
+
+ I18n.with_locale("ja") do
+ json = serialized_for(Guardian.new(user))
+
+ expect(json[:title]).to eq("Participate")
+ expect(json[:links].first[:name]).to eq("Welcome")
+ end
+ end
+
+ it "does not expose localization rows in the regular presentation payload" do
+ SiteSetting.content_localization_enabled = true
+
+ expect(serialized_for(Guardian.new(user))[:localizations]).to eq(nil)
+ expect(serialized_for(Guardian.new(user))[:links].first[:localizations]).to eq(nil)
+ expect(serialized_for(Guardian.new(admin))[:localizations]).to eq(nil)
+ expect(serialized_for(Guardian.new(admin))[:links].first[:localizations]).to eq(nil)
+ end
+
+ it "returns source labels and localization rows from the edit serializer" do
+ SiteSetting.content_localization_enabled = true
+
+ I18n.with_locale("ja") do
+ reloaded =
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(
+ sidebar_section.id,
+ )
+ json =
+ SidebarSectionEditSerializer.new(reloaded, scope: Guardian.new(admin), root: false).as_json
+
+ expect(json[:title]).to eq("Participate")
+ expect(json[:links].first[:name]).to eq("Welcome")
+ expect(json[:localizations].first[:title]).to eq("参加")
+ expect(json[:links].first[:localizations].first[:name]).to eq("ようこそ")
+ end
+ end
+
+ it "returns original labels for private sections with localizations" do
+ SiteSetting.content_localization_enabled = true
+ private_section = Fabricate(:sidebar_section, title: "Private section", locale: "en", user:)
+ private_url = Fabricate(:sidebar_url, name: "Private link", value: "/private", locale: "en")
+ Fabricate(:sidebar_section_link, sidebar_section: private_section, linkable: private_url)
+ Fabricate(
+ :sidebar_section_localization,
+ sidebar_section: private_section,
+ locale: "ja",
+ title: "非公開セクション",
+ )
+ Fabricate(:sidebar_url_localization, sidebar_url: private_url, locale: "ja", name: "非公開リンク")
+
+ I18n.with_locale("ja") do
+ reloaded =
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(
+ private_section.id,
+ )
+ json = described_class.new(reloaded, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:title]).to eq("Private section")
+ expect(json[:links].first[:name]).to eq("Private link")
+ expect(json[:localizations]).to eq(nil)
+ expect(json[:links].first[:localizations]).to eq(nil)
+ end
+ end
+
+ it "returns original labels for built-in sections with localizations" do
+ SiteSetting.content_localization_enabled = true
+ community_section =
+ SidebarSection.find_by(section_type: SidebarSection.section_types[:community])
+ community_section.update!(locale: "en")
+ topics_link = community_section.sidebar_urls.find_by(name: "Topics")
+ topics_link.update!(locale: "en")
+ Fabricate(:sidebar_section_localization, sidebar_section: community_section, locale: "ja")
+ Fabricate(:sidebar_url_localization, sidebar_url: topics_link, locale: "ja")
+
+ I18n.with_locale("ja") do
+ reloaded =
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(
+ community_section.id,
+ )
+ json = described_class.new(reloaded, scope: Guardian.new(user), root: false).as_json
+
+ expect(json[:title]).to eq("Community")
+ expect(json[:links].find { |link| link[:id] == topics_link.id }[:name]).to eq("Topics")
+ expect(json[:localizations]).to eq(nil)
+ expect(json[:links].find { |link| link[:id] == topics_link.id }[:localizations]).to eq(nil)
+ end
+ end
+end
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index 953e5595982..60e1fa5475f 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -340,9 +340,9 @@ RSpec.describe SiteSerializer do
expect(serialized[:anonymous_sidebar_sections].count).to eq(2)
- expect(serialized[:anonymous_sidebar_sections].last[:links].map { |link| link.id }).to eq(
- [public_section_link.linkable.id],
- )
+ expect(
+ serialized[:anonymous_sidebar_sections].last[:links].map { |link| link[:id] },
+ ).to eq([public_section_link.linkable.id])
end.count
public_section_link_2 =
@@ -356,7 +356,9 @@ RSpec.describe SiteSerializer do
expect(serialized[:anonymous_sidebar_sections].count).to eq(2)
- expect(serialized[:anonymous_sidebar_sections].last[:links].map { |link| link.id }).to eq(
+ expect(
+ serialized[:anonymous_sidebar_sections].last[:links].map { |link| link[:id] },
+ ).to eq(
[
public_section_link.linkable.id,
public_section_link_2.linkable.id,
diff --git a/spec/system/custom_sidebar_sections_spec.rb b/spec/system/custom_sidebar_sections_spec.rb
index 98cc2d0fff7..7de5ecc827d 100644
--- a/spec/system/custom_sidebar_sections_spec.rb
+++ b/spec/system/custom_sidebar_sections_spec.rb
@@ -20,6 +20,7 @@ describe "Custom sidebar sections" do
expect(section_modal).to be_visible
expect(section_modal).to have_disabled_save
+ expect(section_modal).to have_section_links_label
expect(sidebar.custom_section_modal_title).to have_content("Add custom section")
section_modal.fill_name("My section")
@@ -378,6 +379,131 @@ describe "Custom sidebar sections" do
expect(sidebar).to have_no_section("Edited public section")
end
+ it "shows localized public custom sections" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja"
+ user.update!(locale: "ja")
+ sidebar_section =
+ Fabricate(:sidebar_section, title: "Public section", public: true, locale: "en")
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "公開セクション")
+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "en")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "タグ")
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+
+ sign_in user
+ visit("/latest")
+
+ expect(page).to have_css(".sidebar-section-header", text: "公開セクション")
+ expect(page).to have_css(".sidebar-section-link", text: "タグ")
+ end
+
+ it "loads source labels when editing localized public custom sections" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja"
+ admin.update!(locale: "ja")
+ sidebar_section =
+ Fabricate(:sidebar_section, title: "Public section", public: true, locale: "en")
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "公開セクション")
+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "en")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "タグ")
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+
+ sign_in admin
+ visit("/latest")
+
+ expect(page).to have_css(".sidebar-section-header", text: "公開セクション")
+ expect(page).to have_css(".sidebar-section-link", text: "タグ")
+
+ sidebar.edit_custom_section("Public section")
+
+ expect(section_modal).to have_section_name("Public section")
+ expect(section_modal).to have_first_link_name("Sidebar Tags")
+ end
+
+ it "shows translation controls only when a section is visible to everyone" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja|zh_CN"
+ sidebar_section =
+ Fabricate(:sidebar_section, title: "Public section", public: true, locale: "en")
+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "公開セクション")
+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "en")
+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "タグ")
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+
+ sign_in admin
+ visit("/latest")
+
+ sidebar.edit_custom_section("Public section")
+
+ expect(section_modal).to have_localization_controls
+
+ section_modal.mark_as_public
+
+ expect(section_modal).to have_no_localization_controls
+ end
+
+ it "does not show translation controls for the built-in community section" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.content_localization_supported_locales = "ja"
+
+ sign_in admin
+ visit("/latest")
+
+ sidebar.click_community_section_more_button
+ sidebar.click_customize_community_section_button
+
+ expect(section_modal).to have_no_localization_controls
+ end
+
+ it "does not offer the default locale as a translation target" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.default_locale = "en"
+ SiteSetting.content_localization_supported_locales = "en|ja"
+ sidebar_section =
+ Fabricate(:sidebar_section, title: "Public section", public: true, locale: "en")
+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "en")
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+
+ sign_in admin
+ visit("/latest")
+
+ sidebar.edit_custom_section("Public section")
+ find(".add-localization").click
+
+ expect(section_modal).to have_locale_option("ja")
+ expect(section_modal).to have_no_locale_option(SiteSetting.default_locale)
+ end
+
+ it "does not allow duplicate section title translation locales" do
+ SiteSetting.content_localization_enabled = true
+ SiteSetting.default_locale = "en"
+ SiteSetting.content_localization_supported_locales = "en|zh_CN|ja"
+ sidebar_section =
+ Fabricate(:sidebar_section, title: "Public section", public: true, locale: "en")
+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "en")
+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+
+ sign_in admin
+ visit("/latest")
+
+ sidebar.edit_custom_section("Public section")
+ section_modal.add_section_title_translation
+ section_modal.add_section_title_translation
+
+ section_title_translation_locales = section_modal.section_title_translation_locales
+
+ expect(section_title_translation_locales).to contain_exactly("zh_CN", "ja")
+ expect(section_modal).to have_disabled_section_title_translation_locale(
+ 0,
+ section_title_translation_locales.second,
+ )
+ expect(section_modal).to have_disabled_section_title_translation_locale(
+ 1,
+ section_title_translation_locales.first,
+ )
+ expect(section_modal).to have_no_add_section_title_translation
+ end
+
it "displays warning when public section is marked as private" do
sign_in admin
visit("/latest")
diff --git a/spec/system/page_objects/modals/sidebar_section_form.rb b/spec/system/page_objects/modals/sidebar_section_form.rb
index b10f9d994d9..97c601406dd 100644
--- a/spec/system/page_objects/modals/sidebar_section_form.rb
+++ b/spec/system/page_objects/modals/sidebar_section_form.rb
@@ -30,6 +30,32 @@ module PageObjects
all(".delete-link").last.click
end
+ def add_section_title_translation
+ find(".add-localization").click
+ end
+
+ def add_section_localization(title)
+ add_section_title_translation
+ all(section_title_translation_locale_selector)
+ .last
+ .find("option[value='ja']", visible: :all)
+ .select_option
+ all(
+ "input[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.title_label")}']",
+ ).last.fill_in(with: title)
+ end
+
+ def add_first_link_localization(name)
+ find(".add-link-localization", match: :first).click
+ all("select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}']")
+ .last
+ .find("option[value='ja']")
+ .select_option
+ all(
+ "input[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.link_label")}']",
+ ).last.fill_in(with: name)
+ end
+
def delete
find("#delete-section").click
end
@@ -72,6 +98,57 @@ module PageObjects
find_button("Save", disabled: false)
end
+ def has_localization_controls?
+ page.has_css?(".sidebar-section-form__localization-row") &&
+ page.has_css?(".add-localization") && page.has_css?(".add-link-localization")
+ end
+
+ def has_no_localization_controls?
+ page.has_no_css?(".sidebar-section-form__localization-row") &&
+ page.has_no_css?(".add-localization") && page.has_no_css?(".add-link-localization")
+ end
+
+ def has_locale_option?(locale)
+ page.has_css?(
+ "select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}'] option[value='#{locale}']",
+ visible: :all,
+ )
+ end
+
+ def has_no_locale_option?(locale)
+ page.has_no_css?(
+ "select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}'] option[value='#{locale}']",
+ visible: :all,
+ )
+ end
+
+ def section_title_translation_locales
+ all(section_title_translation_locale_selector).map(&:value)
+ end
+
+ def has_disabled_section_title_translation_locale?(row, locale)
+ all(section_title_translation_locale_selector)[row].has_css?(
+ "option[value='#{locale}'][disabled]",
+ visible: :all,
+ )
+ end
+
+ def has_no_add_section_title_translation?
+ page.has_no_css?(".add-localization")
+ end
+
+ def has_section_links_label?
+ page.has_css?(".sidebar-section-form__links-label", text: "Section links")
+ end
+
+ def has_section_name?(name)
+ page.has_field?("section-name", with: name)
+ end
+
+ def has_first_link_name?(name)
+ page.has_field?("link-name", with: name, match: :first)
+ end
+
def topics_link
find(".draggable[data-link-name='Topics']")
end
@@ -79,6 +156,12 @@ module PageObjects
def review_link
find(".draggable[data-link-name='Review']")
end
+
+ private
+
+ def section_title_translation_locale_selector
+ ".sidebar-section-form > .sidebar-section-form__localizations select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}']"
+ end
end
end
end