Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

editor.js 27KB

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