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;
20 export class LanguageSelect extends Component<LanguageSelectProps, any> {
21 private id = `language-select-${randomStr()}`;
23 constructor(props: any, context: any) {
24 super(props, context);
28 this.setSelectedValues();
31 // Necessary because there is no HTML way to set selected for multiple in value=
33 let ids = this.props.selectedLanguageIds?.map(toString);
35 let select = (document.getElementById(this.id) as HTMLSelectElement)
37 for (let i = 0; i < select.length; i++) {
39 if (ids.includes(o.value)) {
47 return this.props.iconVersion ? (
51 {this.props.multiple && (
52 <div className="alert alert-warning" role="alert">
53 {i18n.t("undetermined_language_warning")}
56 <div className="form-group row">
58 className={classNames("col-form-label", {
59 "col-sm-3": this.props.multiple,
60 "col-sm-2": !this.props.multiple,
64 {i18n.t(this.props.multiple ? "language_plural" : "language")}
67 className={classNames("input-group", {
68 "col-sm-9": this.props.multiple,
69 "col-sm-10": !this.props.multiple,
73 {this.props.multiple && (
74 <div className="input-group-append">
76 className="input-group-text"
77 onClick={linkEvent(this, this.handleDeselectAll)}
90 let selectedLangs = this.props.selectedLanguageIds;
91 let filteredLangs = selectableLanguages(
92 this.props.allLanguages,
93 this.props.siteLanguages,
96 UserService.Instance.myUserInfo
101 className={classNames("lang-select-action", {
102 "form-control custom-select": !this.props.iconVersion,
103 "btn btn-sm text-muted": this.props.iconVersion,
106 onChange={linkEvent(this, this.handleLanguageChange)}
108 multiple={this.props.multiple}
110 {filteredLangs.map(l => (
114 selected={selectedLangs?.includes(l.id)}
123 handleLanguageChange(i: LanguageSelect, event: any) {
124 let options: HTMLOptionElement[] = Array.from(event.target.options);
125 let selected: number[] = options
126 .filter(o => o.selected)
127 .map(o => Number(o.value));
129 i.props.onChange(selected);
132 handleDeselectAll(i: LanguageSelect, event: any) {
133 event.preventDefault();
134 i.props.onChange([]);