1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
2 // (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
3 // (c) 2005 Jon Tirsen (http://www.tirsen.com)
9 // See scriptaculous.js for full license.
11 // Autocompleter.Base handles all the autocompletion functionality
12 // that's independent of the data source for autocompletion. This
13 // includes drawing the autocompletion menu, observing keyboard
14 // and mouse events, and similar.
16 // Specific autocompleters need to provide, at the very least,
17 // a getUpdatedChoices function that will be invoked every time
18 // the text inside the monitored textbox changes. This method
19 // should get the text for which to provide autocompletion by
20 // invoking this.getToken(), NOT by directly accessing
21 // this.element.value. This is to allow incremental tokenized
22 // autocompletion. Specific auto-completion logic (AJAX, etc)
23 // belongs in getUpdatedChoices.
25 // Tokenized incremental autocompletion is enabled automatically
26 // when an autocompleter is instantiated with the 'tokens' option
27 // in the options parameter, e.g.:
28 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
29 // will incrementally autocomplete with a comma as the token.
30 // Additionally, ',' in the above example can be replaced with
31 // a token array, e.g. { tokens: [',', '\n'] } which
32 // enables autocompletion on multiple tokens. This is most
33 // useful when one of the tokens is \n (a newline), as it
34 // allows smart autocompletion after linebreaks.
36 var Autocompleter = {}
37 Autocompleter.Base = function() {};
38 Autocompleter.Base.prototype = {
39 baseInitialize: function(element, update, options) {
40 this.element = $(element);
41 this.update = $(update);
42 this.hasFocus = false;
49 this.setOptions(options);
51 this.options = options || {};
53 this.options.paramName = this.options.paramName || this.element.name;
54 this.options.tokens = this.options.tokens || [];
55 this.options.frequency = this.options.frequency || 0.4;
56 this.options.minChars = this.options.minChars || 1;
57 this.options.onShow = this.options.onShow ||
58 function(element, update){
59 if(!update.style.position || update.style.position=='absolute') {
60 update.style.position = 'absolute';
61 Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
63 Effect.Appear(update,{duration:0.15});
65 this.options.onHide = this.options.onHide ||
66 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
68 if (typeof(this.options.tokens) == 'string')
69 this.options.tokens = new Array(this.options.tokens);
73 this.element.setAttribute('autocomplete','off');
75 Element.hide(this.update);
77 Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
78 Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
82 if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
84 (navigator.appVersion.indexOf('MSIE')>0) &&
85 (navigator.userAgent.indexOf('Opera')<0) &&
86 (Element.getStyle(this.update, 'position')=='absolute')) {
87 new Insertion.After(this.update,
88 '<iframe id="' + this.update.id + '_iefix" '+
89 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
90 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
91 this.iefix = $(this.update.id+'_iefix');
93 if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
96 fixIEOverlapping: function() {
97 Position.clone(this.update, this.iefix);
98 this.iefix.style.zIndex = 1;
99 this.update.style.zIndex = 2;
100 Element.show(this.iefix);
104 this.stopIndicator();
105 if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
106 if(this.iefix) Element.hide(this.iefix);
109 startIndicator: function() {
110 if(this.options.indicator) Element.show(this.options.indicator);
113 stopIndicator: function() {
114 if(this.options.indicator) Element.hide(this.options.indicator);
117 onKeyPress: function(event) {
119 switch(event.keyCode) {
121 case Event.KEY_RETURN:
130 case Event.KEY_RIGHT:
135 if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
140 if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
144 if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN)
148 this.hasFocus = true;
150 if(this.observer) clearTimeout(this.observer);
152 setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
155 onHover: function(event) {
156 var element = Event.findElement(event, 'LI');
157 if(this.index != element.autocompleteIndex)
159 this.index = element.autocompleteIndex;
165 onClick: function(event) {
166 var element = Event.findElement(event, 'LI');
167 this.index = element.autocompleteIndex;
172 onBlur: function(event) {
173 // needed to make click events working
174 setTimeout(this.hide.bind(this), 250);
175 this.hasFocus = false;
180 if(this.entryCount > 0) {
181 for (var i = 0; i < this.entryCount; i++)
183 Element.addClassName(this.getEntry(i),"selected") :
184 Element.removeClassName(this.getEntry(i),"selected");
196 markPrevious: function() {
197 if(this.index > 0) this.index--
198 else this.index = this.entryCount-1;
201 markNext: function() {
202 if(this.index < this.entryCount-1) this.index++
206 getEntry: function(index) {
207 return this.update.firstChild.childNodes[index];
210 getCurrentEntry: function() {
211 return this.getEntry(this.index);
214 selectEntry: function() {
216 this.updateElement(this.getCurrentEntry());
219 updateElement: function(selectedElement) {
220 if (this.options.updateElement) {
221 this.options.updateElement(selectedElement);
225 if (this.options.select) {
226 var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
227 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
229 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
231 var lastTokenPos = this.findLastToken();
232 if (lastTokenPos != -1) {
233 var newValue = this.element.value.substr(0, lastTokenPos + 1);
234 var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
236 newValue += whitespace[0];
237 this.element.value = newValue + value;
239 this.element.value = value;
241 this.element.focus();
243 if (this.options.afterUpdateElement)
244 this.options.afterUpdateElement(this.element, selectedElement);
247 updateChoices: function(choices) {
248 if(!this.changed && this.hasFocus) {
249 this.update.innerHTML = choices;
250 Element.cleanWhitespace(this.update);
251 Element.cleanWhitespace(this.update.firstChild);
253 if(this.update.firstChild && this.update.firstChild.childNodes) {
255 this.update.firstChild.childNodes.length;
256 for (var i = 0; i < this.entryCount; i++) {
257 var entry = this.getEntry(i);
258 entry.autocompleteIndex = i;
259 this.addObservers(entry);
265 this.stopIndicator();
272 addObservers: function(element) {
273 Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
274 Event.observe(element, "click", this.onClick.bindAsEventListener(this));
277 onObserverEvent: function() {
278 this.changed = false;
279 if(this.getToken().length>=this.options.minChars) {
280 this.startIndicator();
281 this.getUpdatedChoices();
288 getToken: function() {
289 var tokenPos = this.findLastToken();
291 var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
293 var ret = this.element.value;
295 return /\n/.test(ret) ? '' : ret;
298 findLastToken: function() {
299 var lastTokenPos = -1;
301 for (var i=0; i<this.options.tokens.length; i++) {
302 var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
303 if (thisTokenPos > lastTokenPos)
304 lastTokenPos = thisTokenPos;
310 Ajax.Autocompleter = Class.create();
311 Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
312 initialize: function(element, update, url, options) {
313 this.baseInitialize(element, update, options);
314 this.options.asynchronous = true;
315 this.options.onComplete = this.onComplete.bind(this);
316 this.options.defaultParams = this.options.parameters || null;
320 getUpdatedChoices: function() {
321 entry = encodeURIComponent(this.options.paramName) + '=' +
322 encodeURIComponent(this.getToken());
324 this.options.parameters = this.options.callback ?
325 this.options.callback(this.element, entry) : entry;
327 if(this.options.defaultParams)
328 this.options.parameters += '&' + this.options.defaultParams;
330 new Ajax.Request(this.url, this.options);
333 onComplete: function(request) {
334 this.updateChoices(request.responseText);
339 // The local array autocompleter. Used when you'd prefer to
340 // inject an array of autocompletion options into the page, rather
341 // than sending out Ajax queries, which can be quite slow sometimes.
343 // The constructor takes four parameters. The first two are, as usual,
344 // the id of the monitored textbox, and id of the autocompletion menu.
345 // The third is the array you want to autocomplete from, and the fourth
346 // is the options block.
348 // Extra local autocompletion options:
349 // - choices - How many autocompletion choices to offer
351 // - partialSearch - If false, the autocompleter will match entered
352 // text only at the beginning of strings in the
353 // autocomplete array. Defaults to true, which will
354 // match text at the beginning of any *word* in the
355 // strings in the autocomplete array. If you want to
356 // search anywhere in the string, additionally set
357 // the option fullSearch to true (default: off).
359 // - fullSsearch - Search anywhere in autocomplete array strings.
361 // - partialChars - How many characters to enter before triggering
362 // a partial match (unlike minChars, which defines
363 // how many characters are required to do any match
364 // at all). Defaults to 2.
366 // - ignoreCase - Whether to ignore case when autocompleting.
369 // It's possible to pass in a custom function as the 'selector'
370 // option, if you prefer to write your own autocompletion logic.
371 // In that case, the other options above will not apply unless
374 Autocompleter.Local = Class.create();
375 Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
376 initialize: function(element, update, array, options) {
377 this.baseInitialize(element, update, options);
378 this.options.array = array;
381 getUpdatedChoices: function() {
382 this.updateChoices(this.options.selector(this));
385 setOptions: function(options) {
386 this.options = Object.extend({
392 selector: function(instance) {
393 var ret = []; // Beginning matches
394 var partial = []; // Inside matches
395 var entry = instance.getToken();
398 for (var i = 0; i < instance.options.array.length &&
399 ret.length < instance.options.choices ; i++) {
401 var elem = instance.options.array[i];
402 var foundPos = instance.options.ignoreCase ?
403 elem.toLowerCase().indexOf(entry.toLowerCase()) :
406 while (foundPos != -1) {
407 if (foundPos == 0 && elem.length != entry.length) {
408 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
409 elem.substr(entry.length) + "</li>");
411 } else if (entry.length >= instance.options.partialChars &&
412 instance.options.partialSearch && foundPos != -1) {
413 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
414 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
415 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
416 foundPos + entry.length) + "</li>");
421 foundPos = instance.options.ignoreCase ?
422 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
423 elem.indexOf(entry, foundPos + 1);
428 ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
429 return "<ul>" + ret.join('') + "</ul>";
435 // AJAX in-place editor
437 // see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
439 // Use this if you notice weird scrolling problems on some browsers,
440 // the DOM might be a bit confused when this gets called so do this
441 // waits 1 ms (with setTimeout) until it does the activation
442 Field.scrollFreeActivate = function(field) {
443 setTimeout(function() {
444 Field.activate(field);
448 Ajax.InPlaceEditor = Class.create();
449 Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
450 Ajax.InPlaceEditor.prototype = {
451 initialize: function(element, url, options) {
453 this.element = $(element);
455 this.options = Object.extend({
459 cancelText: "cancel",
460 savingText: "Saving...",
461 clickToEditText: "Click to edit",
464 onComplete: function(transport, element) {
465 new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
467 onFailure: function(transport) {
468 alert("Error communicating with the server: " + transport.responseText.stripTags());
470 callback: function(form) {
471 return Form.serialize(form);
473 handleLineBreaks: true,
474 loadingText: 'Loading...',
475 savingClassName: 'inplaceeditor-saving',
476 loadingClassName: 'inplaceeditor-loading',
477 formClassName: 'inplaceeditor-form',
478 highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
479 highlightendcolor: "#FFFFFF",
480 externalControl: null,
485 if(!this.options.formId && this.element.id) {
486 this.options.formId = this.element.id + "-inplaceeditor";
487 if ($(this.options.formId)) {
488 // there's already a form with that name, don't specify an id
489 this.options.formId = null;
493 if (this.options.externalControl) {
494 this.options.externalControl = $(this.options.externalControl);
497 this.originalBackground = Element.getStyle(this.element, 'background-color');
498 if (!this.originalBackground) {
499 this.originalBackground = "transparent";
502 this.element.title = this.options.clickToEditText;
504 this.onclickListener = this.enterEditMode.bindAsEventListener(this);
505 this.mouseoverListener = this.enterHover.bindAsEventListener(this);
506 this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
507 Event.observe(this.element, 'click', this.onclickListener);
508 Event.observe(this.element, 'mouseover', this.mouseoverListener);
509 Event.observe(this.element, 'mouseout', this.mouseoutListener);
510 if (this.options.externalControl) {
511 Event.observe(this.options.externalControl, 'click', this.onclickListener);
512 Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
513 Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
516 enterEditMode: function(evt) {
517 if (this.saving) return;
518 if (this.editing) return;
520 this.onEnterEditMode();
521 if (this.options.externalControl) {
522 Element.hide(this.options.externalControl);
524 Element.hide(this.element);
526 this.element.parentNode.insertBefore(this.form, this.element);
527 Field.scrollFreeActivate(this.editField);
528 // stop the event to avoid a page refresh in Safari
534 createForm: function() {
535 this.form = document.createElement("form");
536 this.form.id = this.options.formId;
537 Element.addClassName(this.form, this.options.formClassName)
538 this.form.onsubmit = this.onSubmit.bind(this);
540 this.createEditField();
542 if (this.options.textarea) {
543 var br = document.createElement("br");
544 this.form.appendChild(br);
547 if (this.options.okButton) {
548 okButton = document.createElement("input");
549 okButton.type = "submit";
550 okButton.value = this.options.okText;
551 this.form.appendChild(okButton);
554 if (this.options.cancelLink) {
555 cancelLink = document.createElement("a");
556 cancelLink.href = "#";
557 cancelLink.appendChild(document.createTextNode(this.options.cancelText));
558 cancelLink.onclick = this.onclickCancel.bind(this);
559 this.form.appendChild(cancelLink);
562 hasHTMLLineBreaks: function(string) {
563 if (!this.options.handleLineBreaks) return false;
564 return string.match(/<br/i) || string.match(/<p>/i);
566 convertHTMLLineBreaks: function(string) {
567 return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
569 createEditField: function() {
571 if(this.options.loadTextURL) {
572 text = this.options.loadingText;
574 text = this.getText();
579 if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
580 this.options.textarea = false;
581 var textField = document.createElement("input");
582 textField.obj = this;
583 textField.type = "text";
584 textField.name = "value";
585 textField.value = text;
586 textField.style.backgroundColor = this.options.highlightcolor;
587 var size = this.options.size || this.options.cols || 0;
588 if (size != 0) textField.size = size;
589 if (this.options.submitOnBlur)
590 textField.onblur = this.onSubmit.bind(this);
591 this.editField = textField;
593 this.options.textarea = true;
594 var textArea = document.createElement("textarea");
596 textArea.name = "value";
597 textArea.value = this.convertHTMLLineBreaks(text);
598 textArea.rows = this.options.rows;
599 textArea.cols = this.options.cols || 40;
600 if (this.options.submitOnBlur)
601 textArea.onblur = this.onSubmit.bind(this);
602 this.editField = textArea;
605 if(this.options.loadTextURL) {
606 this.loadExternalText();
608 this.form.appendChild(this.editField);
610 getText: function() {
611 return this.element.innerHTML;
613 loadExternalText: function() {
614 Element.addClassName(this.form, this.options.loadingClassName);
615 this.editField.disabled = true;
617 this.options.loadTextURL,
620 onComplete: this.onLoadedExternalText.bind(this)
621 }, this.options.ajaxOptions)
624 onLoadedExternalText: function(transport) {
625 Element.removeClassName(this.form, this.options.loadingClassName);
626 this.editField.disabled = false;
627 this.editField.value = transport.responseText.stripTags();
629 onclickCancel: function() {
631 this.leaveEditMode();
634 onFailure: function(transport) {
635 this.options.onFailure(transport);
636 if (this.oldInnerHTML) {
637 this.element.innerHTML = this.oldInnerHTML;
638 this.oldInnerHTML = null;
642 onSubmit: function() {
643 // onLoading resets these so we need to save them away for the Ajax call
644 var form = this.form;
645 var value = this.editField.value;
647 // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
648 // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
649 // to be displayed indefinitely
654 success: this.element,
655 // don't update on failure (this could be an option)
660 parameters: this.options.callback(form, value),
661 onComplete: this.onComplete.bind(this),
662 onFailure: this.onFailure.bind(this)
663 }, this.options.ajaxOptions)
665 // stop the event to avoid a page refresh in Safari
666 if (arguments.length > 1) {
667 Event.stop(arguments[0]);
671 onLoading: function() {
677 showSaving: function() {
678 this.oldInnerHTML = this.element.innerHTML;
679 this.element.innerHTML = this.options.savingText;
680 Element.addClassName(this.element, this.options.savingClassName);
681 this.element.style.backgroundColor = this.originalBackground;
682 Element.show(this.element);
684 removeForm: function() {
686 if (this.form.parentNode) Element.remove(this.form);
690 enterHover: function() {
691 if (this.saving) return;
692 this.element.style.backgroundColor = this.options.highlightcolor;
694 this.effect.cancel();
696 Element.addClassName(this.element, this.options.hoverClassName)
698 leaveHover: function() {
699 if (this.options.backgroundColor) {
700 this.element.style.backgroundColor = this.oldBackground;
702 Element.removeClassName(this.element, this.options.hoverClassName)
703 if (this.saving) return;
704 this.effect = new Effect.Highlight(this.element, {
705 startcolor: this.options.highlightcolor,
706 endcolor: this.options.highlightendcolor,
707 restorecolor: this.originalBackground
710 leaveEditMode: function() {
711 Element.removeClassName(this.element, this.options.savingClassName);
714 this.element.style.backgroundColor = this.originalBackground;
715 Element.show(this.element);
716 if (this.options.externalControl) {
717 Element.show(this.options.externalControl);
719 this.editing = false;
721 this.oldInnerHTML = null;
722 this.onLeaveEditMode();
724 onComplete: function(transport) {
725 this.leaveEditMode();
726 this.options.onComplete.bind(this)(transport, this.element);
728 onEnterEditMode: function() {},
729 onLeaveEditMode: function() {},
730 dispose: function() {
731 if (this.oldInnerHTML) {
732 this.element.innerHTML = this.oldInnerHTML;
734 this.leaveEditMode();
735 Event.stopObserving(this.element, 'click', this.onclickListener);
736 Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
737 Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
738 if (this.options.externalControl) {
739 Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
740 Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
741 Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
746 // Delayed observer, like Form.Element.Observer,
747 // but waits for delay after last key input
748 // Ideal for live-search fields
750 Form.Element.DelayedObserver = Class.create();
751 Form.Element.DelayedObserver.prototype = {
752 initialize: function(element, delay, callback) {
753 this.delay = delay || 0.5;
754 this.element = $(element);
755 this.callback = callback;
757 this.lastValue = $F(this.element);
758 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
760 delayedListener: function(event) {
761 if(this.lastValue == $F(this.element)) return;
762 if(this.timer) clearTimeout(this.timer);
763 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
764 this.lastValue = $F(this.element);
766 onTimerEvent: function() {
768 this.callback(this.element, $F(this.element));