1 import classNames from "classnames";
2 import { Component, linkEvent } from "inferno";
3 import { Language } from "lemmy-js-client";
4 import { i18n } from "../../i18next";
5 import { UserService } from "../../services/UserService";
6 import { randomStr, selectableLanguages } from "../../utils";
7 import { Icon } from "./icon";
9 interface LanguageSelectProps {
10 allLanguages: Language[];
11 siteLanguages: number[];
12 selectedLanguageIds?: number[];
14 onChange(val: number[]): any;
17 iconVersion?: boolean;
19 showLanguageWarning?: boolean;
22 export class LanguageSelect extends Component<LanguageSelectProps, any> {
23 private id = `language-select-${randomStr()}`;
25 constructor(props: any, context: any) {
26 super(props, context);
30 this.setSelectedValues();
33 // Necessary because there is no HTML way to set selected for multiple in value=
35 const ids = this.props.selectedLanguageIds?.map(toString);
37 const select = (document.getElementById(this.id) as HTMLSelectElement)
39 for (let i = 0; i < select.length; i++) {
41 if (ids.includes(o.value)) {
49 return this.props.iconVersion ? (
52 <div className="language-select">
53 {this.props.multiple && this.props.showLanguageWarning && (
54 <div className="alert alert-warning" role="alert">
55 {i18n.t("undetermined_language_warning")}
58 <div className="mb-3 row">
60 className={classNames(
62 `col-sm-${this.props.multiple ? 3 : 2}`
66 {i18n.t(this.props.multiple ? "language_plural" : "language")}
69 className={classNames(`col-sm-${this.props.multiple ? 9 : 10}`, {
70 "input-group": this.props.multiple,
74 {this.props.multiple && (
76 className="btn btn-outline-secondary"
77 onClick={linkEvent(this, this.handleDeselectAll)}
89 const selectedLangs = this.props.selectedLanguageIds;
90 const filteredLangs = selectableLanguages(
91 this.props.allLanguages,
92 this.props.siteLanguages,
95 UserService.Instance.myUserInfo
100 className={classNames("form-select w-auto", {
101 "d-inline-block": !this.props.iconVersion,
104 onChange={linkEvent(this, this.handleLanguageChange)}
105 aria-label={i18n.t("language_select_placeholder")}
106 multiple={this.props.multiple}
107 disabled={this.props.disabled}
109 {!this.props.multiple && (
110 <option selected disabled hidden>
111 {i18n.t("language_select_placeholder")}
114 {filteredLangs.map(l => (
118 selected={selectedLangs?.includes(l.id)}
127 handleLanguageChange(i: LanguageSelect, event: any) {
128 const options: HTMLOptionElement[] = Array.from(event.target.options);
129 const selected: number[] = options
130 .filter(o => o.selected)
131 .map(o => Number(o.value));
133 i.props.onChange(selected);
136 handleDeselectAll(i: LanguageSelect, event: any) {
137 event.preventDefault();
138 i.props.onChange([]);