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 ? (
50 <div className="form-group row">
52 className={classNames("col-form-label", {
53 "col-sm-3": this.props.multiple,
54 "col-sm-2": !this.props.multiple,
58 {i18n.t(this.props.multiple ? "language_plural" : "language")}
61 className={classNames("input-group", {
62 "col-sm-9": this.props.multiple,
63 "col-sm-10": !this.props.multiple,
67 {this.props.multiple && (
68 <div className="input-group-append">
70 className="input-group-text"
71 onClick={linkEvent(this, this.handleDeselectAll)}
83 let selectedLangs = this.props.selectedLanguageIds;
84 let filteredLangs = selectableLanguages(
85 this.props.allLanguages,
86 this.props.siteLanguages,
89 UserService.Instance.myUserInfo
94 className={classNames("lang-select-action", {
95 "form-control custom-select": !this.props.iconVersion,
96 "btn btn-sm text-muted": this.props.iconVersion,
99 onChange={linkEvent(this, this.handleLanguageChange)}
101 multiple={this.props.multiple}
103 {filteredLangs.map(l => (
107 selected={selectedLangs?.includes(l.id)}
116 handleLanguageChange(i: LanguageSelect, event: any) {
117 let options: HTMLOptionElement[] = Array.from(event.target.options);
118 let selected: number[] = options
119 .filter(o => o.selected)
120 .map(o => Number(o.value));
122 i.props.onChange(selected);
125 handleDeselectAll(i: LanguageSelect, event: any) {
126 event.preventDefault();
127 i.props.onChange([]);