bootstrap-wysiwyg.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /* http://github.com/mindmup/bootstrap-wysiwyg */
  2. /*global jQuery, $, FileReader*/
  3. /*jslint browser:true*/
  4. (function ($) {
  5. 'use strict';
  6. var readFileIntoDataUrl = function (fileInfo) {
  7. var loader = $.Deferred(),
  8. fReader = new FileReader();
  9. fReader.onload = function (e) {
  10. loader.resolve(e.target.result);
  11. };
  12. fReader.onerror = loader.reject;
  13. fReader.onprogress = loader.notify;
  14. fReader.readAsDataURL(fileInfo);
  15. return loader.promise();
  16. };
  17. $.fn.cleanHtml = function () {
  18. var html = $(this).html();
  19. return html && html.replace(/(<br>|\s|<div><br><\/div>|&nbsp;)*$/, '');
  20. };
  21. $.fn.wysiwyg = function (userOptions) {
  22. var editor = this,
  23. selectedRange,
  24. options,
  25. toolbarBtnSelector,
  26. updateToolbar = function () {
  27. if (options.activeToolbarClass) {
  28. var selection = window.getSelection();
  29. try {
  30. var tag = 'formatBlock ' + selection.focusNode.parentNode.nodeName.toLowerCase();
  31. }catch (e){
  32. console.log(e);
  33. tag = '';
  34. }
  35. $(options.toolbarSelector).find(toolbarBtnSelector).each(function () {
  36. var command = $(this).data(options.commandRole);
  37. if (document.queryCommandState(command) || tag === command) {
  38. $(this).addClass(options.activeToolbarClass);
  39. } else {
  40. $(this).removeClass(options.activeToolbarClass);
  41. }
  42. });
  43. }
  44. },
  45. execCommand = function (commandWithArgs, valueArg) {
  46. var commandArr = commandWithArgs.split(' '),
  47. command = commandArr.shift(),
  48. args = commandArr.join(' ') + (valueArg || '');
  49. if(command === 'formatBlock'){
  50. var selection = window.getSelection();
  51. if(selection.focusNode.parentNode.nodeName.toLowerCase() === args){
  52. args = '<p>';
  53. }else{
  54. args = '<' + args + '>';
  55. }
  56. }else if(command === 'enterAction'){
  57. }
  58. document.execCommand(command, 0, args);
  59. updateToolbar();
  60. editor.change && editor.change();
  61. },
  62. insertEmpty = function ($selectionElem) {
  63. insertHtml('\r\n');
  64. return true;
  65. },
  66. codeHandler = function () {
  67. var selection = window.getSelection();
  68. try{
  69. var nodeName = selection.parentNode.nodeName;
  70. console.log(nodeName)
  71. if(nodeName !== 'CODE' && nodeName !== 'PRE'){
  72. }
  73. if (!document.queryCommandSupported('insertHTML')) {
  74. }
  75. }catch (e){
  76. console.log(e)
  77. }
  78. },
  79. enterKeyHandle = function (e) {
  80. var selection = getCurrentRange();
  81. try {
  82. var nodeName = selection.commonAncestorContainer.parentNode.nodeName;
  83. if(nodeName === 'CODE' || nodeName === 'PRE'){
  84. return insertEmpty(selection.parentNode);
  85. }
  86. }catch (e){
  87. console.log(selection)
  88. console.log("enterKeyHandle:" + e);
  89. }
  90. },
  91. bindHotkeys = function (hotKeys) {
  92. $.each(hotKeys, function (hotkey, command) {
  93. editor.keydown(hotkey, function (e) {
  94. if (editor.attr('contenteditable') && editor.is(':visible')) {
  95. e.preventDefault();
  96. e.stopPropagation();
  97. if(hotkey === 'return'){
  98. return enterKeyHandle(e);
  99. }
  100. execCommand(command);
  101. }
  102. }).keyup(hotkey, function (e) {
  103. if (editor.attr('contenteditable') && editor.is(':visible')) {
  104. e.preventDefault();
  105. e.stopPropagation();
  106. }
  107. });
  108. });
  109. },
  110. getCurrentRange = function () {
  111. var sel = window.getSelection();
  112. if (sel.getRangeAt && sel.rangeCount) {
  113. return sel.getRangeAt(0);
  114. }
  115. },
  116. saveSelection = function () {
  117. selectedRange = getCurrentRange();
  118. },
  119. restoreSelection = function () {
  120. var selection = window.getSelection();
  121. if (selectedRange) {
  122. try {
  123. selection.removeAllRanges();
  124. } catch (ex) {
  125. document.body.createTextRange().select();
  126. document.selection.empty();
  127. }
  128. selection.addRange(selectedRange);
  129. }
  130. },
  131. insertFiles = function (files) {
  132. editor.focus();
  133. $.each(files, function (idx, fileInfo) {
  134. if (/^image\//.test(fileInfo.type)) {
  135. $.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
  136. execCommand('insertimage', dataUrl);
  137. }).fail(function (e) {
  138. options.fileUploadError("file-reader", e);
  139. });
  140. } else {
  141. options.fileUploadError("unsupported-file-type", fileInfo.type);
  142. }
  143. });
  144. },
  145. markSelection = function (input, color) {
  146. restoreSelection();
  147. if (document.queryCommandSupported('hiliteColor')) {
  148. document.execCommand('hiliteColor', 0, color || 'transparent');
  149. }
  150. saveSelection();
  151. input.data(options.selectionMarker, color);
  152. },
  153. bindToolbar = function (toolbar, options) {
  154. toolbar.find(toolbarBtnSelector).click(function () {
  155. restoreSelection();
  156. editor.focus();
  157. execCommand($(this).data(options.commandRole));
  158. saveSelection();
  159. });
  160. toolbar.find('[data-toggle=dropdown]').click(restoreSelection);
  161. toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () {
  162. var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
  163. this.value = '';
  164. restoreSelection();
  165. if (newValue) {
  166. editor.focus();
  167. execCommand($(this).data(options.commandRole), newValue);
  168. }
  169. saveSelection();
  170. }).on('focus', function () {
  171. var input = $(this);
  172. if (!input.data(options.selectionMarker)) {
  173. markSelection(input, options.selectionColor);
  174. input.focus();
  175. }
  176. }).on('blur', function () {
  177. var input = $(this);
  178. if (input.data(options.selectionMarker)) {
  179. markSelection(input, false);
  180. }
  181. });
  182. toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () {
  183. restoreSelection();
  184. if (this.type === 'file' && this.files && this.files.length > 0) {
  185. insertFiles(this.files);
  186. }
  187. saveSelection();
  188. this.value = '';
  189. });
  190. },
  191. initFileDrops = function () {
  192. editor.on('dragenter dragover', false)
  193. .on('drop', function (e) {
  194. var dataTransfer = e.originalEvent.dataTransfer;
  195. e.stopPropagation();
  196. e.preventDefault();
  197. if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
  198. insertFiles(dataTransfer.files);
  199. }
  200. });
  201. },
  202. insertHtml = function (html) {
  203. if(!document.queryCommandSupported('insertHTML')){
  204. var range = window.getSelection().getRangeAt(0);
  205. if (range.insertNode) {
  206. // IE
  207. range.deleteContents();
  208. range.insertNode($(args)[0]);
  209. updateToolbar();
  210. editor.change && editor.change();
  211. } else if (range.pasteHTML) {
  212. // IE <= 10
  213. range.pasteHTML(args);
  214. updateToolbar();
  215. editor.change && editor.change();
  216. }
  217. }else{
  218. execCommand('insertHTML',html);
  219. }
  220. };
  221. options = $.extend({}, $.fn.wysiwyg.defaults, userOptions);
  222. toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
  223. bindHotkeys(options.hotKeys);
  224. if (options.dragAndDropImages) {
  225. initFileDrops();
  226. }
  227. bindToolbar($(options.toolbarSelector), options);
  228. editor.attr('contenteditable', true)
  229. .on('mouseup keyup mouseout', function () {
  230. saveSelection();
  231. updateToolbar();
  232. });
  233. $(window).bind('touchend', function (e) {
  234. var isInside = (editor.is(e.target) || editor.has(e.target).length > 0),
  235. currentRange = getCurrentRange(),
  236. clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);
  237. if (!clear || isInside) {
  238. saveSelection();
  239. updateToolbar();
  240. }
  241. });
  242. this.insertLink = function (linkUrl,linkTitle) {
  243. restoreSelection();
  244. editor.focus();
  245. var args = '<a href="'+linkUrl+'" target="_blank">'+linkTitle+'</a>';
  246. insertHtml(args);
  247. saveSelection();
  248. };
  249. return this;
  250. };
  251. $.fn.wysiwyg.defaults = {
  252. hotKeys: {
  253. 'ctrl+b meta+b': 'bold',
  254. 'ctrl+i meta+i': 'italic',
  255. 'ctrl+u meta+u': 'underline',
  256. 'ctrl+z meta+z': 'undo',
  257. 'ctrl+y meta+y meta+shift+z': 'redo',
  258. 'ctrl+l meta+l': 'justifyleft',
  259. 'ctrl+r meta+r': 'justifyright',
  260. 'ctrl+e meta+e': 'justifycenter',
  261. 'ctrl+j meta+j': 'justifyfull',
  262. 'shift+tab': 'outdent',
  263. 'tab': 'indent',
  264. 'return':'enterAction'
  265. },
  266. toolbarSelector: '[data-role=editor-toolbar]',
  267. commandRole: 'edit',
  268. activeToolbarClass: 'btn-info',
  269. selectionMarker: 'edit-focus-marker',
  270. selectionColor: 'darkgrey',
  271. dragAndDropImages: true,
  272. fileUploadError: function (reason, detail) { console.log("File upload error", reason, detail); }
  273. };
  274. }(window.jQuery));