tweb/src/components/radioField.ts

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-04-08 15:52:31 +02:00
/*
* https://github.com/morethanwords/tweb
* Copyright (C) 2019-2021 Eduard Kuzmenko
* https://github.com/morethanwords/tweb/blob/master/LICENSE
*/
import appStateManager from "../lib/appManagers/appStateManager";
import { getDeepProperty } from "../helpers/object";
2021-03-22 19:38:03 +01:00
import { LangPackKey, _i18n } from "../lib/langPack";
export default class RadioField {
public input: HTMLInputElement;
public label: HTMLLabelElement;
public main: HTMLElement;
2021-03-16 16:18:51 +01:00
constructor(options: {
2021-03-23 17:13:35 +01:00
text?: string,
langKey?: LangPackKey,
2021-03-16 16:18:51 +01:00
name: string,
value?: string,
stateKey?: string
}) {
const label = this.label = document.createElement('label');
label.classList.add('radio-field');
const input = this.input = document.createElement('input');
input.type = 'radio';
2021-03-16 16:18:51 +01:00
/* input.id = */input.name = 'input-radio-' + options.name;
2021-03-16 16:18:51 +01:00
if(options.value) {
input.value = options.value;
2021-03-16 16:18:51 +01:00
if(options.stateKey) {
appStateManager.getState().then(state => {
2021-03-16 16:18:51 +01:00
input.checked = getDeepProperty(state, options.stateKey) === options.value;
});
input.addEventListener('change', () => {
2021-03-16 16:18:51 +01:00
appStateManager.setByKey(options.stateKey, options.value);
});
}
}
const main = this.main = document.createElement('div');
main.classList.add('radio-field-main');
2021-03-16 16:18:51 +01:00
if(options.text) {
2021-03-23 17:13:35 +01:00
main.innerHTML = options.text;
/* const caption = document.createElement('div');
caption.classList.add('radio-field-main-caption');
caption.innerHTML = text;
if(subtitle) {
label.classList.add('radio-field-with-subtitle');
caption.insertAdjacentHTML('beforeend', `<div class="radio-field-main-subtitle">${subtitle}</div>`);
}
main.append(caption); */
2021-03-23 17:13:35 +01:00
} else if(options.langKey) {
_i18n(main, options.langKey);
}
label.append(input, main);
}
2021-03-16 16:18:51 +01:00
get checked() {
return this.input.checked;
}
set checked(checked: boolean) {
this.setValueSilently(checked);
const event = new Event('change', {bubbles: true, cancelable: true});
this.input.dispatchEvent(event);
}
public setValueSilently(checked: boolean) {
this.input.checked = checked;
}
};