Basic PHP document management system, including automatic detection of corporate logos in letters
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

controls.js 34KB

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