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("lang-select-action custom-select w-auto", {
104 "form-control": !this.props.iconVersion,
107 onChange={linkEvent(this, this.handleLanguageChange)}
108 aria-label={i18n.t("language_select_placeholder")}
109 multiple={this.props.multiple}
110 disabled={this.props.disabled}
112 {!this.props.multiple && (
113 <option selected disabled hidden>
114 {i18n.t("language_select_placeholder")}
117 {filteredLangs.map(l => (
121 selected={selectedLangs?.includes(l.id)}
130 handleLanguageChange(i: LanguageSelect, event: any) {
131 const options: HTMLOptionElement[] = Array.from(event.target.options);
132 const selected: number[] = options
133 .filter(o => o.selected)
134 .map(o => Number(o.value));
136 i.props.onChange(selected);
139 handleDeselectAll(i: LanguageSelect, event: any) {
140 event.preventDefault();
141 i.props.onChange([]);