oxjs/source/Ox.UI/js/Form/Ox.ButtonGroup.js

96 lines
3 KiB
JavaScript

// vim: et:ts=4:sw=4:sts=4:ft=javascript
'use strict';
/*@
Ox.ButtonGroup <f:Ox.Element> ButtonGroup Object
() -> <f> ButtonGroup Object
(options) -> <f> ButtonGroup Object
(options, self) -> <f> ButtonGroup Object
options <o> Options object
buttons <a> array of buttons
max <n> integer, maximum number of selected buttons, 0 for all
min <n> integer, minimum number of selected buttons, 0 for none
selectable <b> if true, buttons are selectable
type <s> string, 'image' or 'text'
self <o> Shared private variable
change <!> {id, value} selection within a group changed
@*/
Ox.ButtonGroup = function(options, self) {
self = self || {};
var that = Ox.Element({}, self)
.defaults({
buttons: [],
max: 1,
min: 1,
selectable: false,
size: 'medium',
style: '',
type: 'text',
})
.options(options || {})
.addClass('OxButtonGroup');
if (self.options.selectable) {
self.optionGroup = new Ox.OptionGroup(
self.options.buttons,
self.options.min,
self.options.max,
'selected'
);
self.options.buttons = self.optionGroup.init();
}
self.$buttons = [];
self.options.buttons.forEach(function(button, position) {
var id = self.options.id + Ox.toTitleCase(button.id)
self.$buttons[position] = Ox.Button({
disabled: button.disabled,
group: true,
id: id,
selectable: self.options.selectable,
selected: button.selected,
size: self.options.size,
style: self.options.style,
title: button.title,
tooltip: button.tooltip,
type: self.options.type
})
.bindEvent('select', function() {
selectButton(position);
})
.appendTo(that);
});
function selectButton(pos) {
var toggled = self.optionGroup.toggle(pos);
if (toggled.length) {
toggled.forEach(function(pos) {
self.$buttons[pos].toggleSelected();
});
that.triggerEvent('change', {
selected: self.optionGroup.selected().map(function(i) {
return self.options.buttons[i].id;
})
});
}
}
that.select = function(id) {
// fixme: this doesn't work in cases where
// multiple buttons can be selected
var position = Ox.getPositionById(self.options.buttons, id);
if (position > -1) {
self.$buttons[position].trigger('click');
}
};
that.value = function() {
return self.optionGroup.selected().map(function(i) {
return self.options.buttons[i].id;
});
};
return that;
};