1 // LOCAL BEST PRACTICAL MODIFICATIONS
2 // lines 218 and 224, removing scrollIntoView
3 // Leaving these in causes autocomplete lists to flip out and jump
4 // the screen around if the length of the returned list is anywhere
5 // near the size of the viewport
7 // script.aculo.us controls.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
9 // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
10 // (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
11 // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
17 // script.aculo.us is freely distributable under the terms of an MIT-style license.
18 // For details, see the script.aculo.us web site: http://script.aculo.us/
20 // Autocompleter.Base handles all the autocompletion functionality
21 // that's independent of the data source for autocompletion. This
22 // includes drawing the autocompletion menu, observing keyboard
23 // and mouse events, and similar.
25 // Specific autocompleters need to provide, at the very least,
26 // a getUpdatedChoices function that will be invoked every time
27 // the text inside the monitored textbox changes. This method
28 // should get the text for which to provide autocompletion by
29 // invoking this.getToken(), NOT by directly accessing
30 // this.element.value. This is to allow incremental tokenized
31 // autocompletion. Specific auto-completion logic (AJAX, etc)
32 // belongs in getUpdatedChoices.
34 // Tokenized incremental autocompletion is enabled automatically
35 // when an autocompleter is instantiated with the 'tokens' option
36 // in the options parameter, e.g.:
37 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
38 // will incrementally autocomplete with a comma as the token.
39 // Additionally, ',' in the above example can be replaced with
40 // a token array, e.g. { tokens: [',', '\n'] } which
41 // enables autocompletion on multiple tokens. This is most
42 // useful when one of the tokens is \n (a newline), as it
43 // allows smart autocompletion after linebreaks.
45 if(typeof Effect == 'undefined')
46 throw("controls.js requires including script.aculo.us' effects.js library");
48 var Autocompleter = { };
49 Autocompleter.Base = Class.create({
50 baseInitialize: function(element, update, options) {
52 this.element = element;
53 this.update = $(update);
54 this.hasFocus = false;
59 this.oldElementValue = this.element.value;
62 this.setOptions(options);
64 this.options = options || { };
66 this.options.paramName = this.options.paramName || this.element.name;
67 this.options.tokens = this.options.tokens || [];
68 this.options.frequency = this.options.frequency || 0.4;
69 this.options.minChars = this.options.minChars || 1;
70 this.options.onShow = this.options.onShow ||
71 function(element, update){
72 if(!update.style.position || update.style.position=='absolute') {
73 update.style.position = 'absolute';
74 Position.clone(element, update, {
76 offsetTop: element.offsetHeight
79 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);
86 // Force carriage returns as token delimiters anyway
87 if (!this.options.tokens.include('\n'))
88 this.options.tokens.push('\n');
92 this.element.setAttribute('autocomplete','off');
94 Element.hide(this.update);
96 Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
97 Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
101 if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
103 (Prototype.Browser.IE) &&
104 (Element.getStyle(this.update, 'position')=='absolute')) {
105 new Insertion.After(this.update,
106 '<iframe id="' + this.update.id + '_iefix" '+
107 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
108 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
109 this.iefix = $(this.update.id+'_iefix');
111 if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
114 fixIEOverlapping: function() {
115 Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
116 this.iefix.style.zIndex = 1;
117 this.update.style.zIndex = 2;
118 Element.show(this.iefix);
122 this.stopIndicator();
123 if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
124 if(this.iefix) Element.hide(this.iefix);
127 startIndicator: function() {
128 if(this.options.indicator) Element.show(this.options.indicator);
131 stopIndicator: function() {
132 if(this.options.indicator) Element.hide(this.options.indicator);
135 onKeyPress: function(event) {
137 switch(event.keyCode) {
139 case Event.KEY_RETURN:
148 case Event.KEY_RIGHT:
162 if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
163 (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
166 this.hasFocus = true;
168 if(this.observer) clearTimeout(this.observer);
170 setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
173 activate: function() {
174 this.changed = false;
175 this.hasFocus = true;
176 this.getUpdatedChoices();
179 onHover: function(event) {
180 var element = Event.findElement(event, 'LI');
181 if(this.index != element.autocompleteIndex)
183 this.index = element.autocompleteIndex;
189 onClick: function(event) {
190 var element = Event.findElement(event, 'LI');
191 this.index = element.autocompleteIndex;
196 onBlur: function(event) {
197 // needed to make click events working
198 setTimeout(this.hide.bind(this), 250);
199 this.hasFocus = false;
204 if(this.entryCount > 0) {
205 for (var i = 0; i < this.entryCount; i++)
207 Element.addClassName(this.getEntry(i),"selected") :
208 Element.removeClassName(this.getEntry(i),"selected");
219 markPrevious: function() {
220 if(this.index > 0) this.index--;
221 else this.index = this.entryCount-1;
222 //this.getEntry(this.index).scrollIntoView(true);
225 markNext: function() {
226 if(this.index < this.entryCount-1) this.index++;
228 //this.getEntry(this.index).scrollIntoView(false);
231 getEntry: function(index) {
232 return this.update.firstChild.childNodes[index];
235 getCurrentEntry: function() {
236 return this.getEntry(this.index);
239 selectEntry: function() {
241 this.updateElement(this.getCurrentEntry());
244 updateElement: function(selectedElement) {
245 if (this.options.updateElement) {
246 this.options.updateElement(selectedElement);
250 if (this.options.select) {
251 var nodes = $(selectedElement).select('.' + this.options.select) || [];
252 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
254 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
256 var bounds = this.getTokenBounds();
257 if (bounds[0] != -1) {
258 var newValue = this.element.value.substr(0, bounds[0]);
259 var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
261 newValue += whitespace[0];
262 this.element.value = newValue + value + this.element.value.substr(bounds[1]);
264 this.element.value = value;
266 this.oldElementValue = this.element.value;
267 this.element.focus();
269 if (this.options.afterUpdateElement)
270 this.options.afterUpdateElement(this.element, selectedElement);
273 updateChoices: function(choices) {
274 if(!this.changed && this.hasFocus) {
275 this.update.innerHTML = choices;
276 Element.cleanWhitespace(this.update);
277 Element.cleanWhitespace(this.update.down());
279 if(this.update.firstChild && this.update.down().childNodes) {
281 this.update.down().childNodes.length;
282 for (var i = 0; i < this.entryCount; i++) {
283 var entry = this.getEntry(i);
284 entry.autocompleteIndex = i;
285 this.addObservers(entry);
291 this.stopIndicator();
294 if(this.entryCount==1 && this.options.autoSelect) {
303 addObservers: function(element) {
304 Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
305 Event.observe(element, "click", this.onClick.bindAsEventListener(this));
308 onObserverEvent: function() {
309 this.changed = false;
310 this.tokenBounds = null;
311 if(this.getToken().length>=this.options.minChars) {
312 this.getUpdatedChoices();
317 this.oldElementValue = this.element.value;
320 getToken: function() {
321 var bounds = this.getTokenBounds();
322 return this.element.value.substring(bounds[0], bounds[1]).strip();
325 getTokenBounds: function() {
326 if (null != this.tokenBounds) return this.tokenBounds;
327 var value = this.element.value;
328 if (value.strip().empty()) return [-1, 0];
329 var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
330 var offset = (diff == this.oldElementValue.length ? 1 : 0);
331 var prevTokenPos = -1, nextTokenPos = value.length;
333 for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
334 tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
335 if (tp > prevTokenPos) prevTokenPos = tp;
336 tp = value.indexOf(this.options.tokens[index], diff + offset);
337 if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
339 return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
343 Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
344 var boundary = Math.min(newS.length, oldS.length);
345 for (var index = 0; index < boundary; ++index)
346 if (newS[index] != oldS[index])
351 Ajax.Autocompleter = Class.create(Autocompleter.Base, {
352 initialize: function(element, update, url, options) {
353 this.baseInitialize(element, update, options);
354 this.options.asynchronous = true;
355 this.options.onComplete = this.onComplete.bind(this);
356 this.options.defaultParams = this.options.parameters || null;
360 getUpdatedChoices: function() {
361 this.startIndicator();
363 var entry = encodeURIComponent(this.options.paramName) + '=' +
364 encodeURIComponent(this.getToken());
366 this.options.parameters = this.options.callback ?
367 this.options.callback(this.element, entry) : entry;
369 if(this.options.defaultParams)
370 this.options.parameters += '&' + this.options.defaultParams;
372 new Ajax.Request(this.url, this.options);
375 onComplete: function(request) {
376 this.updateChoices(request.responseText);
380 // The local array autocompleter. Used when you'd prefer to
381 // inject an array of autocompletion options into the page, rather
382 // than sending out Ajax queries, which can be quite slow sometimes.
384 // The constructor takes four parameters. The first two are, as usual,
385 // the id of the monitored textbox, and id of the autocompletion menu.
386 // The third is the array you want to autocomplete from, and the fourth
387 // is the options block.
389 // Extra local autocompletion options:
390 // - choices - How many autocompletion choices to offer
392 // - partialSearch - If false, the autocompleter will match entered
393 // text only at the beginning of strings in the
394 // autocomplete array. Defaults to true, which will
395 // match text at the beginning of any *word* in the
396 // strings in the autocomplete array. If you want to
397 // search anywhere in the string, additionally set
398 // the option fullSearch to true (default: off).
400 // - fullSsearch - Search anywhere in autocomplete array strings.
402 // - partialChars - How many characters to enter before triggering
403 // a partial match (unlike minChars, which defines
404 // how many characters are required to do any match
405 // at all). Defaults to 2.
407 // - ignoreCase - Whether to ignore case when autocompleting.
410 // It's possible to pass in a custom function as the 'selector'
411 // option, if you prefer to write your own autocompletion logic.
412 // In that case, the other options above will not apply unless
415 Autocompleter.Local = Class.create(Autocompleter.Base, {
416 initialize: function(element, update, array, options) {
417 this.baseInitialize(element, update, options);
418 this.options.array = array;
421 getUpdatedChoices: function() {
422 this.updateChoices(this.options.selector(this));
425 setOptions: function(options) {
426 this.options = Object.extend({
432 selector: function(instance) {
433 var ret = []; // Beginning matches
434 var partial = []; // Inside matches
435 var entry = instance.getToken();
438 for (var i = 0; i < instance.options.array.length &&
439 ret.length < instance.options.choices ; i++) {
441 var elem = instance.options.array[i];
442 var foundPos = instance.options.ignoreCase ?
443 elem.toLowerCase().indexOf(entry.toLowerCase()) :
446 while (foundPos != -1) {
447 if (foundPos == 0 && elem.length != entry.length) {
448 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
449 elem.substr(entry.length) + "</li>");
451 } else if (entry.length >= instance.options.partialChars &&
452 instance.options.partialSearch && foundPos != -1) {
453 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
454 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
455 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
456 foundPos + entry.length) + "</li>");
461 foundPos = instance.options.ignoreCase ?
462 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
463 elem.indexOf(entry, foundPos + 1);
468 ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
469 return "<ul>" + ret.join('') + "</ul>";
475 // AJAX in-place editor and collection editor
476 // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
478 // Use this if you notice weird scrolling problems on some browsers,
479 // the DOM might be a bit confused when this gets called so do this
480 // waits 1 ms (with setTimeout) until it does the activation
481 Field.scrollFreeActivate = function(field) {
482 setTimeout(function() {
483 Field.activate(field);
487 Ajax.InPlaceEditor = Class.create({
488 initialize: function(element, url, options) {
490 this.element = element = $(element);
491 this.prepareOptions();
492 this._controls = { };
493 arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
494 Object.extend(this.options, options || { });
495 if (!this.options.formId && this.element.id) {
496 this.options.formId = this.element.id + '-inplaceeditor';
497 if ($(this.options.formId))
498 this.options.formId = '';
500 if (this.options.externalControl)
501 this.options.externalControl = $(this.options.externalControl);
502 if (!this.options.externalControl)
503 this.options.externalControlOnly = false;
504 this._originalBackground = this.element.getStyle('background-color') || 'transparent';
505 this.element.title = this.options.clickToEditText;
506 this._boundCancelHandler = this.handleFormCancellation.bind(this);
507 this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
508 this._boundFailureHandler = this.handleAJAXFailure.bind(this);
509 this._boundSubmitHandler = this.handleFormSubmission.bind(this);
510 this._boundWrapperHandler = this.wrapUp.bind(this);
511 this.registerListeners();
513 checkForEscapeOrReturn: function(e) {
514 if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
515 if (Event.KEY_ESC == e.keyCode)
516 this.handleFormCancellation(e);
517 else if (Event.KEY_RETURN == e.keyCode)
518 this.handleFormSubmission(e);
520 createControl: function(mode, handler, extraClasses) {
521 var control = this.options[mode + 'Control'];
522 var text = this.options[mode + 'Text'];
523 if ('button' == control) {
524 var btn = document.createElement('input');
527 btn.className = 'editor_' + mode + '_button';
528 if ('cancel' == mode)
529 btn.onclick = this._boundCancelHandler;
530 this._form.appendChild(btn);
531 this._controls[mode] = btn;
532 } else if ('link' == control) {
533 var link = document.createElement('a');
535 link.appendChild(document.createTextNode(text));
536 link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
537 link.className = 'editor_' + mode + '_link';
539 link.className += ' ' + extraClasses;
540 this._form.appendChild(link);
541 this._controls[mode] = link;
544 createEditField: function() {
545 var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
547 if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
548 fld = document.createElement('input');
550 var size = this.options.size || this.options.cols || 0;
551 if (0 < size) fld.size = size;
553 fld = document.createElement('textarea');
554 fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
555 fld.cols = this.options.cols || 40;
557 fld.name = this.options.paramName;
558 fld.value = text; // No HTML breaks conversion anymore
559 fld.className = 'editor_field';
560 if (this.options.submitOnBlur)
561 fld.onblur = this._boundSubmitHandler;
562 this._controls.editor = fld;
563 if (this.options.loadTextURL)
564 this.loadExternalText();
565 this._form.appendChild(this._controls.editor);
567 createForm: function() {
569 function addText(mode, condition) {
570 var text = ipe.options['text' + mode + 'Controls'];
571 if (!text || condition === false) return;
572 ipe._form.appendChild(document.createTextNode(text));
574 this._form = $(document.createElement('form'));
575 this._form.id = this.options.formId;
576 this._form.addClassName(this.options.formClassName);
577 this._form.onsubmit = this._boundSubmitHandler;
578 this.createEditField();
579 if ('textarea' == this._controls.editor.tagName.toLowerCase())
580 this._form.appendChild(document.createElement('br'));
581 if (this.options.onFormCustomization)
582 this.options.onFormCustomization(this, this._form);
583 addText('Before', this.options.okControl || this.options.cancelControl);
584 this.createControl('ok', this._boundSubmitHandler);
585 addText('Between', this.options.okControl && this.options.cancelControl);
586 this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
587 addText('After', this.options.okControl || this.options.cancelControl);
589 destroy: function() {
590 if (this._oldInnerHTML)
591 this.element.innerHTML = this._oldInnerHTML;
592 this.leaveEditMode();
593 this.unregisterListeners();
595 enterEditMode: function(e) {
596 if (this._saving || this._editing) return;
597 this._editing = true;
598 this.triggerCallback('onEnterEditMode');
599 if (this.options.externalControl)
600 this.options.externalControl.hide();
603 this.element.parentNode.insertBefore(this._form, this.element);
604 if (!this.options.loadTextURL)
605 this.postProcessEditField();
606 if (e) Event.stop(e);
608 enterHover: function(e) {
609 if (this.options.hoverClassName)
610 this.element.addClassName(this.options.hoverClassName);
611 if (this._saving) return;
612 this.triggerCallback('onEnterHover');
614 getText: function() {
615 return this.element.innerHTML.unescapeHTML();
617 handleAJAXFailure: function(transport) {
618 this.triggerCallback('onFailure', transport);
619 if (this._oldInnerHTML) {
620 this.element.innerHTML = this._oldInnerHTML;
621 this._oldInnerHTML = null;
624 handleFormCancellation: function(e) {
626 if (e) Event.stop(e);
628 handleFormSubmission: function(e) {
629 var form = this._form;
630 var value = $F(this._controls.editor);
631 this.prepareSubmission();
632 var params = this.options.callback(form, value) || '';
633 if (Object.isString(params))
634 params = params.toQueryParams();
635 params.editorId = this.element.id;
636 if (this.options.htmlResponse) {
637 var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
638 Object.extend(options, {
640 onComplete: this._boundWrapperHandler,
641 onFailure: this._boundFailureHandler
643 new Ajax.Updater({ success: this.element }, this.url, options);
645 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
646 Object.extend(options, {
648 onComplete: this._boundWrapperHandler,
649 onFailure: this._boundFailureHandler
651 new Ajax.Request(this.url, options);
653 if (e) Event.stop(e);
655 leaveEditMode: function() {
656 this.element.removeClassName(this.options.savingClassName);
659 this.element.style.backgroundColor = this._originalBackground;
661 if (this.options.externalControl)
662 this.options.externalControl.show();
663 this._saving = false;
664 this._editing = false;
665 this._oldInnerHTML = null;
666 this.triggerCallback('onLeaveEditMode');
668 leaveHover: function(e) {
669 if (this.options.hoverClassName)
670 this.element.removeClassName(this.options.hoverClassName);
671 if (this._saving) return;
672 this.triggerCallback('onLeaveHover');
674 loadExternalText: function() {
675 this._form.addClassName(this.options.loadingClassName);
676 this._controls.editor.disabled = true;
677 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
678 Object.extend(options, {
679 parameters: 'editorId=' + encodeURIComponent(this.element.id),
680 onComplete: Prototype.emptyFunction,
681 onSuccess: function(transport) {
682 this._form.removeClassName(this.options.loadingClassName);
683 var text = transport.responseText;
684 if (this.options.stripLoadedTextTags)
685 text = text.stripTags();
686 this._controls.editor.value = text;
687 this._controls.editor.disabled = false;
688 this.postProcessEditField();
690 onFailure: this._boundFailureHandler
692 new Ajax.Request(this.options.loadTextURL, options);
694 postProcessEditField: function() {
695 var fpc = this.options.fieldPostCreation;
697 $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
699 prepareOptions: function() {
700 this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
701 Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
702 [this._extraDefaultOptions].flatten().compact().each(function(defs) {
703 Object.extend(this.options, defs);
706 prepareSubmission: function() {
712 registerListeners: function() {
713 this._listeners = { };
715 $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
716 listener = this[pair.value].bind(this);
717 this._listeners[pair.key] = listener;
718 if (!this.options.externalControlOnly)
719 this.element.observe(pair.key, listener);
720 if (this.options.externalControl)
721 this.options.externalControl.observe(pair.key, listener);
724 removeForm: function() {
725 if (!this._form) return;
728 this._controls = { };
730 showSaving: function() {
731 this._oldInnerHTML = this.element.innerHTML;
732 this.element.innerHTML = this.options.savingText;
733 this.element.addClassName(this.options.savingClassName);
734 this.element.style.backgroundColor = this._originalBackground;
737 triggerCallback: function(cbName, arg) {
738 if ('function' == typeof this.options[cbName]) {
739 this.options[cbName](this, arg);
742 unregisterListeners: function() {
743 $H(this._listeners).each(function(pair) {
744 if (!this.options.externalControlOnly)
745 this.element.stopObserving(pair.key, pair.value);
746 if (this.options.externalControl)
747 this.options.externalControl.stopObserving(pair.key, pair.value);
750 wrapUp: function(transport) {
751 this.leaveEditMode();
752 // Can't use triggerCallback due to backward compatibility: requires
753 // binding + direct element
754 this._boundComplete(transport, this.element);
758 Object.extend(Ajax.InPlaceEditor.prototype, {
759 dispose: Ajax.InPlaceEditor.prototype.destroy
762 Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
763 initialize: function($super, element, url, options) {
764 this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
765 $super(element, url, options);
768 createEditField: function() {
769 var list = document.createElement('select');
770 list.name = this.options.paramName;
772 this._controls.editor = list;
773 this._collection = this.options.collection || [];
774 if (this.options.loadCollectionURL)
775 this.loadCollection();
777 this.checkForExternalText();
778 this._form.appendChild(this._controls.editor);
781 loadCollection: function() {
782 this._form.addClassName(this.options.loadingClassName);
783 this.showLoadingText(this.options.loadingCollectionText);
784 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
785 Object.extend(options, {
786 parameters: 'editorId=' + encodeURIComponent(this.element.id),
787 onComplete: Prototype.emptyFunction,
788 onSuccess: function(transport) {
789 var js = transport.responseText.strip();
790 if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
791 throw('Server returned an invalid collection representation.');
792 this._collection = eval(js);
793 this.checkForExternalText();
795 onFailure: this.onFailure
797 new Ajax.Request(this.options.loadCollectionURL, options);
800 showLoadingText: function(text) {
801 this._controls.editor.disabled = true;
802 var tempOption = this._controls.editor.firstChild;
804 tempOption = document.createElement('option');
805 tempOption.value = '';
806 this._controls.editor.appendChild(tempOption);
807 tempOption.selected = true;
809 tempOption.update((text || '').stripScripts().stripTags());
812 checkForExternalText: function() {
813 this._text = this.getText();
814 if (this.options.loadTextURL)
815 this.loadExternalText();
817 this.buildOptionList();
820 loadExternalText: function() {
821 this.showLoadingText(this.options.loadingText);
822 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
823 Object.extend(options, {
824 parameters: 'editorId=' + encodeURIComponent(this.element.id),
825 onComplete: Prototype.emptyFunction,
826 onSuccess: function(transport) {
827 this._text = transport.responseText.strip();
828 this.buildOptionList();
830 onFailure: this.onFailure
832 new Ajax.Request(this.options.loadTextURL, options);
835 buildOptionList: function() {
836 this._form.removeClassName(this.options.loadingClassName);
837 this._collection = this._collection.map(function(entry) {
838 return 2 === entry.length ? entry : [entry, entry].flatten();
840 var marker = ('value' in this.options) ? this.options.value : this._text;
841 var textFound = this._collection.any(function(entry) {
842 return entry[0] == marker;
844 this._controls.editor.update('');
846 this._collection.each(function(entry, index) {
847 option = document.createElement('option');
848 option.value = entry[0];
849 option.selected = textFound ? entry[0] == marker : 0 == index;
850 option.appendChild(document.createTextNode(entry[1]));
851 this._controls.editor.appendChild(option);
853 this._controls.editor.disabled = false;
854 Field.scrollFreeActivate(this._controls.editor);
858 //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
859 //**** This only exists for a while, in order to let ****
860 //**** users adapt to the new API. Read up on the new ****
861 //**** API and convert your code to it ASAP! ****
863 Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
864 if (!options) return;
865 function fallback(name, expr) {
866 if (name in options || expr === undefined) return;
867 options[name] = expr;
869 fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
870 options.cancelLink == options.cancelButton == false ? false : undefined)));
871 fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
872 options.okLink == options.okButton == false ? false : undefined)));
873 fallback('highlightColor', options.highlightcolor);
874 fallback('highlightEndColor', options.highlightendcolor);
877 Object.extend(Ajax.InPlaceEditor, {
880 autoRows: 3, // Use when multi-line w/ rows == 1
881 cancelControl: 'link', // 'link'|'button'|false
882 cancelText: 'cancel',
883 clickToEditText: 'Click to edit',
884 externalControl: null, // id|elt
885 externalControlOnly: false,
886 fieldPostCreation: 'activate', // 'activate'|'focus'|false
887 formClassName: 'inplaceeditor-form',
888 formId: null, // id|elt
889 highlightColor: '#ffff99',
890 highlightEndColor: '#ffffff',
893 loadingClassName: 'inplaceeditor-loading',
894 loadingText: 'Loading...',
895 okControl: 'button', // 'link'|'button'|false
898 rows: 1, // If 1 and multi-line, uses autoRows
899 savingClassName: 'inplaceeditor-saving',
900 savingText: 'Saving...',
902 stripLoadedTextTags: false,
904 textAfterControls: '',
905 textBeforeControls: '',
906 textBetweenControls: ''
909 callback: function(form) {
910 return Form.serialize(form);
912 onComplete: function(transport, element) {
913 // For backward compatibility, this one is bound to the IPE, and passes
914 // the element directly. It was too often customized, so we don't break it.
915 new Effect.Highlight(element, {
916 startcolor: this.options.highlightColor, keepBackgroundImage: true });
918 onEnterEditMode: null,
919 onEnterHover: function(ipe) {
920 ipe.element.style.backgroundColor = ipe.options.highlightColor;
922 ipe._effect.cancel();
924 onFailure: function(transport, ipe) {
925 alert('Error communication with the server: ' + transport.responseText.stripTags());
927 onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
928 onLeaveEditMode: null,
929 onLeaveHover: function(ipe) {
930 ipe._effect = new Effect.Highlight(ipe.element, {
931 startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
932 restorecolor: ipe._originalBackground, keepBackgroundImage: true
937 click: 'enterEditMode',
938 keydown: 'checkForEscapeOrReturn',
939 mouseover: 'enterHover',
940 mouseout: 'leaveHover'
944 Ajax.InPlaceCollectionEditor.DefaultOptions = {
945 loadingCollectionText: 'Loading options...'
948 // Delayed observer, like Form.Element.Observer,
949 // but waits for delay after last key input
950 // Ideal for live-search fields
952 Form.Element.DelayedObserver = Class.create({
953 initialize: function(element, delay, callback) {
954 this.delay = delay || 0.5;
955 this.element = $(element);
956 this.callback = callback;
958 this.lastValue = $F(this.element);
959 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
961 delayedListener: function(event) {
962 if(this.lastValue == $F(this.element)) return;
963 if(this.timer) clearTimeout(this.timer);
964 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
965 this.lastValue = $F(this.element);
967 onTimerEvent: function() {
969 this.callback(this.element, $F(this.element));