mirror of
https://github.com/galaxyproject/galaxy.git
synced 2026-09-24 16:30:27 +08:00
JS files for tagging
This commit is contained in:
@@ -0,0 +1,453 @@
|
||||
/**
|
||||
* JQuery extension for tagging with autocomplete.
|
||||
* @author: Jeremy Goecks
|
||||
* @require: jquery.autocomplete plugin
|
||||
*/
|
||||
var ac_tag_area_id_gen = 1;
|
||||
|
||||
jQuery.fn.autocomplete_tagging = function(options) {
|
||||
|
||||
//
|
||||
// Set up function defaults.
|
||||
//
|
||||
var defaults =
|
||||
{
|
||||
get_toggle_link_text_fn: function(tags)
|
||||
{
|
||||
var text = "";
|
||||
var num_tags = array_length(tags);
|
||||
if (num_tags != 0)
|
||||
text = num_tags + (num_tags != 0 ? " Tags" : " Tag");
|
||||
else
|
||||
// No tags.
|
||||
text = "Add tags";
|
||||
return text;
|
||||
},
|
||||
tag_click_fn : function (tag) { },
|
||||
input_size: 20,
|
||||
in_form: false,
|
||||
tags : {},
|
||||
use_toggle_link: true,
|
||||
item_id: "",
|
||||
add_tag_img: "",
|
||||
add_tag_img_rollover: "",
|
||||
delete_tag_img: "",
|
||||
ajax_autocomplete_tag_url: "",
|
||||
ajax_retag_url: "",
|
||||
ajax_delete_tag_url: "",
|
||||
ajax_add_tag_url: ""
|
||||
};
|
||||
|
||||
//
|
||||
// Extend object.
|
||||
//
|
||||
var settings = jQuery.extend(defaults, options);
|
||||
|
||||
//
|
||||
// Create core elements: tag area and TODO.
|
||||
//
|
||||
|
||||
// Tag area.
|
||||
var area_id = "tag-area-" + (ac_tag_area_id_gen)++;
|
||||
var tag_area = $("<div></div>").attr("id", area_id).addClass("tag-area");
|
||||
this.append(tag_area);
|
||||
|
||||
//
|
||||
// Returns the number of keys (elements) in an array/dictionary.
|
||||
//
|
||||
var array_length = function(an_array)
|
||||
{
|
||||
if (an_array.length)
|
||||
return an_array.length;
|
||||
|
||||
var count = 0;
|
||||
for (element in an_array)
|
||||
count++;
|
||||
return count;
|
||||
};
|
||||
|
||||
//
|
||||
// Function to build toggle link.
|
||||
//
|
||||
var build_toggle_link = function()
|
||||
{
|
||||
var link_text = settings.get_toggle_link_text_fn(settings.tags);
|
||||
var toggle_link = $("<a href='/history/tags'>" + link_text + "</a>").addClass("toggle-link");
|
||||
// Link toggles the display state of the tag area.
|
||||
toggle_link.click( function()
|
||||
{
|
||||
// Take special actions depending on whether toggle is showing or hiding link.
|
||||
var showing_tag_area = (tag_area.css("display") == "none");
|
||||
var after_toggle_fn;
|
||||
if (showing_tag_area)
|
||||
{
|
||||
after_toggle_fn = function()
|
||||
{
|
||||
// If there are no tags, go right to editing mode by generating a
|
||||
// click on the area.
|
||||
var num_tags = array_length(settings.tags);
|
||||
if (num_tags == 0)
|
||||
tag_area.click();
|
||||
};
|
||||
}
|
||||
else // Hiding area.
|
||||
{
|
||||
after_toggle_fn = function()
|
||||
{
|
||||
tag_area.blur();
|
||||
};
|
||||
}
|
||||
tag_area.slideToggle("fast", after_toggle_fn);
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
return toggle_link;
|
||||
};
|
||||
|
||||
// Add toggle link.
|
||||
var toggle_link = build_toggle_link();
|
||||
if (settings.use_toggle_link)
|
||||
{
|
||||
this.prepend(toggle_link);
|
||||
}
|
||||
|
||||
//
|
||||
// Function to build other elements.
|
||||
//
|
||||
|
||||
//
|
||||
// Return a string that contains the contents of an associative array. This is
|
||||
// a debugging method.
|
||||
//
|
||||
var assoc_array_to_str = function(an_array)
|
||||
{
|
||||
// Convert associative array to simple array and then join array elements.
|
||||
var array_str_list = new Array();
|
||||
for (key in an_array)
|
||||
array_str_list[array_str_list.length] = key + "-->" + an_array[key];
|
||||
|
||||
return "{" + array_str_list.join(",") + "}"
|
||||
};
|
||||
|
||||
//
|
||||
// Collapse tag name + value into a single string.
|
||||
//
|
||||
var build_tag_str = function(tag_name, tag_value)
|
||||
{
|
||||
return tag_name + ( (tag_value != "" && tag_value) ? ":" + tag_value : "");
|
||||
};
|
||||
|
||||
//
|
||||
// Get tag name and value from a string.
|
||||
//
|
||||
var get_tag_name_and_value = function(tag_str)
|
||||
{
|
||||
return tag_str.split(":");
|
||||
};
|
||||
|
||||
//
|
||||
// Add "add tag" button.
|
||||
//
|
||||
var build_add_tag_button = function(tag_input_field)
|
||||
{
|
||||
var add_tag_button = $("<img src='" + settings.add_tag_img + "' rollover='" + settings.add_tag_img_rollover + "'/>").addClass("add-tag-button");
|
||||
|
||||
add_tag_button.click( function()
|
||||
{
|
||||
// Hide button.
|
||||
$(this).hide();
|
||||
|
||||
// Clicking on button is the same as clicking on the tag area.
|
||||
tag_area.click();
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
return add_tag_button;
|
||||
};
|
||||
|
||||
//
|
||||
// Function that builds a tag button.
|
||||
//
|
||||
var build_tag_button = function(tag_str)
|
||||
{
|
||||
// Build "delete tag" image and handler.
|
||||
var delete_img = $("<img src='" + settings.delete_tag_img + "'/>").addClass("delete-tag-img");
|
||||
delete_img.mouseenter( function ()
|
||||
{
|
||||
$(this).attr("src", settings.delete_tag_img_rollover);
|
||||
});
|
||||
delete_img.mouseleave( function ()
|
||||
{
|
||||
$(this).attr("src", settings.delete_tag_img);
|
||||
});
|
||||
delete_img.click( function ()
|
||||
{
|
||||
// Tag button is image's parent.
|
||||
var tag_button = $(this).parent();
|
||||
|
||||
// Get tag name.
|
||||
var tag_name_elt = tag_button.find(".tag-name").eq(0);
|
||||
var tag_str = tag_name_elt.text();
|
||||
var tag_name = get_tag_name_and_value(tag_str)[0];
|
||||
|
||||
// TODO: should remove succeed if tag is not already applied to
|
||||
// history?
|
||||
tag_button.remove();
|
||||
|
||||
// Remove tag from local list for consistency.
|
||||
delete settings.tags[tag_name];
|
||||
|
||||
// Update toggle link text.
|
||||
var new_text = settings.get_toggle_link_text_fn(settings.tags);
|
||||
toggle_link.text(new_text);
|
||||
|
||||
// Delete tag.
|
||||
$.ajax({
|
||||
url: settings.ajax_delete_tag_url,
|
||||
data: { tag_name: tag_name },
|
||||
error: function()
|
||||
{
|
||||
// Failed.
|
||||
alert( "Remove tag failed" );
|
||||
},
|
||||
success: function()
|
||||
{
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// Build tag button.
|
||||
var tag_name_elt = $("<span>" + tag_str + "</span>").addClass("tag-name");
|
||||
tag_name_elt.click( function()
|
||||
{
|
||||
settings.tag_click_fn(tag_str);
|
||||
return true;
|
||||
});
|
||||
|
||||
var tag_button = $("<span></span>").addClass("tag-button");
|
||||
tag_button.append(tag_name_elt);
|
||||
tag_button.append(delete_img);
|
||||
|
||||
return tag_button;
|
||||
};
|
||||
|
||||
//
|
||||
// Build input + autocompete for tag.
|
||||
//
|
||||
var build_tag_input = function(tag_text)
|
||||
{
|
||||
// If element is in form, tag input is a textarea; otherwise element is a input type=text.
|
||||
var t;
|
||||
if (settings.in_form)
|
||||
t = $( "<textarea id='history-tag-input' rows='1' cols='" +
|
||||
settings.input_size + "' value='" + tag_text + "'></textarea>" );
|
||||
else // element not in form.
|
||||
t = $( "<input id='history-tag-input' type='text' size='" +
|
||||
settings.input_size + "' value='" + tag_text + "'></input>" );
|
||||
t.keyup( function( e )
|
||||
{
|
||||
if ( e.keyCode == 27 )
|
||||
{
|
||||
// Escape key
|
||||
$(this).trigger( "blur" );
|
||||
} else if (
|
||||
( e.keyCode == 13 ) || // Return Key
|
||||
( e.keyCode == 188 ) || // Comma
|
||||
( e.keyCode == 32 ) // Space
|
||||
)
|
||||
{
|
||||
//
|
||||
// Check input.
|
||||
//
|
||||
|
||||
new_value = this.value;
|
||||
|
||||
// Do nothing if return key was used to autocomplete.
|
||||
if (return_key_pressed_for_autocomplete == true)
|
||||
{
|
||||
return_key_pressed_for_autocomplete = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Suppress space after a ":"
|
||||
if ( new_value.indexOf(": ", new_value.length - 2) != -1)
|
||||
{
|
||||
this.value = new_value.substring(0, new_value.length-1);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove trigger keys from input.
|
||||
if ( (e.keyCode == 188) || (e.keyCode == 32) )
|
||||
new_value = new_value.substring( 0 , new_value.length - 1 );
|
||||
|
||||
// Trim whitespace.
|
||||
new_value = new_value.replace(/^\s+|\s+$/g,"");
|
||||
|
||||
// Too short?
|
||||
if (new_value.length < 3)
|
||||
return false;
|
||||
|
||||
//
|
||||
// New tag OK - apply it.
|
||||
//
|
||||
|
||||
this.value = "";
|
||||
|
||||
// Add button for tag after all other tag buttons.
|
||||
var new_tag_button = build_tag_button(new_value);
|
||||
var tag_buttons = tag_area.children(".tag-button");
|
||||
if (tag_buttons.length != 0)
|
||||
{
|
||||
var last_tag_button = tag_buttons.slice(tag_buttons.length-1);
|
||||
last_tag_button.after(new_tag_button);
|
||||
}
|
||||
else
|
||||
tag_area.prepend(new_tag_button);
|
||||
|
||||
// Add tag to internal list.
|
||||
var tag_name_and_value = new_value.split(":");
|
||||
settings.tags[tag_name_and_value[0]] = tag_name_and_value[1];
|
||||
|
||||
// Update toggle link text.
|
||||
var new_text = settings.get_toggle_link_text_fn(settings.tags);
|
||||
toggle_link.text(new_text);
|
||||
|
||||
// Commit tag to server.
|
||||
var $this = $(this);
|
||||
$.ajax({
|
||||
url: settings.ajax_add_tag_url,
|
||||
data: { new_tag: new_value },
|
||||
error: function()
|
||||
{
|
||||
// Remove tag and show alert.
|
||||
new_tag_button.remove();
|
||||
var new_text = settings.get_toggle_link_text_fn(settings.tags);
|
||||
toggle_link.text(new_text);
|
||||
alert( "Add tag failed" );
|
||||
},
|
||||
success: function()
|
||||
{
|
||||
// Flush autocomplete cache because it's not out of date.
|
||||
// TODO: in the future, we could remove the particular item
|
||||
// that was chosen from the cache rather than flush it.
|
||||
$this.flushCache();
|
||||
}
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// Add autocomplete to input.
|
||||
var format_item_func = function(key, row_position, num_rows, value, search_term) {
|
||||
tag_name_and_value = value.split(":");
|
||||
return (tag_name_and_value.length == 1 ? tag_name_and_value[0] :tag_name_and_value[1]);
|
||||
//var array = new Array(key, value, row_position, num_rows,
|
||||
//search_term ); return "\"" + array.join("*") + "\"";
|
||||
}
|
||||
var autocomplete_options =
|
||||
{ selectFirst: false, formatItem : format_item_func, autoFill: false, highlight: false };
|
||||
|
||||
t.autocomplete(settings.ajax_autocomplete_tag_url, autocomplete_options);
|
||||
|
||||
t.addClass("tag-input");
|
||||
|
||||
return t;
|
||||
};
|
||||
|
||||
//
|
||||
// Build tag area.
|
||||
//
|
||||
|
||||
// Add tag buttons for each current tag to the tag area.
|
||||
for (tag_name in settings.tags)
|
||||
{
|
||||
var tag_value = settings.tags[tag_name];
|
||||
var tag_str = build_tag_str(tag_name, tag_value);
|
||||
var tag_button = build_tag_button(tag_str, toggle_link, settings.tags);
|
||||
tag_area.append(tag_button);
|
||||
}
|
||||
|
||||
// Add tag input field and "add tag" button.
|
||||
var tag_input_field = build_tag_input("");
|
||||
var add_tag_button = build_add_tag_button(tag_input_field);
|
||||
|
||||
// When the tag area blurs, go to "view tag" mode.
|
||||
tag_area.blur( function(e)
|
||||
{
|
||||
add_tag_button.show();
|
||||
tag_input_field.hide();
|
||||
tag_area.removeClass("active-tag-area");
|
||||
});
|
||||
|
||||
tag_area.append(add_tag_button);
|
||||
tag_area.append(tag_input_field);
|
||||
tag_input_field.hide();
|
||||
|
||||
// On click, enable user to add tags.
|
||||
tag_area.click( function(e)
|
||||
{
|
||||
var is_active = $(this).hasClass("active-tag-area");
|
||||
|
||||
// If a "delete image" object was pressed and area is inactive, do nothing.
|
||||
if ($(e.target).hasClass("delete-tag-img") && !is_active)
|
||||
return false;
|
||||
|
||||
// If a "tag name" object was pressed and area is inactive, do nothing.
|
||||
if ($(e.target).hasClass("tag-name") && !is_active)
|
||||
return false;
|
||||
|
||||
// Hide add tag button, show tag_input field. Change background to show
|
||||
// area is active.
|
||||
$(this).addClass("active-tag-area");
|
||||
add_tag_button.hide();
|
||||
tag_input_field.show();
|
||||
tag_input_field.focus();
|
||||
|
||||
// Add handler to document that will call blur when the tag area is blurred;
|
||||
// a tag area is blurred when a user clicks on an element outside the area.
|
||||
var handle_document_click = function(e)
|
||||
{
|
||||
var tag_area_id = tag_area.attr("id");
|
||||
// Blur the tag area if the element clicked on is not in the tag area.
|
||||
if (
|
||||
($(e.target).attr("id") != tag_area_id) &&
|
||||
($(e.target).parents().filter(tag_area_id).length == 0)
|
||||
)
|
||||
{
|
||||
tag_area.blur();
|
||||
$(document).unbind("click", handle_document_click);
|
||||
}
|
||||
};
|
||||
// TODO: we should attach the click handler to all frames in order to capture
|
||||
// clicks outside the frame that this element is in.
|
||||
//window.parent.document.onclick = handle_document_click;
|
||||
//var temp = $(window.parent.document.body).contents().find("iframe").html();
|
||||
//alert(temp);
|
||||
//$(document).parent().click(handle_document_click);
|
||||
$(window).click(handle_document_click);
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
// If using toggle link, hide the tag area. Otherwise, if there are no tags,
|
||||
// hide the "add tags" button and show the input field.
|
||||
if (settings.use_toggle_link)
|
||||
tag_area.hide();
|
||||
else
|
||||
{
|
||||
var num_tags = array_length(settings.tags);
|
||||
if (num_tags == 0)
|
||||
{
|
||||
add_tag_button.hide();
|
||||
tag_input_field.show();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return this.addClass("tag-element");
|
||||
}
|
||||
@@ -0,0 +1,824 @@
|
||||
/*
|
||||
* Autocomplete - jQuery plugin 1.0.2
|
||||
*
|
||||
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
|
||||
*
|
||||
* Dual licensed under the MIT and GPL licenses:
|
||||
* http://www.opensource.org/licenses/mit-license.php
|
||||
* http://www.gnu.org/licenses/gpl.html
|
||||
*
|
||||
* Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
|
||||
*
|
||||
*/
|
||||
|
||||
String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
|
||||
|
||||
|
||||
var return_key_pressed_for_autocomplete = false;
|
||||
|
||||
;(function($) {
|
||||
|
||||
$.fn.extend({
|
||||
autocomplete: function(urlOrData, options) {
|
||||
var isUrl = typeof urlOrData == "string";
|
||||
options = $.extend({}, $.Autocompleter.defaults, {
|
||||
url: isUrl ? urlOrData : null,
|
||||
data: isUrl ? null : urlOrData,
|
||||
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
|
||||
max: options && !options.scroll ? 10 : 150
|
||||
}, options);
|
||||
|
||||
// if highlight is set to false, replace it with a do-nothing function
|
||||
options.highlight = options.highlight || function(value) { return value; };
|
||||
|
||||
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
|
||||
options.formatMatch = options.formatMatch || options.formatItem;
|
||||
|
||||
return this.each(function() {
|
||||
new $.Autocompleter(this, options);
|
||||
});
|
||||
},
|
||||
result: function(handler) {
|
||||
return this.bind("result", handler);
|
||||
},
|
||||
search: function(handler) {
|
||||
return this.trigger("search", [handler]);
|
||||
},
|
||||
flushCache: function() {
|
||||
return this.trigger("flushCache");
|
||||
},
|
||||
setOptions: function(options){
|
||||
return this.trigger("setOptions", [options]);
|
||||
},
|
||||
unautocomplete: function() {
|
||||
return this.trigger("unautocomplete");
|
||||
}
|
||||
});
|
||||
|
||||
$.Autocompleter = function(input, options) {
|
||||
|
||||
var KEY = {
|
||||
UP: 38,
|
||||
DOWN: 40,
|
||||
DEL: 46,
|
||||
TAB: 9,
|
||||
RETURN: 13,
|
||||
ESC: 27,
|
||||
COMMA: 188,
|
||||
PAGEUP: 33,
|
||||
PAGEDOWN: 34,
|
||||
BACKSPACE: 8,
|
||||
COLON: 16
|
||||
};
|
||||
|
||||
// Create $ object for input element
|
||||
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
|
||||
|
||||
var timeout;
|
||||
var previousValue = "";
|
||||
var cache = $.Autocompleter.Cache(options);
|
||||
var hasFocus = 0;
|
||||
var lastKeyPressCode;
|
||||
var config = {
|
||||
mouseDownOnSelect: false
|
||||
};
|
||||
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
|
||||
|
||||
var blockSubmit;
|
||||
|
||||
// prevent form submit in opera when selecting with return key
|
||||
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
|
||||
if (blockSubmit) {
|
||||
blockSubmit = false;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
|
||||
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
|
||||
// track last key pressed
|
||||
lastKeyPressCode = event.keyCode;
|
||||
switch(event.keyCode) {
|
||||
|
||||
case KEY.UP:
|
||||
event.preventDefault();
|
||||
if ( select.visible() ) {
|
||||
select.prev();
|
||||
} else {
|
||||
onChange(0, true);
|
||||
}
|
||||
break;
|
||||
|
||||
case KEY.DOWN:
|
||||
event.preventDefault();
|
||||
if ( select.visible() ) {
|
||||
select.next();
|
||||
} else {
|
||||
onChange(0, true);
|
||||
}
|
||||
break;
|
||||
|
||||
case KEY.PAGEUP:
|
||||
event.preventDefault();
|
||||
if ( select.visible() ) {
|
||||
select.pageUp();
|
||||
} else {
|
||||
onChange(0, true);
|
||||
}
|
||||
break;
|
||||
|
||||
case KEY.PAGEDOWN:
|
||||
event.preventDefault();
|
||||
if ( select.visible() ) {
|
||||
select.pageDown();
|
||||
} else {
|
||||
onChange(0, true);
|
||||
}
|
||||
break;
|
||||
|
||||
// matches also semicolon
|
||||
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
|
||||
case KEY.TAB:
|
||||
case KEY.RETURN:
|
||||
if (event.keyCode == KEY.RETURN)
|
||||
return_key_pressed_for_autocomplete = false;
|
||||
if( selectCurrent() ) {
|
||||
// stop default to prevent a form submit, Opera needs special handling
|
||||
event.preventDefault();
|
||||
blockSubmit = true;
|
||||
|
||||
// JG: set flag to indicate that a selection just occurred using the return key. FYI:
|
||||
// event.stopPropagation() does not work.
|
||||
if (event.keyCode == KEY.RETURN)
|
||||
return_key_pressed_for_autocomplete = true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
case KEY.ESC:
|
||||
select.hide();
|
||||
break;
|
||||
case KEY.COLON:
|
||||
break;
|
||||
|
||||
default:
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(onChange, options.delay);
|
||||
break;
|
||||
}
|
||||
}).focus(function(){
|
||||
// track whether the field has focus, we shouldn't process any
|
||||
// results if the field no longer has focus
|
||||
hasFocus++;
|
||||
}).blur(function() {
|
||||
hasFocus = 0;
|
||||
if (!config.mouseDownOnSelect) {
|
||||
// JG: if blur and user is not selecting with mouse, hide
|
||||
// object.
|
||||
select.hide();
|
||||
}
|
||||
return this;
|
||||
}).click(function() {
|
||||
// show select when clicking in a focused field
|
||||
if ( hasFocus++ > 1 && !select.visible() ) {
|
||||
onChange(0, true);
|
||||
}
|
||||
return this;
|
||||
}).bind("search", function() {
|
||||
// TODO why not just specifying both arguments?
|
||||
var fn = (arguments.length > 1) ? arguments[1] : null;
|
||||
function findValueCallback(q, data) {
|
||||
var result;
|
||||
if( data && data.length ) {
|
||||
for (var i=0; i < data.length; i++) {
|
||||
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
|
||||
result = data[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if( typeof fn == "function" ) fn(result);
|
||||
else $input.trigger("result", result && [result.data, result.value]);
|
||||
}
|
||||
$.each(trimWords($input.val()), function(i, value) {
|
||||
request(value, findValueCallback, findValueCallback);
|
||||
});
|
||||
|
||||
return this;
|
||||
}).bind("flushCache", function() {
|
||||
cache.flush();
|
||||
}).bind("setOptions", function() {
|
||||
$.extend(options, arguments[1]);
|
||||
// if we've updated the data, repopulate
|
||||
if ( "data" in arguments[1] )
|
||||
cache.populate();
|
||||
}).bind("unautocomplete", function() {
|
||||
select.unbind();
|
||||
$input.unbind();
|
||||
$(input.form).unbind(".autocomplete");
|
||||
});
|
||||
|
||||
|
||||
function selectCurrent() {
|
||||
var selected = select.selected();
|
||||
if( !selected )
|
||||
return false;
|
||||
|
||||
var v = selected.result;
|
||||
previousValue = v;
|
||||
|
||||
if ( options.multiple ) {
|
||||
var words = trimWords($input.val());
|
||||
if ( words.length > 1 ) {
|
||||
v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
|
||||
}
|
||||
v += options.multipleSeparator;
|
||||
}
|
||||
|
||||
$input.val(v);
|
||||
hideResultsNow();
|
||||
$input.trigger("result", [selected.data, selected.value]);
|
||||
return true;
|
||||
}
|
||||
|
||||
function onChange(crap, skipPrevCheck) {
|
||||
if( lastKeyPressCode == KEY.DEL ) {
|
||||
select.hide();
|
||||
return;
|
||||
}
|
||||
|
||||
var currentValue = $input.val();
|
||||
|
||||
if ( !skipPrevCheck && currentValue == previousValue )
|
||||
return;
|
||||
|
||||
previousValue = currentValue;
|
||||
|
||||
currentValue = lastWord(currentValue);
|
||||
if ( currentValue.length >= options.minChars) {
|
||||
$input.addClass(options.loadingClass);
|
||||
if (!options.matchCase)
|
||||
currentValue = currentValue.toLowerCase();
|
||||
request(currentValue, receiveData, hideResultsNow);
|
||||
} else {
|
||||
stopLoading();
|
||||
select.hide();
|
||||
}
|
||||
};
|
||||
|
||||
function trimWords(value) {
|
||||
if ( !value ) {
|
||||
return [""];
|
||||
}
|
||||
var words = value.split( options.multipleSeparator );
|
||||
var result = [];
|
||||
$.each(words, function(i, value) {
|
||||
if ( $.trim(value) )
|
||||
result[i] = $.trim(value);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
function lastWord(value) {
|
||||
if ( !options.multiple )
|
||||
return value;
|
||||
var words = trimWords(value);
|
||||
return words[words.length - 1];
|
||||
}
|
||||
|
||||
// fills in the input box w/the first match (assumed to be the best match)
|
||||
// q: the term entered
|
||||
// sValue: the first matching result
|
||||
function autoFill(q, sValue){
|
||||
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
|
||||
// if the last user key pressed was backspace, don't autofill
|
||||
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
|
||||
// fill in the value (keep the case the user has typed)
|
||||
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
|
||||
// select the portion of the value not typed by the user (so the next character will erase)
|
||||
$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
|
||||
}
|
||||
};
|
||||
|
||||
function hideResults() {
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(hideResultsNow, 200);
|
||||
};
|
||||
|
||||
function hideResultsNow() {
|
||||
var wasVisible = select.visible();
|
||||
select.hide();
|
||||
clearTimeout(timeout);
|
||||
stopLoading();
|
||||
if (options.mustMatch) {
|
||||
// call search and run callback
|
||||
$input.search(
|
||||
function (result){
|
||||
// if no value found, clear the input box
|
||||
if( !result ) {
|
||||
if (options.multiple) {
|
||||
var words = trimWords($input.val()).slice(0, -1);
|
||||
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
|
||||
}
|
||||
else
|
||||
$input.val( "" );
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
if (wasVisible)
|
||||
// position cursor at end of input field
|
||||
$.Autocompleter.Selection(input, input.value.length, input.value.length);
|
||||
};
|
||||
|
||||
function receiveData(q, data) {
|
||||
if ( data && data.length && hasFocus ) {
|
||||
stopLoading();
|
||||
select.display(data, q);
|
||||
autoFill(q, data[0].value);
|
||||
select.show();
|
||||
} else {
|
||||
hideResultsNow();
|
||||
}
|
||||
};
|
||||
|
||||
function request(term, success, failure) {
|
||||
if (!options.matchCase)
|
||||
term = term.toLowerCase();
|
||||
var data = cache.load(term);
|
||||
|
||||
// JG: hack: if term ends with ':', kill data to force an ajax request.
|
||||
if (term.endsWith(":"))
|
||||
data = null;
|
||||
|
||||
// recieve the cached data
|
||||
if (data && data.length) {
|
||||
success(term, data);
|
||||
// if an AJAX url has been supplied, try loading the data now
|
||||
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
|
||||
var extraParams = {
|
||||
timestamp: +new Date()
|
||||
};
|
||||
$.each(options.extraParams, function(key, param) {
|
||||
extraParams[key] = typeof param == "function" ? param() : param;
|
||||
});
|
||||
|
||||
$.ajax({
|
||||
// try to leverage ajaxQueue plugin to abort previous requests
|
||||
mode: "abort",
|
||||
// limit abortion to this input
|
||||
port: "autocomplete" + input.name,
|
||||
dataType: options.dataType,
|
||||
url: options.url,
|
||||
data: $.extend({
|
||||
q: lastWord(term),
|
||||
limit: options.max
|
||||
}, extraParams),
|
||||
success: function(data) {
|
||||
var parsed = options.parse && options.parse(data) || parse(data);
|
||||
cache.add(term, parsed);
|
||||
success(term, parsed);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
|
||||
select.emptyList();
|
||||
failure(term);
|
||||
}
|
||||
};
|
||||
|
||||
function parse(data) {
|
||||
var parsed = [];
|
||||
var rows = data.split("\n");
|
||||
for (var i=0; i < rows.length; i++) {
|
||||
var row = $.trim(rows[i]);
|
||||
if (row) {
|
||||
row = row.split("|");
|
||||
parsed[parsed.length] = {
|
||||
data: row,
|
||||
value: row[0],
|
||||
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
|
||||
};
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
|
||||
function stopLoading() {
|
||||
$input.removeClass(options.loadingClass);
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
$.Autocompleter.defaults = {
|
||||
inputClass: "ac_input",
|
||||
resultsClass: "ac_results",
|
||||
loadingClass: "ac_loading",
|
||||
minChars: 1,
|
||||
delay: 400,
|
||||
matchCase: false,
|
||||
matchSubset: true,
|
||||
matchContains: false,
|
||||
cacheLength: 10,
|
||||
max: 100,
|
||||
mustMatch: false,
|
||||
extraParams: {},
|
||||
selectFirst: true,
|
||||
formatItem: function(row) { return row[0]; },
|
||||
formatMatch: null,
|
||||
autoFill: false,
|
||||
width: 0,
|
||||
multiple: false,
|
||||
multipleSeparator: ", ",
|
||||
highlight: function(value, term) {
|
||||
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
|
||||
},
|
||||
scroll: true,
|
||||
scrollHeight: 180
|
||||
};
|
||||
|
||||
$.Autocompleter.Cache = function(options) {
|
||||
|
||||
var data = {};
|
||||
var length = 0;
|
||||
|
||||
function matchSubset(s, sub) {
|
||||
if (!options.matchCase)
|
||||
s = s.toLowerCase();
|
||||
var i = s.indexOf(sub);
|
||||
if (i == -1) return false;
|
||||
return i == 0 || options.matchContains;
|
||||
};
|
||||
|
||||
function add(q, value) {
|
||||
if (length > options.cacheLength){
|
||||
flush();
|
||||
}
|
||||
if (!data[q]){
|
||||
length++;
|
||||
}
|
||||
data[q] = value;
|
||||
}
|
||||
|
||||
function populate(){
|
||||
if( !options.data ) return false;
|
||||
// track the matches
|
||||
var stMatchSets = {},
|
||||
nullData = 0;
|
||||
|
||||
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
|
||||
if( !options.url ) options.cacheLength = 1;
|
||||
|
||||
// track all options for minChars = 0
|
||||
stMatchSets[""] = [];
|
||||
|
||||
// loop through the array and create a lookup structure
|
||||
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
|
||||
var rawValue = options.data[i];
|
||||
// if rawValue is a string, make an array otherwise just reference the array
|
||||
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
|
||||
|
||||
var value = options.formatMatch(rawValue, i+1, options.data.length);
|
||||
if ( value === false )
|
||||
continue;
|
||||
|
||||
var firstChar = value.charAt(0).toLowerCase();
|
||||
// if no lookup array for this character exists, look it up now
|
||||
if( !stMatchSets[firstChar] )
|
||||
stMatchSets[firstChar] = [];
|
||||
|
||||
// if the match is a string
|
||||
var row = {
|
||||
value: value,
|
||||
data: rawValue,
|
||||
result: options.formatResult && options.formatResult(rawValue) || value
|
||||
};
|
||||
|
||||
// push the current match into the set list
|
||||
stMatchSets[firstChar].push(row);
|
||||
|
||||
// keep track of minChars zero items
|
||||
if ( nullData++ < options.max ) {
|
||||
stMatchSets[""].push(row);
|
||||
}
|
||||
};
|
||||
|
||||
// add the data items to the cache
|
||||
$.each(stMatchSets, function(i, value) {
|
||||
// increase the cache size
|
||||
options.cacheLength++;
|
||||
// add to the cache
|
||||
add(i, value);
|
||||
});
|
||||
}
|
||||
|
||||
// populate any existing data
|
||||
setTimeout(populate, 25);
|
||||
|
||||
function flush(){
|
||||
data = {};
|
||||
length = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
flush: flush,
|
||||
add: add,
|
||||
populate: populate,
|
||||
load: function(q) {
|
||||
if (!options.cacheLength || !length)
|
||||
return null;
|
||||
|
||||
/*
|
||||
* if dealing w/local data and matchContains than we must make sure
|
||||
* to loop through all the data collections looking for matches
|
||||
*/
|
||||
if( !options.url && options.matchContains ){
|
||||
// track all matches
|
||||
var csub = [];
|
||||
// loop through all the data grids for matches
|
||||
for( var k in data ){
|
||||
// don't search through the stMatchSets[""] (minChars: 0) cache
|
||||
// this prevents duplicates
|
||||
if( k.length > 0 ){
|
||||
var c = data[k];
|
||||
$.each(c, function(i, x) {
|
||||
// if we've got a match, add it to the array
|
||||
if (matchSubset(x.value, q)) {
|
||||
csub.push(x);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return csub;
|
||||
} else
|
||||
// if the exact item exists, use it
|
||||
if (data[q]){
|
||||
return data[q];
|
||||
} else
|
||||
if (options.matchSubset) {
|
||||
for (var i = q.length - 1; i >= options.minChars; i--) {
|
||||
var c = data[q.substr(0, i)];
|
||||
if (c) {
|
||||
var csub = [];
|
||||
$.each(c, function(i, x) {
|
||||
if ( (x.data.indexOf("#Header") == 0) ||
|
||||
(matchSubset(x.value, q)) ) {
|
||||
csub[csub.length] = x;
|
||||
}
|
||||
});
|
||||
return csub;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
$.Autocompleter.Select = function (options, input, select, config) {
|
||||
var CLASSES = {
|
||||
ACTIVE: "ac_over"
|
||||
};
|
||||
|
||||
var listItems,
|
||||
active = -1,
|
||||
data,
|
||||
term = "",
|
||||
needsInit = true,
|
||||
element,
|
||||
list;
|
||||
|
||||
// Create results
|
||||
function init() {
|
||||
if (!needsInit)
|
||||
return;
|
||||
element = $("<div/>")
|
||||
.hide()
|
||||
.addClass(options.resultsClass)
|
||||
.css("position", "absolute")
|
||||
.appendTo(document.body);
|
||||
|
||||
list = $("<ul/>").appendTo(element).mouseover( function(event) {
|
||||
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
|
||||
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
|
||||
// JG: Only add active class if target is not a header.
|
||||
if (!headerAtPosition(active))
|
||||
$(target(event)).addClass(CLASSES.ACTIVE);
|
||||
}
|
||||
}).click(function(event) {
|
||||
// JG: Ignore click on header.
|
||||
active = $("li", list).index(target(event));
|
||||
if (headerAtPosition(active))
|
||||
return;
|
||||
|
||||
// Handle click on autocomplete options.
|
||||
$(target(event)).addClass(CLASSES.ACTIVE);
|
||||
select();
|
||||
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
|
||||
input.focus();
|
||||
return false;
|
||||
}).mousedown(function() {
|
||||
config.mouseDownOnSelect = true;
|
||||
}).mouseup(function() {
|
||||
config.mouseDownOnSelect = false;
|
||||
});
|
||||
|
||||
if( options.width > 0 )
|
||||
element.css("width", options.width);
|
||||
|
||||
needsInit = false;
|
||||
}
|
||||
|
||||
function target(event) {
|
||||
var element = event.target;
|
||||
while(element && element.tagName != "LI")
|
||||
element = element.parentNode;
|
||||
// more fun with IE, sometimes event.target is empty, just ignore it then
|
||||
if(!element)
|
||||
return [];
|
||||
return element;
|
||||
}
|
||||
|
||||
// JG: Returns true iff there is a header element at the given position.
|
||||
function headerAtPosition(position)
|
||||
{
|
||||
dataAtPosition = data[position].data;
|
||||
return (dataAtPosition.indexOf("#Header") == 0);
|
||||
}
|
||||
|
||||
function moveSelect(step) {
|
||||
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
|
||||
// JG: while active item is a header, continue stepping.
|
||||
var isHeader = false;
|
||||
do
|
||||
{
|
||||
movePosition(step);
|
||||
isHeader = headerAtPosition(active);
|
||||
}
|
||||
while (isHeader);
|
||||
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
|
||||
|
||||
|
||||
if(options.scroll) {
|
||||
var offset = 0;
|
||||
listItems.slice(0, active).each(function() {
|
||||
offset += this.offsetHeight;
|
||||
});
|
||||
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
|
||||
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
|
||||
} else if(offset < list.scrollTop()) {
|
||||
list.scrollTop(offset);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function movePosition(step) {
|
||||
active += step;
|
||||
if (active < 0) {
|
||||
active = listItems.size() - 1;
|
||||
} else if (active >= listItems.size()) {
|
||||
active = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function limitNumberOfItems(available) {
|
||||
return options.max && options.max < available
|
||||
? options.max
|
||||
: available;
|
||||
}
|
||||
|
||||
function fillList() {
|
||||
list.empty();
|
||||
var max = limitNumberOfItems(data.length);
|
||||
for (var i=0; i < max; i++) {
|
||||
if (!data[i])
|
||||
continue;
|
||||
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
|
||||
if ( formatted === false )
|
||||
continue;
|
||||
|
||||
// JG: Build list item by formatting the item and choosing a CSS class.
|
||||
if (headerAtPosition(i))
|
||||
{
|
||||
// Found header element; only add header if there are subsequent elements.
|
||||
if (i != max-1)
|
||||
var li = $("<li/>").html(data[i].data[1]).addClass("ac_header").appendTo(list)[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Found completion element.
|
||||
var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
|
||||
}
|
||||
|
||||
$.data(li, "ac_data", data[i]);
|
||||
}
|
||||
listItems = list.find("li");
|
||||
if ( options.selectFirst ) {
|
||||
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
|
||||
active = 0;
|
||||
}
|
||||
// apply bgiframe if available
|
||||
if ( $.fn.bgiframe )
|
||||
list.bgiframe();
|
||||
}
|
||||
|
||||
return {
|
||||
display: function(d, q) {
|
||||
init();
|
||||
data = d;
|
||||
term = q;
|
||||
fillList();
|
||||
},
|
||||
next: function() {
|
||||
moveSelect(1);
|
||||
},
|
||||
prev: function() {
|
||||
moveSelect(-1);
|
||||
},
|
||||
pageUp: function() {
|
||||
if (active != 0 && active - 8 < 0) {
|
||||
moveSelect( -active );
|
||||
} else {
|
||||
moveSelect(-8);
|
||||
}
|
||||
},
|
||||
pageDown: function() {
|
||||
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
|
||||
moveSelect( listItems.size() - 1 - active );
|
||||
} else {
|
||||
moveSelect(8);
|
||||
}
|
||||
},
|
||||
hide: function() {
|
||||
element && element.hide();
|
||||
listItems && listItems.removeClass(CLASSES.ACTIVE);
|
||||
active = -1;
|
||||
},
|
||||
visible : function() {
|
||||
return element && element.is(":visible");
|
||||
},
|
||||
current: function() {
|
||||
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
|
||||
},
|
||||
show: function() {
|
||||
var offset = $(input).offset();
|
||||
element.css({
|
||||
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
|
||||
top: offset.top + input.offsetHeight,
|
||||
left: offset.left
|
||||
}).show();
|
||||
if(options.scroll) {
|
||||
list.scrollTop(0);
|
||||
list.css({
|
||||
maxHeight: options.scrollHeight,
|
||||
overflow: 'auto'
|
||||
});
|
||||
|
||||
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
|
||||
var listHeight = 0;
|
||||
listItems.each(function() {
|
||||
listHeight += this.offsetHeight;
|
||||
});
|
||||
var scrollbarsVisible = listHeight > options.scrollHeight;
|
||||
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
|
||||
if (!scrollbarsVisible) {
|
||||
// IE doesn't recalculate width when scrollbar disappears
|
||||
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
},
|
||||
selected: function() {
|
||||
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
|
||||
return selected && selected.length && $.data(selected[0], "ac_data");
|
||||
},
|
||||
emptyList: function (){
|
||||
list && list.empty();
|
||||
},
|
||||
unbind: function() {
|
||||
element && element.remove();
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
$.Autocompleter.Selection = function(field, start, end) {
|
||||
if( field.createTextRange ){
|
||||
var selRange = field.createTextRange();
|
||||
selRange.collapse(true);
|
||||
selRange.moveStart("character", start);
|
||||
selRange.moveEnd("character", end);
|
||||
selRange.select();
|
||||
} else if( field.setSelectionRange ){
|
||||
field.setSelectionRange(start, end);
|
||||
} else {
|
||||
if( field.selectionStart ){
|
||||
field.selectionStart = start;
|
||||
field.selectionEnd = end;
|
||||
}
|
||||
}
|
||||
field.focus();
|
||||
};
|
||||
|
||||
})(jQuery);
|
||||
Reference in New Issue
Block a user