bootstrap-wysiwyg.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. }else if(nodeName === "DIV" || nodeName === "P"){
  86. return insertHtml('<br/>');
  87. }
  88. console.log(nodeName);
  89. }catch (e){
  90. console.log(selection)
  91. console.log("enterKeyHandle:" + e);
  92. }
  93. },
  94. bindHotkeys = function (hotKeys) {
  95. $.each(hotKeys, function (hotkey, command) {
  96. editor.keydown(hotkey, function (e) {
  97. if (editor.attr('contenteditable') && editor.is(':visible')) {
  98. e.preventDefault();
  99. e.stopPropagation();
  100. if(hotkey === 'return'){
  101. return enterKeyHandle(e);
  102. }
  103. execCommand(command);
  104. }
  105. }).keyup(hotkey, function (e) {
  106. if (editor.attr('contenteditable') && editor.is(':visible')) {
  107. e.preventDefault();
  108. e.stopPropagation();
  109. }
  110. });
  111. });
  112. },
  113. getCurrentRange = function () {
  114. var sel = window.getSelection();
  115. if (sel.getRangeAt && sel.rangeCount) {
  116. return sel.getRangeAt(0);
  117. }
  118. },
  119. saveSelection = function () {
  120. selectedRange = getCurrentRange();
  121. },
  122. restoreSelection = function () {
  123. var selection = window.getSelection();
  124. if (selectedRange) {
  125. try {
  126. selection.removeAllRanges();
  127. } catch (ex) {
  128. document.body.createTextRange().select();
  129. document.selection.empty();
  130. }
  131. selection.addRange(selectedRange);
  132. }
  133. },
  134. insertFiles = function (files) {
  135. editor.focus();
  136. $.each(files, function (idx, fileInfo) {
  137. if (/^image\//.test(fileInfo.type)) {
  138. $.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
  139. execCommand('insertimage', dataUrl);
  140. }).fail(function (e) {
  141. options.fileUploadError("file-reader", e);
  142. });
  143. } else {
  144. options.fileUploadError("unsupported-file-type", fileInfo.type);
  145. }
  146. });
  147. },
  148. markSelection = function (input, color) {
  149. restoreSelection();
  150. if (document.queryCommandSupported('hiliteColor')) {
  151. document.execCommand('hiliteColor', 0, color || 'transparent');
  152. }
  153. saveSelection();
  154. input.data(options.selectionMarker, color);
  155. },
  156. bindToolbar = function (toolbar, options) {
  157. toolbar.find(toolbarBtnSelector).click(function () {
  158. restoreSelection();
  159. editor.focus();
  160. execCommand($(this).data(options.commandRole));
  161. saveSelection();
  162. });
  163. toolbar.find('[data-toggle=dropdown]').click(restoreSelection);
  164. toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () {
  165. var newValue = this.value; /* ugly but prevents fake double-calls due to selection restoration */
  166. this.value = '';
  167. restoreSelection();
  168. if (newValue) {
  169. editor.focus();
  170. execCommand($(this).data(options.commandRole), newValue);
  171. }
  172. saveSelection();
  173. }).on('focus', function () {
  174. var input = $(this);
  175. if (!input.data(options.selectionMarker)) {
  176. markSelection(input, options.selectionColor);
  177. input.focus();
  178. }
  179. }).on('blur', function () {
  180. var input = $(this);
  181. if (input.data(options.selectionMarker)) {
  182. markSelection(input, false);
  183. }
  184. });
  185. toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () {
  186. restoreSelection();
  187. if (this.type === 'file' && this.files && this.files.length > 0) {
  188. insertFiles(this.files);
  189. }
  190. saveSelection();
  191. this.value = '';
  192. });
  193. },
  194. initFileDrops = function () {
  195. editor.on('dragenter dragover', false)
  196. .on('drop', function (e) {
  197. var dataTransfer = e.originalEvent.dataTransfer;
  198. e.stopPropagation();
  199. e.preventDefault();
  200. if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
  201. insertFiles(dataTransfer.files);
  202. }
  203. });
  204. },
  205. insertHtml = function (html) {
  206. if(!document.queryCommandSupported('insertHTML')){
  207. var range = window.getSelection().getRangeAt(0);
  208. if (range.insertNode) {
  209. // IE
  210. range.deleteContents();
  211. range.insertNode($(args)[0]);
  212. updateToolbar();
  213. editor.change && editor.change();
  214. } else if (range.pasteHTML) {
  215. // IE <= 10
  216. range.pasteHTML(args);
  217. updateToolbar();
  218. editor.change && editor.change();
  219. }
  220. }else{
  221. console.log(html)
  222. execCommand('insertHTML',html);
  223. }
  224. };
  225. options = $.extend({}, $.fn.wysiwyg.defaults, userOptions);
  226. toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']';
  227. bindHotkeys(options.hotKeys);
  228. if (options.dragAndDropImages) {
  229. initFileDrops();
  230. }
  231. bindToolbar($(options.toolbarSelector), options);
  232. editor.attr('contenteditable', true)
  233. .on('mouseup keyup mouseout', function () {
  234. saveSelection();
  235. updateToolbar();
  236. });
  237. $(window).bind('touchend', function (e) {
  238. var isInside = (editor.is(e.target) || editor.has(e.target).length > 0),
  239. currentRange = getCurrentRange(),
  240. clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset);
  241. if (!clear || isInside) {
  242. saveSelection();
  243. updateToolbar();
  244. }
  245. });
  246. this.insertLink = function (linkUrl,linkTitle) {
  247. restoreSelection();
  248. editor.focus();
  249. var args = '<a href="'+linkUrl+'" target="_blank">'+linkTitle+'</a>';
  250. insertHtml(args);
  251. saveSelection();
  252. };
  253. this.insertHtml = insertHtml;
  254. return this;
  255. };
  256. $.fn.wysiwyg.defaults = {
  257. hotKeys: {
  258. 'ctrl+b meta+b': 'bold',
  259. 'ctrl+i meta+i': 'italic',
  260. 'ctrl+u meta+u': 'underline',
  261. 'ctrl+z meta+z': 'undo',
  262. 'ctrl+y meta+y meta+shift+z': 'redo',
  263. 'ctrl+l meta+l': 'justifyleft',
  264. 'ctrl+r meta+r': 'justifyright',
  265. 'ctrl+e meta+e': 'justifycenter',
  266. 'ctrl+j meta+j': 'justifyfull',
  267. 'shift+tab': 'outdent',
  268. 'tab': 'indent',
  269. 'return':'enterAction'
  270. },
  271. toolbarSelector: '[data-role=editor-toolbar]',
  272. commandRole: 'edit',
  273. activeToolbarClass: 'btn-info',
  274. selectionMarker: 'edit-focus-marker',
  275. selectionColor: 'darkgrey',
  276. dragAndDropImages: true,
  277. fileUploadError: function (reason, detail) { console.log("File upload error", reason, detail); }
  278. };
  279. }(window.jQuery));