"use strict";
//
// Takes a input form element and a hidden form element (to store the selected id in) along with an array of objects, to build a dropdown select control that allows the user to type part of the selection to filter the list.
//
(function($) {
var EditableSelect = function($input, $hidden, data, options) {
var _this = this;
this.$input = $input;
this.$hidden = $hidden;
this.options = $.extend({}, EditableSelect.DEFAULTS, options);
this.$selected = null;
this.$listContainer = $('
', {style: 'position: relative; height: 0;'});
this.$list = $('', {role: 'menu', class: this.options.listClass});
//Ensure that if the hidden field exists and changes, that the hidden field's id matches the text in the input field. If not then the hidden id field was changed manually and externally and the text field should be updated.
if(this.$hidden) {
this.$hidden.on('change', function(event) {
var id = _this.$hidden.val();
var $li = _this.$list.children("[role!='node']");
for(var i = 0; i < $li.length; i++) {
var $next = $($li[i]);
if($next.data('model').id == id) {
if(_this.$input.val() != $next.text())
_this.$input.val($next.text());
}
}
});
}
//this.$list.appendTo($input.parent());
this.$list.appendTo(this.$listContainer);
this.$listContainer.appendTo($input.parent());
//Setup the list to highlight the item the user is hovering over, to select the item the user clicks, and to remove the hover styling when the list closes due to a selection being made.
this.$list
.on('mousemove', 'li', function() {
// _this.$list.find(_this.options.selectionClass).removeClass(_this.options.selectionClass);
var $this = $(this);
//Skip nodes.
while($this && $this.attr('role') == 'node') {
$this = $this.next();
}
//If we could find a non-node element then highlight it.
if($this) $this.addClass(_this.options.selectionClass).siblings().removeClass(_this.options.selectionClass);
})
.on('mousedown', 'li', function() {
var $this = $(this);
//Skip nodes.
while($this && $this.attr('role') == 'node') {
$this = $this.next();
}
//If we could find a non-node element then highlight it.
if($this) _this.select($this);
})
.on('mouseup', function() {
//Remove the selection highlighting.
_this.$list.children().removeClass(_this.options.selectionClass);
//Hide the list.
_this.hide();
});
//Setup the input field to handle opening the list when it receives focus, and close it when it loses focus.
this.$input
.on('focus', $.proxy(_this.focus, _this))
.on('blur', $.proxy(_this.blur, _this));
//Handle key events on the input field. Up/down arrows should change the selection in the list. Enter should select an item and close the list. Tab and escape should hide the list before moving to the next focusable element on the page.
this.$input.on('input keydown', function(event) {
switch(event.keyCode) {
case 38: //Up
var visibles = _this.$list.find('li.visible[role!="node"]');
var selected = visibles.index(visibles.filter('.' + _this.options.selectionClass)) || 0;
_this.highlight(selected - 1);
event.preventDefault();
break;
case 40: //Down
var visibles = _this.$list.find('li.visible[role!="node"]');
var selected = visibles.index(visibles.filter('li.selected')) || 0;
_this.highlight(selected + 1);
event.preventDefault();
break;
case 13: //Enter
if(_this.$list.is(':visible')) {
_this.select(_this.$list.find('li.selected'));
event.preventDefault();
}
case 9: //Tab
_this.select(_this.$list.find('li.selected'));
case 27: //Esc
if(_this.$input.hasClass('open')) {
_this.hide();
//Try to stop any default behavior from occurring.
if(event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true; //IE 6-8
event.preventDefault();
return false;
}
else {
return true;
}
default:
_this.filter();
_this.highlight(0);
break;
}
});
//
// Adds one or more elements to the control.
// data: The item or array of items to add. This will be the root tree elements if groupFunctions is provided.
function add(data) {
var groupFunctions = _this.options.groupFunctions;
var addOne = function(data, parent) { //role is optional.
var text = $.isFunction(_this.options.textAttr) ? _this.options.textAttr(data) : data[_this.options.textAttr];
var li = $("" + text + "");
li.appendTo(_this.$list);
li.data('model', data);
if(parent) li.data('parent-li', parent);
};
var addOneGroup = function(data, text, children) {
var li = $("" + text + "");
li.appendTo(_this.$list);
li.data('model', data);
for(var childIndex = 0; childIndex < children.length; childIndex++) {
addOne(children[childIndex], li);
}
};
var addOneBranch = function(data) {
var parents = $.isFunction(groupFunctions.groupParents) ? groupFunctions.groupParents(data) : data;
//Since there may be one or more parents identified for each data element passed to us...
if(Array.isArray(parents)) {
for(var parentIndex = 0; parentIndex < parents.length; parentIndex++) {
addOneGroup(parents[parentIndex], groupFunctions.parentText(parents[parentIndex]), groupFunctions.children(parents[parentIndex]));
}
}
else {
addOneGroup(parents, groupFunctions.parentText(parents), groupFunctions.children(parents));
}
};
if(groupFunctions instanceof Object && $.isFunction(groupFunctions.children) && $.isFunction(groupFunctions.parentText)) {
if(Array.isArray(data)) {
for(var dataIndex = 0; dataIndex < data.length; dataIndex++) {
addOneBranch(data[dataIndex]);
}
}
else {
addOneBranch(data);
}
}
else {
if(Array.isArray(data)) {
for(var dataIndex = 0; dataIndex < data.length; dataIndex++) {
addOne(data[dataIndex]);
}
}
else {
addOne(data);
}
}
//Filter the set of elements so that only those matching the text in the input field are marked as visible.
_this.filter();
}
//Add the initial set of data.
add(data);
};
EditableSelect.DEFAULTS = {
textAttr: 'text', //The attribute of the data elements to use for the name. This can also be a function that takes the data object and returns the text.
idAttr: 'id', //The attribute of the data elements to use for the ID. This can also be a function that takes the data obejct and returns the ID.
// groupFunctions: The object containing three functions: 'groupParent', 'parentText', 'children'.
// groupParents(data) will take a data element and return the objects that best represents the parents of the children (for a multi layer tree, this would be the node just before the leaf nodes).
// parentText(parent) will be passed the group parent and the data object that generated it, and will return the text that represents the path to that parent.
// children(parent) will be passed the group parent (returned by groupParents()), and will return an array of children or leaf nodes for the tree.
groupFunctions: undefined,
filter: true, //Whether to filter the list as the user types.
effects: 'fade',
duration: '200',
listClass: 'editable-select-list',
selectionClass: 'selected' //The class to use for the selected element in the dropdown list.
};
EditableSelect.prototype.select = function($li) {
if($li.length == 0) {
if(this.$input.val() != '') {
this.$input.val("")
if(this.$hidden) this.$hidden.val(undefined);
this.filter();
//Note: Don't trigger the select event - for some reason it causes the dropdown to reopen and the control to retain focus when clicking out of the widget.
}
}
else {
if(!this.$list.has($li) || !$li.is('li.visible')) return;
//No need to change selection if the selection has not changed.
if(this.$input.val() != $li.text()) {
this.$input.val($li.text()); //Save the selected text into the text input.
if(this.$hidden) this.$hidden.val($li.data('model')[this.options.idAttr]); //Save the ID into the hidden form input if it exists.
this.hide();
this.filter();
//this.trigger('select', $li);
}
}
};
//Filters the list items by marking those that match the text in the text field as having the class 'visible'.
EditableSelect.prototype.filter = function() {
try {
var search = this.$input.val();
var _this = this;
search = search ? search : "";
search = search.toLowerCase().trim();
//Show all list elements.
this.$list.find('li').addClass('visible').show();
//Hide any node list elements.
this.$list.find('li[role="node"]').removeClass('visible').hide();
if(this.options.filter) {
//Hide non-node elements (leaf nodes) that don't match.
var li = this.$list.children();
//Iterate over the list elements:
// hide all list items that are nodes;
// show all list items that are not nodes and whose text matches the input value;
// show all node list items associated with visible child list items (they occur after the parent, so the parent will be hidden first, then made visible).
for(var i = 0; i < li.length; i++) {
var $next = $(li[i]);
var node = $next.attr('role') == 'node';
var hidden = node || $next.text().toLowerCase().indexOf(search) < 0;
if(hidden) $next.removeClass('visible').hide();
//If this isn't hidden and we have a tree with grouping, then turn on the group (parent) associated with this option.
if(!hidden && _this.options.groupFunctions) {
var parent = $next.data('parent-li');
if(!parent.hasClass('visible')) parent.addClass('visible').show();
}
}
//If we hid all elements then hide the whole list.
if(this.$list.find('li.visible').length == 0) this.hide();
}
}catch (e) {
console.log(e);
}
};
EditableSelect.prototype.focus = function() {
this.show();
this.$input.select();
};
EditableSelect.prototype.blur = function() {
this.hide();
this.select(this.$list.find('li.selected'));
};
EditableSelect.prototype.show = function() {
//Position the list relative to the edit field.
this.$list.css({position: 'absolute', top: 0, left: 0, width: this.$input.outerWidth()});
if(!this.$list.is(':visible') && this.$list.find('li.visible').length > 0) {
var fns = {default: 'show', fade: 'fadeIn', slide: 'slideDown'};
var fn = fns[this.options.effects];
this.trigger('show');
this.$input.addClass('open');
this.$list[fn](this.options.duration, $.proxy(this.trigger, this, 'shown'));
}
};
EditableSelect.prototype.hide = function() {
var fns = {default: 'hide', fade: 'fadeOut', slide: 'slideUp'};
var fn = fns[this.options.effects];
this.trigger('hide');
this.$input.removeClass('open');
this.$list[fn](this.options.duration, $.proxy(this.trigger, this, 'hidden'));
};
// goDown: true/false - defaults to true - indicating whether the highlighting should go up or down if the requested item is a node. Nodes cannot be highlighted or selected.
EditableSelect.prototype.highlight = function(index) {
var _this = this;
this.show();
setTimeout(function() {
var visibles = _this.$list.find('li.visible[role!="node"]');
var oldSelected = _this.$list.find('li.' + _this.options.selectionClass).removeClass(_this.options.selectionClass);
var oldSelectedIndex = visibles.index(oldSelected);
if(visibles.length > 0) {
var selectedIndex = (visibles.length + index) % visibles.length;
var selected = visibles.eq(selectedIndex);
var top = selected.position().top;
if(selected.attr('role') != 'node') selected.addClass(_this.options.selectionClass);
if(selectedIndex < oldSelectedIndex && top < 0)
_this.$list.scrollTop(_this.$list.scrollTop() + top);
if(selectedIndex > oldSelectedIndex && top + selected.outerHeight() > _this.$list.outerHeight())
_this.$list.scrollTop(_this.$list.scrollTop() + selected.outerHeight() + 2 * (top - _this.$list.outerHeight()));
}
});
};
EditableSelect.prototype.trigger = function(event) {
var params = Array.prototype.slice.call(arguments, 1);
var args = [event + '.editable-select'];
args.push(params);
if(this.$select) this.$select.trigger.apply(this.$select, args);
this.$input.trigger.apply(this.$input, args);
};
$.fn.buildEditableSelect = function(data, options) {
for(var index = 0; index < this.length; index++) {
var $next = $(this[index]);
var nextEditableSelect = new EditableSelect($next, $next.siblings('input[type=hidden]').first(), data, options);
$next.data("editable-select", nextEditableSelect);
}
};
$.fn.editableSelect = function() {
if(this.length > 0) {
return $(this[0]).data('editable-select');
}
};
})(jQuery);