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)
8 // Permission is hereby granted, free of charge, to any person obtaining
9 // a copy of this software and associated documentation files (the
10 // "Software"), to deal in the Software without restriction, including
11 // without limitation the rights to use, copy, modify, merge, publish,
12 // distribute, sublicense, and/or sell copies of the Software, and to
13 // permit persons to whom the Software is furnished to do so, subject to
14 // the following conditions:
16 // The above copyright notice and this permission notice shall be
17 // included in all copies or substantial portions of the Software.
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 // Autocompleter.Base handles all the autocompletion functionality
28 // that's independent of the data source for autocompletion. This
29 // includes drawing the autocompletion menu, observing keyboard
30 // and mouse events, and similar.
32 // Specific autocompleters need to provide, at the very least,
33 // a getUpdatedChoices function that will be invoked every time
34 // the text inside the monitored textbox changes. This method
35 // should get the text for which to provide autocompletion by
36 // invoking this.getToken(), NOT by directly accessing
37 // this.element.value. This is to allow incremental tokenized
38 // autocompletion. Specific auto-completion logic (AJAX, etc)
39 // belongs in getUpdatedChoices.
41 // Tokenized incremental autocompletion is enabled automatically
42 // when an autocompleter is instantiated with the 'tokens' option
43 // in the options parameter, e.g.:
44 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
45 // will incrementally autocomplete with a comma as the token.
46 // Additionally, ',' in the above example can be replaced with
47 // a token array, e.g. { tokens: [',', '\n'] } which
48 // enables autocompletion on multiple tokens. This is most
49 // useful when one of the tokens is \n (a newline), as it
50 // allows smart autocompletion after linebreaks.
52 var Autocompleter = {}
53 Autocompleter.Base = function() {};
54 Autocompleter.Base.prototype = {
55 baseInitialize: function(element, update, options) {
56 this.element = $(element);
57 this.update = $(update);
58 this.hasFocus = false;
65 this.setOptions(options);
67 this.options = options || {};
69 this.options.paramName = this.options.paramName || this.element.name;
70 this.options.tokens = this.options.tokens || [];
71 this.options.frequency = this.options.frequency || 0.4;
72 this.options.minChars = this.options.minChars || 1;
73 this.options.onShow = this.options.onShow ||
74 function(element, update){
75 if(!update.style.position || update.style.position=='absolute') {
76 update.style.position = 'absolute';
77 Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
79 new Effect.Appear(update,{duration:0.15});
81 this.options.onHide = this.options.onHide ||
82 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
84 if (typeof(this.options.tokens) == 'string')
85 this.options.tokens = new Array(this.options.tokens);
89 this.element.setAttribute('autocomplete','off');
91 Element.hide(this.update);
93 Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this));
94 Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this));
98 if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
99 if(!this.iefix && (navigator.appVersion.indexOf('MSIE')>0) && (Element.getStyle(this.update, 'position')=='absolute')) {
100 new Insertion.After(this.update,
101 '<iframe id="' + this.update.id + '_iefix" '+
102 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
103 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
104 this.iefix = $(this.update.id+'_iefix');
107 Position.clone(this.update, this.iefix);
108 this.iefix.style.zIndex = 1;
109 this.update.style.zIndex = 2;
110 Element.show(this.iefix);
115 if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
116 if(this.iefix) Element.hide(this.iefix);
119 startIndicator: function() {
120 if(this.options.indicator) Element.show(this.options.indicator);
123 stopIndicator: function() {
124 if(this.options.indicator) Element.hide(this.options.indicator);
127 onKeyPress: function(event) {
129 switch(event.keyCode) {
131 case Event.KEY_RETURN:
140 case Event.KEY_RIGHT:
145 if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
150 if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
154 if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN)
158 this.hasFocus = true;
160 if(this.observer) clearTimeout(this.observer);
162 setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
165 onHover: function(event) {
166 var element = Event.findElement(event, 'LI');
167 if(this.index != element.autocompleteIndex)
169 this.index = element.autocompleteIndex;
175 onClick: function(event) {
176 var element = Event.findElement(event, 'LI');
177 this.index = element.autocompleteIndex;
182 onBlur: function(event) {
183 // needed to make click events working
184 setTimeout(this.hide.bind(this), 250);
185 this.hasFocus = false;
190 if(this.entryCount > 0) {
191 for (var i = 0; i < this.entryCount; i++)
193 Element.addClassName(this.getEntry(i),"selected") :
194 Element.removeClassName(this.getEntry(i),"selected");
203 markPrevious: function() {
204 if(this.index > 0) this.index--
205 else this.index = this.entryCcount-1;
208 markNext: function() {
209 if(this.index < this.entryCount-1) this.index++
213 getEntry: function(index) {
214 return this.update.firstChild.childNodes[index];
217 getCurrentEntry: function() {
218 return this.getEntry(this.index);
221 selectEntry: function() {
223 this.updateElement(this.getCurrentEntry());
226 updateElement: function(selectedElement) {
227 if (this.options.updateElement) {
228 this.options.updateElement(selectedElement);
232 var value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
233 var lastTokenPos = this.findLastToken();
234 if (lastTokenPos != -1) {
235 var newValue = this.element.value.substr(0, lastTokenPos + 1);
236 var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
238 newValue += whitespace[0];
239 this.element.value = newValue + value;
241 this.element.value = value;
243 this.element.focus();
246 updateChoices: function(choices) {
247 if(!this.changed && this.hasFocus) {
248 this.update.innerHTML = choices;
249 Element.cleanWhitespace(this.update);
250 Element.cleanWhitespace(this.update.firstChild);
252 if(this.update.firstChild && this.update.firstChild.childNodes) {
254 this.update.firstChild.childNodes.length;
255 for (var i = 0; i < this.entryCount; i++) {
256 var entry = this.getEntry(i);
257 entry.autocompleteIndex = i;
258 this.addObservers(entry);
264 this.stopIndicator();
271 addObservers: function(element) {
272 Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
273 Event.observe(element, "click", this.onClick.bindAsEventListener(this));
276 onObserverEvent: function() {
277 this.changed = false;
278 if(this.getToken().length>=this.options.minChars) {
279 this.startIndicator();
280 this.getUpdatedChoices();
287 getToken: function() {
288 var tokenPos = this.findLastToken();
290 var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
292 var ret = this.element.value;
294 return /\n/.test(ret) ? '' : ret;
297 findLastToken: function() {
298 var lastTokenPos = -1;
300 for (var i=0; i<this.options.tokens.length; i++) {
301 var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
302 if (thisTokenPos > lastTokenPos)
303 lastTokenPos = thisTokenPos;
309 Ajax.Autocompleter = Class.create();
310 Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), {
311 initialize: function(element, update, url, options) {
312 this.baseInitialize(element, update, options);
313 this.options.asynchronous = true;
314 this.options.onComplete = this.onComplete.bind(this);
315 this.options.defaultParams = this.options.parameters || null;
319 getUpdatedChoices: function() {
320 entry = encodeURIComponent(this.options.paramName) + '=' +
321 encodeURIComponent(this.getToken());
323 this.options.parameters = this.options.callback ?
324 this.options.callback(this.element, entry) : entry;
326 if(this.options.defaultParams)
327 this.options.parameters += '&' + this.options.defaultParams;
329 new Ajax.Request(this.url, this.options);
332 onComplete: function(request) {
333 this.updateChoices(request.responseText);
338 // The local array autocompleter. Used when you'd prefer to
339 // inject an array of autocompletion options into the page, rather
340 // than sending out Ajax queries, which can be quite slow sometimes.
342 // The constructor takes four parameters. The first two are, as usual,
343 // the id of the monitored textbox, and id of the autocompletion menu.
344 // The third is the array you want to autocomplete from, and the fourth
345 // is the options block.
347 // Extra local autocompletion options:
348 // - choices - How many autocompletion choices to offer
350 // - partialSearch - If false, the autocompleter will match entered
351 // text only at the beginning of strings in the
352 // autocomplete array. Defaults to true, which will
353 // match text at the beginning of any *word* in the
354 // strings in the autocomplete array. If you want to
355 // search anywhere in the string, additionally set
356 // the option fullSearch to true (default: off).
358 // - fullSsearch - Search anywhere in autocomplete array strings.
360 // - partialChars - How many characters to enter before triggering
361 // a partial match (unlike minChars, which defines
362 // how many characters are required to do any match
363 // at all). Defaults to 2.
365 // - ignoreCase - Whether to ignore case when autocompleting.
368 // It's possible to pass in a custom function as the 'selector'
369 // option, if you prefer to write your own autocompletion logic.
370 // In that case, the other options above will not apply unless
373 Autocompleter.Local = Class.create();
374 Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), {
375 initialize: function(element, update, array, options) {
376 this.baseInitialize(element, update, options);
377 this.options.array = array;
380 getUpdatedChoices: function() {
381 this.updateChoices(this.options.selector(this));
384 setOptions: function(options) {
385 this.options = Object.extend({
391 selector: function(instance) {
392 var ret = []; // Beginning matches
393 var partial = []; // Inside matches
394 var entry = instance.getToken();
397 for (var i = 0; i < instance.options.array.length &&
398 ret.length < instance.options.choices ; i++) {
400 var elem = instance.options.array[i];
401 var foundPos = instance.options.ignoreCase ?
402 elem.toLowerCase().indexOf(entry.toLowerCase()) :
405 while (foundPos != -1) {
406 if (foundPos == 0 && elem.length != entry.length) {
407 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
408 elem.substr(entry.length) + "</li>");
410 } else if (entry.length >= instance.options.partialChars &&
411 instance.options.partialSearch && foundPos != -1) {
412 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
413 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
414 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
415 foundPos + entry.length) + "</li>");
420 foundPos = instance.options.ignoreCase ?
421 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
422 elem.indexOf(entry, foundPos + 1);
427 ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
428 return "<ul>" + ret.join('') + "</ul>";
434 // AJAX in-place editor
436 // The constructor takes three parameters. The first is the element
437 // that should support in-place editing. The second is the url to submit
438 // the changed value to. The server should respond with the updated
439 // value (the server might have post-processed it or validation might
440 // have prevented it from changing). The third is a hash of options.
442 // Supported options are (all are optional and have sensible defaults):
443 // - okText - The text of the submit button that submits the changed value
444 // to the server (default: "ok")
445 // - cancelText - The text of the link that cancels editing (default: "cancel")
446 // - savingText - The text being displayed as the AJAX engine communicates
447 // with the server (default: "Saving...")
448 // - formId - The id given to the <form> element
449 // (default: the id of the element to edit plus '-inplaceeditor')
451 Ajax.InPlaceEditor = Class.create();
452 Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99";
453 Ajax.InPlaceEditor.prototype = {
454 initialize: function(element, url, options) {
456 this.element = $(element);
458 this.options = Object.extend({
460 cancelText: "cancel",
461 savingText: "Saving...",
462 clickToEditText: "Click to edit",
465 onComplete: function(transport, element) {
466 new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
468 onFailure: function(transport) {
469 alert("Error communicating with the server: " + transport.responseText.stripTags());
471 callback: function(form) {
472 return Form.serialize(form);
474 loadingText: 'Loading...',
475 savingClassName: 'inplaceeditor-saving',
476 formClassName: 'inplaceeditor-form',
477 highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
478 highlightendcolor: "#FFFFFF",
479 externalControl: null,
483 if(!this.options.formId && this.element.id) {
484 this.options.formId = this.element.id + "-inplaceeditor";
485 if ($(this.options.formId)) {
486 // there's already a form with that name, don't specify an id
487 this.options.formId = null;
491 if (this.options.externalControl) {
492 this.options.externalControl = $(this.options.externalControl);
495 this.originalBackground = Element.getStyle(this.element, 'background-color');
496 if (!this.originalBackground) {
497 this.originalBackground = "transparent";
500 this.element.title = this.options.clickToEditText;
502 this.onclickListener = this.enterEditMode.bindAsEventListener(this);
503 this.mouseoverListener = this.enterHover.bindAsEventListener(this);
504 this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
505 Event.observe(this.element, 'click', this.onclickListener);
506 Event.observe(this.element, 'mouseover', this.mouseoverListener);
507 Event.observe(this.element, 'mouseout', this.mouseoutListener);
508 if (this.options.externalControl) {
509 Event.observe(this.options.externalControl, 'click', this.onclickListener);
510 Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
511 Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
514 enterEditMode: function() {
515 if (this.saving) return;
516 if (this.editing) return;
518 this.onEnterEditMode();
519 if (this.options.externalControl) {
520 Element.hide(this.options.externalControl);
522 Element.hide(this.element);
523 this.form = this.getForm();
524 this.element.parentNode.insertBefore(this.form, this.element);
526 getForm: function() {
527 form = document.createElement("form");
528 form.id = this.options.formId;
529 Element.addClassName(form, this.options.formClassName)
530 form.onsubmit = this.onSubmit.bind(this);
532 this.createEditField(form);
534 if (this.options.textarea) {
535 var br = document.createElement("br");
536 form.appendChild(br);
539 okButton = document.createElement("input");
540 okButton.type = "submit";
541 okButton.value = this.options.okText;
542 form.appendChild(okButton);
544 cancelLink = document.createElement("a");
545 cancelLink.href = "#";
546 cancelLink.appendChild(document.createTextNode(this.options.cancelText));
547 cancelLink.onclick = this.onclickCancel.bind(this);
548 form.appendChild(cancelLink);
551 createEditField: function(form) {
552 if (this.options.rows == 1) {
553 this.options.textarea = false;
554 var textField = document.createElement("input");
555 textField.type = "text";
556 textField.name = "value";
557 textField.value = this.getText();
558 textField.style.backgroundColor = this.options.highlightcolor;
559 var size = this.options.size || this.options.cols || 0;
561 textField.size = size;
562 form.appendChild(textField);
563 this.editField = textField;
565 this.options.textarea = true;
566 var textArea = document.createElement("textarea");
567 textArea.name = "value";
568 textArea.value = this.getText();
569 textArea.rows = this.options.rows;
570 textArea.cols = this.options.cols || 40;
571 form.appendChild(textArea);
572 this.editField = textArea;
575 getText: function() {
576 if (this.options.loadTextURL) {
577 this.loadExternalText();
578 return this.options.loadingText;
580 return this.element.innerHTML;
583 loadExternalText: function() {
585 this.options.loadTextURL,
588 onComplete: this.onLoadedExternalText.bind(this)
592 onLoadedExternalText: function(transport) {
593 this.form.value.value = transport.responseText.stripTags();
595 onclickCancel: function() {
597 this.leaveEditMode();
600 onFailure: function(transport) {
601 this.options.onFailure(transport);
602 if (this.oldInnerHTML) {
603 this.element.innerHTML = this.oldInnerHTML;
604 this.oldInnerHTML = null;
608 onSubmit: function() {
612 success: this.element,
613 // don't update on failure (this could be an option)
618 parameters: this.options.callback(this.form, this.editField.value),
619 onComplete: this.onComplete.bind(this),
620 onFailure: this.onFailure.bind(this)
621 }, this.options.ajaxOptions)
626 onLoading: function() {
632 showSaving: function() {
633 this.oldInnerHTML = this.element.innerHTML;
634 this.element.innerHTML = this.options.savingText;
635 Element.addClassName(this.element, this.options.savingClassName);
636 this.element.style.backgroundColor = this.originalBackground;
637 Element.show(this.element);
639 removeForm: function() {
641 Element.remove(this.form);
645 enterHover: function() {
646 if (this.saving) return;
647 this.element.style.backgroundColor = this.options.highlightcolor;
649 this.effect.cancel();
651 Element.addClassName(this.element, this.options.hoverClassName)
653 leaveHover: function() {
654 if (this.options.backgroundColor) {
655 this.element.style.backgroundColor = this.oldBackground;
657 Element.removeClassName(this.element, this.options.hoverClassName)
658 if (this.saving) return;
659 this.effect = new Effect.Highlight(this.element, {
660 startcolor: this.options.highlightcolor,
661 endcolor: this.options.highlightendcolor,
662 restorecolor: this.originalBackground
665 leaveEditMode: function() {
666 Element.removeClassName(this.element, this.options.savingClassName);
669 this.element.style.backgroundColor = this.originalBackground;
670 Element.show(this.element);
671 if (this.options.externalControl) {
672 Element.show(this.options.externalControl);
674 this.editing = false;
676 this.oldInnerHTML = null;
677 this.onLeaveEditMode();
679 onComplete: function(transport) {
680 this.leaveEditMode();
681 this.options.onComplete.bind(this)(transport, this.element);
683 onEnterEditMode: function() {},
684 onLeaveEditMode: function() {},
685 dispose: function() {
686 if (this.oldInnerHTML) {
687 this.element.innerHTML = this.oldInnerHTML;
689 this.leaveEditMode();
690 Event.stopObserving(this.element, 'click', this.onclickListener);
691 Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
692 Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
693 if (this.options.externalControl) {
694 Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
695 Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
696 Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);