editor.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /**
  2. * Roundcube editor js library
  3. *
  4. * This file is part of the Roundcube Webmail client
  5. *
  6. * @licstart The following is the entire license notice for the
  7. * JavaScript code in this file.
  8. *
  9. * Copyright (c) 2006-2014, The Roundcube Dev Team
  10. *
  11. * The JavaScript code in this page is free software: you can
  12. * redistribute it and/or modify it under the terms of the GNU
  13. * General Public License (GNU GPL) as published by the Free Software
  14. * Foundation, either version 3 of the License, or (at your option)
  15. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  16. * without even the implied warranty of MERCHANTABILITY or FITNESS
  17. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  18. *
  19. * As additional permission under GNU GPL version 3 section 7, you
  20. * may distribute non-source (e.g., minimized or compacted) forms of
  21. * that code without the copy of the GNU GPL normally required by
  22. * section 4, provided you include this license notice and a URL
  23. * through which recipients can access the Corresponding Source.
  24. *
  25. * @licend The above is the entire license notice
  26. * for the JavaScript code in this file.
  27. *
  28. * @author Eric Stadtherr <estadtherr@gmail.com>
  29. * @author Aleksander Machniak <alec@alec.pl>
  30. */
  31. /**
  32. * Roundcube Text Editor Widget class
  33. * @constructor
  34. */
  35. function rcube_text_editor(config, id)
  36. {
  37. var ref = this,
  38. abs_url = location.href.replace(/[?#].*$/, '').replace(/\/$/, ''),
  39. conf = {
  40. selector: '#' + ($('#' + id).is('.mce_editor') ? id : 'fake-editor-id'),
  41. cache_suffix: 's=4050100',
  42. theme: 'modern',
  43. language: config.lang,
  44. content_css: rcmail.assets_path('program/resources/tinymce/content.css'),
  45. menubar: false,
  46. statusbar: false,
  47. toolbar_items_size: 'small',
  48. extended_valid_elements: 'font[face|size|color|style],span[id|class|align|style]',
  49. relative_urls: false,
  50. remove_script_host: false,
  51. convert_urls: false, // #1486944
  52. image_description: false,
  53. paste_webkit_style: "color font-size font-family",
  54. paste_data_images: true,
  55. browser_spellcheck: true
  56. };
  57. // register spellchecker for plain text editor
  58. this.spellcheck_observer = function() {};
  59. if (config.spellchecker) {
  60. this.spellchecker = config.spellchecker;
  61. if (config.spellcheck_observer) {
  62. this.spellchecker.spelling_state_observer = this.spellcheck_observer = config.spellcheck_observer;
  63. }
  64. }
  65. // secure spellchecker requests with Roundcube token
  66. // Note: must be registered only once (#1490311)
  67. if (!tinymce.registered_request_token) {
  68. tinymce.registered_request_token = true;
  69. tinymce.util.XHR.on('beforeSend', function(e) {
  70. e.xhr.setRequestHeader('X-Roundcube-Request', rcmail.env.request_token);
  71. });
  72. }
  73. // minimal editor
  74. if (config.mode == 'identity') {
  75. $.extend(conf, {
  76. plugins: 'autolink charmap code colorpicker hr image link paste tabfocus textcolor',
  77. toolbar: 'bold italic underline alignleft aligncenter alignright alignjustify'
  78. + ' | outdent indent charmap hr link unlink image code forecolor'
  79. + ' | fontselect fontsizeselect',
  80. file_browser_callback: function(name, url, type, win) { ref.file_browser_callback(name, url, type); },
  81. file_browser_callback_types: 'image'
  82. });
  83. }
  84. // full-featured editor
  85. else {
  86. $.extend(conf, {
  87. plugins: 'autolink charmap code colorpicker directionality link image media nonbreaking'
  88. + ' paste table tabfocus textcolor searchreplace spellchecker',
  89. toolbar: 'bold italic underline | alignleft aligncenter alignright alignjustify'
  90. + ' | bullist numlist outdent indent ltr rtl blockquote | forecolor backcolor | fontselect fontsizeselect'
  91. + ' | link unlink table | $extra charmap image media | code searchreplace undo redo',
  92. spellchecker_rpc_url: abs_url + '/?_task=utils&_action=spell_html&_remote=1',
  93. spellchecker_language: rcmail.env.spell_lang,
  94. accessibility_focus: false,
  95. file_browser_callback: function(name, url, type, win) { ref.file_browser_callback(name, url, type); },
  96. // @todo: support more than image (types: file, image, media)
  97. file_browser_callback_types: 'image media'
  98. });
  99. }
  100. // add TinyMCE plugins/buttons from Roundcube plugin
  101. $.each(config.extra_plugins || [], function() {
  102. if (conf.plugins.indexOf(this) < 0)
  103. conf.plugins = conf.plugins + ' ' + this;
  104. });
  105. $.each(config.extra_buttons || [], function() {
  106. if (conf.toolbar.indexOf(this) < 0)
  107. conf.toolbar = conf.toolbar.replace('$extra', '$extra ' + this);
  108. });
  109. // disable TinyMCE plugins/buttons from Roundcube plugin
  110. $.each(config.disabled_plugins || [], function() {
  111. conf.plugins = conf.plugins.replace(this, '');
  112. });
  113. $.each(config.disabled_buttons || [], function() {
  114. conf.toolbar = conf.toolbar.replace(this, '');
  115. });
  116. conf.toolbar = conf.toolbar.replace('$extra', '').replace(/\|\s+\|/g, '|');
  117. // support external configuration settings e.g. from skin
  118. if (window.rcmail_editor_settings)
  119. $.extend(conf, window.rcmail_editor_settings);
  120. conf.setup = function(ed) {
  121. ed.on('init', function(ed) { ref.init_callback(ed); });
  122. // add handler for spellcheck button state update
  123. ed.on('SpellcheckStart SpellcheckEnd', function(args) {
  124. ref.spellcheck_active = args.type == 'spellcheckstart';
  125. ref.spellcheck_observer();
  126. });
  127. ed.on('keypress', function() {
  128. rcmail.compose_type_activity++;
  129. });
  130. };
  131. // textarea identifier
  132. this.id = id;
  133. // reference to active editor (if in HTML mode)
  134. this.editor = null;
  135. tinymce.init(conf);
  136. // react to real individual tinyMCE editor init
  137. this.init_callback = function(event)
  138. {
  139. this.editor = event.target;
  140. if (rcmail.env.action != 'compose') {
  141. return;
  142. }
  143. var area = $('#' + this.id),
  144. height = $('div.mce-toolbar-grp:first', area.parent()).height();
  145. // the editor might be still not fully loaded, making the editing area
  146. // inaccessible, wait and try again (#1490310)
  147. if (height > 200 || height > area.height()) {
  148. return setTimeout(function () { ref.init_callback(event); }, 300);
  149. }
  150. var css = {},
  151. elem = rcube_find_object('_from'),
  152. fe = rcmail.env.compose_focus_elem;
  153. if (rcmail.env.default_font)
  154. css['font-family'] = rcmail.env.default_font;
  155. if (rcmail.env.default_font_size)
  156. css['font-size'] = rcmail.env.default_font_size;
  157. if (css['font-family'] || css['font-size'])
  158. $(this.editor.getBody()).css(css);
  159. if (elem && elem.type == 'select-one') {
  160. // insert signature (only for the first time)
  161. if (!rcmail.env.identities_initialized)
  162. rcmail.change_identity(elem);
  163. // Focus previously focused element
  164. if (fe && fe.id != this.id) {
  165. window.focus(); // for WebKit (#1486674)
  166. fe.focus();
  167. rcmail.env.compose_focus_elem = null;
  168. }
  169. }
  170. // set tabIndex and set focus to element that was focused before
  171. ref.tabindex(fe && fe.id == ref.id);
  172. // Trigger resize (needed for proper editor resizing in some browsers)
  173. $(window).resize();
  174. };
  175. // set tabIndex on tinymce editor
  176. this.tabindex = function(focus)
  177. {
  178. if (rcmail.env.task == 'mail' && this.editor) {
  179. var textarea = this.editor.getElement(),
  180. body = this.editor.getBody(),
  181. node = this.editor.getContentAreaContainer().childNodes[0];
  182. if (textarea && node)
  183. node.tabIndex = textarea.tabIndex;
  184. // find :prev and :next elements to get focus when tabbing away
  185. if (textarea.tabIndex > 0) {
  186. var x = null,
  187. tabfocus_elements = [':prev',':next'],
  188. el = tinymce.DOM.select('*[tabindex='+textarea.tabIndex+']:not(iframe)');
  189. tinymce.each(el, function(e, i) { if (e.id == ref.id) { x = i; return false; } });
  190. if (x !== null) {
  191. if (el[x-1] && el[x-1].id) {
  192. tabfocus_elements[0] = el[x-1].id;
  193. }
  194. if (el[x+1] && el[x+1].id) {
  195. tabfocus_elements[1] = el[x+1].id;
  196. }
  197. this.editor.settings.tabfocus_elements = tabfocus_elements.join(',');
  198. }
  199. }
  200. // ContentEditable reset fixes invisible cursor issue in Firefox < 25
  201. if (bw.mz && bw.vendver < 25)
  202. $(body).prop('contenteditable', false).prop('contenteditable', true);
  203. if (focus)
  204. body.focus();
  205. }
  206. };
  207. // switch html/plain mode
  208. this.toggle = function(ishtml, noconvert)
  209. {
  210. var curr, content, result,
  211. // these non-printable chars are not removed on text2html and html2text
  212. // we can use them as temp signature replacement
  213. sig_mark = "\u0002\u0003",
  214. input = $('#' + this.id),
  215. signature = rcmail.env.identity ? rcmail.env.signatures[rcmail.env.identity] : null,
  216. is_sig = signature && signature.text && signature.text.length > 1;
  217. // apply spellcheck changes if spell checker is active
  218. this.spellcheck_stop();
  219. if (ishtml) {
  220. content = input.val();
  221. // replace current text signature with temp mark
  222. if (is_sig) {
  223. content = content.replace(/\r\n/, "\n");
  224. content = content.replace(signature.text.replace(/\r\n/, "\n"), sig_mark);
  225. }
  226. var init_editor = function(data) {
  227. // replace signature mark with html version of the signature
  228. if (is_sig)
  229. data = data.replace(sig_mark, '<div id="_rc_sig">' + signature.html + '</div>');
  230. input.val(data);
  231. tinymce.execCommand('mceAddEditor', false, ref.id);
  232. if (ref.editor) {
  233. var body = $(ref.editor.getBody());
  234. // #1486593
  235. ref.tabindex(true);
  236. // put cursor on start of the compose body
  237. ref.editor.selection.setCursorLocation(body.children().first().get(0));
  238. }
  239. };
  240. // convert to html
  241. if (!noconvert) {
  242. result = rcmail.plain2html(content, init_editor);
  243. }
  244. else {
  245. init_editor(content);
  246. result = true;
  247. }
  248. }
  249. else if (this.editor) {
  250. if (is_sig) {
  251. // get current version of signature, we'll need it in
  252. // case of html2text conversion abort
  253. if (curr = this.editor.dom.get('_rc_sig'))
  254. curr = curr.innerHTML;
  255. // replace current signature with some non-printable characters
  256. // we use non-printable characters, because this replacement
  257. // is visible to the user
  258. // doing this after getContent() would be hard
  259. this.editor.dom.setHTML('_rc_sig', sig_mark);
  260. }
  261. // get html content
  262. content = this.editor.getContent();
  263. var init_plaintext = function(data) {
  264. tinymce.execCommand('mceRemoveEditor', false, ref.id);
  265. ref.editor = null;
  266. // replace signture mark with text version of the signature
  267. if (is_sig)
  268. data = data.replace(sig_mark, "\n" + signature.text);
  269. input.val(data).focus();
  270. rcmail.set_caret_pos(input.get(0), 0);
  271. };
  272. // convert html to text
  273. if (!noconvert) {
  274. result = rcmail.html2plain(content, init_plaintext);
  275. }
  276. else {
  277. init_plaintext(input.val());
  278. result = true;
  279. }
  280. // bring back current signature
  281. if (!result && curr)
  282. this.editor.dom.setHTML('_rc_sig', curr);
  283. }
  284. return result;
  285. };
  286. // start spellchecker
  287. this.spellcheck_start = function()
  288. {
  289. if (this.editor) {
  290. tinymce.execCommand('mceSpellCheck', true);
  291. this.spellcheck_observer();
  292. }
  293. else if (this.spellchecker && this.spellchecker.spellCheck) {
  294. this.spellchecker.spellCheck();
  295. }
  296. };
  297. // stop spellchecker
  298. this.spellcheck_stop = function()
  299. {
  300. var ed = this.editor;
  301. if (ed) {
  302. if (ed.plugins && ed.plugins.spellchecker && this.spellcheck_active) {
  303. ed.execCommand('mceSpellCheck', false);
  304. this.spellcheck_observer();
  305. }
  306. }
  307. else if (ed = this.spellchecker) {
  308. if (ed.state && ed.state != 'ready' && ed.state != 'no_error_found')
  309. $(ed.spell_span).trigger('click');
  310. }
  311. };
  312. // spellchecker state
  313. this.spellcheck_state = function()
  314. {
  315. var ed;
  316. if (this.editor)
  317. return this.spellcheck_active;
  318. else if ((ed = this.spellchecker) && ed.state)
  319. return ed.state != 'ready' && ed.state != 'no_error_found';
  320. };
  321. // resume spellchecking, highlight provided mispellings without a new ajax request
  322. this.spellcheck_resume = function(data)
  323. {
  324. var ed = this.editor;
  325. if (ed) {
  326. ed.plugins.spellchecker.markErrors(data);
  327. }
  328. else if (ed = this.spellchecker) {
  329. ed.prepare(false, true);
  330. ed.processData(data);
  331. }
  332. };
  333. // get selected (spellcheker) language
  334. this.get_language = function()
  335. {
  336. if (this.editor) {
  337. return this.editor.settings.spellchecker_language || rcmail.env.spell_lang;
  338. }
  339. else if (this.spellchecker) {
  340. return GOOGIE_CUR_LANG;
  341. }
  342. };
  343. // set language for spellchecking
  344. this.set_language = function(lang)
  345. {
  346. var ed = this.editor;
  347. if (ed) {
  348. ed.settings.spellchecker_language = lang;
  349. }
  350. if (ed = this.spellchecker) {
  351. ed.setCurrentLanguage(lang);
  352. }
  353. };
  354. // replace selection with text snippet
  355. // input can be a string or object with 'text' and 'html' properties
  356. this.replace = function(input)
  357. {
  358. var format, ed = this.editor;
  359. if (!input)
  360. return false;
  361. // insert into tinymce editor
  362. if (ed) {
  363. ed.getWin().focus(); // correct focus in IE & Chrome
  364. if ($.type(input) == 'object' && ('html' in input)) {
  365. input = input.html;
  366. format = 'html';
  367. }
  368. else {
  369. if ($.type(input) == 'object')
  370. input = input.text || '';
  371. input = rcmail.quote_html(input).replace(/\r?\n/g, '<br/>');
  372. format = 'text';
  373. }
  374. ed.selection.setContent(input, {format: format});
  375. }
  376. // replace selection in compose textarea
  377. else if (ed = rcube_find_object(this.id)) {
  378. var selection = $(ed).is(':focus') ? rcmail.get_input_selection(ed) : {start: 0, end: 0},
  379. value = ed.value;
  380. pre = value.substring(0, selection.start),
  381. end = value.substring(selection.end, value.length);
  382. if ($.type(input) == 'object')
  383. input = input.text || '';
  384. // insert response text
  385. ed.value = pre + input + end;
  386. // set caret after inserted text
  387. rcmail.set_caret_pos(ed, selection.start + input.length);
  388. ed.focus();
  389. }
  390. };
  391. // get selected text (if no selection returns all text) from the editor
  392. this.get_content = function(args)
  393. {
  394. var sigstart, ed = this.editor, text = '', strip = false,
  395. defaults = {refresh: true, selection: false, nosig: false, format: 'html'};
  396. args = $.extend(defaults, args);
  397. // apply spellcheck changes if spell checker is active
  398. if (args.refresh) {
  399. this.spellcheck_stop();
  400. }
  401. // get selected text from tinymce editor
  402. if (ed) {
  403. if (args.selection)
  404. text = ed.selection.getContent({format: args.format});
  405. if (!text) {
  406. text = ed.getContent({format: args.format});
  407. // @todo: strip signature in html mode
  408. strip = args.format == 'text';
  409. }
  410. }
  411. // get selected text from compose textarea
  412. else if (ed = rcube_find_object(this.id)) {
  413. if (args.selection && $(ed).is(':focus')) {
  414. text = rcmail.get_input_selection(ed).text;
  415. }
  416. if (!text) {
  417. text = ed.value;
  418. strip = true;
  419. }
  420. }
  421. // strip off signature
  422. // @todo: make this optional
  423. if (strip && args.nosig) {
  424. sigstart = text.indexOf('-- \n');
  425. if (sigstart > 0) {
  426. text = text.substring(0, sigstart);
  427. }
  428. }
  429. return text;
  430. };
  431. // change user signature text
  432. this.change_signature = function(id, show_sig)
  433. {
  434. var position_element, cursor_pos, p = -1,
  435. input_message = $('#' + this.id),
  436. message = input_message.val(),
  437. sig = rcmail.env.identity;
  438. if (!this.editor) { // plain text mode
  439. // remove the 'old' signature
  440. if (show_sig && sig && rcmail.env.signatures && rcmail.env.signatures[sig]) {
  441. sig = rcmail.env.signatures[sig].text;
  442. sig = sig.replace(/\r\n/g, '\n');
  443. p = rcmail.env.top_posting ? message.indexOf(sig) : message.lastIndexOf(sig);
  444. if (p >= 0)
  445. message = message.substring(0, p) + message.substring(p+sig.length, message.length);
  446. }
  447. // add the new signature string
  448. if (show_sig && rcmail.env.signatures && rcmail.env.signatures[id]) {
  449. sig = rcmail.env.signatures[id].text;
  450. sig = sig.replace(/\r\n/g, '\n');
  451. // in place of removed signature
  452. if (p >= 0) {
  453. message = message.substring(0, p) + sig + message.substring(p, message.length);
  454. cursor_pos = p - 1;
  455. }
  456. // empty message or new-message mode
  457. else if (!message || !rcmail.env.compose_mode) {
  458. cursor_pos = message.length;
  459. message += '\n\n' + sig;
  460. }
  461. else if (rcmail.env.top_posting && !rcmail.env.sig_below) {
  462. // at cursor position
  463. if (pos = rcmail.get_caret_pos(input_message.get(0))) {
  464. message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
  465. cursor_pos = pos;
  466. }
  467. // on top
  468. else {
  469. message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
  470. cursor_pos = 0;
  471. }
  472. }
  473. else {
  474. message = message.replace(/[\r\n]+$/, '');
  475. cursor_pos = !rcmail.env.top_posting && message.length ? message.length + 1 : 0;
  476. message += '\n\n' + sig;
  477. }
  478. }
  479. else {
  480. cursor_pos = rcmail.env.top_posting ? 0 : message.length;
  481. }
  482. input_message.val(message);
  483. // move cursor before the signature
  484. rcmail.set_caret_pos(input_message.get(0), cursor_pos);
  485. }
  486. else if (show_sig && rcmail.env.signatures) { // html
  487. var sigElem = this.editor.dom.get('_rc_sig');
  488. // Append the signature as a div within the body
  489. if (!sigElem) {
  490. var body = this.editor.getBody();
  491. sigElem = $('<div id="_rc_sig"></div>').get(0);
  492. // insert at start or at cursor position in top-posting mode
  493. // (but not if the content is empty and not in new-message mode)
  494. if (rcmail.env.top_posting && !rcmail.env.sig_below
  495. && rcmail.env.compose_mode && (body.childNodes.length > 1 || $(body).text())
  496. ) {
  497. this.editor.getWin().focus(); // correct focus in IE & Chrome
  498. var node = this.editor.selection.getNode();
  499. $(sigElem).insertBefore(node.nodeName == 'BODY' ? body.firstChild : node.nextSibling);
  500. $('<p>').append($('<br>')).insertBefore(sigElem);
  501. }
  502. else {
  503. body.appendChild(sigElem);
  504. position_element = rcmail.env.top_posting && rcmail.env.compose_mode ? body.firstChild : $(sigElem).prev();
  505. }
  506. }
  507. sigElem.innerHTML = rcmail.env.signatures[id] ? rcmail.env.signatures[id].html : '';
  508. }
  509. else if (!rcmail.env.top_posting) {
  510. position_element = $(this.editor.getBody()).children().last();
  511. }
  512. // put cursor before signature and scroll the window
  513. if (this.editor && position_element && position_element.length) {
  514. this.editor.selection.setCursorLocation(position_element.get(0));
  515. this.editor.getWin().scroll(0, position_element.offset().top);
  516. }
  517. };
  518. // trigger content save
  519. this.save = function()
  520. {
  521. if (this.editor) {
  522. this.editor.save();
  523. }
  524. };
  525. // focus the editing area
  526. this.focus = function()
  527. {
  528. (this.editor || rcube_find_object(this.id)).focus();
  529. };
  530. // image selector
  531. this.file_browser_callback = function(field_name, url, type)
  532. {
  533. var i, elem, cancel, dialog, fn, list = [];
  534. // open image selector dialog
  535. dialog = this.editor.windowManager.open({
  536. title: rcmail.get_label('select' + type),
  537. width: 500,
  538. height: 300,
  539. html: '<div id="image-selector-list"><ul></ul></div>'
  540. + '<div id="image-selector-form"><div id="image-upload-button" class="mce-widget mce-btn" role="button" tabindex="0"></div></div>',
  541. buttons: [{text: 'Cancel', onclick: function() { ref.file_browser_close(); }}]
  542. });
  543. rcmail.env.file_browser_field = field_name;
  544. rcmail.env.file_browser_type = type;
  545. // fill images list with available images
  546. for (i in rcmail.env.attachments) {
  547. if (elem = ref.file_browser_entry(i, rcmail.env.attachments[i])) {
  548. list.push(elem);
  549. }
  550. }
  551. if (list.length) {
  552. $('#image-selector-list > ul').append(list).find('li:first').focus();
  553. }
  554. // add hint about max file size (in dialog footer)
  555. $('div.mce-abs-end', dialog.getEl()).append($('<div class="hint">')
  556. .text($('div.hint', rcmail.gui_objects.uploadform).text()));
  557. // init upload button
  558. elem = $('#image-upload-button').append($('<span>').text(rcmail.get_label('add' + type)));
  559. cancel = elem.parents('.mce-panel').find('button:last').parent();
  560. // we need custom Tab key handlers, until we find out why
  561. // tabindex do not work here as expected
  562. elem.keydown(function(e) {
  563. if (e.which == 9) {
  564. // on Tab + Shift focus first file
  565. if (rcube_event.get_modifier(e) == SHIFT_KEY)
  566. $('#image-selector-list li:last').focus();
  567. // on Tab focus Cancel button
  568. else
  569. cancel.focus();
  570. return false;
  571. }
  572. });
  573. cancel.keydown(function(e) {
  574. if (e.which == 9) {
  575. // on Tab + Shift focus upload button
  576. if (rcube_event.get_modifier(e) == SHIFT_KEY)
  577. elem.focus();
  578. else
  579. $('#image-selector-list li:first').focus();
  580. return false;
  581. }
  582. });
  583. // enable (smart) upload button
  584. this.hack_file_input(elem, rcmail.gui_objects.uploadform);
  585. // enable drag-n-drop area
  586. if ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData) {
  587. if (!rcmail.env.filedrop) {
  588. rcmail.env.filedrop = {};
  589. }
  590. if (rcmail.gui_objects.filedrop) {
  591. rcmail.env.old_file_drop = rcmail.gui_objects.filedrop;
  592. }
  593. rcmail.gui_objects.filedrop = $('#image-selector-form');
  594. rcmail.gui_objects.filedrop.addClass('droptarget')
  595. .on('dragover dragleave', function(e) {
  596. e.preventDefault();
  597. e.stopPropagation();
  598. $(this)[(e.type == 'dragover' ? 'addClass' : 'removeClass')]('hover');
  599. })
  600. .get(0).addEventListener('drop', function(e) { return rcmail.file_dropped(e); }, false);
  601. }
  602. // register handler for successful file upload
  603. if (!rcmail.env.file_dialog_event) {
  604. rcmail.env.file_dialog_event = true;
  605. rcmail.addEventListener('fileuploaded', function(attr) {
  606. var elem;
  607. if (elem = ref.file_browser_entry(attr.name, attr.attachment)) {
  608. $('#image-selector-list > ul').prepend(elem);
  609. elem.focus();
  610. }
  611. });
  612. }
  613. // @todo: upload progress indicator
  614. };
  615. // close file browser window
  616. this.file_browser_close = function(url)
  617. {
  618. var input = $('#' + rcmail.env.file_browser_field);
  619. if (url)
  620. input.val(url);
  621. this.editor.windowManager.close();
  622. input.focus();
  623. if (rcmail.env.old_file_drop)
  624. rcmail.gui_objects.filedrop = rcmail.env.old_file_drop;
  625. };
  626. // creates file browser entry
  627. this.file_browser_entry = function(file_id, file)
  628. {
  629. if (!file.complete || !file.mimetype) {
  630. return;
  631. }
  632. if (rcmail.file_upload_id) {
  633. rcmail.set_busy(false, null, rcmail.file_upload_id);
  634. }
  635. var rx, img_src;
  636. switch (rcmail.env.file_browser_type) {
  637. case 'image':
  638. rx = /^image\//i;
  639. break;
  640. case 'media':
  641. rx = /^video\//i;
  642. img_src = 'program/resources/tinymce/video.png';
  643. break;
  644. default:
  645. return;
  646. }
  647. if (rx.test(file.mimetype)) {
  648. var path = rcmail.env.comm_path + '&_from=' + rcmail.env.action,
  649. action = rcmail.env.compose_id ? '&_id=' + rcmail.env.compose_id + '&_action=display-attachment' : '&_action=upload-display',
  650. href = path + action + '&_file=' + file_id,
  651. img = $('<img>').attr({title: file.name, src: img_src ? img_src : href + '&_thumbnail=1'});
  652. return $('<li>').attr({tabindex: 0})
  653. .data('url', href)
  654. .append($('<span class="img">').append(img))
  655. .append($('<span class="name">').text(file.name))
  656. .click(function() { ref.file_browser_close($(this).data('url')); })
  657. .keydown(function(e) {
  658. if (e.which == 13) {
  659. ref.file_browser_close($(this).data('url'));
  660. }
  661. // we need custom Tab key handlers, until we find out why
  662. // tabindex do not work here as expected
  663. else if (e.which == 9) {
  664. if (rcube_event.get_modifier(e) == SHIFT_KEY) {
  665. if (!$(this).prev().focus().length)
  666. $('#image-upload-button').parents('.mce-panel').find('button:last').parent().focus();
  667. }
  668. else {
  669. if (!$(this).next().focus().length)
  670. $('#image-upload-button').focus();
  671. }
  672. return false;
  673. }
  674. });
  675. }
  676. };
  677. // create smart files upload button
  678. this.hack_file_input = function(elem, clone_form)
  679. {
  680. var offset, link = $(elem),
  681. file = $('<input>').attr('name', '_file[]'),
  682. form = $('<form>').attr({method: 'post', enctype: 'multipart/form-data'});
  683. // clone existing upload form
  684. if (clone_form) {
  685. file.attr('name', $('input[type="file"]', clone_form).attr('name'));
  686. form.attr('action', $(clone_form).attr('action'))
  687. .append($('<input>').attr({type: 'hidden', name: '_token', value: rcmail.env.request_token}));
  688. }
  689. function move_file_input(e) {
  690. if (!offset) offset = link.offset();
  691. file.css({top: (e.pageY - offset.top - 10) + 'px', left: (e.pageX - offset.left - 10) + 'px'});
  692. }
  693. file.attr({type: 'file', multiple: 'multiple', size: 5, title: '', tabindex: -1})
  694. .change(function() { rcmail.upload_file(form, 'upload'); })
  695. .click(function() { setTimeout(function() { link.mouseleave(); }, 20); })
  696. // opacity:0 does the trick, display/visibility doesn't work
  697. .css({opacity: 0, cursor: 'pointer', position: 'relative', outline: 'none'})
  698. .appendTo(form);
  699. // In FF and IE we need to move the browser file-input's button under the cursor
  700. // Thanks to the size attribute above we know the length of the input field
  701. if (navigator.userAgent.match(/Firefox|MSIE/))
  702. file.css({marginLeft: '-80px'});
  703. // Note: now, I observe problem with cursor style on FF < 4 only
  704. link.css({overflow: 'hidden', cursor: 'pointer'})
  705. .mouseenter(function() { this.__active = true; })
  706. // place button under the cursor
  707. .mousemove(function(e) {
  708. if (this.__active)
  709. move_file_input(e);
  710. // move the input away if button is disabled
  711. else
  712. $(this).mouseleave();
  713. })
  714. .mouseleave(function() {
  715. file.css({top: '-10000px', left: '-10000px'});
  716. this.__active = false;
  717. })
  718. .click(function(e) {
  719. // forward click if mouse-enter event was missed
  720. if (!this.__active) {
  721. this.__active = true;
  722. move_file_input(e);
  723. file.trigger(e);
  724. }
  725. })
  726. .keydown(function(e) {
  727. if (e.which == 13) file.trigger('click');
  728. })
  729. .mouseleave()
  730. .append(form);
  731. };
  732. }