Chris@0: // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) Chris@0: // (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan) Chris@0: // (c) 2005-2008 Jon Tirsen (http://www.tirsen.com) Chris@0: // Contributors: Chris@0: // Richard Livsey Chris@0: // Rahul Bhargava Chris@0: // Rob Wills Chris@0: // Chris@0: // script.aculo.us is freely distributable under the terms of an MIT-style license. Chris@0: // For details, see the script.aculo.us web site: http://script.aculo.us/ Chris@0: Chris@0: // Autocompleter.Base handles all the autocompletion functionality Chris@0: // that's independent of the data source for autocompletion. This Chris@0: // includes drawing the autocompletion menu, observing keyboard Chris@0: // and mouse events, and similar. Chris@0: // Chris@0: // Specific autocompleters need to provide, at the very least, Chris@0: // a getUpdatedChoices function that will be invoked every time Chris@0: // the text inside the monitored textbox changes. This method Chris@0: // should get the text for which to provide autocompletion by Chris@0: // invoking this.getToken(), NOT by directly accessing Chris@0: // this.element.value. This is to allow incremental tokenized Chris@0: // autocompletion. Specific auto-completion logic (AJAX, etc) Chris@0: // belongs in getUpdatedChoices. Chris@0: // Chris@0: // Tokenized incremental autocompletion is enabled automatically Chris@0: // when an autocompleter is instantiated with the 'tokens' option Chris@0: // in the options parameter, e.g.: Chris@0: // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' }); Chris@0: // will incrementally autocomplete with a comma as the token. Chris@0: // Additionally, ',' in the above example can be replaced with Chris@0: // a token array, e.g. { tokens: [',', '\n'] } which Chris@0: // enables autocompletion on multiple tokens. This is most Chris@0: // useful when one of the tokens is \n (a newline), as it Chris@0: // allows smart autocompletion after linebreaks. Chris@0: Chris@0: if(typeof Effect == 'undefined') Chris@0: throw("controls.js requires including script.aculo.us' effects.js library"); Chris@0: Chris@0: var Autocompleter = { }; Chris@0: Autocompleter.Base = Class.create({ Chris@0: baseInitialize: function(element, update, options) { Chris@0: element = $(element); Chris@0: this.element = element; Chris@0: this.update = $(update); Chris@0: this.hasFocus = false; Chris@0: this.changed = false; Chris@0: this.active = false; Chris@0: this.index = 0; Chris@0: this.entryCount = 0; Chris@0: this.oldElementValue = this.element.value; Chris@0: Chris@0: if(this.setOptions) Chris@0: this.setOptions(options); Chris@0: else Chris@0: this.options = options || { }; Chris@0: Chris@0: this.options.paramName = this.options.paramName || this.element.name; Chris@0: this.options.tokens = this.options.tokens || []; Chris@0: this.options.frequency = this.options.frequency || 0.4; Chris@0: this.options.minChars = this.options.minChars || 1; Chris@0: this.options.onShow = this.options.onShow || Chris@0: function(element, update){ Chris@0: if(!update.style.position || update.style.position=='absolute') { Chris@0: update.style.position = 'absolute'; Chris@0: Position.clone(element, update, { Chris@0: setHeight: false, Chris@0: offsetTop: element.offsetHeight Chris@0: }); Chris@0: } Chris@0: Effect.Appear(update,{duration:0.15}); Chris@0: }; Chris@0: this.options.onHide = this.options.onHide || Chris@0: function(element, update){ new Effect.Fade(update,{duration:0.15}) }; Chris@0: Chris@0: if(typeof(this.options.tokens) == 'string') Chris@0: this.options.tokens = new Array(this.options.tokens); Chris@0: // Force carriage returns as token delimiters anyway Chris@0: if (!this.options.tokens.include('\n')) Chris@0: this.options.tokens.push('\n'); Chris@0: Chris@0: this.observer = null; Chris@0: Chris@0: this.element.setAttribute('autocomplete','off'); Chris@0: Chris@0: Element.hide(this.update); Chris@0: Chris@0: Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this)); Chris@0: Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this)); Chris@0: }, Chris@0: Chris@0: show: function() { Chris@0: if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); Chris@0: if(!this.iefix && Chris@0: (Prototype.Browser.IE) && Chris@0: (Element.getStyle(this.update, 'position')=='absolute')) { Chris@0: new Insertion.After(this.update, Chris@0: ''); Chris@0: this.iefix = $(this.update.id+'_iefix'); Chris@0: } Chris@0: if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); Chris@0: }, Chris@0: Chris@0: fixIEOverlapping: function() { Chris@0: Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); Chris@0: this.iefix.style.zIndex = 1; Chris@0: this.update.style.zIndex = 2; Chris@0: Element.show(this.iefix); Chris@0: }, Chris@0: Chris@0: hide: function() { Chris@0: this.stopIndicator(); Chris@0: if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); Chris@0: if(this.iefix) Element.hide(this.iefix); Chris@0: }, Chris@0: Chris@0: startIndicator: function() { Chris@0: if(this.options.indicator) Element.show(this.options.indicator); Chris@0: }, Chris@0: Chris@0: stopIndicator: function() { Chris@0: if(this.options.indicator) Element.hide(this.options.indicator); Chris@0: }, Chris@0: Chris@0: onKeyPress: function(event) { Chris@0: if(this.active) Chris@0: switch(event.keyCode) { Chris@0: case Event.KEY_TAB: Chris@0: case Event.KEY_RETURN: Chris@0: this.selectEntry(); Chris@0: Event.stop(event); Chris@0: case Event.KEY_ESC: Chris@0: this.hide(); Chris@0: this.active = false; Chris@0: Event.stop(event); Chris@0: return; Chris@0: case Event.KEY_LEFT: Chris@0: case Event.KEY_RIGHT: Chris@0: return; Chris@0: case Event.KEY_UP: Chris@0: this.markPrevious(); Chris@0: this.render(); Chris@0: Event.stop(event); Chris@0: return; Chris@0: case Event.KEY_DOWN: Chris@0: this.markNext(); Chris@0: this.render(); Chris@0: Event.stop(event); Chris@0: return; Chris@0: } Chris@0: else Chris@0: if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || Chris@0: (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; Chris@0: Chris@0: this.changed = true; Chris@0: this.hasFocus = true; Chris@0: Chris@0: if(this.observer) clearTimeout(this.observer); Chris@0: this.observer = Chris@0: setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); Chris@0: }, Chris@0: Chris@0: activate: function() { Chris@0: this.changed = false; Chris@0: this.hasFocus = true; Chris@0: this.getUpdatedChoices(); Chris@0: }, Chris@0: Chris@0: onHover: function(event) { Chris@0: var element = Event.findElement(event, 'LI'); Chris@0: if(this.index != element.autocompleteIndex) Chris@0: { Chris@0: this.index = element.autocompleteIndex; Chris@0: this.render(); Chris@0: } Chris@0: Event.stop(event); Chris@0: }, Chris@0: Chris@0: onClick: function(event) { Chris@0: var element = Event.findElement(event, 'LI'); Chris@0: this.index = element.autocompleteIndex; Chris@0: this.selectEntry(); Chris@0: this.hide(); Chris@0: }, Chris@0: Chris@0: onBlur: function(event) { Chris@0: // needed to make click events working Chris@0: setTimeout(this.hide.bind(this), 250); Chris@0: this.hasFocus = false; Chris@0: this.active = false; Chris@0: }, Chris@0: Chris@0: render: function() { Chris@0: if(this.entryCount > 0) { Chris@0: for (var i = 0; i < this.entryCount; i++) Chris@0: this.index==i ? Chris@0: Element.addClassName(this.getEntry(i),"selected") : Chris@0: Element.removeClassName(this.getEntry(i),"selected"); Chris@0: if(this.hasFocus) { Chris@0: this.show(); Chris@0: this.active = true; Chris@0: } Chris@0: } else { Chris@0: this.active = false; Chris@0: this.hide(); Chris@0: } Chris@0: }, Chris@0: Chris@0: markPrevious: function() { Chris@0: if(this.index > 0) this.index--; Chris@0: else this.index = this.entryCount-1; Chris@0: this.getEntry(this.index).scrollIntoView(true); Chris@0: }, Chris@0: Chris@0: markNext: function() { Chris@0: if(this.index < this.entryCount-1) this.index++; Chris@0: else this.index = 0; Chris@0: this.getEntry(this.index).scrollIntoView(false); Chris@0: }, Chris@0: Chris@0: getEntry: function(index) { Chris@0: return this.update.firstChild.childNodes[index]; Chris@0: }, Chris@0: Chris@0: getCurrentEntry: function() { Chris@0: return this.getEntry(this.index); Chris@0: }, Chris@0: Chris@0: selectEntry: function() { Chris@0: this.active = false; Chris@0: this.updateElement(this.getCurrentEntry()); Chris@0: }, Chris@0: Chris@0: updateElement: function(selectedElement) { Chris@0: if (this.options.updateElement) { Chris@0: this.options.updateElement(selectedElement); Chris@0: return; Chris@0: } Chris@0: var value = ''; Chris@0: if (this.options.select) { Chris@0: var nodes = $(selectedElement).select('.' + this.options.select) || []; Chris@0: if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); Chris@0: } else Chris@0: value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); Chris@0: Chris@0: var bounds = this.getTokenBounds(); Chris@0: if (bounds[0] != -1) { Chris@0: var newValue = this.element.value.substr(0, bounds[0]); Chris@0: var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); Chris@0: if (whitespace) Chris@0: newValue += whitespace[0]; Chris@0: this.element.value = newValue + value + this.element.value.substr(bounds[1]); Chris@0: } else { Chris@0: this.element.value = value; Chris@0: } Chris@0: this.oldElementValue = this.element.value; Chris@0: this.element.focus(); Chris@0: Chris@0: if (this.options.afterUpdateElement) Chris@0: this.options.afterUpdateElement(this.element, selectedElement); Chris@0: }, Chris@0: Chris@0: updateChoices: function(choices) { Chris@0: if(!this.changed && this.hasFocus) { Chris@0: this.update.innerHTML = choices; Chris@0: Element.cleanWhitespace(this.update); Chris@0: Element.cleanWhitespace(this.update.down()); Chris@0: Chris@0: if(this.update.firstChild && this.update.down().childNodes) { Chris@0: this.entryCount = Chris@0: this.update.down().childNodes.length; Chris@0: for (var i = 0; i < this.entryCount; i++) { Chris@0: var entry = this.getEntry(i); Chris@0: entry.autocompleteIndex = i; Chris@0: this.addObservers(entry); Chris@0: } Chris@0: } else { Chris@0: this.entryCount = 0; Chris@0: } Chris@0: Chris@0: this.stopIndicator(); Chris@0: this.index = 0; Chris@0: Chris@0: if(this.entryCount==1 && this.options.autoSelect) { Chris@0: this.selectEntry(); Chris@0: this.hide(); Chris@0: } else { Chris@0: this.render(); Chris@0: } Chris@0: } Chris@0: }, Chris@0: Chris@0: addObservers: function(element) { Chris@0: Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); Chris@0: Event.observe(element, "click", this.onClick.bindAsEventListener(this)); Chris@0: }, Chris@0: Chris@0: onObserverEvent: function() { Chris@0: this.changed = false; Chris@0: this.tokenBounds = null; Chris@0: if(this.getToken().length>=this.options.minChars) { Chris@0: this.getUpdatedChoices(); Chris@0: } else { Chris@0: this.active = false; Chris@0: this.hide(); Chris@0: } Chris@0: this.oldElementValue = this.element.value; Chris@0: }, Chris@0: Chris@0: getToken: function() { Chris@0: var bounds = this.getTokenBounds(); Chris@0: return this.element.value.substring(bounds[0], bounds[1]).strip(); Chris@0: }, Chris@0: Chris@0: getTokenBounds: function() { Chris@0: if (null != this.tokenBounds) return this.tokenBounds; Chris@0: var value = this.element.value; Chris@0: if (value.strip().empty()) return [-1, 0]; Chris@0: var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); Chris@0: var offset = (diff == this.oldElementValue.length ? 1 : 0); Chris@0: var prevTokenPos = -1, nextTokenPos = value.length; Chris@0: var tp; Chris@0: for (var index = 0, l = this.options.tokens.length; index < l; ++index) { Chris@0: tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); Chris@0: if (tp > prevTokenPos) prevTokenPos = tp; Chris@0: tp = value.indexOf(this.options.tokens[index], diff + offset); Chris@0: if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; Chris@0: } Chris@0: return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); Chris@0: } Chris@0: }); Chris@0: Chris@0: Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { Chris@0: var boundary = Math.min(newS.length, oldS.length); Chris@0: for (var index = 0; index < boundary; ++index) Chris@0: if (newS[index] != oldS[index]) Chris@0: return index; Chris@0: return boundary; Chris@0: }; Chris@0: Chris@0: Ajax.Autocompleter = Class.create(Autocompleter.Base, { Chris@0: initialize: function(element, update, url, options) { Chris@0: this.baseInitialize(element, update, options); Chris@0: this.options.asynchronous = true; Chris@0: this.options.onComplete = this.onComplete.bind(this); Chris@0: this.options.defaultParams = this.options.parameters || null; Chris@0: this.url = url; Chris@0: }, Chris@0: Chris@0: getUpdatedChoices: function() { Chris@0: this.startIndicator(); Chris@0: Chris@0: var entry = encodeURIComponent(this.options.paramName) + '=' + Chris@0: encodeURIComponent(this.getToken()); Chris@0: Chris@0: this.options.parameters = this.options.callback ? Chris@0: this.options.callback(this.element, entry) : entry; Chris@0: Chris@0: if(this.options.defaultParams) Chris@0: this.options.parameters += '&' + this.options.defaultParams; Chris@0: Chris@0: new Ajax.Request(this.url, this.options); Chris@0: }, Chris@0: Chris@0: onComplete: function(request) { Chris@0: this.updateChoices(request.responseText); Chris@0: } Chris@0: }); Chris@0: Chris@0: // The local array autocompleter. Used when you'd prefer to Chris@0: // inject an array of autocompletion options into the page, rather Chris@0: // than sending out Ajax queries, which can be quite slow sometimes. Chris@0: // Chris@0: // The constructor takes four parameters. The first two are, as usual, Chris@0: // the id of the monitored textbox, and id of the autocompletion menu. Chris@0: // The third is the array you want to autocomplete from, and the fourth Chris@0: // is the options block. Chris@0: // Chris@0: // Extra local autocompletion options: Chris@0: // - choices - How many autocompletion choices to offer Chris@0: // Chris@0: // - partialSearch - If false, the autocompleter will match entered Chris@0: // text only at the beginning of strings in the Chris@0: // autocomplete array. Defaults to true, which will Chris@0: // match text at the beginning of any *word* in the Chris@0: // strings in the autocomplete array. If you want to Chris@0: // search anywhere in the string, additionally set Chris@0: // the option fullSearch to true (default: off). Chris@0: // Chris@0: // - fullSsearch - Search anywhere in autocomplete array strings. Chris@0: // Chris@0: // - partialChars - How many characters to enter before triggering Chris@0: // a partial match (unlike minChars, which defines Chris@0: // how many characters are required to do any match Chris@0: // at all). Defaults to 2. Chris@0: // Chris@0: // - ignoreCase - Whether to ignore case when autocompleting. Chris@0: // Defaults to true. Chris@0: // Chris@0: // It's possible to pass in a custom function as the 'selector' Chris@0: // option, if you prefer to write your own autocompletion logic. Chris@0: // In that case, the other options above will not apply unless Chris@0: // you support them. Chris@0: Chris@0: Autocompleter.Local = Class.create(Autocompleter.Base, { Chris@0: initialize: function(element, update, array, options) { Chris@0: this.baseInitialize(element, update, options); Chris@0: this.options.array = array; Chris@0: }, Chris@0: Chris@0: getUpdatedChoices: function() { Chris@0: this.updateChoices(this.options.selector(this)); Chris@0: }, Chris@0: Chris@0: setOptions: function(options) { Chris@0: this.options = Object.extend({ Chris@0: choices: 10, Chris@0: partialSearch: true, Chris@0: partialChars: 2, Chris@0: ignoreCase: true, Chris@0: fullSearch: false, Chris@0: selector: function(instance) { Chris@0: var ret = []; // Beginning matches Chris@0: var partial = []; // Inside matches Chris@0: var entry = instance.getToken(); Chris@0: var count = 0; Chris@0: Chris@0: for (var i = 0; i < instance.options.array.length && Chris@0: ret.length < instance.options.choices ; i++) { Chris@0: Chris@0: var elem = instance.options.array[i]; Chris@0: var foundPos = instance.options.ignoreCase ? Chris@0: elem.toLowerCase().indexOf(entry.toLowerCase()) : Chris@0: elem.indexOf(entry); Chris@0: Chris@0: while (foundPos != -1) { Chris@0: if (foundPos == 0 && elem.length != entry.length) { Chris@0: ret.push("
  • " + elem.substr(0, entry.length) + "" + Chris@0: elem.substr(entry.length) + "
  • "); Chris@0: break; Chris@0: } else if (entry.length >= instance.options.partialChars && Chris@0: instance.options.partialSearch && foundPos != -1) { Chris@0: if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { Chris@0: partial.push("
  • " + elem.substr(0, foundPos) + "" + Chris@0: elem.substr(foundPos, entry.length) + "" + elem.substr( Chris@0: foundPos + entry.length) + "
  • "); Chris@0: break; Chris@0: } Chris@0: } Chris@0: Chris@0: foundPos = instance.options.ignoreCase ? Chris@0: elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : Chris@0: elem.indexOf(entry, foundPos + 1); Chris@0: Chris@0: } Chris@0: } Chris@0: if (partial.length) Chris@0: ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)); Chris@0: return ""; Chris@0: } Chris@0: }, options || { }); Chris@0: } Chris@0: }); Chris@0: Chris@0: // AJAX in-place editor and collection editor Chris@0: // Full rewrite by Christophe Porteneuve (April 2007). Chris@0: Chris@0: // Use this if you notice weird scrolling problems on some browsers, Chris@0: // the DOM might be a bit confused when this gets called so do this Chris@0: // waits 1 ms (with setTimeout) until it does the activation Chris@0: Field.scrollFreeActivate = function(field) { Chris@0: setTimeout(function() { Chris@0: Field.activate(field); Chris@0: }, 1); Chris@0: }; Chris@0: Chris@0: Ajax.InPlaceEditor = Class.create({ Chris@0: initialize: function(element, url, options) { Chris@0: this.url = url; Chris@0: this.element = element = $(element); Chris@0: this.prepareOptions(); Chris@0: this._controls = { }; Chris@0: arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! Chris@0: Object.extend(this.options, options || { }); Chris@0: if (!this.options.formId && this.element.id) { Chris@0: this.options.formId = this.element.id + '-inplaceeditor'; Chris@0: if ($(this.options.formId)) Chris@0: this.options.formId = ''; Chris@0: } Chris@0: if (this.options.externalControl) Chris@0: this.options.externalControl = $(this.options.externalControl); Chris@0: if (!this.options.externalControl) Chris@0: this.options.externalControlOnly = false; Chris@0: this._originalBackground = this.element.getStyle('background-color') || 'transparent'; Chris@0: this.element.title = this.options.clickToEditText; Chris@0: this._boundCancelHandler = this.handleFormCancellation.bind(this); Chris@0: this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); Chris@0: this._boundFailureHandler = this.handleAJAXFailure.bind(this); Chris@0: this._boundSubmitHandler = this.handleFormSubmission.bind(this); Chris@0: this._boundWrapperHandler = this.wrapUp.bind(this); Chris@0: this.registerListeners(); Chris@0: }, Chris@0: checkForEscapeOrReturn: function(e) { Chris@0: if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; Chris@0: if (Event.KEY_ESC == e.keyCode) Chris@0: this.handleFormCancellation(e); Chris@0: else if (Event.KEY_RETURN == e.keyCode) Chris@0: this.handleFormSubmission(e); Chris@0: }, Chris@0: createControl: function(mode, handler, extraClasses) { Chris@0: var control = this.options[mode + 'Control']; Chris@0: var text = this.options[mode + 'Text']; Chris@0: if ('button' == control) { Chris@0: var btn = document.createElement('input'); Chris@0: btn.type = 'submit'; Chris@0: btn.value = text; Chris@0: btn.className = 'editor_' + mode + '_button'; Chris@0: if ('cancel' == mode) Chris@0: btn.onclick = this._boundCancelHandler; Chris@0: this._form.appendChild(btn); Chris@0: this._controls[mode] = btn; Chris@0: } else if ('link' == control) { Chris@0: var link = document.createElement('a'); Chris@0: link.href = '#'; Chris@0: link.appendChild(document.createTextNode(text)); Chris@0: link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; Chris@0: link.className = 'editor_' + mode + '_link'; Chris@0: if (extraClasses) Chris@0: link.className += ' ' + extraClasses; Chris@0: this._form.appendChild(link); Chris@0: this._controls[mode] = link; Chris@0: } Chris@0: }, Chris@0: createEditField: function() { Chris@0: var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); Chris@0: var fld; Chris@0: if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { Chris@0: fld = document.createElement('input'); Chris@0: fld.type = 'text'; Chris@0: var size = this.options.size || this.options.cols || 0; Chris@0: if (0 < size) fld.size = size; Chris@0: } else { Chris@0: fld = document.createElement('textarea'); Chris@0: fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); Chris@0: fld.cols = this.options.cols || 40; Chris@0: } Chris@0: fld.name = this.options.paramName; Chris@0: fld.value = text; // No HTML breaks conversion anymore Chris@0: fld.className = 'editor_field'; Chris@0: if (this.options.submitOnBlur) Chris@0: fld.onblur = this._boundSubmitHandler; Chris@0: this._controls.editor = fld; Chris@0: if (this.options.loadTextURL) Chris@0: this.loadExternalText(); Chris@0: this._form.appendChild(this._controls.editor); Chris@0: }, Chris@0: createForm: function() { Chris@0: var ipe = this; Chris@0: function addText(mode, condition) { Chris@0: var text = ipe.options['text' + mode + 'Controls']; Chris@0: if (!text || condition === false) return; Chris@0: ipe._form.appendChild(document.createTextNode(text)); Chris@0: }; Chris@0: this._form = $(document.createElement('form')); Chris@0: this._form.id = this.options.formId; Chris@0: this._form.addClassName(this.options.formClassName); Chris@0: this._form.onsubmit = this._boundSubmitHandler; Chris@0: this.createEditField(); Chris@0: if ('textarea' == this._controls.editor.tagName.toLowerCase()) Chris@0: this._form.appendChild(document.createElement('br')); Chris@0: if (this.options.onFormCustomization) Chris@0: this.options.onFormCustomization(this, this._form); Chris@0: addText('Before', this.options.okControl || this.options.cancelControl); Chris@0: this.createControl('ok', this._boundSubmitHandler); Chris@0: addText('Between', this.options.okControl && this.options.cancelControl); Chris@0: this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); Chris@0: addText('After', this.options.okControl || this.options.cancelControl); Chris@0: }, Chris@0: destroy: function() { Chris@0: if (this._oldInnerHTML) Chris@0: this.element.innerHTML = this._oldInnerHTML; Chris@0: this.leaveEditMode(); Chris@0: this.unregisterListeners(); Chris@0: }, Chris@0: enterEditMode: function(e) { Chris@0: if (this._saving || this._editing) return; Chris@0: this._editing = true; Chris@0: this.triggerCallback('onEnterEditMode'); Chris@0: if (this.options.externalControl) Chris@0: this.options.externalControl.hide(); Chris@0: this.element.hide(); Chris@0: this.createForm(); Chris@0: this.element.parentNode.insertBefore(this._form, this.element); Chris@0: if (!this.options.loadTextURL) Chris@0: this.postProcessEditField(); Chris@0: if (e) Event.stop(e); Chris@0: }, Chris@0: enterHover: function(e) { Chris@0: if (this.options.hoverClassName) Chris@0: this.element.addClassName(this.options.hoverClassName); Chris@0: if (this._saving) return; Chris@0: this.triggerCallback('onEnterHover'); Chris@0: }, Chris@0: getText: function() { Chris@0: return this.element.innerHTML.unescapeHTML(); Chris@0: }, Chris@0: handleAJAXFailure: function(transport) { Chris@0: this.triggerCallback('onFailure', transport); Chris@0: if (this._oldInnerHTML) { Chris@0: this.element.innerHTML = this._oldInnerHTML; Chris@0: this._oldInnerHTML = null; Chris@0: } Chris@0: }, Chris@0: handleFormCancellation: function(e) { Chris@0: this.wrapUp(); Chris@0: if (e) Event.stop(e); Chris@0: }, Chris@0: handleFormSubmission: function(e) { Chris@0: var form = this._form; Chris@0: var value = $F(this._controls.editor); Chris@0: this.prepareSubmission(); Chris@0: var params = this.options.callback(form, value) || ''; Chris@0: if (Object.isString(params)) Chris@0: params = params.toQueryParams(); Chris@0: params.editorId = this.element.id; Chris@0: if (this.options.htmlResponse) { Chris@0: var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); Chris@0: Object.extend(options, { Chris@0: parameters: params, Chris@0: onComplete: this._boundWrapperHandler, Chris@0: onFailure: this._boundFailureHandler Chris@0: }); Chris@0: new Ajax.Updater({ success: this.element }, this.url, options); Chris@0: } else { Chris@0: var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); Chris@0: Object.extend(options, { Chris@0: parameters: params, Chris@0: onComplete: this._boundWrapperHandler, Chris@0: onFailure: this._boundFailureHandler Chris@0: }); Chris@0: new Ajax.Request(this.url, options); Chris@0: } Chris@0: if (e) Event.stop(e); Chris@0: }, Chris@0: leaveEditMode: function() { Chris@0: this.element.removeClassName(this.options.savingClassName); Chris@0: this.removeForm(); Chris@0: this.leaveHover(); Chris@0: this.element.style.backgroundColor = this._originalBackground; Chris@0: this.element.show(); Chris@0: if (this.options.externalControl) Chris@0: this.options.externalControl.show(); Chris@0: this._saving = false; Chris@0: this._editing = false; Chris@0: this._oldInnerHTML = null; Chris@0: this.triggerCallback('onLeaveEditMode'); Chris@0: }, Chris@0: leaveHover: function(e) { Chris@0: if (this.options.hoverClassName) Chris@0: this.element.removeClassName(this.options.hoverClassName); Chris@0: if (this._saving) return; Chris@0: this.triggerCallback('onLeaveHover'); Chris@0: }, Chris@0: loadExternalText: function() { Chris@0: this._form.addClassName(this.options.loadingClassName); Chris@0: this._controls.editor.disabled = true; Chris@0: var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); Chris@0: Object.extend(options, { Chris@0: parameters: 'editorId=' + encodeURIComponent(this.element.id), Chris@0: onComplete: Prototype.emptyFunction, Chris@0: onSuccess: function(transport) { Chris@0: this._form.removeClassName(this.options.loadingClassName); Chris@0: var text = transport.responseText; Chris@0: if (this.options.stripLoadedTextTags) Chris@0: text = text.stripTags(); Chris@0: this._controls.editor.value = text; Chris@0: this._controls.editor.disabled = false; Chris@0: this.postProcessEditField(); Chris@0: }.bind(this), Chris@0: onFailure: this._boundFailureHandler Chris@0: }); Chris@0: new Ajax.Request(this.options.loadTextURL, options); Chris@0: }, Chris@0: postProcessEditField: function() { Chris@0: var fpc = this.options.fieldPostCreation; Chris@0: if (fpc) Chris@0: $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); Chris@0: }, Chris@0: prepareOptions: function() { Chris@0: this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); Chris@0: Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); Chris@0: [this._extraDefaultOptions].flatten().compact().each(function(defs) { Chris@0: Object.extend(this.options, defs); Chris@0: }.bind(this)); Chris@0: }, Chris@0: prepareSubmission: function() { Chris@0: this._saving = true; Chris@0: this.removeForm(); Chris@0: this.leaveHover(); Chris@0: this.showSaving(); Chris@0: }, Chris@0: registerListeners: function() { Chris@0: this._listeners = { }; Chris@0: var listener; Chris@0: $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { Chris@0: listener = this[pair.value].bind(this); Chris@0: this._listeners[pair.key] = listener; Chris@0: if (!this.options.externalControlOnly) Chris@0: this.element.observe(pair.key, listener); Chris@0: if (this.options.externalControl) Chris@0: this.options.externalControl.observe(pair.key, listener); Chris@0: }.bind(this)); Chris@0: }, Chris@0: removeForm: function() { Chris@0: if (!this._form) return; Chris@0: this._form.remove(); Chris@0: this._form = null; Chris@0: this._controls = { }; Chris@0: }, Chris@0: showSaving: function() { Chris@0: this._oldInnerHTML = this.element.innerHTML; Chris@0: this.element.innerHTML = this.options.savingText; Chris@0: this.element.addClassName(this.options.savingClassName); Chris@0: this.element.style.backgroundColor = this._originalBackground; Chris@0: this.element.show(); Chris@0: }, Chris@0: triggerCallback: function(cbName, arg) { Chris@0: if ('function' == typeof this.options[cbName]) { Chris@0: this.options[cbName](this, arg); Chris@0: } Chris@0: }, Chris@0: unregisterListeners: function() { Chris@0: $H(this._listeners).each(function(pair) { Chris@0: if (!this.options.externalControlOnly) Chris@0: this.element.stopObserving(pair.key, pair.value); Chris@0: if (this.options.externalControl) Chris@0: this.options.externalControl.stopObserving(pair.key, pair.value); Chris@0: }.bind(this)); Chris@0: }, Chris@0: wrapUp: function(transport) { Chris@0: this.leaveEditMode(); Chris@0: // Can't use triggerCallback due to backward compatibility: requires Chris@0: // binding + direct element Chris@0: this._boundComplete(transport, this.element); Chris@0: } Chris@0: }); Chris@0: Chris@0: Object.extend(Ajax.InPlaceEditor.prototype, { Chris@0: dispose: Ajax.InPlaceEditor.prototype.destroy Chris@0: }); Chris@0: Chris@0: Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { Chris@0: initialize: function($super, element, url, options) { Chris@0: this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; Chris@0: $super(element, url, options); Chris@0: }, Chris@0: Chris@0: createEditField: function() { Chris@0: var list = document.createElement('select'); Chris@0: list.name = this.options.paramName; Chris@0: list.size = 1; Chris@0: this._controls.editor = list; Chris@0: this._collection = this.options.collection || []; Chris@0: if (this.options.loadCollectionURL) Chris@0: this.loadCollection(); Chris@0: else Chris@0: this.checkForExternalText(); Chris@0: this._form.appendChild(this._controls.editor); Chris@0: }, Chris@0: Chris@0: loadCollection: function() { Chris@0: this._form.addClassName(this.options.loadingClassName); Chris@0: this.showLoadingText(this.options.loadingCollectionText); Chris@0: var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); Chris@0: Object.extend(options, { Chris@0: parameters: 'editorId=' + encodeURIComponent(this.element.id), Chris@0: onComplete: Prototype.emptyFunction, Chris@0: onSuccess: function(transport) { Chris@0: var js = transport.responseText.strip(); Chris@0: if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check Chris@0: throw('Server returned an invalid collection representation.'); Chris@0: this._collection = eval(js); Chris@0: this.checkForExternalText(); Chris@0: }.bind(this), Chris@0: onFailure: this.onFailure Chris@0: }); Chris@0: new Ajax.Request(this.options.loadCollectionURL, options); Chris@0: }, Chris@0: Chris@0: showLoadingText: function(text) { Chris@0: this._controls.editor.disabled = true; Chris@0: var tempOption = this._controls.editor.firstChild; Chris@0: if (!tempOption) { Chris@0: tempOption = document.createElement('option'); Chris@0: tempOption.value = ''; Chris@0: this._controls.editor.appendChild(tempOption); Chris@0: tempOption.selected = true; Chris@0: } Chris@0: tempOption.update((text || '').stripScripts().stripTags()); Chris@0: }, Chris@0: Chris@0: checkForExternalText: function() { Chris@0: this._text = this.getText(); Chris@0: if (this.options.loadTextURL) Chris@0: this.loadExternalText(); Chris@0: else Chris@0: this.buildOptionList(); Chris@0: }, Chris@0: Chris@0: loadExternalText: function() { Chris@0: this.showLoadingText(this.options.loadingText); Chris@0: var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); Chris@0: Object.extend(options, { Chris@0: parameters: 'editorId=' + encodeURIComponent(this.element.id), Chris@0: onComplete: Prototype.emptyFunction, Chris@0: onSuccess: function(transport) { Chris@0: this._text = transport.responseText.strip(); Chris@0: this.buildOptionList(); Chris@0: }.bind(this), Chris@0: onFailure: this.onFailure Chris@0: }); Chris@0: new Ajax.Request(this.options.loadTextURL, options); Chris@0: }, Chris@0: Chris@0: buildOptionList: function() { Chris@0: this._form.removeClassName(this.options.loadingClassName); Chris@0: this._collection = this._collection.map(function(entry) { Chris@0: return 2 === entry.length ? entry : [entry, entry].flatten(); Chris@0: }); Chris@0: var marker = ('value' in this.options) ? this.options.value : this._text; Chris@0: var textFound = this._collection.any(function(entry) { Chris@0: return entry[0] == marker; Chris@0: }.bind(this)); Chris@0: this._controls.editor.update(''); Chris@0: var option; Chris@0: this._collection.each(function(entry, index) { Chris@0: option = document.createElement('option'); Chris@0: option.value = entry[0]; Chris@0: option.selected = textFound ? entry[0] == marker : 0 == index; Chris@0: option.appendChild(document.createTextNode(entry[1])); Chris@0: this._controls.editor.appendChild(option); Chris@0: }.bind(this)); Chris@0: this._controls.editor.disabled = false; Chris@0: Field.scrollFreeActivate(this._controls.editor); Chris@0: } Chris@0: }); Chris@0: Chris@0: //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** Chris@0: //**** This only exists for a while, in order to let **** Chris@0: //**** users adapt to the new API. Read up on the new **** Chris@0: //**** API and convert your code to it ASAP! **** Chris@0: Chris@0: Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { Chris@0: if (!options) return; Chris@0: function fallback(name, expr) { Chris@0: if (name in options || expr === undefined) return; Chris@0: options[name] = expr; Chris@0: }; Chris@0: fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : Chris@0: options.cancelLink == options.cancelButton == false ? false : undefined))); Chris@0: fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : Chris@0: options.okLink == options.okButton == false ? false : undefined))); Chris@0: fallback('highlightColor', options.highlightcolor); Chris@0: fallback('highlightEndColor', options.highlightendcolor); Chris@0: }; Chris@0: Chris@0: Object.extend(Ajax.InPlaceEditor, { Chris@0: DefaultOptions: { Chris@0: ajaxOptions: { }, Chris@0: autoRows: 3, // Use when multi-line w/ rows == 1 Chris@0: cancelControl: 'link', // 'link'|'button'|false Chris@0: cancelText: 'cancel', Chris@0: clickToEditText: 'Click to edit', Chris@0: externalControl: null, // id|elt Chris@0: externalControlOnly: false, Chris@0: fieldPostCreation: 'activate', // 'activate'|'focus'|false Chris@0: formClassName: 'inplaceeditor-form', Chris@0: formId: null, // id|elt Chris@0: highlightColor: '#ffff99', Chris@0: highlightEndColor: '#ffffff', Chris@0: hoverClassName: '', Chris@0: htmlResponse: true, Chris@0: loadingClassName: 'inplaceeditor-loading', Chris@0: loadingText: 'Loading...', Chris@0: okControl: 'button', // 'link'|'button'|false Chris@0: okText: 'ok', Chris@0: paramName: 'value', Chris@0: rows: 1, // If 1 and multi-line, uses autoRows Chris@0: savingClassName: 'inplaceeditor-saving', Chris@0: savingText: 'Saving...', Chris@0: size: 0, Chris@0: stripLoadedTextTags: false, Chris@0: submitOnBlur: false, Chris@0: textAfterControls: '', Chris@0: textBeforeControls: '', Chris@0: textBetweenControls: '' Chris@0: }, Chris@0: DefaultCallbacks: { Chris@0: callback: function(form) { Chris@0: return Form.serialize(form); Chris@0: }, Chris@0: onComplete: function(transport, element) { Chris@0: // For backward compatibility, this one is bound to the IPE, and passes Chris@0: // the element directly. It was too often customized, so we don't break it. Chris@0: new Effect.Highlight(element, { Chris@0: startcolor: this.options.highlightColor, keepBackgroundImage: true }); Chris@0: }, Chris@0: onEnterEditMode: null, Chris@0: onEnterHover: function(ipe) { Chris@0: ipe.element.style.backgroundColor = ipe.options.highlightColor; Chris@0: if (ipe._effect) Chris@0: ipe._effect.cancel(); Chris@0: }, Chris@0: onFailure: function(transport, ipe) { Chris@0: alert('Error communication with the server: ' + transport.responseText.stripTags()); Chris@0: }, Chris@0: onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. Chris@0: onLeaveEditMode: null, Chris@0: onLeaveHover: function(ipe) { Chris@0: ipe._effect = new Effect.Highlight(ipe.element, { Chris@0: startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, Chris@0: restorecolor: ipe._originalBackground, keepBackgroundImage: true Chris@0: }); Chris@0: } Chris@0: }, Chris@0: Listeners: { Chris@0: click: 'enterEditMode', Chris@0: keydown: 'checkForEscapeOrReturn', Chris@0: mouseover: 'enterHover', Chris@0: mouseout: 'leaveHover' Chris@0: } Chris@0: }); Chris@0: Chris@0: Ajax.InPlaceCollectionEditor.DefaultOptions = { Chris@0: loadingCollectionText: 'Loading options...' Chris@0: }; Chris@0: Chris@0: // Delayed observer, like Form.Element.Observer, Chris@0: // but waits for delay after last key input Chris@0: // Ideal for live-search fields Chris@0: Chris@0: Form.Element.DelayedObserver = Class.create({ Chris@0: initialize: function(element, delay, callback) { Chris@0: this.delay = delay || 0.5; Chris@0: this.element = $(element); Chris@0: this.callback = callback; Chris@0: this.timer = null; Chris@0: this.lastValue = $F(this.element); Chris@0: Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); Chris@0: }, Chris@0: delayedListener: function(event) { Chris@0: if(this.lastValue == $F(this.element)) return; Chris@0: if(this.timer) clearTimeout(this.timer); Chris@0: this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); Chris@0: this.lastValue = $F(this.element); Chris@0: }, Chris@0: onTimerEvent: function() { Chris@0: this.timer = null; Chris@0: this.callback(this.element, $F(this.element)); Chris@0: } Chris@0: });