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="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(
71 `col-sm-${this.props.multiple ? 9 : 10}`
75 {this.props.multiple && (
77 className="btn btn-outline-secondary"
78 onClick={linkEvent(this, this.handleDeselectAll)}
90 const selectedLangs = this.props.selectedLanguageIds;
91 const filteredLangs = selectableLanguages(
92 this.props.allLanguages,
93 this.props.siteLanguages,
96 UserService.Instance.myUserInfo
101 className={classNames("form-select w-auto", {
102 "d-inline-block": !this.props.iconVersion,
105 onChange={linkEvent(this, this.handleLanguageChange)}
106 aria-label={i18n.t("language_select_placeholder")}
107 multiple={this.props.multiple}
108 disabled={this.props.disabled}
110 {!this.props.multiple && (
111 <option selected disabled hidden>
112 {i18n.t("language_select_placeholder")}
115 {filteredLangs.map(l => (
119 selected={selectedLangs?.includes(l.id)}
128 handleLanguageChange(i: LanguageSelect, event: any) {
129 const options: HTMLOptionElement[] = Array.from(event.target.options);
130 const selected: number[] = options
131 .filter(o => o.selected)
132 .map(o => Number(o.value));
134 i.props.onChange(selected);
137 handleDeselectAll(i: LanguageSelect, event: any) {
138 event.preventDefault();
139 i.props.onChange([]);