選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

editor.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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=4031300',
  42. theme: 'modern',
  43. language: config.lang,
  44. content_css: rcmail.assets_path('program/js/tinymce/roundcube/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. this.replace = function(text)
  356. {
  357. var ed = this.editor;
  358. // insert into tinymce editor
  359. if (ed) {
  360. ed.getWin().focus(); // correct focus in IE & Chrome
  361. ed.selection.setContent(rcmail.quote_html(text).replace(/\r?\n/g, '<br/>'), { format:'text' });
  362. }
  363. // replace selection in compose textarea
  364. else if (ed = rcube_find_object(this.id)) {
  365. var selection = $(ed).is(':focus') ? rcmail.get_input_selection(ed) : { start:0, end:0 },
  366. inp_value = ed.value;
  367. pre = inp_value.substring(0, selection.start),
  368. end = inp_value.substring(selection.end, inp_value.length);
  369. // insert response text
  370. ed.value = pre + text + end;
  371. // set caret after inserted text
  372. rcmail.set_caret_pos(ed, selection.start + text.length);
  373. ed.focus();
  374. }
  375. };
  376. // get selected text (if no selection returns all text) from the editor
  377. this.get_content = function(args)
  378. {
  379. var sigstart, ed = this.editor, text = '', strip = false,
  380. defaults = {refresh: true, selection: false, nosig: false, format: 'html'};
  381. args = $.extend(defaults, args);
  382. // apply spellcheck changes if spell checker is active
  383. if (args.refresh) {
  384. this.spellcheck_stop();
  385. }
  386. // get selected text from tinymce editor
  387. if (ed) {
  388. if (args.selection)
  389. text = ed.selection.getContent({format: args.format});
  390. if (!text) {
  391. text = ed.getContent({format: args.format});
  392. // @todo: strip signature in html mode
  393. strip = args.format == 'text';
  394. }
  395. }
  396. // get selected text from compose textarea
  397. else if (ed = rcube_find_object(this.id)) {
  398. if (args.selection && $(ed).is(':focus')) {
  399. text = rcmail.get_input_selection(ed).text;
  400. }
  401. if (!text) {
  402. text = ed.value;
  403. strip = true;
  404. }
  405. }
  406. // strip off signature
  407. // @todo: make this optional
  408. if (strip && args.nosig) {
  409. sigstart = text.indexOf('-- \n');
  410. if (sigstart > 0) {
  411. text = text.substring(0, sigstart);
  412. }
  413. }
  414. return text;
  415. };
  416. // change user signature text
  417. this.change_signature = function(id, show_sig)
  418. {
  419. var position_element, cursor_pos, p = -1,
  420. input_message = $('#' + this.id),
  421. message = input_message.val(),
  422. sig = rcmail.env.identity;
  423. if (!this.editor) { // plain text mode
  424. // remove the 'old' signature
  425. if (show_sig && sig && rcmail.env.signatures && rcmail.env.signatures[sig]) {
  426. sig = rcmail.env.signatures[sig].text;
  427. sig = sig.replace(/\r\n/g, '\n');
  428. p = rcmail.env.top_posting ? message.indexOf(sig) : message.lastIndexOf(sig);
  429. if (p >= 0)
  430. message = message.substring(0, p) + message.substring(p+sig.length, message.length);
  431. }
  432. // add the new signature string
  433. if (show_sig && rcmail.env.signatures && rcmail.env.signatures[id]) {
  434. sig = rcmail.env.signatures[id].text;
  435. sig = sig.replace(/\r\n/g, '\n');
  436. // in place of removed signature
  437. if (p >= 0) {
  438. message = message.substring(0, p) + sig + message.substring(p, message.length);
  439. cursor_pos = p - 1;
  440. }
  441. // empty message or new-message mode
  442. else if (!message || !rcmail.env.compose_mode) {
  443. cursor_pos = message.length;
  444. message += '\n\n' + sig;
  445. }
  446. else if (rcmail.env.top_posting && !rcmail.env.sig_below) {
  447. // at cursor position
  448. if (pos = rcmail.get_caret_pos(input_message.get(0))) {
  449. message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
  450. cursor_pos = pos;
  451. }
  452. // on top
  453. else {
  454. message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
  455. cursor_pos = 0;
  456. }
  457. }
  458. else {
  459. message = message.replace(/[\r\n]+$/, '');
  460. cursor_pos = !rcmail.env.top_posting && message.length ? message.length + 1 : 0;
  461. message += '\n\n' + sig;
  462. }
  463. }
  464. else {
  465. cursor_pos = rcmail.env.top_posting ? 0 : message.length;
  466. }
  467. input_message.val(message);
  468. // move cursor before the signature
  469. rcmail.set_caret_pos(input_message.get(0), cursor_pos);
  470. }
  471. else if (show_sig && rcmail.env.signatures) { // html
  472. var sigElem = this.editor.dom.get('_rc_sig');
  473. // Append the signature as a div within the body
  474. if (!sigElem) {
  475. var body = this.editor.getBody();
  476. sigElem = $('<div id="_rc_sig"></div>').get(0);
  477. // insert at start or at cursor position in top-posting mode
  478. // (but not if the content is empty and not in new-message mode)
  479. if (rcmail.env.top_posting && !rcmail.env.sig_below
  480. && rcmail.env.compose_mode && (body.childNodes.length > 1 || $(body).text())
  481. ) {
  482. this.editor.getWin().focus(); // correct focus in IE & Chrome
  483. var node = this.editor.selection.getNode();
  484. $(sigElem).insertBefore(node.nodeName == 'BODY' ? body.firstChild : node.nextSibling);
  485. $('<p>').append($('<br>')).insertBefore(sigElem);
  486. }
  487. else {
  488. body.appendChild(sigElem);
  489. position_element = rcmail.env.top_posting && rcmail.env.compose_mode ? body.firstChild : $(sigElem).prev();
  490. }
  491. }
  492. sigElem.innerHTML = rcmail.env.signatures[id] ? rcmail.env.signatures[id].html : '';
  493. }
  494. else if (!rcmail.env.top_posting) {
  495. position_element = $(this.editor.getBody()).children().last();
  496. }
  497. // put cursor before signature and scroll the window
  498. if (this.editor && position_element && position_element.length) {
  499. this.editor.selection.setCursorLocation(position_element.get(0));
  500. this.editor.getWin().scroll(0, position_element.offset().top);
  501. }
  502. };
  503. // trigger content save
  504. this.save = function()
  505. {
  506. if (this.editor) {
  507. this.editor.save();
  508. }
  509. };
  510. // focus the editing area
  511. this.focus = function()
  512. {
  513. (this.editor || rcube_find_object(this.id)).focus();
  514. };
  515. // image selector
  516. this.file_browser_callback = function(field_name, url, type)
  517. {
  518. var i, elem, cancel, dialog, fn, list = [];
  519. // open image selector dialog
  520. dialog = this.editor.windowManager.open({
  521. title: rcmail.get_label('select' + type),
  522. width: 500,
  523. height: 300,
  524. html: '<div id="image-selector-list"><ul></ul></div>'
  525. + '<div id="image-selector-form"><div id="image-upload-button" class="mce-widget mce-btn" role="button" tabindex="0"></div></div>',
  526. buttons: [{text: 'Cancel', onclick: function() { ref.file_browser_close(); }}]
  527. });
  528. rcmail.env.file_browser_field = field_name;
  529. rcmail.env.file_browser_type = type;
  530. // fill images list with available images
  531. for (i in rcmail.env.attachments) {
  532. if (elem = ref.file_browser_entry(i, rcmail.env.attachments[i])) {
  533. list.push(elem);
  534. }
  535. }
  536. if (list.length) {
  537. $('#image-selector-list > ul').append(list).find('li:first').focus();
  538. }
  539. // add hint about max file size (in dialog footer)
  540. $('div.mce-abs-end', dialog.getEl()).append($('<div class="hint">')
  541. .text($('div.hint', rcmail.gui_objects.uploadform).text()));
  542. // init upload button
  543. elem = $('#image-upload-button').append($('<span>').text(rcmail.get_label('add' + type)));
  544. cancel = elem.parents('.mce-panel').find('button:last').parent();
  545. // we need custom Tab key handlers, until we find out why
  546. // tabindex do not work here as expected
  547. elem.keydown(function(e) {
  548. if (e.which == 9) {
  549. // on Tab + Shift focus first file
  550. if (rcube_event.get_modifier(e) == SHIFT_KEY)
  551. $('#image-selector-list li:last').focus();
  552. // on Tab focus Cancel button
  553. else
  554. cancel.focus();
  555. return false;
  556. }
  557. });
  558. cancel.keydown(function(e) {
  559. if (e.which == 9) {
  560. // on Tab + Shift focus upload button
  561. if (rcube_event.get_modifier(e) == SHIFT_KEY)
  562. elem.focus();
  563. else
  564. $('#image-selector-list li:first').focus();
  565. return false;
  566. }
  567. });
  568. // enable (smart) upload button
  569. this.hack_file_input(elem, rcmail.gui_objects.uploadform);
  570. // enable drag-n-drop area
  571. if ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData) {
  572. if (!rcmail.env.filedrop) {
  573. rcmail.env.filedrop = {};
  574. }
  575. if (rcmail.gui_objects.filedrop) {
  576. rcmail.env.old_file_drop = rcmail.gui_objects.filedrop;
  577. }
  578. rcmail.gui_objects.filedrop = $('#image-selector-form');
  579. rcmail.gui_objects.filedrop.addClass('droptarget')
  580. .on('dragover dragleave', function(e) {
  581. e.preventDefault();
  582. e.stopPropagation();
  583. $(this)[(e.type == 'dragover' ? 'addClass' : 'removeClass')]('hover');
  584. })
  585. .get(0).addEventListener('drop', function(e) { return rcmail.file_dropped(e); }, false);
  586. }
  587. // register handler for successful file upload
  588. if (!rcmail.env.file_dialog_event) {
  589. rcmail.env.file_dialog_event = true;
  590. rcmail.addEventListener('fileuploaded', function(attr) {
  591. var elem;
  592. if (elem = ref.file_browser_entry(attr.name, attr.attachment)) {
  593. $('#image-selector-list > ul').prepend(elem);
  594. elem.focus();
  595. }
  596. });
  597. }
  598. // @todo: upload progress indicator
  599. };
  600. // close file browser window
  601. this.file_browser_close = function(url)
  602. {
  603. var input = $('#' + rcmail.env.file_browser_field);
  604. if (url)
  605. input.val(url);
  606. this.editor.windowManager.close();
  607. input.focus();
  608. if (rcmail.env.old_file_drop)
  609. rcmail.gui_objects.filedrop = rcmail.env.old_file_drop;
  610. };
  611. // creates file browser entry
  612. this.file_browser_entry = function(file_id, file)
  613. {
  614. if (!file.complete || !file.mimetype) {
  615. return;
  616. }
  617. if (rcmail.file_upload_id) {
  618. rcmail.set_busy(false, null, rcmail.file_upload_id);
  619. }
  620. var rx, img_src;
  621. switch (rcmail.env.file_browser_type) {
  622. case 'image':
  623. rx = /^image\//i;
  624. break;
  625. case 'media':
  626. rx = /^video\//i;
  627. img_src = 'program/js/tinymce/roundcube/video.png';
  628. break;
  629. default:
  630. return;
  631. }
  632. if (rx.test(file.mimetype)) {
  633. var path = rcmail.env.comm_path + '&_from=' + rcmail.env.action,
  634. action = rcmail.env.compose_id ? '&_id=' + rcmail.env.compose_id + '&_action=display-attachment' : '&_action=upload-display',
  635. href = path + action + '&_file=' + file_id,
  636. img = $('<img>').attr({title: file.name, src: img_src ? img_src : href + '&_thumbnail=1'});
  637. return $('<li>').attr({tabindex: 0})
  638. .data('url', href)
  639. .append($('<span class="img">').append(img))
  640. .append($('<span class="name">').text(file.name))
  641. .click(function() { ref.file_browser_close($(this).data('url')); })
  642. .keydown(function(e) {
  643. if (e.which == 13) {
  644. ref.file_browser_close($(this).data('url'));
  645. }
  646. // we need custom Tab key handlers, until we find out why
  647. // tabindex do not work here as expected
  648. else if (e.which == 9) {
  649. if (rcube_event.get_modifier(e) == SHIFT_KEY) {
  650. if (!$(this).prev().focus().length)
  651. $('#image-upload-button').parents('.mce-panel').find('button:last').parent().focus();
  652. }
  653. else {
  654. if (!$(this).next().focus().length)
  655. $('#image-upload-button').focus();
  656. }
  657. return false;
  658. }
  659. });
  660. }
  661. };
  662. // create smart files upload button
  663. this.hack_file_input = function(elem, clone_form)
  664. {
  665. var offset, link = $(elem),
  666. file = $('<input>').attr('name', '_file[]'),
  667. form = $('<form>').attr({method: 'post', enctype: 'multipart/form-data'});
  668. // clone existing upload form
  669. if (clone_form) {
  670. file.attr('name', $('input[type="file"]', clone_form).attr('name'));
  671. form.attr('action', $(clone_form).attr('action'))
  672. .append($('<input>').attr({type: 'hidden', name: '_token', value: rcmail.env.request_token}));
  673. }
  674. function move_file_input(e) {
  675. if (!offset) offset = link.offset();
  676. file.css({top: (e.pageY - offset.top - 10) + 'px', left: (e.pageX - offset.left - 10) + 'px'});
  677. }
  678. file.attr({type: 'file', multiple: 'multiple', size: 5, title: '', tabindex: -1})
  679. .change(function() { rcmail.upload_file(form, 'upload'); })
  680. .click(function() { setTimeout(function() { link.mouseleave(); }, 20); })
  681. // opacity:0 does the trick, display/visibility doesn't work
  682. .css({opacity: 0, cursor: 'pointer', position: 'relative', outline: 'none'})
  683. .appendTo(form);
  684. // In FF and IE we need to move the browser file-input's button under the cursor
  685. // Thanks to the size attribute above we know the length of the input field
  686. if (navigator.userAgent.match(/Firefox|MSIE/))
  687. file.css({marginLeft: '-80px'});
  688. // Note: now, I observe problem with cursor style on FF < 4 only
  689. link.css({overflow: 'hidden', cursor: 'pointer'})
  690. .mouseenter(function() { this.__active = true; })
  691. // place button under the cursor
  692. .mousemove(function(e) {
  693. if (this.__active)
  694. move_file_input(e);
  695. // move the input away if button is disabled
  696. else
  697. $(this).mouseleave();
  698. })
  699. .mouseleave(function() {
  700. file.css({top: '-10000px', left: '-10000px'});
  701. this.__active = false;
  702. })
  703. .click(function(e) {
  704. // forward click if mouse-enter event was missed
  705. if (!this.__active) {
  706. this.__active = true;
  707. move_file_input(e);
  708. file.trigger(e);
  709. }
  710. })
  711. .keydown(function(e) {
  712. if (e.which == 13) file.trigger('click');
  713. })
  714. .mouseleave()
  715. .append(form);
  716. };
  717. }