A platform for community discussion. Free, open, simple.
FIX: Base custom sidebar section translations on their source locale (#42027)
Régis Hanol00aad38a64a0
diff --git a/app/assets/stylesheets/common/base/sidebar.scss b/app/assets/stylesheets/common/base/sidebar.scssindex 573fd2a2243..082cbc18868 100644--- a/app/assets/stylesheets/common/base/sidebar.scss+++ b/app/assets/stylesheets/common/base/sidebar.scss@@ -233,51 +233,97 @@font-weight: var(--token-font-weight-bold);}- .sidebar-section-form__localizations,- .sidebar-section-form-link__localizations {- margin-block: 0 1em;+ .sidebar-section-form__source-locale {+ margin-bottom: 1em;++ label {+ display: block;+ font-weight: var(--token-font-weight-bold);+ }++ .sidebar-section-form__source-locale-select {+ width: auto;+ max-width: 100%;+ }}- .sidebar-section-form__localization-row {- display: grid;- grid-template-columns: 6.2em 0.8em 1fr 0.5em 2em;+ .sidebar-section-form__source-locale-description {+ margin: 0.25em 0 1.5em;+ color: var(--token-color-text-subtle);+ font-size: var(--font-down-1);+ }++ .sidebar-section-form__manage-translations {+ justify-content: flex-start;+ width: 100%;+ }++ .sidebar-section-form__translations-incomplete {+ margin-inline-start: 0.5em;+ color: var(--token-color-text-subtle);+ font-size: var(--font-down-1);+ }++ .sidebar-section-translations__back {+ margin-bottom: 1em;+ padding-inline-start: 0;+ }++ .sidebar-section-translations__language {+ margin-bottom: 1.5em;+ padding: 0.75em;+ border: 1px solid var(--token-color-border);+ border-radius: var(--d-border-radius);+ }++ .sidebar-section-translations__language-header {+ display: flex;align-items: center;- margin-bottom: 0.5em;+ justify-content: space-between;+ gap: 0.5em;+ margin-bottom: 0.75em;- .sidebar-section-form__localization-locale {- grid-column: 1;+ .sidebar-section-translations__language-select {width: auto;+ max-width: 100%;}+ }- .sidebar-section-form__localization-value {- grid-column: 3;- }+ .sidebar-section-translations__caption {+ margin-bottom: 0.25em;+ color: var(--token-color-text-subtle);+ font-size: var(--font-down-1);+ font-weight: var(--token-font-weight-bold);+ }- .remove-localization {- grid-column: 5;- width: 2em;- min-width: 2em;- padding-inline: 0;- justify-self: center;- }+ .sidebar-section-translations__row {+ display: grid;+ grid-template-columns: minmax(6em, 1fr) 2fr;+ align-items: center;+ gap: 0.5em;+ margin-bottom: 0.5em;@include viewport.until(sm) {- grid-template-columns: 1fr auto;+ grid-template-columns: 1fr;+ gap: 0.25em;+ }- .sidebar-section-form__localization-locale,- .sidebar-section-form__localization-value {- grid-column: 1 / span 2;- }+ .sidebar-section-translations__source {+ overflow-wrap: anywhere;+ font-weight: var(--token-font-weight-regular);+ }++ .sidebar-section-translations__value {+ width: 100%;+ margin-bottom: 0;- .remove-localization {- grid-column: 2;- grid-row: auto;+ &.--untranslated {+ border-style: dashed;}}- input,- select {- width: 100%;+ .warning {+ grid-column: 1 / -1;}}diff --git a/app/controllers/sidebar_sections_controller.rb b/app/controllers/sidebar_sections_controller.rbindex f10fc23c63a..ffc6bde4999 100644--- a/app/controllers/sidebar_sections_controller.rb+++ b/app/controllers/sidebar_sections_controller.rb@@ -34,8 +34,13 @@ class SidebarSectionsController < ApplicationControllerenddef create+ new_section = SidebarSection.new(public: submitted_public)+ ensure_localization_params_allowed(new_section)+sidebar_section =- SidebarSection.create!(section_params.merge(sidebar_urls_attributes: links_params))+ SidebarSection.create!(+ section_params(new_section).merge(sidebar_urls_attributes: links_params(new_section)),+ )if sidebar_section.public?StaffActionLogger.new(current_user).log_create_public_sidebar_section(sidebar_section)@@ -48,12 +53,14 @@ class SidebarSectionsController < ApplicationControllerrender_json_error(e.record.errors.full_messages.first)rescue ActiveRecord::NestedAttributes::TooManyRecords => erender_json_error(e.message)+ rescue Discourse::InvalidAccess+ render json: failed_json, status: :forbiddenenddef updatesidebar_section = SidebarSection.find(params[:id])@guardian.ensure_can_edit!(sidebar_section)- ensure_localization_params_allowed(sidebar_section) if localization_params_present?+ ensure_localization_params_allowed(sidebar_section)permitted_section_params = section_params(sidebar_section)permitted_links_params = links_params(sidebar_section)@@ -108,7 +115,8 @@ class SidebarSectionsController < ApplicationControllersection_params.merge!(params.permit(:public).to_h.with_indifferent_access)if SiteSetting.content_localization_enabled &&- (sidebar_section.blank? || guardian.can_localize_sidebar_section_title?(sidebar_section))+ guardian.can_localize_sidebar_section_title?(sidebar_section, public: submitted_public)+ validate_source_locale!(params[:locale], sidebar_section&.locale)section_params.merge!(params.permit(:locale, localizations: %i[id locale title _destroy])@@ -123,6 +131,7 @@ class SidebarSectionsController < ApplicationControllerif section_params[:localizations]section_params[:localizations_attributes] = prepare_localization_attributes(section_params.delete(:localizations),+ resolved_source_locale(section_params[:locale], sidebar_section&.locale),)endsection_params@@ -131,20 +140,39 @@ class SidebarSectionsController < ApplicationControllerdef links_params(sidebar_section = nil)permitted_link_params = %i[icon name value id _destroy segment]if current_user.admin? && SiteSetting.content_localization_enabled+ permitted_link_params << :localepermitted_link_params << { localizations: %i[id locale name _destroy] }endlinks = params.permit(links: permitted_link_params)["links"]+ public_submitted = submitted_public+ stored_locales = nillinks&.each do |link|- next if link[:localizations].blank?+ next if link[:locale].blank? && link[:localizations].blank?+if sidebar_section.present? &&- !guardian.can_localize_sidebar_section_link?(sidebar_section, link[:value])+ !guardian.can_localize_sidebar_section_link?(+ sidebar_section,+ link[:value],+ public: public_submitted,+ )+ link.delete(:locale)link.delete(:localizations)nextend- link[:localizations_attributes] = prepare_localization_attributes(link.delete(:localizations))+ stored_locales ||=+ sidebar_section ? sidebar_section.sidebar_urls.to_h { |url| [url.id, url.locale] } : {}+ stored_locale = stored_locales[link[:id].to_i]+ validate_source_locale!(link[:locale], stored_locale.presence || sidebar_section&.locale)++ next if link[:localizations].blank?++ link[:localizations_attributes] = prepare_localization_attributes(+ link.delete(:localizations),+ resolved_source_locale(link[:locale], stored_locale),+ )endlinks@@ -157,38 +185,58 @@ class SidebarSectionsController < ApplicationControllerprivatedef check_access_if_public- public_section = ActiveModel::Type::Boolean.new.cast(params[:public])- return true if !public_section+ return true if !submitted_publicraise 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? }+ def validate_source_locale!(locale, stored_locale)+ return if locale.blank? || locale == stored_locale+ return if LocaleSiteSetting.supported_locales.include?(locale)++ raise Discourse::InvalidParameters.new(:locale)+ end++ def resolved_source_locale(submitted_locale, stored_locale)+ return stored_locale.presence || SiteSetting.default_locale if submitted_locale.nil?++ submitted_locale.presence || SiteSetting.default_locale+ end++ def submitted_public+ ActiveModel::Type::Boolean.new.cast(params[:public]) if params.key?(:public)enddef ensure_localization_params_allowed(sidebar_section)- if params[:localizations].present? &&- !guardian.can_localize_sidebar_section_title?(sidebar_section)+ return if !SiteSetting.content_localization_enabled++ public = submitted_public++ if (params[:locale].present? || params[:localizations].present?) &&+ !guardian.can_localize_sidebar_section_title?(sidebar_section, public:)raise Discourse::InvalidAccessendparams[:links]&.each do |link|next if link[:localizations].blank?- next if guardian.can_localize_sidebar_section_link?(sidebar_section, link[:value])+ next if guardian.can_localize_sidebar_section_link?(sidebar_section, link[:value], public:)raise Discourse::InvalidAccessendend- def prepare_localization_attributes(localizations)+ def prepare_localization_attributes(localizations, source_locale)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+ next localization if ActiveModel::Type::Boolean.new.cast(localization[:_destroy])+ next localization if !LocaleNormalizer.is_same?(localization[:locale], source_locale)- localization+ if exact_locale_match?(localization[:locale], source_locale) && localization[:id].present?+ localization.merge(_destroy: true)+ endendend++ def exact_locale_match?(locale, source_locale)+ LocaleNormalizer.normalize_to_i18n(locale) == LocaleNormalizer.normalize_to_i18n(source_locale)+ endenddiff --git a/app/models/sidebar_section.rb b/app/models/sidebar_section.rbindex fd71997a410..3132597df72 100644--- a/app/models/sidebar_section.rb+++ b/app/models/sidebar_section.rb@@ -31,6 +31,8 @@ class SidebarSection < ActiveRecord::Basemaximum: MAX_TITLE_LENGTH,}+ validates :locale, presence: true, length: { maximum: 20 }+scope :public_sections, -> { where("public") }scope :custom_sections, -> { where(section_type: nil) }enum :section_type, { community: 0 }, scopes: false, suffix: true@@ -77,7 +79,7 @@ class SidebarSection < ActiveRecord::Baseenddef set_default_locale- self.locale ||= SiteSetting.default_locale.to_s+ self.locale = SiteSetting.default_locale.to_s if locale.blank?endenddiff --git a/app/models/sidebar_url.rb b/app/models/sidebar_url.rbindex 149e5be2a34..dff2e7c6bb7 100644--- a/app/models/sidebar_url.rb+++ b/app/models/sidebar_url.rb@@ -62,6 +62,7 @@ class SidebarUrl < ActiveRecord::Basevalidates :icon, presence: true, length: { maximum: MAX_ICON_LENGTH }validates :name, presence: true, length: { maximum: MAX_NAME_LENGTH }validates :value, presence: true, length: { maximum: MAX_VALUE_LENGTH }+ validates :locale, presence: true, length: { maximum: 20 }validate :path_validator@@ -89,7 +90,7 @@ class SidebarUrl < ActiveRecord::Baseenddef set_default_locale- self.locale ||= SiteSetting.default_locale.to_s+ self.locale = SiteSetting.default_locale.to_s if locale.blank?enddef self.built_in_community_section_link_value?(value)diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex 244c68d98eb..1e46bf8302e 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -6252,13 +6252,26 @@ en:always_public: "Content in this section is always public"more_menu: "More menu"localizations:- title: "Translations"locale: "Language"+ language: "Section language"+ language_description: "The primary language of this section's title and link names."title_label: "Section title"- link_label: "Link name"- add_section: "Add section title translation"- add_link: "Add link name translation"- remove: "Remove translation"+ link_label: "Link names"+ back: "Section content"+ add_first: "Add translations"+ manage:+ one: "Manage translations (%{count} language)"+ other: "Manage translations (%{count} languages)"+ incomplete:+ one: "%{count} string missing"+ other: "%{count} strings missing"+ add_language: "Add language"+ remove_language: "Remove"+ remove_language_confirm: "Remove every %{language} translation for this section?"+ remove_cleared_confirm:+ one: "You cleared %{count} saved translation. It will be removed. Continue?"+ other: "You cleared %{count} saved translations. They will be removed. Continue?"+ untranslated: "Not translated yet"links:title: "Section links"add: "Add another link"diff --git a/frontend/discourse/app/components/modal/sidebar-section-form.gjs b/frontend/discourse/app/components/modal/sidebar-section-form.gjsindex 7934088de60..3dfe5c5d404 100644--- a/frontend/discourse/app/components/modal/sidebar-section-form.gjs+++ b/frontend/discourse/app/components/modal/sidebar-section-form.gjs@@ -1,7 +1,7 @@/* eslint-disable ember/no-classic-components */import { cached, tracked } from "@glimmer/tracking";import Component, { Input } from "@ember/component";-import { fn } from "@ember/helper";+import { fn, uniqueId } from "@ember/helper";import { on } from "@ember/modifier";import { action } from "@ember/object";import { service } from "@ember/service";@@ -12,12 +12,16 @@ import DTooltip from "discourse/float-kit/components/d-tooltip";import withEventValue from "discourse/helpers/with-event-value";import { ajax } from "discourse/lib/ajax";import { extractError } from "discourse/lib/ajax-error";-import { removeValueFromArray } from "discourse/lib/array-tools";+import {+ removeValueFromArray,+ uniqueItemsFromArray,+} from "discourse/lib/array-tools";import { SIDEBAR_SECTION, SIDEBAR_URL } from "discourse/lib/constants";import { afterRender, bind } from "discourse/lib/decorators";+import { isSameLocale } from "discourse/lib/locale-normalizer";import { sanitize } from "discourse/lib/text";import { autoTrackedArray } from "discourse/lib/tracked-tools";-import { and, not } from "discourse/truth-helpers";+import { 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";@@ -27,6 +31,7 @@ import { i18n } from "discourse-i18n";class Section {@tracked title;@tracked public;+ @tracked locale;@autoTrackedArray links;@autoTrackedArray secondaryLinks;@autoTrackedArray localizations;@@ -40,6 +45,7 @@ class Section {sectionType,hideTitleInput,localizations,+ locale,}) {this.title = title;this.public = publicSection;@@ -49,6 +55,7 @@ class Section {this.id = id;this.hideTitleInput = hideTitleInput;this.localizations = localizations || [];+ this.locale = locale;}get valid() {@@ -105,78 +112,55 @@ class Section {}}-class SectionLocalization {+class Localization {@tracked locale;- @tracked title;+ @tracked value;@tracked _destroy;- constructor({ id, locale, title }) {+ constructor({ id, locale, ...rest } = {}) {this.id = id;this.locale = locale;- this.title = title;+ this.value = rest[this.constructor.key];+ }++ get translated() {+ return !isEmpty(this.value);}get valid() {- return !isEmpty(this.locale) && !isEmpty(this.title) && !this.#tooLongTitle;+ return !isEmpty(this.locale) && !this.#tooLong;}- 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 invalidMessage() {+ if (this.#tooLong) {+ return i18n(this.constructor.tooLongKey, {+ count: this.constructor.maxLength,});}}- get #tooLongTitle() {- return this.title?.length > SIDEBAR_SECTION.max_title_length;+ get #tooLong() {+ return this.value?.length > this.constructor.maxLength;}}-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,- });- }- }+class SectionLocalization extends Localization {+ static key = "title";+ static maxLength = SIDEBAR_SECTION.max_title_length;+ static tooLongKey = "sidebar.sections.custom.title.validation.maximum";+}- get #tooLongName() {- return this.name?.length > SIDEBAR_URL.max_name_length;- }+class LinkLocalization extends Localization {+ static key = "name";+ static maxLength = SIDEBAR_URL.max_name_length;+ static tooLongKey = "sidebar.sections.custom.links.name.validation.maximum";}class SectionLink {@tracked icon;@tracked name;@tracked value;+ @tracked locale;@autoTrackedArray localizations;@tracked _destroy;@@ -189,6 +173,7 @@ class SectionLink {objectId,segment,localizations,+ locale,canLocalize = true,}) {this.router = router;@@ -201,6 +186,7 @@ class SectionLink {this.objectId = objectId;this.segment = segment;this.localizations = localizations || [];+ this.locale = locale;this.canLocalize = canLocalize;}@@ -326,6 +312,35 @@ class SectionLink {}}+const TranslationRow = <template>+ {{#let (uniqueId) as |inputId|}}+ <div class="sidebar-section-translations__row">+ <label class="sidebar-section-translations__source" for={{inputId}}>+ {{@source}}+ </label>++ <Input+ @type="text"+ @value={{@localization.value}}+ id={{inputId}}+ class="sidebar-section-translations__value+ {{unless @localization.translated '--untranslated'}}"+ placeholder={{i18n+ "sidebar.sections.custom.localizations.untranslated"+ }}+ lang={{@localization.locale}}+ {{on "input" (withEventValue (fn (mut @localization.value)))}}+ />++ {{#if @localization.invalidMessage}}+ <div role="alert" aria-live="assertive" class="warning">+ {{@localization.invalidMessage}}+ </div>+ {{/if}}+ </div>+ {{/let}}+</template>;+@tagName("")export default class SidebarSectionForm extends Component {@service dialog;@@ -335,14 +350,19 @@ export default class SidebarSectionForm extends Component {@tracked flash;@tracked flashType;+ @tracked showingTranslations = false;nextObjectId = 0;+ nextGroupKey = 0;+ groupKeys = new Map();@cachedget transformedModel() {const section = this.model?.section;if (section) {+ const sectionLocale = section.locale || this.siteSettings.default_locale;+return new Section({title: section.title,publicSection: section.public,@@ -350,14 +370,14 @@ export default class SidebarSectionForm extends Component {links: section.links.reduce((acc, link) => {if (link.segment === "primary") {this.nextObjectId++;- acc.push(this.initLink(link));+ acc.push(this.initLink(link, sectionLocale));}return acc;}, []),secondaryLinks: section.links.reduce((acc, link) => {if (link.segment === "secondary") {this.nextObjectId++;- acc.push(this.initLink(link));+ acc.push(this.initLink(link, sectionLocale));}return acc;}, []),@@ -367,6 +387,7 @@ export default class SidebarSectionForm extends Component {section.localizations,SectionLocalization),+ locale: sectionLocale,});} else {return new Section({@@ -375,13 +396,15 @@ export default class SidebarSectionForm extends Component {router: this.router,objectId: this.nextObjectId,segment: "primary",+ locale: this.siteSettings.default_locale,}),],+ locale: this.siteSettings.default_locale,});}}- initLink(link) {+ initLink(link, sectionLocale) {return new SectionLink({router: this.router,icon: link.icon,@@ -394,6 +417,7 @@ export default class SidebarSectionForm extends Component {link.localizations,LinkLocalization),+ locale: link.locale || sectionLocale,canLocalize: link.can_localize ?? link.canLocalize,});}@@ -410,12 +434,14 @@ export default class SidebarSectionForm extends Component {data: JSON.stringify({title: this.transformedModel.title,public: this.transformedModel.public,+ locale: this.serializeSectionSourceLocale(),localizations: this.serializeSectionLocalizations(),links: this.transformedModel.links.map((link) => {return {icon: link.icon,name: link.name,value: link.path,+ locale: this.serializeLinkSourceLocale(link),localizations: this.serializeLinkLocalizations(link),};}),@@ -435,16 +461,41 @@ export default class SidebarSectionForm extends Component {}update() {- this.wasPublic || this.isPublic+ return this.wasPublic || this.isPublic? this.#updateWithConfirm(): this.#updateCall();}+ get clearedTranslationCount() {+ const cleared = (record) =>+ record.localizations.filter(+ (localization) =>+ localization.id && !localization._destroy && !localization.translated+ ).length;++ return (+ (this.showLocalizations ? cleared(this.transformedModel) : 0) ++ this.localizableLinks.reduce((count, link) => count + cleared(link), 0)+ );+ }+#updateWithConfirm() {- return this.dialog.yesNoConfirm({- message: this.isPublic+ const messages = [+ this.isPublic? i18n("sidebar.sections.custom.update_public_confirm"): i18n("sidebar.sections.custom.mark_as_private_confirm"),+ ];++ if (this.clearedTranslationCount > 0) {+ messages.push(+ i18n("sidebar.sections.custom.localizations.remove_cleared_confirm", {+ count: this.clearedTranslationCount,+ })+ );+ }++ return this.dialog.yesNoConfirm({+ message: messages.join("<br><br>"),didConfirm: () => {return this.#updateCall();},@@ -459,6 +510,7 @@ export default class SidebarSectionForm extends Component {data: JSON.stringify({title: this.transformedModel.title,public: this.transformedModel.public,+ locale: this.serializeSectionSourceLocale(),localizations: this.serializeSectionLocalizations(),links: this.transformedModel.links.concat(this.transformedModel?.secondaryLinks || [])@@ -470,6 +522,7 @@ export default class SidebarSectionForm extends Component {value: link.path,segment: link.segment,_destroy: link._destroy,+ locale: this.serializeLinkSourceLocale(link),localizations: this.serializeLinkLocalizations(link),};}),@@ -503,22 +556,145 @@ export default class SidebarSectionForm extends Component {);}+ @cachedget activeLocalizations() {- return this.transformedModel.localizations.filter(- (localization) => !localization._destroy+ return this.#activeLocalizations(this.transformedModel);+ }++ get translationsLabel() {+ const count = this.translationLocales.length;++ return count === 0+ ? i18n("sidebar.sections.custom.localizations.add_first")+ : i18n("sidebar.sections.custom.localizations.manage", { count });+ }++ get hasTranslatableLocales() {+ return this.localeOptions.length > 0;+ }++ get showSourceLocale() {+ return this.showLocalizations && this.hasTranslatableLocales;+ }++ get canTranslate() {+ return (+ (this.showLocalizations || this.localizableLinks.length > 0) &&+ this.hasTranslatableLocales);}- get localeOptions() {- const configuredLocales =+ @cached+ get localizableLinks() {+ if (!this.showLinkLocalizations) {+ return [];+ }++ return this.transformedModel.links+ .concat(this.transformedModel.secondaryLinks || [])+ .filter((link) => !link._destroy && this.canLocalizeLink(link));+ }++ canLocalizeLink(link) {+ return this.transformedModel.customSection || link.canLocalize;+ }++ #activeLocalizations(record) {+ return record.localizations.filter(+ (localization) =>+ !localization._destroy &&+ !isSameLocale(localization.locale, record.locale)+ );+ }++ @cached+ get translationLocales() {+ const locales = [];++ const track = (localizations) =>+ localizations.forEach(({ locale }) => {+ if (locale && !locales.includes(locale)) {+ locales.push(locale);+ }+ });++ if (this.showLocalizations) {+ track(this.activeLocalizations);+ }++ this.localizableLinks.forEach((link) =>+ track(this.#activeLocalizations(link))+ );++ return locales;+ }++ @cached+ get translationGroups() {+ return this.translationLocales.map((locale) => ({+ key: this.#groupKey(locale),+ locale,+ name: this.languageNameLookup.getLanguageName(locale),+ localeOptions: this.#localeOptionsFor(locale),+ sectionLocalization: this.showLocalizations+ ? this.activeLocalizations.find(+ (localization) => localization.locale === locale+ )+ : null,+ links: this.localizableLinks+ .filter((link) => !isSameLocale(link.locale, locale))+ .map((link) => ({+ link,+ localization: this.#activeLocalizations(link).find(+ (localization) => localization.locale === locale+ ),+ })),+ }));+ }++ get nextTranslationLocale() {+ return (+ this.localeOptions.find(+ (locale) => !this.translationLocales.includes(locale.value)+ )?.value || ""+ );+ }++ get missingTranslationCount() {+ return this.translationGroups.reduce(+ (count, group) =>+ count ++ (this.showLocalizations && !group.sectionLocalization?.translated+ ? 1+ : 0) ++ group.links.filter(({ localization }) => !localization?.translated)+ .length,+ 0+ );+ }++ get configuredLocales() {+ return (this.siteSettings.available_content_localization_locales?.map((locale) => locale.value) ||this.siteSettings.content_localization_supported_locales?.split("|").filter(Boolean) ||- [];- const locales = new Set(configuredLocales);+ []+ );+ }++ get sourceLocaleOptions() {+ return this.#toLocaleOptions([+ ...this.configuredLocales,+ this.transformedModel.locale,+ ]);+ }++ @cached+ get localeOptions() {+ const locales = new Set(this.configuredLocales);this.transformedModel.localizations.forEach((localization) =>locales.add(localization.locale)@@ -531,12 +707,51 @@ export default class SidebarSectionForm extends Component {));- return [...locales]- .filter((locale) => locale && locale !== this.siteSettings.default_locale)- .map((locale) => ({- name: this.languageNameLookup.getLanguageName(locale),- value: locale,- }));+ return this.#toLocaleOptions(+ [...locales].filter((locale) => this.#isTranslationTarget(locale))+ );+ }++ #isTranslationTarget(locale) {+ if (+ this.showLocalizations &&+ !isSameLocale(locale, this.transformedModel.locale)+ ) {+ return true;+ }++ return this.localizableLinks.some(+ (link) => !isSameLocale(link.locale, locale)+ );+ }++ #groupKey(locale) {+ if (!this.groupKeys.has(locale)) {+ this.groupKeys.set(locale, `group-${this.nextGroupKey++}`);+ }++ return this.groupKeys.get(locale);+ }++ #localeOptionsFor(locale) {+ const options = this.localeOptions;+ const own = options.some((option) => option.value === locale)+ ? []+ : this.#toLocaleOptions([locale]);++ return [...options, ...own].map((option) => ({+ ...option,+ disabled:+ option.value !== locale &&+ this.translationLocales.includes(option.value),+ }));+ }++ #toLocaleOptions(locales) {+ return uniqueItemsFromArray(locales.filter(Boolean)).map((locale) => ({+ name: this.languageNameLookup.getLanguageName(locale),+ value: locale,+ }));}get showLocalizations() {@@ -558,10 +773,6 @@ export default class SidebarSectionForm extends Component {);}- get canAddSectionLocalization() {- return this.nextLocale(this.transformedModel.localizations) !== "";- }-get header() {return this.transformedModel.id? "sidebar.sections.custom.edit"@@ -623,113 +834,176 @@ export default class SidebarSectionForm extends Component {}}- @bind- deleteLocalization(localization) {- if (localization.id) {- localization._destroy = "1";- } else {- removeValueFromArray(this.transformedModel.localizations, localization);+ @action+ showTranslations() {+ this.#syncLocalizationSlots();+ this.showingTranslations = true;+ }++ #syncLocalizationSlots() {+ this.translationGroups+ .map((group) => group.locale)+ .forEach((locale) => this.#addLocalizationSlots(locale));+ }++ @action+ hideTranslations() {+ this.showingTranslations = false;+ }++ @action+ addLanguage() {+ const locale = this.nextTranslationLocale;+ if (!locale) {+ return;}++ this.#addLocalizationSlots(locale);}- @bind- deleteLinkLocalization(link, localization) {- if (localization.id) {- localization._destroy = "1";- } else {- removeValueFromArray(link.localizations, localization);+ @action+ removeLanguage(group) {+ const persisted =+ group.sectionLocalization?.id ||+ group.links.some(({ localization }) => localization?.id);++ if (!persisted) {+ this.#removeLocalizationSlots(group.locale);+ return;}++ return this.dialog.yesNoConfirm({+ message: i18n(+ "sidebar.sections.custom.localizations.remove_language_confirm",+ { language: group.name }+ ),+ didConfirm: () => this.#removeLocalizationSlots(group.locale),+ });}@bind- addLinkLocalization(link) {- const locale = this.nextLocale(link.localizations);- if (!locale) {+ setGroupLocale(group, locale) {+ if (locale !== group.locale && this.translationLocales.includes(locale)) {return;}- link.localizations.push(- new LinkLocalization({- locale,- })+ this.groupKeys.set(locale, group.key);+ this.groupKeys.delete(group.locale);++ this.#moveLocalization(+ this.transformedModel.localizations,+ group.sectionLocalization,+ locale);++ group.links.forEach(({ link, localization }) => {+ if (isSameLocale(link.locale, locale)) {+ return;+ }++ this.#moveLocalization(link.localizations, localization, locale);+ });++ this.#addLocalizationSlots(locale);}- @action- addLocalization() {- const locale = this.nextLocale(this.transformedModel.localizations);- if (!locale) {+ #moveLocalization(localizations, localization, locale) {+ if (!localization || localization.locale === locale) {return;}- this.transformedModel.localizations.push(- new SectionLocalization({- locale,- })+ const occupant = localizations.find(+ (other) => other !== localization && other.locale === locale);++ if (!occupant) {+ localization.locale = locale;+ return;+ }++ occupant.value = localization.value;+ occupant._destroy = undefined;+ this.#discardLocalization(localizations, localization);}- nextLocale(localizations) {- const selectedLocales = localizations- .filter((localization) => !localization._destroy)- .map((localization) => localization.locale);+ #addLocalizationSlots(locale) {+ if (+ this.showLocalizations &&+ !isSameLocale(locale, this.transformedModel.locale) &&+ !this.#reclaimLocalization(this.transformedModel.localizations, locale)+ ) {+ this.transformedModel.localizations.push(+ new SectionLocalization({ locale })+ );+ }- return (- this.localeOptions.find(- (locale) => !selectedLocales.includes(locale.value)- )?.value || ""+ this.localizableLinks.forEach((link) => {+ if (isSameLocale(link.locale, locale)) {+ return;+ }++ if (!this.#reclaimLocalization(link.localizations, locale)) {+ link.localizations.push(new LinkLocalization({ locale }));+ }+ });+ }++ #reclaimLocalization(localizations, locale) {+ const existing = localizations.find(+ (localization) => localization.locale === locale);++ if (existing) {+ existing._destroy = undefined;+ }++ return existing;}- @bind- setSectionLocalizationLocale(localization, locale) {- this.setLocalizationLocale(- this.transformedModel.localizations,- localization,- locale+ #removeLocalizationSlots(locale) {+ this.groupKeys.delete(locale);++ this.#discardLocalizations(this.transformedModel.localizations, locale);+ this.localizableLinks.forEach((link) =>+ this.#discardLocalizations(link.localizations, locale));}- @bind- setLinkLocalizationLocale(link, localization, locale) {- this.setLocalizationLocale(link.localizations, localization, locale);+ #discardLocalizations(localizations, locale) {+ localizations+ .filter((localization) => localization.locale === locale)+ .forEach((localization) =>+ this.#discardLocalization(localizations, localization)+ );}- @bind- isSectionLocalizationLocaleDisabled(localization, locale) {- return this.isLocalizationLocaleSelected(- this.transformedModel.localizations,- localization,- locale- );+ #discardLocalization(localizations, localization) {+ if (localization.id) {+ localization._destroy = "1";+ } else {+ removeValueFromArray(localizations, localization);+ }}- @bind- isLinkLocalizationLocaleDisabled(link, localization, locale) {- return this.isLocalizationLocaleSelected(- link.localizations,- localization,- locale+ @action+ setSourceLocale(locale) {+ this.transformedModel.locale = locale;+ this.transformedModel.links.forEach((link) => (link.locale = locale));+ this.transformedModel.secondaryLinks?.forEach(+ (link) => (link.locale = locale));}- setLocalizationLocale(localizations, localization, locale) {- if (- !this.isLocalizationLocaleSelected(localizations, localization, locale)- ) {- localization.locale = locale;- }+ serializeSectionSourceLocale() {+ return this.showLocalizations ? this.transformedModel.locale : undefined;}- isLocalizationLocaleSelected(localizations, localization, locale) {- return localizations- .filter((existingLocalization) => {- return (- existingLocalization !== localization &&- !existingLocalization._destroy- );- })- .some((existingLocalization) => existingLocalization.locale === locale);+ serializeLinkSourceLocale(link) {+ if (!this.showLinkLocalizations || !this.canLocalizeLink(link)) {+ return undefined;+ }++ return link.locale;}serializeSectionLocalizations() {@@ -737,25 +1011,36 @@ export default class SidebarSectionForm extends Component {return [];}- return this.transformedModel.localizations.map((localization) => ({- id: localization.id,- locale: localization.locale,- title: localization.title,- _destroy: localization._destroy,- }));+ return this.#serializeLocalizations(+ this.transformedModel.localizations,+ "title"+ );}serializeLinkLocalizations(link) {- if (!this.showLinkLocalizations || !link.canLocalize) {+ if (!this.showLinkLocalizations || !this.canLocalizeLink(link)) {return [];}- return link.localizations.map((localization) => ({- id: localization.id,- locale: localization.locale,- name: localization.name,- _destroy: localization._destroy,- }));+ return this.#serializeLocalizations(link.localizations);+ }++ #serializeLocalizations(localizations) {+ return localizations+ .map((localization) => {+ const { id, locale, _destroy, translated } = localization;++ if (_destroy || !translated) {+ return id ? { id, locale, _destroy: "1" } : null;+ }++ return {+ id,+ locale,+ [localization.constructor.key]: localization.value,+ };+ })+ .filter(Boolean);}@action@@ -766,6 +1051,7 @@ export default class SidebarSectionForm extends Component {router: this.router,objectId: this.nextObjectId,segment: "primary",+ locale: this.transformedModel.locale,canLocalize: true,}));@@ -781,6 +1067,7 @@ export default class SidebarSectionForm extends Component {router: this.router,objectId: this.nextObjectId,segment: "secondary",+ locale: this.transformedModel.locale,canLocalize: true,}));@@ -859,211 +1146,249 @@ export default class SidebarSectionForm extends Component {class="sidebar-section-form-modal --large"><:body>- <form class="form-horizontal sidebar-section-form">- {{#unless this.transformedModel.hideTitleInput}}- <div class="sidebar-section-form__input-wrapper">- <label for="section-name">- {{i18n "sidebar.sections.custom.title.label"}}- </label>-- <Input- name="section-name"- @type="text"- @value={{this.transformedModel.title}}- class={{this.transformedModel.titleCssClass}}- id="section-name"- {{on- "input"- (withEventValue (fn (mut this.transformedModel.title)))- }}- />+ {{#if this.showingTranslations}}+ <div class="sidebar-section-translations">+ <DButton+ @action={{this.hideTranslations}}+ @icon="chevron-left"+ @label="sidebar.sections.custom.localizations.back"+ class="btn-flat btn-text sidebar-section-translations__back"+ />- {{#if this.transformedModel.invalidTitleMessage}}- <div class="title warning">- {{this.transformedModel.invalidTitleMessage}}- </div>- {{/if}}- </div>- {{/unless}}- {{#if this.showLocalizations}}- <div class="sidebar-section-form__localizations">- {{#each this.activeLocalizations as |localization|}}- <div class="sidebar-section-form__localization-row">+ {{#each this.translationGroups key="key" as |group|}}+ <div+ class="sidebar-section-translations__language"+ data-locale={{group.locale}}+ >+ <div class="sidebar-section-translations__language-header"><DSelect- @value={{localization.locale}}- @onChange={{fn- this.setSectionLocalizationLocale- localization- }}+ @value={{group.locale}}+ @onChange={{fn this.setGroupLocale group}}@includeNone={{false}}- class="sidebar-section-form__localization-locale"+ class="sidebar-section-translations__language-select"aria-label={{i18n"sidebar.sections.custom.localizations.locale"}}as |select|>- {{#each this.localeOptions as |locale|}}+ {{#each group.localeOptions key="value" as |locale|}}<select.Option@value={{locale.value}}- disabled={{this.isSectionLocalizationLocaleDisabled- localization- locale.value- }}+ disabled={{locale.disabled}}>{{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+ @action={{fn this.removeLanguage group}}@icon="trash-can"- @action={{fn this.deleteLocalization localization}}- @title="sidebar.sections.custom.localizations.remove"- class="btn-flat delete-link remove-localization"+ @label="sidebar.sections.custom.localizations.remove_language"+ class="btn-flat btn-text sidebar-section-translations__remove-language"/></div>- {{#if localization.invalidTitleMessage}}- <div role="alert" aria-live="assertive" class="title warning">- {{localization.invalidTitleMessage}}+ {{#if group.sectionLocalization}}+ <div class="sidebar-section-translations__caption">+ {{i18n "sidebar.sections.custom.localizations.title_label"}}</div>++ <TranslationRow+ @source={{this.transformedModel.title}}+ @localization={{group.sectionLocalization}}+ />{{/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}}+ {{#if group.links}}+ <div class="sidebar-section-translations__caption">+ {{i18n "sidebar.sections.custom.localizations.link_label"}}+ </div>- <div- id="section-links-label"- class="sidebar-section-form__links-label"- >- {{i18n "sidebar.sections.custom.links.title"}}+ {{#each group.links key="link.objectId" as |entry|}}+ <TranslationRow+ @source={{entry.link.name}}+ @localization={{entry.localization}}+ />+ {{/each}}+ {{/if}}+ </div>+ {{/each}}++ {{#if this.nextTranslationLocale}}+ <DButton+ @action={{this.addLanguage}}+ @icon="plus"+ @label="sidebar.sections.custom.localizations.add_language"+ class="btn-flat btn-text sidebar-section-translations__add-language"+ />+ {{/if}}</div>+ {{else}}+ <form class="form-horizontal sidebar-section-form">+ {{#if this.showSourceLocale}}+ <div class="sidebar-section-form__source-locale">+ <label for="section-source-locale">+ {{i18n "sidebar.sections.custom.localizations.language"}}+ </label>++ <DSelect+ @value={{this.transformedModel.locale}}+ @onChange={{this.setSourceLocale}}+ @includeNone={{false}}+ class="sidebar-section-form__source-locale-select"+ id="section-source-locale"+ as |select|+ >+ {{#each this.sourceLocaleOptions as |locale|}}+ <select.Option+ @value={{locale.value}}+ >{{locale.name}}</select.Option>+ {{/each}}+ </DSelect>++ <p class="sidebar-section-form__source-locale-description">+ {{i18n+ "sidebar.sections.custom.localizations.language_description"+ }}+ </p>+ </div>+ {{/if}}- <div- role="table"- aria-labelledby="section-links-label"- aria-rowcount={{this.activeLinks.length}}- class="sidebar-section-form__links-wrapper"- >+ {{#unless this.transformedModel.hideTitleInput}}+ <div class="sidebar-section-form__input-wrapper">+ <label for="section-name">+ {{i18n "sidebar.sections.custom.title.label"}}+ </label>- <div class="row-wrapper header" role="row">- <div- class="input-group link-icon"- role="columnheader"- aria-sort="none"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.icon.label"- }}</label>- </div>+ <Input+ name="section-name"+ @type="text"+ @value={{this.transformedModel.title}}+ class={{this.transformedModel.titleCssClass}}+ id="section-name"+ {{on+ "input"+ (withEventValue (fn (mut this.transformedModel.title)))+ }}+ />- <div- class="input-group link-name"- role="columnheader"- aria-sort="none"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.name.label"- }}</label>+ {{#if this.transformedModel.invalidTitleMessage}}+ <div class="title warning">+ {{this.transformedModel.invalidTitleMessage}}+ </div>+ {{/if}}</div>+ {{/unless}}- <div- class="input-group link-url"- role="columnheader"- aria-sort="none"- >- {{! eslint-disable-next-line ember/template-no-nested-interactive }}- <label>{{i18n- "sidebar.sections.custom.links.value.label"- }}</label>- </div>+ <div+ id="section-links-label"+ class="sidebar-section-form__links-label"+ >+ {{i18n "sidebar.sections.custom.links.title"}}</div>- {{#each this.activeLinks as |link|}}- <SectionFormLink- @link={{link}}- @deleteLink={{this.deleteLink}}- @reorderCallback={{this.reorder}}- @setDraggedLinkCallback={{this.setDraggedLink}}- @showLocalizations={{and- this.showLinkLocalizations- link.canLocalize- }}- @localeOptions={{this.localeOptions}}- @deleteLocalization={{this.deleteLinkLocalization}}- @addLocalization={{this.addLinkLocalization}}- @setLocalizationLocale={{this.setLinkLocalizationLocale}}- @isLocalizationLocaleDisabled={{this.isLinkLocalizationLocaleDisabled}}- />- {{/each}}+ <div+ role="table"+ aria-labelledby="section-links-label"+ aria-rowcount={{this.activeLinks.length}}+ class="sidebar-section-form__links-wrapper"+ >++ <div class="row-wrapper header" role="row">+ <div+ class="input-group link-icon"+ role="columnheader"+ aria-sort="none"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n+ "sidebar.sections.custom.links.icon.label"+ }}</label>+ </div>- </div>- <DButton- @action={{this.addLink}}- @title="sidebar.sections.custom.links.add"- @icon="plus"- @label="sidebar.sections.custom.links.add"- @ariaLabel="sidebar.sections.custom.links.add"- class="btn-flat btn-text add-link"- />+ <div+ class="input-group link-name"+ role="columnheader"+ aria-sort="none"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n+ "sidebar.sections.custom.links.name.label"+ }}</label>+ </div>- {{#if this.transformedModel.sectionType}}- <hr />- <h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>- {{#each this.activeSecondaryLinks as |link|}}- <SectionFormLink- @link={{link}}- @deleteLink={{this.deleteLink}}- @reorderCallback={{this.reorder}}- @setDraggedLinkCallback={{this.setDraggedLink}}- @showLocalizations={{and- this.showLinkLocalizations- link.canLocalize- }}- @localeOptions={{this.localeOptions}}- @deleteLocalization={{this.deleteLinkLocalization}}- @addLocalization={{this.addLinkLocalization}}- @setLocalizationLocale={{this.setLinkLocalizationLocale}}- @isLocalizationLocaleDisabled={{this.isLinkLocalizationLocaleDisabled}}- />- {{/each}}+ <div+ class="input-group link-url"+ role="columnheader"+ aria-sort="none"+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <label>{{i18n+ "sidebar.sections.custom.links.value.label"+ }}</label>+ </div>+ </div>++ {{#each this.activeLinks as |link|}}+ <SectionFormLink+ @link={{link}}+ @deleteLink={{this.deleteLink}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}++ </div><DButton- @action={{this.addSecondaryLink}}+ @action={{this.addLink}}@title="sidebar.sections.custom.links.add"@icon="plus"@label="sidebar.sections.custom.links.add"@ariaLabel="sidebar.sections.custom.links.add"class="btn-flat btn-text add-link"/>- {{/if}}- </form>++ {{#if this.transformedModel.sectionType}}+ <hr />+ <h3>{{i18n "sidebar.sections.custom.more_menu"}}</h3>+ {{#each this.activeSecondaryLinks as |link|}}+ <SectionFormLink+ @link={{link}}+ @deleteLink={{this.deleteLink}}+ @reorderCallback={{this.reorder}}+ @setDraggedLinkCallback={{this.setDraggedLink}}+ />+ {{/each}}+ <DButton+ @action={{this.addSecondaryLink}}+ @title="sidebar.sections.custom.links.add"+ @icon="plus"+ @label="sidebar.sections.custom.links.add"+ @ariaLabel="sidebar.sections.custom.links.add"+ class="btn-flat btn-text add-link"+ />+ {{/if}}++ {{#if this.canTranslate}}+ <hr />++ <DButton+ @action={{this.showTranslations}}+ @icon="globe"+ @translatedLabel={{this.translationsLabel}}+ class="btn-flat btn-text sidebar-section-form__manage-translations"+ >+ {{#if this.missingTranslationCount}}+ <span class="sidebar-section-form__translations-incomplete">+ {{i18n+ "sidebar.sections.custom.localizations.incomplete"+ count=this.missingTranslationCount+ }}+ </span>+ {{/if}}+ </DButton>+ {{/if}}+ </form>+ {{/if}}</:body><:footer><DButton@@ -1074,7 +1399,7 @@ export default class SidebarSectionForm extends Component {id="save-section"class="btn-primary"/>- {{#if (and this.currentUser.admin)}}+ {{#if this.currentUser.admin}}<divclass="mark-public-wrapper{{if this.transformedModel.sectionType '-disabled'}}"diff --git a/frontend/discourse/app/components/sidebar/section-form-link.gjs b/frontend/discourse/app/components/sidebar/section-form-link.gjsindex 5c87b963279..7c01ceed1cb 100644--- a/frontend/discourse/app/components/sidebar/section-form-link.gjs+++ b/frontend/discourse/app/components/sidebar/section-form-link.gjs@@ -9,7 +9,6 @@ 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";@@ -78,22 +77,6 @@ export default class SectionFormLink extends Component {this.dragCssClass = null;}- get activeLocalizations() {- return this.args.link.localizations.filter(- (localization) => !localization._destroy- );- }-- get canAddLocalization() {- const selectedLocales = this.activeLocalizations.map(- (localization) => localization.locale- );-- return this.args.localeOptions.some(- (locale) => !selectedLocales.includes(locale.value)- );- }-<template><div class="sidebar-section-form-link-wrapper" role="rowgroup"><div@@ -182,72 +165,6 @@ export default class SectionFormLink extends Component {class="btn-flat delete-link"/></div>-- {{#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/locale-normalizer.js b/frontend/discourse/app/lib/locale-normalizer.jsnew file mode 100644index 00000000000..f26f0f9ec29--- /dev/null+++ b/frontend/discourse/app/lib/locale-normalizer.js@@ -0,0 +1,18 @@+/**+ * Two locales are the same when they are equal or share the same base language,+ * ignoring region and separator/case differences, e.g. `en_GB` and `en`, or+ * `zh-TW` and `zh_CN`. A blank locale never matches.+ *+ * @param {string} locale1+ * @param {string} locale2+ * @returns {boolean}+ */+export function isSameLocale(locale1, locale2) {+ if (!locale1 || !locale2) {+ return false;+ }++ const base = (locale) => locale.toLowerCase().split(/[-_]/)[0];++ return base(locale1) === base(locale2);+}diff --git a/frontend/discourse/tests/unit/lib/locale-normalizer-test.js b/frontend/discourse/tests/unit/lib/locale-normalizer-test.jsnew file mode 100644index 00000000000..a5587e71123--- /dev/null+++ b/frontend/discourse/tests/unit/lib/locale-normalizer-test.js@@ -0,0 +1,27 @@+import { module, test } from "qunit";+import { isSameLocale } from "discourse/lib/locale-normalizer";++module("Unit | lib | locale-normalizer", function () {+ test("isSameLocale matches identical locales", function (assert) {+ assert.true(isSameLocale("en", "en"));+ assert.true(isSameLocale("zh_CN", "zh_CN"));+ });++ test("isSameLocale ignores region and separator/case differences", function (assert) {+ assert.true(isSameLocale("en_GB", "en"));+ assert.true(isSameLocale("en", "en_GB"));+ assert.true(isSameLocale("zh-TW", "zh_CN"));+ assert.true(isSameLocale("EN", "en"));+ });++ test("isSameLocale distinguishes different base languages", function (assert) {+ assert.false(isSameLocale("en", "hu"));+ assert.false(isSameLocale("pt", "es"));+ });++ test("isSameLocale is false when either locale is blank", function (assert) {+ assert.false(isSameLocale("en", null));+ assert.false(isSameLocale(undefined, "en"));+ assert.false(isSameLocale("", "en"));+ });+});diff --git a/lib/guardian/localization_guardian.rb b/lib/guardian/localization_guardian.rbindex 3195299d727..8cf834ddfa4 100644--- a/lib/guardian/localization_guardian.rb+++ b/lib/guardian/localization_guardian.rb@@ -55,22 +55,25 @@ module LocalizationGuardiancan_localize_sidebar_section_title?(section)end- def can_localize_sidebar_section_title?(section_or_section_id)+ def can_localize_sidebar_section_title?(section_or_section_id, public: nil)return false if !SiteSetting.content_localization_enabledreturn false if anonymous?return false if [email protected]?section = find_sidebar_section(section_or_section_id)- section.present? && section.public? && section.custom_section?+ return false if section.blank?++ (public.nil? ? section.public? : public) && section.custom_section?end- def can_localize_sidebar_section_link?(section_or_section_id, link_value)+ def can_localize_sidebar_section_link?(section_or_section_id, link_value, public: nil)return false if !SiteSetting.content_localization_enabledreturn false if anonymous?return false if [email protected]?section = find_sidebar_section(section_or_section_id)- return false if !section&.public?+ return false if section.blank?+ return false if !(public.nil? ? section.public? : public)return true if section.custom_section?section.community_section? && !SidebarUrl.built_in_community_section_link_value?(link_value)diff --git a/spec/requests/sidebar_sections_controller_spec.rb b/spec/requests/sidebar_sections_controller_spec.rbindex 212406c035c..ef5dd44c751 100644--- a/spec/requests/sidebar_sections_controller_spec.rb+++ b/spec/requests/sidebar_sections_controller_spec.rb@@ -213,12 +213,57 @@ RSpec.describe SidebarSectionsController do],}+ expect(response.status).to eq(403)+ expect(SidebarSection.where(title: "custom section")).to be_empty+ end++ it "does not allow an admin to create localizations on a private section" do+ SiteSetting.content_localization_enabled = true+ sign_in(admin)++ post "/sidebar_sections.json",+ params: {+ title: "private section",+ public: false,+ locale: "ja",+ localizations: [{ locale: "ja", title: "カスタム" }],+ links: [{ icon: "link", name: "categories", value: "/categories" }],+ }++ expect(response.status).to eq(403)+ expect(SidebarSection.where(title: "private section")).to be_empty+ end++ it "allows an admin to create localizations on a public section" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ sign_in(admin)++ post "/sidebar_sections.json",+ params: {+ title: "public section",+ public: true,+ locale: "en",+ localizations: [{ locale: "ja", title: "カスタム" }],+ links: [+ {+ icon: "link",+ name: "categories",+ value: "/categories",+ locale: "en",+ 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+ expect(sidebar_section.locale).to eq("en")+ expect(sidebar_section.localizations.pluck(:locale, :title)).to eq([%w[ja カスタム]])+ expect(sidebar_section.sidebar_urls.first.localizations.pluck(:locale, :name)).to eq(+ [%w[ja カテゴリー]],+ )endit "does not allow moderator to create public section" do@@ -376,7 +421,7 @@ RSpec.describe SidebarSectionsController dolinks: [{ icon: "link", id: sidebar_url_1.id, name: "latest", value: "/latest" }],}- expect(response.status).to eq(200)+ expect(response.status).to eq(403)expect(sidebar_section.reload.locale).to eq(SiteSetting.default_locale)end@@ -712,6 +757,357 @@ RSpec.describe SidebarSectionsController doendend+ describe "localization after the default locale changes" do+ before do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|hu"+ SiteSetting.allow_user_locale = true+ SiteSetting.default_locale = "en"+ sign_in(admin)+ end++ it "lets an admin relabel the source language and translate into the old default" do+ english_user = Fabricate(:user, locale: "en")+ hungarian_user = Fabricate(:user, locale: "hu")++ post "/sidebar_sections.json",+ params: {+ title: "Főoldal",+ public: true,+ locale: "en",+ links: [{ icon: "link", name: "Főoldal", value: "/", locale: "en" }],+ }+ expect(response.status).to eq(200)++ section = SidebarSection.last+ link = section.sidebar_urls.first+ expect(section.locale).to eq("en")+ expect(link.locale).to eq("en")++ SiteSetting.default_locale = "hu"++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Főoldal",+ public: true,+ locale: "hu",+ localizations: [{ locale: "en", title: "Homepage" }],+ links: [+ {+ id: link.id,+ icon: "link",+ name: "Főoldal",+ value: "/",+ locale: "hu",+ localizations: [{ locale: "en", name: "Homepage" }],+ },+ ],+ }+ expect(response.status).to eq(200)++ expect(section.reload.locale).to eq("hu")+ expect(link.reload.locale).to eq("hu")+ expect(section.localizations.order(:locale).pluck(:locale, :title)).to eq([%w[en Homepage]])+ expect(link.localizations.order(:locale).pluck(:locale, :name)).to eq([%w[en Homepage]])++ sign_in(english_user)+ get "/sidebar_sections.json"+ english = response.parsed_body["sidebar_sections"].find { |s| s["id"] == section.id }+ expect(english["title"]).to eq("Homepage")+ expect(english["links"].first["name"]).to eq("Homepage")++ sign_in(hungarian_user)+ get "/sidebar_sections.json"+ hungarian = response.parsed_body["sidebar_sections"].find { |s| s["id"] == section.id }+ expect(hungarian["title"]).to eq("Főoldal")+ expect(hungarian["links"].first["name"]).to eq("Főoldal")+ end++ it "drops a localization whose locale matches the section's own source locale" do+ section = Fabricate(:sidebar_section, title: "Home", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Home", value: "/", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)++ SiteSetting.default_locale = "hu"++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Home",+ public: true,+ localizations: [+ { locale: "en", title: "Home again" },+ { locale: "hu", title: "Főoldal" },+ ],+ links: [+ {+ id: sidebar_url.id,+ icon: "link",+ name: "Home",+ value: "/",+ localizations: [+ { locale: "en", name: "Home again" },+ { locale: "hu", name: "Főoldal" },+ ],+ },+ ],+ }+ expect(response.status).to eq(200)++ expect(section.reload.localizations.order(:locale).pluck(:locale, :title)).to eq(+ [%w[hu Főoldal]],+ )+ expect(sidebar_url.reload.localizations.order(:locale).pluck(:locale, :name)).to eq(+ [%w[hu Főoldal]],+ )+ end++ it "destroys an existing localization that collides with the new source locale" do+ section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)+ section_localization =+ Fabricate(+ :sidebar_section_localization,+ sidebar_section: section,+ locale: "hu",+ title: "Dok",+ )+ url_localization =+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "hu", name: "Útmutató")++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Docs",+ public: true,+ locale: "hu",+ localizations: [{ id: section_localization.id, locale: "hu", title: "Dok" }],+ links: [+ {+ id: sidebar_url.id,+ icon: "link",+ name: "Guide",+ value: "/guide",+ locale: "hu",+ localizations: [{ id: url_localization.id, locale: "hu", name: "Útmutató" }],+ },+ ],+ }+ expect(response.status).to eq(200)++ expect(section.reload.locale).to eq("hu")+ expect(section.localizations).to be_empty+ expect(sidebar_url.reload.localizations).to be_empty+ end++ it "dedupes each link against its own source locale, not the section's" do+ section = Fabricate(:sidebar_section, title: "Home", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Kezdőlap", value: "/", locale: "hu")+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Home",+ public: true,+ locale: "en",+ links: [+ {+ id: sidebar_url.id,+ icon: "link",+ name: "Kezdőlap",+ value: "/",+ locale: "hu",+ localizations: [+ { locale: "hu", name: "Kezdőlap again" },+ { locale: "en", name: "Home" },+ ],+ },+ ],+ }+ expect(response.status).to eq(200)++ expect(sidebar_url.reload.localizations.order(:locale).pluck(:locale, :name)).to eq(+ [%w[en Home]],+ )+ end++ it "keeps a regional variant of the source language instead of destroying it" do+ SiteSetting.content_localization_supported_locales = "en|en_GB|hu"+ section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)+ localization =+ Fabricate(+ :sidebar_section_localization,+ sidebar_section: section,+ locale: "en_GB",+ title: "Docs GB",+ )++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Docs renamed",+ public: true,+ locale: "en",+ localizations: [{ id: localization.id, locale: "en_GB", title: "Docs GB" }],+ links: [+ { id: sidebar_url.id, icon: "link", name: "Guide", value: "/guide", locale: "en" },+ ],+ }+ expect(response.status).to eq(200)++ expect(section.reload.localizations.pluck(:locale, :title)).to eq([%w[en_GB Docs\ GB]])+ end++ it "keeps a manually added Community section link's own source locale" do+ community_section =+ SidebarSection.find_by(section_type: SidebarSection.section_types[:community])+ manual_link = Fabricate(:sidebar_url, name: "Kezdőlap", value: "/solutions", locale: "hu")+ Fabricate(:sidebar_section_link, sidebar_section: community_section, linkable: manual_link)++ put "/sidebar_sections/#{community_section.id}.json",+ params: {+ title: "Community",+ links: [{ id: manual_link.id, icon: "link", name: "Kezdőlap", value: "/solutions" }],+ }+ expect(response.status).to eq(200)++ expect(manual_link.reload.locale).to eq("hu")+ end+ end++ describe "source locale validation" do+ fab!(:section) { Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en") }+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en") }+ fab!(:section_link) do+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)+ end++ before do+ SiteSetting.content_localization_enabled = true+ SiteSetting.default_locale = "en"+ sign_in(admin)+ end++ def update_section(params)+ put "/sidebar_sections/#{section.id}.json",+ params: { title: "Docs", public: true }.merge(params)+ end++ it "rejects a locale longer than the column allows" do+ update_section(locale: "x" * 100)++ expect(response.status).to eq(400)+ expect(section.reload.locale).to eq("en")+ end++ it "rejects an unsupported locale on the section and on a link" do+ update_section(locale: "klingon")+ expect(response.status).to eq(400)++ update_section(+ links: [+ { id: sidebar_url.id, icon: "link", name: "Guide", value: "/guide", locale: "elvish" },+ ],+ )+ expect(response.status).to eq(400)++ expect(section.reload.locale).to eq("en")+ expect(sidebar_url.reload.locale).to eq("en")+ end++ it "accepts an unsupported locale that is already stored" do+ section.update_column(:locale, "af")+ sidebar_url.update_column(:locale, "af")++ update_section(+ locale: "af",+ localizations: [{ locale: "en", title: "Docs EN" }],+ links: [+ {+ id: sidebar_url.id,+ icon: "link",+ name: "Guide",+ value: "/guide",+ locale: "af",+ localizations: [{ locale: "en", name: "Guide EN" }],+ },+ ],+ )++ expect(response.status).to eq(200)+ expect(section.reload.locale).to eq("af")+ expect(section.localizations.pluck(:locale, :title)).to eq([["en", "Docs EN"]])+ expect(sidebar_url.reload.localizations.pluck(:locale, :name)).to eq([["en", "Guide EN"]])+ end++ it "falls back to the default locale when a blank locale is submitted" do+ update_section(+ locale: "",+ links: [{ id: sidebar_url.id, icon: "link", name: "Guide", value: "/guide", locale: "" }],+ )++ expect(response.status).to eq(200)+ expect(section.reload.locale).to eq("en")+ expect(sidebar_url.reload.locale).to eq("en")+ end+ end++ describe "localization params on a section being made public" do+ fab!(:section) { Fabricate(:sidebar_section, title: "Docs", user: admin, locale: "en") }+ fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en") }+ fab!(:section_link) do+ Fabricate(:sidebar_section_link, sidebar_section: section, linkable: sidebar_url)+ end++ before do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ SiteSetting.default_locale = "en"+ sign_in(admin)+ end++ it "authorizes against the submitted visibility, not the stored one" do+ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Docs",+ public: true,+ locale: "ja",+ localizations: [{ locale: "en", title: "Docs EN" }],+ links: [+ {+ id: sidebar_url.id,+ icon: "link",+ name: "Guide",+ value: "/guide",+ locale: "ja",+ localizations: [{ locale: "en", name: "Guide EN" }],+ },+ ],+ }++ expect(response.status).to eq(200)+ expect(section.reload.locale).to eq("ja")+ expect(section.localizations.pluck(:locale, :title)).to eq([["en", "Docs EN"]])+ expect(sidebar_url.reload.localizations.pluck(:locale, :name)).to eq([["en", "Guide EN"]])+ end++ it "ignores localization params when content localization is disabled" do+ SiteSetting.content_localization_enabled = false++ put "/sidebar_sections/#{section.id}.json",+ params: {+ title: "Docs",+ public: true,+ locale: "ja",+ localizations: [{ locale: "en", title: "Docs EN" }],+ }++ expect(response.status).to eq(200)+ expect(section.reload.locale).to eq("en")+ expect(section.localizations).to be_empty+ end+ end+describe "#destroy" dofab!(:sidebar_section) { Fabricate(:sidebar_section, user: user) }diff --git a/spec/system/custom_sidebar_sections_spec.rb b/spec/system/custom_sidebar_sections_spec.rbindex 7de5ecc827d..7ba2ebd79b1 100644--- a/spec/system/custom_sidebar_sections_spec.rb+++ b/spec/system/custom_sidebar_sections_spec.rb@@ -455,6 +455,42 @@ describe "Custom sidebar sections" doexpect(section_modal).to have_no_localization_controlsend+ it "hides translation controls when no other language is available" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")++ expect(section_modal).to have_no_source_language_control+ expect(section_modal).to have_no_localization_controls+ end++ it "keeps translation controls when only an existing translation needs managing" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "ドキュメント")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations++ expect(section_modal).to have_translation_language("ja")+ expect(section_modal).to have_no_add_language+ end+it "does not offer the default locale as a translation target" doSiteSetting.content_localization_enabled = trueSiteSetting.default_locale = "en"@@ -468,40 +504,293 @@ describe "Custom sidebar sections" dovisit("/latest")sidebar.edit_custom_section("Public section")- find(".add-localization").click+ section_modal.open_translations+ section_modal.add_language("ja")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+ it "excludes the section's own source language, not the site default, from translation targets" doSiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"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, title: "Public section", public: true, locale: "ja")+ sidebar_url = Fabricate(:sidebar_url, name: "Sidebar Tags", value: "/tags", locale: "ja")Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)sign_in adminvisit("/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_modal).to have_source_language("ja")++ section_modal.open_translations+ section_modal.add_language("en")+ expect(section_modal).to have_locale_option("en")+ expect(section_modal).to have_no_locale_option("ja")++ section_modal.close_translations+ section_modal.select_source_language("en")+ section_modal.open_translations+ section_modal.add_language("ja")++ expect(section_modal).to have_locale_option("ja")+ expect(section_modal).to have_no_locale_option("en")+ end++ it "hides a link translation that collides with the section's source language" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "ガイド")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations++ expect(section_modal).to have_translation_row("ja", "Guide")++ section_modal.close_translations+ section_modal.select_source_language("ja")+ section_modal.open_translations++ expect(section_modal).to have_no_translation_language("ja")+ end++ it "keeps a link's own source language when the section is saved" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "ガイド", value: "/guide", locale: "ja")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)+ Fabricate(:sidebar_url_localization, sidebar_url:, locale: "en", name: "Guide")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.fill_name("Documentation")+ section_modal.save+ section_modal.confirm_update++ expect(section_modal).to be_closed+ expect(sidebar_url.reload.locale).to eq("ja")+ expect(sidebar_url.localizations.pluck(:locale, :name)).to eq([%w[en Guide]])+ end++ it "keeps an existing translation when the source language is toggled away and back" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|fr"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ sidebar_url = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "fr", title: "Docs FR")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")++ section_modal.select_source_language("fr")+ section_modal.select_source_language("en")+ section_modal.save+ section_modal.confirm_update++ expect(section_modal).to be_closed+ expect(sidebar_section.reload.localizations.pluck(:locale, :title)).to eq([["fr", "Docs FR"]])+ end++ it "edits the section title and every link name for one language at a time" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|fr"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ guide = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ api = Fabricate(:sidebar_url, name: "API", value: "/api", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide)+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: api)++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations+ section_modal.add_language("fr")++ section_modal.fill_translation("fr", "Docs", "Documentation")+ section_modal.fill_translation("fr", "Guide", "Guide FR")+ section_modal.save+ section_modal.confirm_update- 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 be_closed+ expect(sidebar_section.reload.localizations.pluck(:locale, :title)).to eq(+ [%w[fr Documentation]],)- expect(section_modal).to have_disabled_section_title_translation_locale(- 1,- section_title_translation_locales.first,+ expect(guide.reload.localizations.pluck(:locale, :name)).to eq([["fr", "Guide FR"]])+ expect(api.reload.localizations).to be_empty+ end++ it "labels a group by its own language when a link has a different source" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|hu|ja|fr"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ guide = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ guide_ja = Fabricate(:sidebar_url, name: "ガイド v2", value: "/guide-2", locale: "ja")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide)+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide_ja)+ Fabricate(:sidebar_url_localization, sidebar_url: guide, locale: "ja", name: "ガイド")+ Fabricate(:sidebar_url_localization, sidebar_url: guide_ja, locale: "en", name: "Guide v2")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations++ expect(section_modal).to have_translation_language("en")+ expect(section_modal).to have_selected_translation_language("en")+ expect(section_modal).to have_translation_row("en", "ガイド v2")+ expect(section_modal).to have_no_translation_row("en", "Guide")+ end++ it "stops offering languages once every target is used" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|hu|ja"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ guide = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide)++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations+ section_modal.add_language("hu")+ section_modal.add_language("ja")++ expect(section_modal).to have_translation_languages(2)+ expect(section_modal).to have_no_add_language+ end++ it "offers link translations in the same session a section is made public" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|ja"+ SiteSetting.default_locale = "en"+ sidebar_section =+ Fabricate(:sidebar_section, title: "Drafts", public: false, user: admin, locale: "en")+ scratch = Fabricate(:sidebar_url, name: "Scratch", value: "/scratch", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: scratch)++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Drafts")+ section_modal.mark_as_public+ section_modal.open_translations+ section_modal.add_language("ja")++ expect(section_modal).to have_translation_row("ja", "Scratch")++ section_modal.fill_translation("ja", "Scratch", "スクラッチ")+ section_modal.save+ section_modal.confirm_update++ expect(section_modal).to be_closed+ expect(scratch.reload.localizations.pluck(:locale, :name)).to eq([%w[ja スクラッチ]])+ end++ it "confirms before removing a translation that was cleared" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|fr"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ guide = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide)+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "fr", title: "Documentation")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations+ section_modal.fill_translation("fr", "Docs", "")+ section_modal.save++ expect(page).to have_css(+ ".dialog-body",+ text: I18n.t("js.sidebar.sections.custom.localizations.remove_cleared_confirm", count: 1),)- expect(section_modal).to have_no_add_section_title_translation++ section_modal.confirm_update++ expect(section_modal).to be_closed+ expect(sidebar_section.reload.localizations).to be_empty+ end++ it "removes every translation for a language at once" do+ SiteSetting.content_localization_enabled = true+ SiteSetting.content_localization_supported_locales = "en|fr"+ SiteSetting.default_locale = "en"+ sidebar_section = Fabricate(:sidebar_section, title: "Docs", public: true, locale: "en")+ guide = Fabricate(:sidebar_url, name: "Guide", value: "/guide", locale: "en")+ Fabricate(:sidebar_section_link, sidebar_section:, linkable: guide)+ Fabricate(:sidebar_section_localization, sidebar_section:, locale: "fr", title: "Documentation")+ Fabricate(:sidebar_url_localization, sidebar_url: guide, locale: "fr", name: "Guide FR")++ sign_in admin+ visit("/latest")++ sidebar.edit_custom_section("Docs")+ section_modal.open_translations++ expect(section_modal).to have_translation_languages(1)++ section_modal.remove_language("fr")+ section_modal.confirm_dialog++ expect(section_modal).to have_translation_languages(0)++ section_modal.save+ section_modal.confirm_update++ expect(section_modal).to be_closed+ expect(sidebar_section.reload.localizations).to be_empty+ expect(guide.reload.localizations).to be_empty+ 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.open_translations+ section_modal.add_language("zh_CN")+ section_modal.add_language("ja")++ expect(section_modal).to have_translation_languages(2)+ expect(section_modal).to have_disabled_translation_locale("zh_CN", "ja")+ expect(section_modal).to have_disabled_translation_locale("ja", "zh_CN")+ expect(section_modal).to have_no_add_languageendit "displays warning when public section is marked as private" dodiff --git a/spec/system/editing_sidebar_community_section_spec.rb b/spec/system/editing_sidebar_community_section_spec.rbindex 8d9ebcb22d6..d7fac8366d8 100644--- a/spec/system/editing_sidebar_community_section_spec.rb+++ b/spec/system/editing_sidebar_community_section_spec.rb@@ -68,7 +68,10 @@ RSpec.describe "Editing Sidebar Community Section" domodal = sidebar.click_community_section_more_button.click_customize_community_section_buttonmodal.add_linkmodal.fill_last_link("Solutions Leaderboard", "/solutions-leaderboard")- modal.add_last_link_localization("ソリューションリーダーボード")+ modal.open_translations+ modal.add_language("ja")+ modal.fill_translation("ja", "Solutions Leaderboard", "ソリューションリーダーボード")+ modal.close_translationsmodal.add_linkmodal.fill_last_link("Untranslated Link", "/untranslated-link")modal.savediff --git a/spec/system/page_objects/modals/sidebar_section_form.rb b/spec/system/page_objects/modals/sidebar_section_form.rbindex 9c090e80128..19953771c2d 100644--- a/spec/system/page_objects/modals/sidebar_section_form.rb+++ b/spec/system/page_objects/modals/sidebar_section_form.rb@@ -50,45 +50,30 @@ module PageObjectsall(".delete-link").last.clickend- def add_section_title_translation- find(".add-localization").click+ def open_translations+ find(".sidebar-section-form__manage-translations").click+ selfend- 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)+ def close_translations+ find(".sidebar-section-translations__back").click+ selfend- 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)+ def add_language(locale)+ find(".sidebar-section-translations__add-language").click+ PageObjects::Components::DSelect.new(translation_language_selects.last).select(locale)end- def add_last_link_localization(name)- primary_links_wrapper- .all(".sidebar-section-form-link-wrapper")- .last- .find(".add-link-localization")- .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)+ def remove_language(locale)+ translation_language(locale).find(".sidebar-section-translations__remove-language").click+ end++ def fill_translation(locale, source, value)+ translation_language(locale)+ .find(".sidebar-section-translations__row", text: source)+ .find("input")+ .fill_in(with: value)enddef delete@@ -96,18 +81,25 @@ module PageObjectsenddef confirm_delete- find(".dialog-container .btn-danger").click+ PageObjects::Components::Dialog.new.click_dangerclosed?enddef confirm_update- find(".dialog-container .btn-primary").click+ confirm_dialogclosed?end+ def confirm_dialog+ dialog = PageObjects::Components::Dialog.new+ dialog.click_yes+ dialog.closed?+ self+ end+def resetfind(".reset-link").click- find(".dialog-footer .btn-primary").click+ PageObjects::Components::Dialog.new.click_yesclosed?selfend@@ -134,42 +126,64 @@ module PageObjectsenddef has_localization_controls?- page.has_css?(".sidebar-section-form__localization-row") &&- page.has_css?(".add-localization") && page.has_css?(".add-link-localization")+ page.has_css?(".sidebar-section-form__manage-translations")enddef 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")+ page.has_no_css?(".sidebar-section-form__manage-translations")enddef has_locale_option?(locale)page.has_css?(- "select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}'] option[value='#{locale}']",+ ".sidebar-section-translations__language-select option[value='#{locale}']",visible: :all,)enddef has_no_locale_option?(locale)page.has_no_css?(- "select[aria-label='#{I18n.t("js.sidebar.sections.custom.localizations.locale")}'] option[value='#{locale}']",+ ".sidebar-section-translations__language-select option[value='#{locale}']",visible: :all,)end- def section_title_translation_locales- all(section_title_translation_locale_selector).map(&:value)+ def has_translation_languages?(count)+ page.has_css?(".sidebar-section-translations__language", count:)+ end++ def has_translation_row?(locale, source)+ page.has_css?(translation_row_selector(locale), text: source)+ end++ def has_no_translation_row?(locale, source)+ page.has_no_css?(translation_row_selector(locale), text: source)end- def has_disabled_section_title_translation_locale?(row, locale)- all(section_title_translation_locale_selector)[row].has_css?(- "option[value='#{locale}'][disabled]",+ def has_translation_language?(locale)+ page.has_css?(translation_language_selector(locale))+ end++ def has_selected_translation_language?(locale)+ page.has_css?(+ "#{translation_language_selector(locale)} " \+ ".sidebar-section-translations__language-select option[value='#{locale}'][selected]",visible: :all,)end- def has_no_add_section_title_translation?- page.has_no_css?(".add-localization")+ def has_no_translation_language?(locale)+ page.has_no_css?(translation_language_selector(locale))+ end++ def has_disabled_translation_locale?(locale, disabled)+ translation_language(locale).has_css?(+ ".sidebar-section-translations__language-select option[value='#{disabled}'][disabled]",+ visible: :all,+ )+ end++ def has_no_add_language?+ page.has_no_css?(".sidebar-section-translations__add-language")enddef has_section_links_label?@@ -192,10 +206,39 @@ module PageObjectsfind(".draggable[data-link-name='Review']")end+ def has_source_language?(locale)+ page.has_css?(+ ".sidebar-section-form__source-locale-select option[value='#{locale}'][selected]",+ visible: :all,+ )+ end++ def has_no_source_language_control?+ page.has_no_css?(".sidebar-section-form__source-locale")+ end++ def select_source_language(locale)+ PageObjects::Components::DSelect.new(".sidebar-section-form__source-locale-select").select(+ locale,+ )+ 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")}']"+ def translation_language(locale)+ find(translation_language_selector(locale))+ end++ def translation_language_selector(locale)+ ".sidebar-section-translations__language[data-locale='#{locale}']"+ end++ def translation_row_selector(locale)+ "#{translation_language_selector(locale)} .sidebar-section-translations__row"+ end++ def translation_language_selects+ all(".sidebar-section-translations__language-select")enddef primary_links_wrapper