discourse-translator/assets/javascripts/discourse/components/language-switcher.gjs
Natalie Tay 2fa47c2d8a
DEV: Prevent multiple instances of same locale cookie due to path (#272)
When using the language switcher, the cookie gets added but the path is not specified, so we may have multiple of the same cookie with varying paths.

This commit fixes the path to root so there won't be dups.
2025-04-11 15:02:51 +08:00

67 lines
1.8 KiB
Text

import Component from "@glimmer/component";
import { fn } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
import DButton from "discourse/components/d-button";
import DropdownMenu from "discourse/components/dropdown-menu";
import cookie from "discourse/lib/cookie";
import DMenu from "float-kit/components/d-menu";
export default class LanguageSwitcher extends Component {
@service site;
@service siteSettings;
@service router;
get localeOptions() {
const targetLanguages = (
this.siteSettings.automatic_translation_target_languages || ""
).split("|");
return JSON.parse(this.siteSettings.available_locales)
.filter(({ value }) => targetLanguages.includes(value))
.map(({ name, value }) => {
return {
label: name,
value,
};
});
}
@action
async changeLocale(locale) {
cookie("locale", locale, { path: "/" });
this.dMenu.close();
// we need a hard refresh here for the locale to take effect
window.location.reload();
}
@action
onRegisterApi(api) {
this.dMenu = api;
}
<template>
<DMenu
@identifier="discourse-translator_language-switcher"
title="Language switcher"
@icon="language"
class="btn-flat btn-icon icon"
@onRegisterApi={{this.onRegisterApi}}
>
<:content>
<DropdownMenu as |dropdown|>
{{#each this.localeOptions as |option|}}
<dropdown.item
class="discourse-translator_locale-option"
data-menu-option-id={{option.value}}
>
<DButton
@translatedLabel={{option.label}}
@action={{fn this.changeLocale option.value}}
/>
</dropdown.item>
{{/each}}
</DropdownMenu>
</:content>
</DMenu>
</template>
}