controls.js 35 KB

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