controls.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /***
  2. * Excerpted from "Agile Web Development with Rails",
  3. * published by The Pragmatic Bookshelf.
  4. * Copyrights apply to this code. It may not be used to create training material,
  5. * courses, books, articles, and the like. Contact us if you are in doubt.
  6. * We make no guarantees that this code is fit for any purpose.
  7. * Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. ***/
  9. /***
  10. * Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. * published by The Pragmatic Bookshelf.
  12. * Copyrights apply to this code. It may not be used to create training material,
  13. * courses, books, articles, and the like. Contact us if you are in doubt.
  14. * We make no guarantees that this code is fit for any purpose.
  15. * Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. ***/
  17. // script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
  18. // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
  19. // (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
  20. // (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
  21. // Contributors:
  22. // Richard Livsey
  23. // Rahul Bhargava
  24. // Rob Wills
  25. //
  26. // script.aculo.us is freely distributable under the terms of an MIT-style license.
  27. // For details, see the script.aculo.us web site: http://script.aculo.us/
  28. // Autocompleter.Base handles all the autocompletion functionality
  29. // that's independent of the data source for autocompletion. This
  30. // includes drawing the autocompletion menu, observing keyboard
  31. // and mouse events, and similar.
  32. //
  33. // Specific autocompleters need to provide, at the very least,
  34. // a getUpdatedChoices function that will be invoked every time
  35. // the text inside the monitored textbox changes. This method
  36. // should get the text for which to provide autocompletion by
  37. // invoking this.getToken(), NOT by directly accessing
  38. // this.element.value. This is to allow incremental tokenized
  39. // autocompletion. Specific auto-completion logic (AJAX, etc)
  40. // belongs in getUpdatedChoices.
  41. //
  42. // Tokenized incremental autocompletion is enabled automatically
  43. // when an autocompleter is instantiated with the 'tokens' option
  44. // in the options parameter, e.g.:
  45. // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
  46. // will incrementally autocomplete with a comma as the token.
  47. // Additionally, ',' in the above example can be replaced with
  48. // a token array, e.g. { tokens: [',', '\n'] } which
  49. // enables autocompletion on multiple tokens. This is most
  50. // useful when one of the tokens is \n (a newline), as it
  51. // allows smart autocompletion after linebreaks.
  52. if(typeof Effect == 'undefined')
  53. throw("controls.js requires including script.aculo.us' effects.js library");
  54. var Autocompleter = { };
  55. Autocompleter.Base = Class.create({
  56. baseInitialize: function(element, update, options) {
  57. element = $(element);
  58. this.element = element;
  59. this.update = $(update);
  60. this.hasFocus = false;
  61. this.changed = false;
  62. this.active = false;
  63. this.index = 0;
  64. this.entryCount = 0;
  65. this.oldElementValue = this.element.value;
  66. if(this.setOptions)
  67. this.setOptions(options);
  68. else
  69. this.options = options || { };
  70. this.options.paramName = this.options.paramName || this.element.name;
  71. this.options.tokens = this.options.tokens || [];
  72. this.options.frequency = this.options.frequency || 0.4;
  73. this.options.minChars = this.options.minChars || 1;
  74. this.options.onShow = this.options.onShow ||
  75. function(element, update){
  76. if(!update.style.position || update.style.position=='absolute') {
  77. update.style.position = 'absolute';
  78. Position.clone(element, update, {
  79. setHeight: false,
  80. offsetTop: element.offsetHeight
  81. });
  82. }
  83. Effect.Appear(update,{duration:0.15});
  84. };
  85. this.options.onHide = this.options.onHide ||
  86. function(element, update){ new Effect.Fade(update,{duration:0.15}) };
  87. if(typeof(this.options.tokens) == 'string')
  88. this.options.tokens = new Array(this.options.tokens);
  89. // Force carriage returns as token delimiters anyway
  90. if (!this.options.tokens.include('\n'))
  91. this.options.tokens.push('\n');
  92. this.observer = null;
  93. this.element.setAttribute('autocomplete','off');
  94. Element.hide(this.update);
  95. Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
  96. Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
  97. },
  98. show: function() {
  99. if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
  100. if(!this.iefix &&
  101. (Prototype.Browser.IE) &&
  102. (Element.getStyle(this.update, 'position')=='absolute')) {
  103. new Insertion.After(this.update,
  104. '<iframe id="' + this.update.id + '_iefix" '+
  105. 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
  106. 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
  107. this.iefix = $(this.update.id+'_iefix');
  108. }
  109. if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  110. },
  111. fixIEOverlapping: function() {
  112. Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
  113. this.iefix.style.zIndex = 1;
  114. this.update.style.zIndex = 2;
  115. Element.show(this.iefix);
  116. },
  117. hide: function() {
  118. this.stopIndicator();
  119. if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
  120. if(this.iefix) Element.hide(this.iefix);
  121. },
  122. startIndicator: function() {
  123. if(this.options.indicator) Element.show(this.options.indicator);
  124. },
  125. stopIndicator: function() {
  126. if(this.options.indicator) Element.hide(this.options.indicator);
  127. },
  128. onKeyPress: function(event) {
  129. if(this.active)
  130. switch(event.keyCode) {
  131. case Event.KEY_TAB:
  132. case Event.KEY_RETURN:
  133. this.selectEntry();
  134. Event.stop(event);
  135. case Event.KEY_ESC:
  136. this.hide();
  137. this.active = false;
  138. Event.stop(event);
  139. return;
  140. case Event.KEY_LEFT:
  141. case Event.KEY_RIGHT:
  142. return;
  143. case Event.KEY_UP:
  144. this.markPrevious();
  145. this.render();
  146. Event.stop(event);
  147. return;
  148. case Event.KEY_DOWN:
  149. this.markNext();
  150. this.render();
  151. Event.stop(event);
  152. return;
  153. }
  154. else
  155. if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
  156. (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
  157. this.changed = true;
  158. this.hasFocus = true;
  159. if(this.observer) clearTimeout(this.observer);
  160. this.observer =
  161. setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  162. },
  163. activate: function() {
  164. this.changed = false;
  165. this.hasFocus = true;
  166. this.getUpdatedChoices();
  167. },
  168. onHover: function(event) {
  169. var element = Event.findElement(event, 'LI');
  170. if(this.index != element.autocompleteIndex)
  171. {
  172. this.index = element.autocompleteIndex;
  173. this.render();
  174. }
  175. Event.stop(event);
  176. },
  177. onClick: function(event) {
  178. var element = Event.findElement(event, 'LI');
  179. this.index = element.autocompleteIndex;
  180. this.selectEntry();
  181. this.hide();
  182. },
  183. onBlur: function(event) {
  184. // needed to make click events working
  185. setTimeout(this.hide.bind(this), 250);
  186. this.hasFocus = false;
  187. this.active = false;
  188. },
  189. render: function() {
  190. if(this.entryCount > 0) {
  191. for (var i = 0; i < this.entryCount; i++)
  192. this.index==i ?
  193. Element.addClassName(this.getEntry(i),"selected") :
  194. Element.removeClassName(this.getEntry(i),"selected");
  195. if(this.hasFocus) {
  196. this.show();
  197. this.active = true;
  198. }
  199. } else {
  200. this.active = false;
  201. this.hide();
  202. }
  203. },
  204. markPrevious: function() {
  205. if(this.index > 0) this.index--;
  206. else this.index = this.entryCount-1;
  207. this.getEntry(this.index).scrollIntoView(true);
  208. },
  209. markNext: function() {
  210. if(this.index < this.entryCount-1) this.index++;
  211. else this.index = 0;
  212. this.getEntry(this.index).scrollIntoView(false);
  213. },
  214. getEntry: function(index) {
  215. return this.update.firstChild.childNodes[index];
  216. },
  217. getCurrentEntry: function() {
  218. return this.getEntry(this.index);
  219. },
  220. selectEntry: function() {
  221. this.active = false;
  222. this.updateElement(this.getCurrentEntry());
  223. },
  224. updateElement: function(selectedElement) {
  225. if (this.options.updateElement) {
  226. this.options.updateElement(selectedElement);
  227. return;
  228. }
  229. var value = '';
  230. if (this.options.select) {
  231. var nodes = $(selectedElement).select('.' + this.options.select) || [];
  232. if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
  233. } else
  234. value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
  235. var bounds = this.getTokenBounds();
  236. if (bounds[0] != -1) {
  237. var newValue = this.element.value.substr(0, bounds[0]);
  238. var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
  239. if (whitespace)
  240. newValue += whitespace[0];
  241. this.element.value = newValue + value + this.element.value.substr(bounds[1]);
  242. } else {
  243. this.element.value = value;
  244. }
  245. this.oldElementValue = this.element.value;
  246. this.element.focus();
  247. if (this.options.afterUpdateElement)
  248. this.options.afterUpdateElement(this.element, selectedElement);
  249. },
  250. updateChoices: function(choices) {
  251. if(!this.changed && this.hasFocus) {
  252. this.update.innerHTML = choices;
  253. Element.cleanWhitespace(this.update);
  254. Element.cleanWhitespace(this.update.down());
  255. if(this.update.firstChild && this.update.down().childNodes) {
  256. this.entryCount =
  257. this.update.down().childNodes.length;
  258. for (var i = 0; i < this.entryCount; i++) {
  259. var entry = this.getEntry(i);
  260. entry.autocompleteIndex = i;
  261. this.addObservers(entry);
  262. }
  263. } else {
  264. this.entryCount = 0;
  265. }
  266. this.stopIndicator();
  267. this.index = 0;
  268. if(this.entryCount==1 && this.options.autoSelect) {
  269. this.selectEntry();
  270. this.hide();
  271. } else {
  272. this.render();
  273. }
  274. }
  275. },
  276. addObservers: function(element) {
  277. Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
  278. Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  279. },
  280. onObserverEvent: function() {
  281. this.changed = false;
  282. this.tokenBounds = null;
  283. if(this.getToken().length>=this.options.minChars) {
  284. this.getUpdatedChoices();
  285. } else {
  286. this.active = false;
  287. this.hide();
  288. }
  289. this.oldElementValue = this.element.value;
  290. },
  291. getToken: function() {
  292. var bounds = this.getTokenBounds();
  293. return this.element.value.substring(bounds[0], bounds[1]).strip();
  294. },
  295. getTokenBounds: function() {
  296. if (null != this.tokenBounds) return this.tokenBounds;
  297. var value = this.element.value;
  298. if (value.strip().empty()) return [-1, 0];
  299. var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
  300. var offset = (diff == this.oldElementValue.length ? 1 : 0);
  301. var prevTokenPos = -1, nextTokenPos = value.length;
  302. var tp;
  303. for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
  304. tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
  305. if (tp > prevTokenPos) prevTokenPos = tp;
  306. tp = value.indexOf(this.options.tokens[index], diff + offset);
  307. if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
  308. }
  309. return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  310. }
  311. });
  312. Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  313. var boundary = Math.min(newS.length, oldS.length);
  314. for (var index = 0; index < boundary; ++index)
  315. if (newS[index] != oldS[index])
  316. return index;
  317. return boundary;
  318. };
  319. Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  320. initialize: function(element, update, url, options) {
  321. this.baseInitialize(element, update, options);
  322. this.options.asynchronous = true;
  323. this.options.onComplete = this.onComplete.bind(this);
  324. this.options.defaultParams = this.options.parameters || null;
  325. this.url = url;
  326. },
  327. getUpdatedChoices: function() {
  328. this.startIndicator();
  329. var entry = encodeURIComponent(this.options.paramName) + '=' +
  330. encodeURIComponent(this.getToken());
  331. this.options.parameters = this.options.callback ?
  332. this.options.callback(this.element, entry) : entry;
  333. if(this.options.defaultParams)
  334. this.options.parameters += '&' + this.options.defaultParams;
  335. new Ajax.Request(this.url, this.options);
  336. },
  337. onComplete: function(request) {
  338. this.updateChoices(request.responseText);
  339. }
  340. });
  341. // The local array autocompleter. Used when you'd prefer to
  342. // inject an array of autocompletion options into the page, rather
  343. // than sending out Ajax queries, which can be quite slow sometimes.
  344. //
  345. // The constructor takes four parameters. The first two are, as usual,
  346. // the id of the monitored textbox, and id of the autocompletion menu.
  347. // The third is the array you want to autocomplete from, and the fourth
  348. // is the options block.
  349. //
  350. // Extra local autocompletion options:
  351. // - choices - How many autocompletion choices to offer
  352. //
  353. // - partialSearch - If false, the autocompleter will match entered
  354. // text only at the beginning of strings in the
  355. // autocomplete array. Defaults to true, which will
  356. // match text at the beginning of any *word* in the
  357. // strings in the autocomplete array. If you want to
  358. // search anywhere in the string, additionally set
  359. // the option fullSearch to true (default: off).
  360. //
  361. // - fullSsearch - Search anywhere in autocomplete array strings.
  362. //
  363. // - partialChars - How many characters to enter before triggering
  364. // a partial match (unlike minChars, which defines
  365. // how many characters are required to do any match
  366. // at all). Defaults to 2.
  367. //
  368. // - ignoreCase - Whether to ignore case when autocompleting.
  369. // Defaults to true.
  370. //
  371. // It's possible to pass in a custom function as the 'selector'
  372. // option, if you prefer to write your own autocompletion logic.
  373. // In that case, the other options above will not apply unless
  374. // you support them.
  375. Autocompleter.Local = Class.create(Autocompleter.Base, {
  376. initialize: function(element, update, array, options) {
  377. this.baseInitialize(element, update, options);
  378. this.options.array = array;
  379. },
  380. getUpdatedChoices: function() {
  381. this.updateChoices(this.options.selector(this));
  382. },
  383. setOptions: function(options) {
  384. this.options = Object.extend({
  385. choices: 10,
  386. partialSearch: true,
  387. partialChars: 2,
  388. ignoreCase: true,
  389. fullSearch: false,
  390. selector: function(instance) {
  391. var ret = []; // Beginning matches
  392. var partial = []; // Inside matches
  393. var entry = instance.getToken();
  394. var count = 0;
  395. for (var i = 0; i < instance.options.array.length &&
  396. ret.length < instance.options.choices ; i++) {
  397. var elem = instance.options.array[i];
  398. var foundPos = instance.options.ignoreCase ?
  399. elem.toLowerCase().indexOf(entry.toLowerCase()) :
  400. elem.indexOf(entry);
  401. while (foundPos != -1) {
  402. if (foundPos == 0 && elem.length != entry.length) {
  403. ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
  404. elem.substr(entry.length) + "</li>");
  405. break;
  406. } else if (entry.length >= instance.options.partialChars &&
  407. instance.options.partialSearch && foundPos != -1) {
  408. if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
  409. partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
  410. elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
  411. foundPos + entry.length) + "</li>");
  412. break;
  413. }
  414. }
  415. foundPos = instance.options.ignoreCase ?
  416. elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
  417. elem.indexOf(entry, foundPos + 1);
  418. }
  419. }
  420. if (partial.length)
  421. ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
  422. return "<ul>" + ret.join('') + "</ul>";
  423. }
  424. }, options || { });
  425. }
  426. });
  427. // AJAX in-place editor and collection editor
  428. // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
  429. // Use this if you notice weird scrolling problems on some browsers,
  430. // the DOM might be a bit confused when this gets called so do this
  431. // waits 1 ms (with setTimeout) until it does the activation
  432. Field.scrollFreeActivate = function(field) {
  433. setTimeout(function() {
  434. Field.activate(field);
  435. }, 1);
  436. };
  437. Ajax.InPlaceEditor = Class.create({
  438. initialize: function(element, url, options) {
  439. this.url = url;
  440. this.element = element = $(element);
  441. this.prepareOptions();
  442. this._controls = { };
  443. arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
  444. Object.extend(this.options, options || { });
  445. if (!this.options.formId && this.element.id) {
  446. this.options.formId = this.element.id + '-inplaceeditor';
  447. if ($(this.options.formId))
  448. this.options.formId = '';
  449. }
  450. if (this.options.externalControl)
  451. this.options.externalControl = $(this.options.externalControl);
  452. if (!this.options.externalControl)
  453. this.options.externalControlOnly = false;
  454. this._originalBackground = this.element.getStyle('background-color') || 'transparent';
  455. this.element.title = this.options.clickToEditText;
  456. this._boundCancelHandler = this.handleFormCancellation.bind(this);
  457. this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
  458. this._boundFailureHandler = this.handleAJAXFailure.bind(this);
  459. this._boundSubmitHandler = this.handleFormSubmission.bind(this);
  460. this._boundWrapperHandler = this.wrapUp.bind(this);
  461. this.registerListeners();
  462. },
  463. checkForEscapeOrReturn: function(e) {
  464. if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
  465. if (Event.KEY_ESC == e.keyCode)
  466. this.handleFormCancellation(e);
  467. else if (Event.KEY_RETURN == e.keyCode)
  468. this.handleFormSubmission(e);
  469. },
  470. createControl: function(mode, handler, extraClasses) {
  471. var control = this.options[mode + 'Control'];
  472. var text = this.options[mode + 'Text'];
  473. if ('button' == control) {
  474. var btn = document.createElement('input');
  475. btn.type = 'submit';
  476. btn.value = text;
  477. btn.className = 'editor_' + mode + '_button';
  478. if ('cancel' == mode)
  479. btn.onclick = this._boundCancelHandler;
  480. this._form.appendChild(btn);
  481. this._controls[mode] = btn;
  482. } else if ('link' == control) {
  483. var link = document.createElement('a');
  484. link.href = '#';
  485. link.appendChild(document.createTextNode(text));
  486. link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
  487. link.className = 'editor_' + mode + '_link';
  488. if (extraClasses)
  489. link.className += ' ' + extraClasses;
  490. this._form.appendChild(link);
  491. this._controls[mode] = link;
  492. }
  493. },
  494. createEditField: function() {
  495. var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
  496. var fld;
  497. if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
  498. fld = document.createElement('input');
  499. fld.type = 'text';
  500. var size = this.options.size || this.options.cols || 0;
  501. if (0 < size) fld.size = size;
  502. } else {
  503. fld = document.createElement('textarea');
  504. fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
  505. fld.cols = this.options.cols || 40;
  506. }
  507. fld.name = this.options.paramName;
  508. fld.value = text; // No HTML breaks conversion anymore
  509. fld.className = 'editor_field';
  510. if (this.options.submitOnBlur)
  511. fld.onblur = this._boundSubmitHandler;
  512. this._controls.editor = fld;
  513. if (this.options.loadTextURL)
  514. this.loadExternalText();
  515. this._form.appendChild(this._controls.editor);
  516. },
  517. createForm: function() {
  518. var ipe = this;
  519. function addText(mode, condition) {
  520. var text = ipe.options['text' + mode + 'Controls'];
  521. if (!text || condition === false) return;
  522. ipe._form.appendChild(document.createTextNode(text));
  523. };
  524. this._form = $(document.createElement('form'));
  525. this._form.id = this.options.formId;
  526. this._form.addClassName(this.options.formClassName);
  527. this._form.onsubmit = this._boundSubmitHandler;
  528. this.createEditField();
  529. if ('textarea' == this._controls.editor.tagName.toLowerCase())
  530. this._form.appendChild(document.createElement('br'));
  531. if (this.options.onFormCustomization)
  532. this.options.onFormCustomization(this, this._form);
  533. addText('Before', this.options.okControl || this.options.cancelControl);
  534. this.createControl('ok', this._boundSubmitHandler);
  535. addText('Between', this.options.okControl && this.options.cancelControl);
  536. this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
  537. addText('After', this.options.okControl || this.options.cancelControl);
  538. },
  539. destroy: function() {
  540. if (this._oldInnerHTML)
  541. this.element.innerHTML = this._oldInnerHTML;
  542. this.leaveEditMode();
  543. this.unregisterListeners();
  544. },
  545. enterEditMode: function(e) {
  546. if (this._saving || this._editing) return;
  547. this._editing = true;
  548. this.triggerCallback('onEnterEditMode');
  549. if (this.options.externalControl)
  550. this.options.externalControl.hide();
  551. this.element.hide();
  552. this.createForm();
  553. this.element.parentNode.insertBefore(this._form, this.element);
  554. if (!this.options.loadTextURL)
  555. this.postProcessEditField();
  556. if (e) Event.stop(e);
  557. },
  558. enterHover: function(e) {
  559. if (this.options.hoverClassName)
  560. this.element.addClassName(this.options.hoverClassName);
  561. if (this._saving) return;
  562. this.triggerCallback('onEnterHover');
  563. },
  564. getText: function() {
  565. return this.element.innerHTML.unescapeHTML();
  566. },
  567. handleAJAXFailure: function(transport) {
  568. this.triggerCallback('onFailure', transport);
  569. if (this._oldInnerHTML) {
  570. this.element.innerHTML = this._oldInnerHTML;
  571. this._oldInnerHTML = null;
  572. }
  573. },
  574. handleFormCancellation: function(e) {
  575. this.wrapUp();
  576. if (e) Event.stop(e);
  577. },
  578. handleFormSubmission: function(e) {
  579. var form = this._form;
  580. var value = $F(this._controls.editor);
  581. this.prepareSubmission();
  582. var params = this.options.callback(form, value) || '';
  583. if (Object.isString(params))
  584. params = params.toQueryParams();
  585. params.editorId = this.element.id;
  586. if (this.options.htmlResponse) {
  587. var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
  588. Object.extend(options, {
  589. parameters: params,
  590. onComplete: this._boundWrapperHandler,
  591. onFailure: this._boundFailureHandler
  592. });
  593. new Ajax.Updater({ success: this.element }, this.url, options);
  594. } else {
  595. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  596. Object.extend(options, {
  597. parameters: params,
  598. onComplete: this._boundWrapperHandler,
  599. onFailure: this._boundFailureHandler
  600. });
  601. new Ajax.Request(this.url, options);
  602. }
  603. if (e) Event.stop(e);
  604. },
  605. leaveEditMode: function() {
  606. this.element.removeClassName(this.options.savingClassName);
  607. this.removeForm();
  608. this.leaveHover();
  609. this.element.style.backgroundColor = this._originalBackground;
  610. this.element.show();
  611. if (this.options.externalControl)
  612. this.options.externalControl.show();
  613. this._saving = false;
  614. this._editing = false;
  615. this._oldInnerHTML = null;
  616. this.triggerCallback('onLeaveEditMode');
  617. },
  618. leaveHover: function(e) {
  619. if (this.options.hoverClassName)
  620. this.element.removeClassName(this.options.hoverClassName);
  621. if (this._saving) return;
  622. this.triggerCallback('onLeaveHover');
  623. },
  624. loadExternalText: function() {
  625. this._form.addClassName(this.options.loadingClassName);
  626. this._controls.editor.disabled = true;
  627. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  628. Object.extend(options, {
  629. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  630. onComplete: Prototype.emptyFunction,
  631. onSuccess: function(transport) {
  632. this._form.removeClassName(this.options.loadingClassName);
  633. var text = transport.responseText;
  634. if (this.options.stripLoadedTextTags)
  635. text = text.stripTags();
  636. this._controls.editor.value = text;
  637. this._controls.editor.disabled = false;
  638. this.postProcessEditField();
  639. }.bind(this),
  640. onFailure: this._boundFailureHandler
  641. });
  642. new Ajax.Request(this.options.loadTextURL, options);
  643. },
  644. postProcessEditField: function() {
  645. var fpc = this.options.fieldPostCreation;
  646. if (fpc)
  647. $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
  648. },
  649. prepareOptions: function() {
  650. this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
  651. Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
  652. [this._extraDefaultOptions].flatten().compact().each(function(defs) {
  653. Object.extend(this.options, defs);
  654. }.bind(this));
  655. },
  656. prepareSubmission: function() {
  657. this._saving = true;
  658. this.removeForm();
  659. this.leaveHover();
  660. this.showSaving();
  661. },
  662. registerListeners: function() {
  663. this._listeners = { };
  664. var listener;
  665. $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
  666. listener = this[pair.value].bind(this);
  667. this._listeners[pair.key] = listener;
  668. if (!this.options.externalControlOnly)
  669. this.element.observe(pair.key, listener);
  670. if (this.options.externalControl)
  671. this.options.externalControl.observe(pair.key, listener);
  672. }.bind(this));
  673. },
  674. removeForm: function() {
  675. if (!this._form) return;
  676. this._form.remove();
  677. this._form = null;
  678. this._controls = { };
  679. },
  680. showSaving: function() {
  681. this._oldInnerHTML = this.element.innerHTML;
  682. this.element.innerHTML = this.options.savingText;
  683. this.element.addClassName(this.options.savingClassName);
  684. this.element.style.backgroundColor = this._originalBackground;
  685. this.element.show();
  686. },
  687. triggerCallback: function(cbName, arg) {
  688. if ('function' == typeof this.options[cbName]) {
  689. this.options[cbName](this, arg);
  690. }
  691. },
  692. unregisterListeners: function() {
  693. $H(this._listeners).each(function(pair) {
  694. if (!this.options.externalControlOnly)
  695. this.element.stopObserving(pair.key, pair.value);
  696. if (this.options.externalControl)
  697. this.options.externalControl.stopObserving(pair.key, pair.value);
  698. }.bind(this));
  699. },
  700. wrapUp: function(transport) {
  701. this.leaveEditMode();
  702. // Can't use triggerCallback due to backward compatibility: requires
  703. // binding + direct element
  704. this._boundComplete(transport, this.element);
  705. }
  706. });
  707. Object.extend(Ajax.InPlaceEditor.prototype, {
  708. dispose: Ajax.InPlaceEditor.prototype.destroy
  709. });
  710. Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
  711. initialize: function($super, element, url, options) {
  712. this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
  713. $super(element, url, options);
  714. },
  715. createEditField: function() {
  716. var list = document.createElement('select');
  717. list.name = this.options.paramName;
  718. list.size = 1;
  719. this._controls.editor = list;
  720. this._collection = this.options.collection || [];
  721. if (this.options.loadCollectionURL)
  722. this.loadCollection();
  723. else
  724. this.checkForExternalText();
  725. this._form.appendChild(this._controls.editor);
  726. },
  727. loadCollection: function() {
  728. this._form.addClassName(this.options.loadingClassName);
  729. this.showLoadingText(this.options.loadingCollectionText);
  730. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  731. Object.extend(options, {
  732. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  733. onComplete: Prototype.emptyFunction,
  734. onSuccess: function(transport) {
  735. var js = transport.responseText.strip();
  736. if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
  737. throw('Server returned an invalid collection representation.');
  738. this._collection = eval(js);
  739. this.checkForExternalText();
  740. }.bind(this),
  741. onFailure: this.onFailure
  742. });
  743. new Ajax.Request(this.options.loadCollectionURL, options);
  744. },
  745. showLoadingText: function(text) {
  746. this._controls.editor.disabled = true;
  747. var tempOption = this._controls.editor.firstChild;
  748. if (!tempOption) {
  749. tempOption = document.createElement('option');
  750. tempOption.value = '';
  751. this._controls.editor.appendChild(tempOption);
  752. tempOption.selected = true;
  753. }
  754. tempOption.update((text || '').stripScripts().stripTags());
  755. },
  756. checkForExternalText: function() {
  757. this._text = this.getText();
  758. if (this.options.loadTextURL)
  759. this.loadExternalText();
  760. else
  761. this.buildOptionList();
  762. },
  763. loadExternalText: function() {
  764. this.showLoadingText(this.options.loadingText);
  765. var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
  766. Object.extend(options, {
  767. parameters: 'editorId=' + encodeURIComponent(this.element.id),
  768. onComplete: Prototype.emptyFunction,
  769. onSuccess: function(transport) {
  770. this._text = transport.responseText.strip();
  771. this.buildOptionList();
  772. }.bind(this),
  773. onFailure: this.onFailure
  774. });
  775. new Ajax.Request(this.options.loadTextURL, options);
  776. },
  777. buildOptionList: function() {
  778. this._form.removeClassName(this.options.loadingClassName);
  779. this._collection = this._collection.map(function(entry) {
  780. return 2 === entry.length ? entry : [entry, entry].flatten();
  781. });
  782. var marker = ('value' in this.options) ? this.options.value : this._text;
  783. var textFound = this._collection.any(function(entry) {
  784. return entry[0] == marker;
  785. }.bind(this));
  786. this._controls.editor.update('');
  787. var option;
  788. this._collection.each(function(entry, index) {
  789. option = document.createElement('option');
  790. option.value = entry[0];
  791. option.selected = textFound ? entry[0] == marker : 0 == index;
  792. option.appendChild(document.createTextNode(entry[1]));
  793. this._controls.editor.appendChild(option);
  794. }.bind(this));
  795. this._controls.editor.disabled = false;
  796. Field.scrollFreeActivate(this._controls.editor);
  797. }
  798. });
  799. //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
  800. //**** This only exists for a while, in order to let ****
  801. //**** users adapt to the new API. Read up on the new ****
  802. //**** API and convert your code to it ASAP! ****
  803. Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
  804. if (!options) return;
  805. function fallback(name, expr) {
  806. if (name in options || expr === undefined) return;
  807. options[name] = expr;
  808. };
  809. fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
  810. options.cancelLink == options.cancelButton == false ? false : undefined)));
  811. fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
  812. options.okLink == options.okButton == false ? false : undefined)));
  813. fallback('highlightColor', options.highlightcolor);
  814. fallback('highlightEndColor', options.highlightendcolor);
  815. };
  816. Object.extend(Ajax.InPlaceEditor, {
  817. DefaultOptions: {
  818. ajaxOptions: { },
  819. autoRows: 3, // Use when multi-line w/ rows == 1
  820. cancelControl: 'link', // 'link'|'button'|false
  821. cancelText: 'cancel',
  822. clickToEditText: 'Click to edit',
  823. externalControl: null, // id|elt
  824. externalControlOnly: false,
  825. fieldPostCreation: 'activate', // 'activate'|'focus'|false
  826. formClassName: 'inplaceeditor-form',
  827. formId: null, // id|elt
  828. highlightColor: '#ffff99',
  829. highlightEndColor: '#ffffff',
  830. hoverClassName: '',
  831. htmlResponse: true,
  832. loadingClassName: 'inplaceeditor-loading',
  833. loadingText: 'Loading...',
  834. okControl: 'button', // 'link'|'button'|false
  835. okText: 'ok',
  836. paramName: 'value',
  837. rows: 1, // If 1 and multi-line, uses autoRows
  838. savingClassName: 'inplaceeditor-saving',
  839. savingText: 'Saving...',
  840. size: 0,
  841. stripLoadedTextTags: false,
  842. submitOnBlur: false,
  843. textAfterControls: '',
  844. textBeforeControls: '',
  845. textBetweenControls: ''
  846. },
  847. DefaultCallbacks: {
  848. callback: function(form) {
  849. return Form.serialize(form);
  850. },
  851. onComplete: function(transport, element) {
  852. // For backward compatibility, this one is bound to the IPE, and passes
  853. // the element directly. It was too often customized, so we don't break it.
  854. new Effect.Highlight(element, {
  855. startcolor: this.options.highlightColor, keepBackgroundImage: true });
  856. },
  857. onEnterEditMode: null,
  858. onEnterHover: function(ipe) {
  859. ipe.element.style.backgroundColor = ipe.options.highlightColor;
  860. if (ipe._effect)
  861. ipe._effect.cancel();
  862. },
  863. onFailure: function(transport, ipe) {
  864. alert('Error communication with the server: ' + transport.responseText.stripTags());
  865. },
  866. onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
  867. onLeaveEditMode: null,
  868. onLeaveHover: function(ipe) {
  869. ipe._effect = new Effect.Highlight(ipe.element, {
  870. startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
  871. restorecolor: ipe._originalBackground, keepBackgroundImage: true
  872. });
  873. }
  874. },
  875. Listeners: {
  876. click: 'enterEditMode',
  877. keydown: 'checkForEscapeOrReturn',
  878. mouseover: 'enterHover',
  879. mouseout: 'leaveHover'
  880. }
  881. });
  882. Ajax.InPlaceCollectionEditor.DefaultOptions = {
  883. loadingCollectionText: 'Loading options...'
  884. };
  885. // Delayed observer, like Form.Element.Observer,
  886. // but waits for delay after last key input
  887. // Ideal for live-search fields
  888. Form.Element.DelayedObserver = Class.create({
  889. initialize: function(element, delay, callback) {
  890. this.delay = delay || 0.5;
  891. this.element = $(element);
  892. this.callback = callback;
  893. this.timer = null;
  894. this.lastValue = $F(this.element);
  895. Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
  896. },
  897. delayedListener: function(event) {
  898. if(this.lastValue == $F(this.element)) return;
  899. if(this.timer) clearTimeout(this.timer);
  900. this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
  901. this.lastValue = $F(this.element);
  902. },
  903. onTimerEvent: function() {
  904. this.timer = null;
  905. this.callback(this.element, $F(this.element));
  906. }
  907. });