pvbemu/web/toolkit/Radio.js

114 lines
2.8 KiB
JavaScript
Raw Normal View History

2023-03-08 16:42:27 +00:00
let register = Toolkit => Toolkit.Radio =
// Radio button group manager
class Radio extends Toolkit.Checkbox {
///////////////////////// Initialization Methods //////////////////////////
constructor(app, options) {
super(app, options = Object.assign({
class: "tk radio",
role : "radio"
}, options || {}));
// Configure instance fields
this._group = null;
// Configure options
if ("group" in options)
this.group = options.group;
if ("checked" in options) {
this.checked = false;
this.checked = options.checked;
}
}
///////////////////////////// Event Handlers //////////////////////////////
// Key press
onKeyDown(e) {
// Error checking
if (e.altKey || e.ctrlKey || e.shiftKey || this.disabled)
return;
// Processing by key
let item = null;
switch (e.key) {
// Activate the radio button
case " ":
case "Enter":
this.checked = true;
break;
// Focus the next button in the group
case "ArrowDown":
case "ArrowRight":
if (this.group == null)
return;
item = this.group.next(this);
break;
// Focus the previous button in the group
case "ArrowLeft":
case "ArrowUp":
if (this.group == null)
return;
item = this.group.previous(this);
break;
default: return;
}
// Select and focus another item in the group
if (item != null && item != this) {
this.group.active = item;
item.focus();
item.element.dispatchEvent(new Event("input"));
}
Toolkit.handle(e);
}
///////////////////////////// Public Methods //////////////////////////////
// The check box is checked
get checked() { return super.checked; }
set checked(checked) {
super.checked = checked;
if (this.group != null && this != this.group.active && checked)
this.group.active = this;
}
// Managing radio button group
get group() { return this._group; }
set group(group) {
if (group == this.group)
return;
if (group)
group.add(this);
this._group = group ? group : null;
}
///////////////////////////// Private Methods /////////////////////////////
// Specify the checked state
setChecked(checked) {
if (!checked || this.checked)
return;
this.checked = true;
this.element.dispatchEvent(new Event("input"));
}
}
export { register };