assassin-bug/framework/ui/menu/items/selector-item.js

63 lines
2.4 KiB
JavaScript

import { BaseItem } from './base-item';
export class SelectorItem extends BaseItem {
constructor(id, title, items) {
super(id, title);
this.items = items;
this.entries = [];
}
getDOMNode() {
this.container = document.createElement('div');
this.listContainer = document.createElement('ul');
this.label = document.createElement('legend');
this.fieldSet = document.createElement('fieldset');
this.fieldSet.setAttribute('class', 'radiogroup');
this.fieldSet.id = `fs_selector_${this.id}`;
const name = document.createTextNode(this.title);
this.label.appendChild(name);
this.fieldSet.appendChild(this.label);
this.buildEntries();
this.container.appendChild(this.fieldSet);
this.container.addEventListener('focus', this.onFocus.bind(this));
return this.container;
}
buildEntries() {
this.items.forEach((item, index) => {
const node = document.createElement('input');
node.type = 'radio';
node.id = `${this.id}_${item.id}`;
node.name = this.id;
node.value = item.id || `${index}`;
node.addEventListener('focus', this.onItemFocus.bind(this));
node.addEventListener('select', this.onSelectItem.bind(this));
node.addEventListener('change', this.onChangeItem.bind(this));
this.entries.push(node);
const label = document.createElement('label');
label.setAttribute('for', `${this.id}_${item.id}`);
label.textContent = item.title;
this.fieldSet.append(node);
this.fieldSet.append(label);
});
}
onItemFocus(event) {
console.log(`Item focused: `, event);
this.emit('focus', this.id);
}
getContents() {
return this.currentValue;
}
onSelectItem(event) { }
onChangeItem(event) {
const node = document.querySelector(`input[name = "${this.id}"]:checked`);
this.currentValue = this.items.find((item) => `${this.id}_${item.id}` === node.id);
this.emit('update', {
type: 'selector',
value: this.currentValue
});
}
focus() {
const node = document.querySelector(`input[name = "${this.id}"]:checked`) ||
this.entries[0];
node.focus();
}
}