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 ? (
53 {this.props.multiple && this.props.showLanguageWarning && (
54 <div className="alert alert-warning" role="alert">
55 {i18n.t("undetermined_language_warning")}
58 <div className="form-group row">
60 className={classNames(
62 `col-sm-${this.props.multiple ? 3 : 2}`
66 {i18n.t(this.props.multiple ? "language_plural" : "language")}
69 className={classNames(
71 `col-sm-${this.props.multiple ? 9 : 10}`
75 {this.props.multiple && (
76 <div className="input-group-append">
78 className="input-group-text"
79 onClick={linkEvent(this, this.handleDeselectAll)}
92 const selectedLangs = this.props.selectedLanguageIds;
93 const filteredLangs = selectableLanguages(
94 this.props.allLanguages,
95 this.props.siteLanguages,
98 UserService.Instance.myUserInfo
103 className={classNames(
104 "lang-select-action",
105 this.props.iconVersion
106 ? "btn btn-sm text-muted"
107 : "form-control custom-select"
110 onChange={linkEvent(this, this.handleLanguageChange)}
111 aria-label={i18n.t("language_select_placeholder")}
112 multiple={this.props.multiple}
113 disabled={this.props.disabled}
115 {!this.props.multiple && (
116 <option selected disabled hidden>
117 {i18n.t("language_select_placeholder")}
120 {filteredLangs.map(l => (
124 selected={selectedLangs?.includes(l.id)}
133 handleLanguageChange(i: LanguageSelect, event: any) {
134 const options: HTMLOptionElement[] = Array.from(event.target.options);
135 const selected: number[] = options
136 .filter(o => o.selected)
137 .map(o => Number(o.value));
139 i.props.onChange(selected);
142 handleDeselectAll(i: LanguageSelect, event: any) {
143 event.preventDefault();
144 i.props.onChange([]);