EventHandler.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. define([
  2. 'summernote/core/agent',
  3. 'summernote/core/func',
  4. 'summernote/core/dom',
  5. 'summernote/core/async',
  6. 'summernote/core/key',
  7. 'summernote/core/list',
  8. 'summernote/editing/History',
  9. 'summernote/module/Editor',
  10. 'summernote/module/Toolbar',
  11. 'summernote/module/Statusbar',
  12. 'summernote/module/Popover',
  13. 'summernote/module/Handle',
  14. 'summernote/module/Fullscreen',
  15. 'summernote/module/Codeview',
  16. 'summernote/module/DragAndDrop',
  17. 'summernote/module/Clipboard',
  18. 'summernote/module/LinkDialog',
  19. 'summernote/module/ImageDialog',
  20. 'summernote/module/HelpDialog'
  21. ], function (agent, func, dom, async, key, list, History,
  22. Editor, Toolbar, Statusbar, Popover, Handle, Fullscreen, Codeview,
  23. DragAndDrop, Clipboard, LinkDialog, ImageDialog, HelpDialog) {
  24. /**
  25. * @class EventHandler
  26. *
  27. * EventHandler
  28. * - TODO: new instance per a editor
  29. */
  30. var EventHandler = function () {
  31. var self = this;
  32. /**
  33. * Modules
  34. */
  35. var modules = this.modules = {
  36. editor: new Editor(this),
  37. toolbar: new Toolbar(this),
  38. statusbar: new Statusbar(this),
  39. popover: new Popover(this),
  40. handle: new Handle(this),
  41. fullscreen: new Fullscreen(this),
  42. codeview: new Codeview(this),
  43. dragAndDrop: new DragAndDrop(this),
  44. clipboard: new Clipboard(this),
  45. linkDialog: new LinkDialog(this),
  46. imageDialog: new ImageDialog(this),
  47. helpDialog: new HelpDialog(this)
  48. };
  49. /**
  50. * invoke module's method
  51. *
  52. * @param {String} moduleAndMethod - ex) 'editor.redo'
  53. * @param {...*} arguments - arguments of method
  54. * @return {*}
  55. */
  56. this.invoke = function () {
  57. var moduleAndMethod = list.head(list.from(arguments));
  58. var args = list.tail(list.from(arguments));
  59. var splits = moduleAndMethod.split('.');
  60. var hasSeparator = splits.length > 1;
  61. var moduleName = hasSeparator && list.head(splits);
  62. var methodName = hasSeparator ? list.last(splits) : list.head(splits);
  63. var module = this.getModule(moduleName);
  64. var method = module[methodName];
  65. return method && method.apply(module, args);
  66. };
  67. /**
  68. * returns module
  69. *
  70. * @param {String} moduleName - name of module
  71. * @return {Module} - defaults is editor
  72. */
  73. this.getModule = function (moduleName) {
  74. return this.modules[moduleName] || this.modules.editor;
  75. };
  76. /**
  77. * @param {jQuery} $holder
  78. * @param {Object} callbacks
  79. * @param {String} eventNamespace
  80. * @returns {Function}
  81. */
  82. var bindCustomEvent = this.bindCustomEvent = function ($holder, callbacks, eventNamespace) {
  83. return function () {
  84. var callback = callbacks[func.namespaceToCamel(eventNamespace, 'on')];
  85. if (callback) {
  86. callback.apply($holder[0], arguments);
  87. }
  88. return $holder.trigger('summernote.' + eventNamespace, arguments);
  89. };
  90. };
  91. /**
  92. * insert Images from file array.
  93. *
  94. * @private
  95. * @param {Object} layoutInfo
  96. * @param {File[]} files
  97. */
  98. this.insertImages = function (layoutInfo, files) {
  99. var $editor = layoutInfo.editor(),
  100. $editable = layoutInfo.editable(),
  101. $holder = layoutInfo.holder();
  102. var callbacks = $editable.data('callbacks');
  103. var options = $editor.data('options');
  104. // If onImageUpload options setted
  105. if (callbacks.onImageUpload) {
  106. bindCustomEvent($holder, callbacks, 'image.upload')(files);
  107. // else insert Image as dataURL
  108. } else {
  109. $.each(files, function (idx, file) {
  110. var filename = file.name;
  111. if (options.maximumImageFileSize && options.maximumImageFileSize < file.size) {
  112. bindCustomEvent($holder, callbacks, 'image.upload.error')(options.langInfo.image.maximumFileSizeError);
  113. } else {
  114. async.readFileAsDataURL(file).then(function (sDataURL) {
  115. modules.editor.insertImage($editable, sDataURL, filename);
  116. }).fail(function () {
  117. bindCustomEvent($holder, callbacks, 'image.upload.error')(options.langInfo.image.maximumFileSizeError);
  118. });
  119. }
  120. });
  121. }
  122. };
  123. var commands = {
  124. /**
  125. * @param {Object} layoutInfo
  126. */
  127. showLinkDialog: function (layoutInfo) {
  128. modules.linkDialog.show(layoutInfo);
  129. },
  130. /**
  131. * @param {Object} layoutInfo
  132. */
  133. showImageDialog: function (layoutInfo) {
  134. modules.imageDialog.show(layoutInfo);
  135. },
  136. /**
  137. * @param {Object} layoutInfo
  138. */
  139. showHelpDialog: function (layoutInfo) {
  140. modules.helpDialog.show(layoutInfo);
  141. },
  142. /**
  143. * @param {Object} layoutInfo
  144. */
  145. fullscreen: function (layoutInfo) {
  146. modules.fullscreen.toggle(layoutInfo);
  147. },
  148. /**
  149. * @param {Object} layoutInfo
  150. */
  151. codeview: function (layoutInfo) {
  152. modules.codeview.toggle(layoutInfo);
  153. }
  154. };
  155. var hMousedown = function (event) {
  156. //preventDefault Selection for FF, IE8+
  157. if (dom.isImg(event.target)) {
  158. event.preventDefault();
  159. }
  160. };
  161. var hKeyupAndMouseup = function (event) {
  162. var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target);
  163. modules.editor.removeBogus(layoutInfo.editable());
  164. hToolbarAndPopoverUpdate(event);
  165. };
  166. /**
  167. * update sytle info
  168. * @param {Object} styleInfo
  169. * @param {Object} layoutInfo
  170. */
  171. this.updateStyleInfo = function (styleInfo, layoutInfo) {
  172. if (!styleInfo) {
  173. return;
  174. }
  175. var isAirMode = layoutInfo.editor().data('options').airMode;
  176. if (!isAirMode) {
  177. modules.toolbar.update(layoutInfo.toolbar(), styleInfo);
  178. }
  179. modules.popover.update(layoutInfo.popover(), styleInfo, isAirMode);
  180. modules.handle.update(layoutInfo.handle(), styleInfo, isAirMode);
  181. };
  182. var hToolbarAndPopoverUpdate = function (event) {
  183. var target = event.target;
  184. // delay for range after mouseup
  185. setTimeout(function () {
  186. var layoutInfo = dom.makeLayoutInfo(target);
  187. var styleInfo = modules.editor.currentStyle(target);
  188. self.updateStyleInfo(styleInfo, layoutInfo);
  189. }, 0);
  190. };
  191. var hScroll = function (event) {
  192. var layoutInfo = dom.makeLayoutInfo(event.currentTarget || event.target);
  193. //hide popover and handle when scrolled
  194. modules.popover.hide(layoutInfo.popover());
  195. modules.handle.hide(layoutInfo.handle());
  196. };
  197. var hToolbarAndPopoverMousedown = function (event) {
  198. // prevent default event when insertTable (FF, Webkit)
  199. var $btn = $(event.target).closest('[data-event]');
  200. if ($btn.length) {
  201. event.preventDefault();
  202. }
  203. };
  204. var hToolbarAndPopoverClick = function (event) {
  205. var $btn = $(event.target).closest('[data-event]');
  206. if (!$btn.length) {
  207. return;
  208. }
  209. var eventName = $btn.attr('data-event'),
  210. value = $btn.attr('data-value'),
  211. hide = $btn.attr('data-hide');
  212. var layoutInfo = dom.makeLayoutInfo(event.target);
  213. // before command: detect control selection element($target)
  214. var $target;
  215. if ($.inArray(eventName, ['resize', 'floatMe', 'removeMedia', 'imageShape']) !== -1) {
  216. var $selection = layoutInfo.handle().find('.note-control-selection');
  217. $target = $($selection.data('target'));
  218. }
  219. // If requested, hide the popover when the button is clicked.
  220. // Useful for things like showHelpDialog.
  221. if (hide) {
  222. $btn.parents('.popover').hide();
  223. }
  224. if ($.isFunction($.summernote.pluginEvents[eventName])) {
  225. $.summernote.pluginEvents[eventName](event, modules.editor, layoutInfo, value);
  226. } else if (modules.editor[eventName]) { // on command
  227. var $editable = layoutInfo.editable();
  228. $editable.focus();
  229. modules.editor[eventName]($editable, value, $target);
  230. event.preventDefault();
  231. } else if (commands[eventName]) {
  232. commands[eventName].call(this, layoutInfo);
  233. event.preventDefault();
  234. }
  235. // after command
  236. if ($.inArray(eventName, ['backColor', 'foreColor']) !== -1) {
  237. var options = layoutInfo.editor().data('options', options);
  238. var module = options.airMode ? modules.popover : modules.toolbar;
  239. module.updateRecentColor(list.head($btn), eventName, value);
  240. }
  241. hToolbarAndPopoverUpdate(event);
  242. };
  243. var PX_PER_EM = 18;
  244. var hDimensionPickerMove = function (event, options) {
  245. var $picker = $(event.target.parentNode); // target is mousecatcher
  246. var $dimensionDisplay = $picker.next();
  247. var $catcher = $picker.find('.note-dimension-picker-mousecatcher');
  248. var $highlighted = $picker.find('.note-dimension-picker-highlighted');
  249. var $unhighlighted = $picker.find('.note-dimension-picker-unhighlighted');
  250. var posOffset;
  251. // HTML5 with jQuery - e.offsetX is undefined in Firefox
  252. if (event.offsetX === undefined) {
  253. var posCatcher = $(event.target).offset();
  254. posOffset = {
  255. x: event.pageX - posCatcher.left,
  256. y: event.pageY - posCatcher.top
  257. };
  258. } else {
  259. posOffset = {
  260. x: event.offsetX,
  261. y: event.offsetY
  262. };
  263. }
  264. var dim = {
  265. c: Math.ceil(posOffset.x / PX_PER_EM) || 1,
  266. r: Math.ceil(posOffset.y / PX_PER_EM) || 1
  267. };
  268. $highlighted.css({ width: dim.c + 'em', height: dim.r + 'em' });
  269. $catcher.attr('data-value', dim.c + 'x' + dim.r);
  270. if (3 < dim.c && dim.c < options.insertTableMaxSize.col) {
  271. $unhighlighted.css({ width: dim.c + 1 + 'em'});
  272. }
  273. if (3 < dim.r && dim.r < options.insertTableMaxSize.row) {
  274. $unhighlighted.css({ height: dim.r + 1 + 'em'});
  275. }
  276. $dimensionDisplay.html(dim.c + ' x ' + dim.r);
  277. };
  278. /**
  279. * bind KeyMap on keydown
  280. *
  281. * @param {Object} layoutInfo
  282. * @param {Object} keyMap
  283. */
  284. this.bindKeyMap = function (layoutInfo, keyMap) {
  285. var $editor = layoutInfo.editor();
  286. var $editable = layoutInfo.editable();
  287. $editable.on('keydown', function (event) {
  288. var keys = [];
  289. // modifier
  290. if (event.metaKey) { keys.push('CMD'); }
  291. if (event.ctrlKey && !event.altKey) { keys.push('CTRL'); }
  292. if (event.shiftKey) { keys.push('SHIFT'); }
  293. // keycode
  294. var keyName = key.nameFromCode[event.keyCode];
  295. if (keyName) {
  296. keys.push(keyName);
  297. }
  298. var pluginEvent;
  299. var keyString = keys.join('+');
  300. var eventName = keyMap[keyString];
  301. if (eventName) {
  302. // FIXME Summernote doesn't support event pipeline yet.
  303. // - Plugin -> Base Code
  304. pluginEvent = $.summernote.pluginEvents[keyString];
  305. if ($.isFunction(pluginEvent)) {
  306. if (pluginEvent(event, modules.editor, layoutInfo)) {
  307. return false;
  308. }
  309. }
  310. pluginEvent = $.summernote.pluginEvents[eventName];
  311. if ($.isFunction(pluginEvent)) {
  312. pluginEvent(event, modules.editor, layoutInfo);
  313. } else if (modules.editor[eventName]) {
  314. modules.editor[eventName]($editable, $editor.data('options'));
  315. event.preventDefault();
  316. } else if (commands[eventName]) {
  317. commands[eventName].call(this, layoutInfo);
  318. event.preventDefault();
  319. }
  320. } else if (key.isEdit(event.keyCode)) {
  321. modules.editor.afterCommand($editable);
  322. }
  323. });
  324. };
  325. /**
  326. * attach eventhandler
  327. *
  328. * @param {Object} layoutInfo - layout Informations
  329. * @param {Object} options - user options include custom event handlers
  330. */
  331. this.attach = function (layoutInfo, options) {
  332. // handlers for editable
  333. if (options.shortcuts) {
  334. this.bindKeyMap(layoutInfo, options.keyMap[agent.isMac ? 'mac' : 'pc']);
  335. }
  336. layoutInfo.editable().on('mousedown', hMousedown);
  337. layoutInfo.editable().on('keyup mouseup', hKeyupAndMouseup);
  338. layoutInfo.editable().on('scroll', hScroll);
  339. // handler for clipboard
  340. modules.clipboard.attach(layoutInfo, options);
  341. // handler for handle and popover
  342. modules.handle.attach(layoutInfo, options);
  343. layoutInfo.popover().on('click', hToolbarAndPopoverClick);
  344. layoutInfo.popover().on('mousedown', hToolbarAndPopoverMousedown);
  345. // handler for drag and drop
  346. modules.dragAndDrop.attach(layoutInfo, options);
  347. // handlers for frame mode (toolbar, statusbar)
  348. if (!options.airMode) {
  349. // handler for toolbar
  350. layoutInfo.toolbar().on('click', hToolbarAndPopoverClick);
  351. layoutInfo.toolbar().on('mousedown', hToolbarAndPopoverMousedown);
  352. // handler for statusbar
  353. modules.statusbar.attach(layoutInfo, options);
  354. }
  355. // handler for table dimension
  356. var $catcherContainer = options.airMode ? layoutInfo.popover() :
  357. layoutInfo.toolbar();
  358. var $catcher = $catcherContainer.find('.note-dimension-picker-mousecatcher');
  359. $catcher.css({
  360. width: options.insertTableMaxSize.col + 'em',
  361. height: options.insertTableMaxSize.row + 'em'
  362. }).on('mousemove', function (event) {
  363. hDimensionPickerMove(event, options);
  364. });
  365. // save options on editor
  366. layoutInfo.editor().data('options', options);
  367. // ret styleWithCSS for backColor / foreColor clearing with 'inherit'.
  368. if (!agent.isMSIE) {
  369. // [workaround] for Firefox
  370. // - protect FF Error: NS_ERROR_FAILURE: Failure
  371. setTimeout(function () {
  372. document.execCommand('styleWithCSS', 0, options.styleWithSpan);
  373. }, 0);
  374. }
  375. // History
  376. var history = new History(layoutInfo.editable());
  377. layoutInfo.editable().data('NoteHistory', history);
  378. // All editor status will be saved on editable with jquery's data
  379. // for support multiple editor with singleton object.
  380. layoutInfo.editable().data('callbacks', {
  381. onInit: options.onInit,
  382. onFocus: options.onFocus,
  383. onBlur: options.onBlur,
  384. onKeydown: options.onKeydown,
  385. onKeyup: options.onKeyup,
  386. onMousedown: options.onMousedown,
  387. onEnter: options.onEnter,
  388. onPaste: options.onPaste,
  389. onBeforeCommand: options.onBeforeCommand,
  390. onChange: options.onChange,
  391. onImageUpload: options.onImageUpload,
  392. onImageUploadError: options.onImageUploadError,
  393. onMediaDelete: options.onMediaDelete,
  394. onToolbarClick: options.onToolbarClick
  395. });
  396. var styleInfo = modules.editor.styleFromNode(layoutInfo.editable());
  397. this.updateStyleInfo(styleInfo, layoutInfo);
  398. };
  399. /**
  400. * attach jquery custom event
  401. *
  402. * @param {Object} layoutInfo - layout Informations
  403. */
  404. this.attachCustomEvent = function (layoutInfo, options) {
  405. var $holder = layoutInfo.holder();
  406. var $editable = layoutInfo.editable();
  407. var callbacks = $editable.data('callbacks');
  408. $editable.focus(bindCustomEvent($holder, callbacks, 'focus'));
  409. $editable.blur(bindCustomEvent($holder, callbacks, 'blur'));
  410. $editable.keydown(function (event) {
  411. if (event.keyCode === key.code.ENTER) {
  412. bindCustomEvent($holder, callbacks, 'enter').call(this, event);
  413. }
  414. bindCustomEvent($holder, callbacks, 'keydown').call(this, event);
  415. });
  416. $editable.keyup(bindCustomEvent($holder, callbacks, 'keyup'));
  417. $editable.on('mousedown', bindCustomEvent($holder, callbacks, 'mousedown'));
  418. $editable.on('mouseup', bindCustomEvent($holder, callbacks, 'mouseup'));
  419. $editable.on('scroll', bindCustomEvent($holder, callbacks, 'scroll'));
  420. $editable.on('paste', bindCustomEvent($holder, callbacks, 'paste'));
  421. // [workaround] IE doesn't have input events for contentEditable
  422. // - see: https://goo.gl/4bfIvA
  423. var changeEventName = agent.isMSIE ? 'DOMCharacterDataModified DOMSubtreeModified DOMNodeInserted' : 'input';
  424. $editable.on(changeEventName, function () {
  425. bindCustomEvent($holder, callbacks, 'change')($editable.html(), $editable);
  426. });
  427. if (!options.airMode) {
  428. layoutInfo.toolbar().click(bindCustomEvent($holder, callbacks, 'toolbar.click'));
  429. layoutInfo.popover().click(bindCustomEvent($holder, callbacks, 'popover.click'));
  430. }
  431. // Textarea: auto filling the code before form submit.
  432. if (dom.isTextarea(list.head($holder))) {
  433. $holder.closest('form').submit(function (e) {
  434. layoutInfo.holder().val(layoutInfo.holder().code());
  435. bindCustomEvent($holder, callbacks, 'submit').call(this, e, $holder.code());
  436. });
  437. }
  438. // textarea auto sync
  439. if (dom.isTextarea(list.head($holder)) && options.textareaAutoSync) {
  440. $holder.on('summernote.change', function () {
  441. layoutInfo.holder().val(layoutInfo.holder().code());
  442. });
  443. }
  444. // fire init event
  445. bindCustomEvent($holder, callbacks, 'init')(layoutInfo);
  446. // fire plugin init event
  447. for (var i = 0, len = $.summernote.plugins.length; i < len; i++) {
  448. if ($.isFunction($.summernote.plugins[i].init)) {
  449. $.summernote.plugins[i].init(layoutInfo);
  450. }
  451. }
  452. };
  453. this.detach = function (layoutInfo, options) {
  454. layoutInfo.holder().off();
  455. layoutInfo.editable().off();
  456. layoutInfo.popover().off();
  457. layoutInfo.handle().off();
  458. layoutInfo.dialog().off();
  459. if (!options.airMode) {
  460. layoutInfo.dropzone().off();
  461. layoutInfo.toolbar().off();
  462. layoutInfo.statusbar().off();
  463. }
  464. };
  465. };
  466. return EventHandler;
  467. });